From 6a07420f26fafb6e2ef90a0ec46c7c1c8c1d725a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:37:09 -0600 Subject: [PATCH] fix(google-workspace): refuse unknown tool arguments; list_threads filters by query (#22706) 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. > - Agents use Google Workspace through Paperclip's own REST tools for Gmail, Drive, Docs, Sheets, Slides and Calendar (#22634). > - In a live test on staging, an agent called `gmail__list_threads` with `query` and `q`. The tool did not have these arguments. > - The tool ignored them and returned threads that did not match. The agent read mail that it did not ask for. > - Google reviews this connector for restricted scopes. A tool that ignores a filter and reads too much data is a data-minimisation defect. > - This pull request makes every tool refuse an argument that is not in its input schema, before it sends a request to Google. It also adds `query` to `list_threads`. > - The benefit is that a filter can never be ignored. An agent gets a clear error that names the bad argument and lists the correct arguments. ## Linked Issues or Issue Description Refs #22634 **What happened?** On staging, against real Google, an agent called `gmail__list_threads` with `query` (and `q`) to list only threads with a marker. These arguments are not in the tool's input schema. The tool dropped them and returned unfiltered threads (5 shown, estimate 201). **What did you expect to happen?** The tool refuses an argument that it does not know, names it, and sends nothing to Google. `list_threads` accepts a Gmail search query, as `search_threads` does. **Steps to reproduce** 1. Connect Google Workspace with Gmail read access. 2. Call `gmail__list_threads` with `{ "query": "subject:marker" }`. 3. See that the result contains threads that do not match the query. ## What Changed - `defineTool` in `server/src/google-workspace-rest-tools/tool.ts` checks the arguments of all 36 tools against the advertised input schema before the zod parse. It checks the top level and structured inputs (for example `attendees[0]`, `writeControl`). An unknown argument gives a tool error and no request goes to Google. Example: `Invalid arguments for list_threads: unknown argument "q". Accepted arguments: pageSize, pageToken, query, labelIds, includeTrash, view. Nothing was sent to Google.` - `defineTool` sets `additionalProperties: false` on each object in the advertised input schema that lists `properties`. Agents get the schema from code, so existing connections see it with no reconnect and no refresh. - Google's batchUpdate request objects stay pass-through: `docs__update_doc`, `slides__update_presentation` and `sheets__update_spreadsheet` `requests[]`. The request-kind checks stay the same. - `gmail__list_threads` has a new optional `query`. It goes to Gmail as `q`, with the same name and meaning as in `search_threads`. It works together with `labelIds`. The draft and spam exclusions use the same shared function (`queryWithExclusions`) as `search_threads`. The page size stays default 20, maximum 50. - The README has a new "Unknown arguments" section, a new row in the input-differences table, a "Filters on list tools" decision list (`search_messages` and `list_drafts` already have `query`; `list_labels`, `list_calendars` have no REST filter; `list_events` uses `fullText`; Drive `list_recent_files` stays without `query`, and `search_files` is the Drive filter tool), and an updated `list_threads` design note. - `sheets/get-values.test.ts` expected that an unknown `valueRenderOption` was ignored. It now expects a refusal. ## Verification - `cd server && npx vitest run src/google-workspace-rest-tools` passes: 55 files, 1,400+ tests. - New `strict-arguments.test.ts` makes one case for each of the 36 tools from the tool list. Each case calls the tool with an unknown argument and expects the exact error and zero HTTP requests. It also checks `additionalProperties: false` on each closed object, the exact list of pass-through paths, and that the zod schema of each tool validates the same fields as its JSON schema. Red first: with the old `tool.ts`, 39 of 42 cases failed. - `gmail/list-threads.test.ts`: `{ query: "x" }` reaches Google as `q=(x) -in:draft`; `{ q: "marker" }` is refused with zero requests. - `src/__tests__/google-workspace-rest-transport.test.ts` (embedded Postgres, `executeTool` path): a connection with an older saved `list_threads` schema (no `query`, no `additionalProperties`) gets the new schema with no refresh and no Google request. A `query` call sends the right `q`. A `q` call fails as `tool_error` with the readable message, makes no Google request, and is recorded as a failed invocation and one `call_failed` audit event. - All Google-related server test files pass: 61 files, 1,542 tests. The allowlist and boundary tests pass. - `pnpm verify` exited 2 (the README is a broad input). Required CI gives the broad coverage. - Not checked against Google's servers. No request was sent to staging, production or Google. ## Risks - An agent that sent extra arguments before now gets an error, not a silent drop. This is the intended change. The error lists the accepted arguments, so the agent can correct the call at once. - If a tool's JSON schema and zod schema do not agree, a valid argument could be refused. A new test checks that they agree for all 36 tools. - What Google's own MCP servers do with unknown arguments is not recorded. We chose to refuse. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code, with tool use (shell, file edits) and extended thinking. ## 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 - [ ] 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 --- .../google-workspace-rest-transport.test.ts | 32 ++++ .../src/google-workspace-rest-tools/README.md | 65 +++++++- .../allowlist.test.ts | 2 +- .../gmail/list-threads.test.ts | 25 +++ .../gmail/list-threads.ts | 14 +- .../gmail/search-threads.ts | 12 +- .../sheets/get-values.test.ts | 12 +- .../strict-arguments.test.ts | 153 ++++++++++++++++++ .../src/google-workspace-rest-tools/tool.ts | 72 ++++++++- 9 files changed, 363 insertions(+), 24 deletions(-) create mode 100644 server/src/google-workspace-rest-tools/strict-arguments.test.ts diff --git a/server/src/__tests__/google-workspace-rest-transport.test.ts b/server/src/__tests__/google-workspace-rest-transport.test.ts index 6924f387d8c..4fad149c81f 100644 --- a/server/src/__tests__/google-workspace-rest-transport.test.ts +++ b/server/src/__tests__/google-workspace-rest-transport.test.ts @@ -624,6 +624,38 @@ const support = await getEmbeddedPostgresTestSupport(); expect(f.mcpRequests).toHaveLength(refreshesBefore); }); + it("gives a connection saved with older definitions the closed schemas and list_threads' query at once, and refuses unknown arguments", async () => { + const f = await connectWorkspace({ permissions: DEFAULT_PERMISSIONS }); + const saved = f.catalog.find((entry) => entry.toolName === "gmail__list_threads")!; + const current = restDispatch.listGoogleWorkspaceRest("gmail").find((tool) => tool.name === "list_threads")!.inputSchema; + const { query: _query, ...olderProperties } = current.properties as Record; + await db.update(toolCatalogEntries).set({ inputSchema: { type: "object", properties: olderProperties } }).where(eq(toolCatalogEntries.id, saved.id)); + const requestsBefore = f.restRequests.length; + + const listed = await f.toolNamed("gmail__list_threads"); + expect(listed.parametersSchema).toEqual(current); + expect(listed.parametersSchema).toMatchObject({ additionalProperties: false, properties: { query: { type: "string" } } }); + for (const tool of (await f.gateway.listToolsForSession(f.session.token)).filter((item) => item.connectionId === f.connectionId)) { + expect(tool.parametersSchema, String(tool.upstreamToolName)).toMatchObject({ additionalProperties: false }); + } + expect(f.restRequests).toHaveLength(requestsBefore); + + const queries: Array = []; + f.setGoogle((url) => { if (url.pathname === "/gmail/v1/users/me/threads") queries.push(url.searchParams.get("q")); return undefined; }); + await expect(f.call("gmail__list_threads", { query: "subject:marker-123" })).resolves.toMatchObject({ status: "completed" }); + expect(queries).toEqual(["(subject:marker-123) -in:draft"]); + + f.restRequests.length = 0; + const refusal = "Invalid arguments for list_threads: unknown argument \"q\". Accepted arguments: pageSize, pageToken, query, labelIds, includeTrash, view. Nothing was sent to Google."; + await expect(f.call("gmail__list_threads", { q: "subject:marker-123" })).rejects.toMatchObject({ status: 502, reasonCode: "tool_error", message: expect.stringContaining(refusal) }); + expect(f.restRequests).toEqual([]); + const failed = (await f.invocations()).filter((invocation) => invocation.status === "failed"); + expect(failed).toEqual([expect.objectContaining({ errorCode: "tool_error", errorMessage: expect.stringContaining(refusal) })]); + const audit = await db.select().from(toolAccessAuditEvents).where(and(eq(toolAccessAuditEvents.companyId, f.company.id), eq(toolAccessAuditEvents.action, "call_failed"))); + expect(audit).toHaveLength(1); + expect(JSON.stringify(audit[0])).toContain("unknown argument"); + }); + it("on the first refresh after the switch, releases actions held for review and keeps Off and Ask first", async () => { for (const service of LAUNCH_SERVICES) useTransport(service, "google_mcp"); const f = await connectWorkspace({ off: ["gmail__search_threads"], askFirst: ["gmail__create_draft"] }); diff --git a/server/src/google-workspace-rest-tools/README.md b/server/src/google-workspace-rest-tools/README.md index 11d2d43bf14..9e40a4468c8 100644 --- a/server/src/google-workspace-rest-tools/README.md +++ b/server/src/google-workspace-rest-tools/README.md @@ -95,12 +95,54 @@ so they can be deleted cleanly when that happens. | 403 `appNotAuthorizedToFile` (Drive) | Tool error saying `drive.file` covers only files this app created or opened, without the app's project number | | Any 3xx redirect | Tool error; the redirect is not followed | | Other 403, 404, 400, 429, 5xx, timeout, network failure | Tool error result (`isError: true`) with a short message | +| Unknown argument (see "Unknown arguments") | Tool error result that names it and lists the accepted ones, no request sent | | Invalid arguments | Tool error result, no request sent | | Unknown tool | Throws `McpError` `InvalidParams` | Token problems are thrown, not returned, so a caller can refresh the token or ask the user to reconnect exactly as it does for Google's MCP servers. +### Unknown arguments + +No tool ignores an argument. `defineTool` in `tool.ts` checks the call's +arguments against the tool's advertised input schema before anything else, +for all 36 tools. An argument that is not in the schema, at the top level or +inside a structured input (for example `attendees[0]` or `writeControl`), +fails the call before any request is sent to Google: + +```text +Invalid arguments for list_threads: unknown argument "q". Accepted arguments: pageSize, pageToken, query, labelIds, includeTrash, view. Nothing was sent to Google. +``` + +`defineTool` also sets `additionalProperties: false` on every object in the +advertised input schema that lists its `properties`, so agents see the rule. +`strict-arguments.test.ts` builds its cases from the tool list, so a new tool +is covered without a test change, and checks that the zod schema of each tool +has the same objects, at the same paths, with the same fields, types and +enums as its JSON schema. Every field the zod schema requires is also +required in the JSON schema. Only `update_doc` and `update_presentation` +require more in the JSON schema than in zod (`writeControl` and its +`requiredRevisionId`); the tool checks those itself, to give an error that +says to read the file first. The check follows only `properties` and `items`, +so `defineTool` refuses to define a tool whose input schema uses anything it +cannot follow (`anyOf`, `oneOf`, `allOf`, `$ref`, tuple `items`, an +`additionalProperties` other than `false` beside `properties`, and similar). A new schema shape +fails at startup and in tests; it can never let an argument through unchecked. + +**Pass-through inputs.** These are Google's own request objects and are sent +to Google as given. Their contents are not checked for unknown fields here +(each tool still checks the request kind, see "Allowed request kinds"): + +- `docs__update_doc` `requests[]` (`documents.batchUpdate` requests) +- `slides__update_presentation` `requests[]` (`presentations.batchUpdate` requests) +- `sheets__update_spreadsheet` `requests[]` (`spreadsheets.batchUpdate` requests) + +The recorded Google MCP references do not say what Google's servers do with +an unknown argument, and this was not checked against Google's servers. The +decision is to refuse: an ignored filter can read data the agent did not ask +for (a staging test on 2026-11-23 called `list_threads` with `query` and got +every thread). + ## How it plugs in The gateway calls this folder in process. There is no loopback or hosted MCP @@ -294,6 +336,7 @@ in the tool's own description and schema, which agents now receive: | `calendar__delete_event` | a recurring series ID deletes the series | refused; pass one occurrence | | `gmail__create_draft` | attachments | refused, as Google's tool does today | | `drive__search_files` | full MCP query language and `orderBy` | terms without a Drive `q` equivalent refused; `orderBy` limited | +| every tool | not recorded what an argument outside the schema does | refused with the argument's name (see "Unknown arguments") | Each refusal is a tool error that says what to do, and nothing is changed. @@ -375,6 +418,15 @@ Each refusal is a tool error that says what to do, and nothing is changed. this folder. `threadsTotal` and `threadsUnread` are left out: REST returns them only from `labels.get`, one request per label. A label with only one of its two colors set is returned without `color`. +- **Filters on list tools** (checked 2026-11-23). `list_threads` had no + `query`, so a call with `query` listed every thread; it now takes `query` + (see "Not verified against Google's servers"). `search_messages` and + `list_drafts` already take `query`, sent as Gmail's `q`. `list_labels` has + no filter: Gmail's `labels.list` has none. Calendar `list_events` filters + with `fullText`, and `list_calendars` has no filter in REST. Drive + `list_recent_files` stays without `query`, as in Google's Drive MCP tool; + `search_files` is the Drive tool that filters. In each case an argument the + tool does not have is refused, never ignored. - **Errors** for Google failures are tool error results with our own short messages, not Google's raw error text (except for 400 and 403 messages, trimmed to one line). @@ -435,11 +487,13 @@ Google's servers return if they ever expose tools with these names: - **`get_draft`**: input `draftId` (required) and `view` (`DraftView` from `list_drafts`); result is one `Draft`, the shape `list_drafts` and `create_draft` return. One `drafts.get`, plus bodies. -- **`list_threads`**: input `pageSize`, `pageToken`, `includeTrash` and `view` - as in `search_threads`, plus `labelIds` (at most 20; a thread must have all - of them) instead of `query`; result is `search_threads`'s. Drafts are - excluded unless `DRAFT` is among the labels; spam and trash are included - when `SPAM` or `TRASH` is among them. +- **`list_threads`**: input `pageSize`, `pageToken`, `query`, `includeTrash` + and `view` as in `search_threads`, plus `labelIds` (at most 20; a thread + must have all of them); result is `search_threads`'s. `query` is sent as + Gmail's `q`, with the same name and meaning as in `search_threads`, and a + thread must match both the query and the labels. Drafts are excluded unless + `DRAFT` is among the labels or the query uses `in:draft`; spam and trash are + included when `SPAM` or `TRASH` is among the labels or `includeTrash` is set. - **`search_messages`**: input as `search_threads`, with `messageFormat` from `get_message` instead of `view`; result is `{ messages, nextPageToken, resultCountEstimate }` with `get_message`'s `Message`. Unlike `get_message`, @@ -1011,6 +1065,7 @@ made" warning. option). Numbers, currency, percentages and dates come back as the displayed text (`"$1,200.50"`, `"12%"`, `"1/5/2026"`), booleans as `"TRUE"`/`"FALSE"`, errors as their text (`"#DIV/0!"`), and formula cells as their result. + Any other argument, such as `valueRenderOption`, is refused. Google's answer is returned unchanged: trailing empty rows and columns are left out, so rows can differ in length; an empty range has no `values` field; in a merged area only the top-left cell holds the value. One range per diff --git a/server/src/google-workspace-rest-tools/allowlist.test.ts b/server/src/google-workspace-rest-tools/allowlist.test.ts index 4fc0ebc145b..6ec20c73f95 100644 --- a/server/src/google-workspace-rest-tools/allowlist.test.ts +++ b/server/src/google-workspace-rest-tools/allowlist.test.ts @@ -39,7 +39,7 @@ describe("tool allowlist", () => { .map((tool) => (tool.inputSchema.properties as Record | undefined)?.query?.description) .filter((text): text is string => typeof text === "string"); expect(queries.length).toBeGreaterThanOrEqual(3); - expect(queries.filter((item) => item.includes("label:"))).toHaveLength(2); + expect(queries.filter((item) => item.includes("label:"))).toHaveLength(3); for (const text of queries.filter((item) => item.includes("label:"))) { expect(text).toMatch(/`label:` takes a label name/); } diff --git a/server/src/google-workspace-rest-tools/gmail/list-threads.test.ts b/server/src/google-workspace-rest-tools/gmail/list-threads.test.ts index fd0d55de4b1..03ca449aca7 100644 --- a/server/src/google-workspace-rest-tools/gmail/list-threads.test.ts +++ b/server/src/google-workspace-rest-tools/gmail/list-threads.test.ts @@ -21,6 +21,15 @@ describe("list_threads request", () => { expect(listThreadsQuery({ includeTrash: true })).toEqual({ q: "-in:draft -in:spam", includeSpamTrash: true }); }); + it("filters by a Gmail search query, combined with labels and the default exclusions", () => { + expect(listThreadsToolRequest({ query: "subject:marker-123" }).query).toMatchObject({ q: "(subject:marker-123) -in:draft", labelIds: undefined }); + expect(listThreadsQuery({ query: "from:sam@example.test", labelIds: ["INBOX"] })).toEqual({ q: "(from:sam@example.test) -in:draft", includeSpamTrash: undefined }); + expect(listThreadsQuery({ query: "in:draft marker" })).toEqual({ q: "in:draft marker", includeSpamTrash: undefined }); + expect(listThreadsQuery({ query: "marker", labelIds: ["DRAFT"] })).toEqual({ q: "marker", includeSpamTrash: undefined }); + expect(listThreadsQuery({ query: "marker", includeTrash: true })).toEqual({ q: "(marker) -in:draft -in:spam", includeSpamTrash: true }); + expect(listThreadsQuery({ query: " " })).toEqual({ q: "-in:draft", includeSpamTrash: undefined }); + }); + it("defaults the page size to 20 and caps it at 50", () => { expect(listThreadsToolRequest({ pageSize: 500 }).query?.maxResults).toBe(50); expect(listThreadsToolRequest({ pageSize: 5, pageToken: "page-2-token" }).query).toMatchObject({ maxResults: 5, pageToken: "page-2-token" }); @@ -50,6 +59,22 @@ describe("list_threads tool", () => { expect(calls).toHaveLength(51); }); + it("sends the query to Google as q", async () => { + const { fetch, calls } = fakeGoogle(({ url }) => (url.pathname.endsWith("/threads") ? json({ threads: [], resultSizeEstimate: 0 }) : json({}, 404))); + const result = await listThreads.call({ query: "x" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(result.isError).toBeFalsy(); + expect(calls).toHaveLength(1); + expect(calls[0]!.url.searchParams.get("q")).toBe("(x) -in:draft"); + }); + + it("refuses q, which is not one of its arguments, instead of listing every thread", async () => { + const { fetch, calls } = fakeGoogle(() => json({})); + const result = await listThreads.call({ q: "marker" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(result).toEqual({ isError: true, content: [{ type: "text", + text: "Invalid arguments for list_threads: unknown argument \"q\". Accepted arguments: pageSize, pageToken, query, labelIds, includeTrash, view. Nothing was sent to Google." }] }); + expect(calls).toHaveLength(0); + }); + it("refuses label IDs that are not Gmail IDs and too many labels", async () => { const { fetch, calls } = fakeGoogle(() => json({})); const http = createGoogleHttp({ accessToken: "t", fetch }); diff --git a/server/src/google-workspace-rest-tools/gmail/list-threads.ts b/server/src/google-workspace-rest-tools/gmail/list-threads.ts index de8ee1bc70e..0147baf004c 100644 --- a/server/src/google-workspace-rest-tools/gmail/list-threads.ts +++ b/server/src/google-workspace-rest-tools/gmail/list-threads.ts @@ -4,6 +4,7 @@ import { defineTool } from "../tool.js"; import { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, + queryWithExclusions, readThreads, searchThreadsResult, THREAD_VIEWS, @@ -17,6 +18,7 @@ export const MAX_LABEL_FILTERS = 20; const args = z.object({ pageSize: z.number().int().positive().optional(), pageToken: z.string().max(2048).optional(), + query: z.string().max(4096).optional(), labelIds: z.array(z.string().regex(/^[A-Za-z0-9_-]{1,256}$/, "Must be a Gmail label ID")).max(MAX_LABEL_FILTERS).optional(), includeTrash: z.boolean().optional(), view: z.enum(THREAD_VIEWS).optional(), @@ -26,10 +28,8 @@ export type ListThreadsArgs = z.infer; export function listThreadsQuery(input: ListThreadsArgs): { q?: string; includeSpamTrash?: true } { const labels = new Set(input.labelIds ?? []); const includeSpamTrash = Boolean(input.includeTrash) || labels.has("SPAM") || labels.has("TRASH"); - const excluded: string[] = []; - if (!labels.has("DRAFT")) excluded.push("-in:draft"); - if (includeSpamTrash && !labels.has("SPAM")) excluded.push("-in:spam"); - return { q: excluded.join(" ") || undefined, includeSpamTrash: includeSpamTrash ? true : undefined }; + const q = queryWithExclusions(input.query, { drafts: !labels.has("DRAFT"), spam: includeSpamTrash && !labels.has("SPAM") }); + return { q: q || undefined, includeSpamTrash: includeSpamTrash ? true : undefined }; } export function listThreadsToolRequest(input: ListThreadsArgs): GoogleRequest { @@ -50,12 +50,16 @@ export const listThreads = defineTool({ definition: { name: "list_threads", title: "List threads", - description: "Lists the signed-in user's Gmail threads, newest first, one page at a time, optionally only threads that have every given label. Returns thread IDs with message summaries, not full bodies; use get_thread with a thread ID for full messages. To filter by words, senders or dates, use search_threads.", + description: "Lists the signed-in user's Gmail threads, newest first, one page at a time, optionally only threads that match a Gmail search query and have every given label. Returns thread IDs with message summaries, not full bodies; use get_thread with a thread ID for full messages. A thread matches the query when any of its messages matches.", inputSchema: { type: "object", properties: { pageSize: { type: "integer", description: "Optional. Most threads to return. Default 20, maximum 50." }, pageToken: { type: "string", description: "Optional. The nextPageToken from a previous call. Leave empty for the first page." }, + query: { + type: "string", + description: "Optional. A Gmail search query, the same as search_threads takes (for example `from:user@example.com newer_than:7d`). `label:` takes a label name with spaces written as hyphens (for example `label:client-work`), not a label ID. Without a query, threads are filtered only by labelIds. Drafts are excluded unless the query includes in:draft or DRAFT is in labelIds.", + }, labelIds: { type: "array", items: { type: "string" }, diff --git a/server/src/google-workspace-rest-tools/gmail/search-threads.ts b/server/src/google-workspace-rest-tools/gmail/search-threads.ts index e04a4389b7c..40b5d114f7f 100644 --- a/server/src/google-workspace-rest-tools/gmail/search-threads.ts +++ b/server/src/google-workspace-rest-tools/gmail/search-threads.ts @@ -31,17 +31,21 @@ export function unquotedOperators(query: string): string { return query.replace(/"[^"]*"?/g, " "); } -export function effectiveQuery(input: SearchThreadsArgs): string { - const query = (input.query ?? "").trim(); +export function queryWithExclusions(rawQuery: string | undefined, exclude: { drafts: boolean; spam: boolean }): string { + const query = (rawQuery ?? "").trim(); const operators = unquotedOperators(query); const added: string[] = []; - if (!/(^|[\s({])-?(in|is):(drafts?|anywhere)\b/i.test(operators)) added.push("-in:draft"); - if (input.includeTrash && !/(^|[\s({])-?(in|is):(spam|anywhere)\b/i.test(operators)) added.push("-in:spam"); + if (exclude.drafts && !/(^|[\s({])-?(in|is):(drafts?|anywhere)\b/i.test(operators)) added.push("-in:draft"); + if (exclude.spam && !/(^|[\s({])-?(in|is):(spam|anywhere)\b/i.test(operators)) added.push("-in:spam"); if (!query) return added.join(" "); if (added.length === 0) return query; return [`(${query})`, ...added].join(" "); } +export function effectiveQuery(input: SearchThreadsArgs): string { + return queryWithExclusions(input.query, { drafts: true, spam: Boolean(input.includeTrash) }); +} + export function threadDetail(view: SearchThreadsArgs["view"]): MessageDetail { return view === "THREAD_VIEW_METADATA_ONLY" ? "metadata_only" : "minimal"; } diff --git a/server/src/google-workspace-rest-tools/sheets/get-values.test.ts b/server/src/google-workspace-rest-tools/sheets/get-values.test.ts index 169f80c7581..9d2e7e821a5 100644 --- a/server/src/google-workspace-rest-tools/sheets/get-values.test.ts +++ b/server/src/google-workspace-rest-tools/sheets/get-values.test.ts @@ -84,16 +84,12 @@ describe("get_values tool", () => { [{ spreadsheetId: SPREADSHEET_ID, range: "Q1 Plan!A1" }, /must be quoted/], [{ spreadsheetId: "../other", range: "A1" }, /spreadsheet ID/], [{ spreadsheetId: SPREADSHEET_ID }, /range/], - [{ spreadsheetId: SPREADSHEET_ID, range: "Sheet1!A1", valueRenderOption: "FORMULA" }, null], + [{ spreadsheetId: SPREADSHEET_ID, range: "Sheet1!A1", valueRenderOption: "FORMULA" }, /unknown argument "valueRenderOption"/], ])("validates %j before sending", async (args, message) => { const { fetch, calls } = fakeGoogle(() => json(EMPTY_VALUES)); const result = await getValues.call(args, createGoogleHttp({ accessToken: "t", fetch })); - if (message) { - expect(result.isError).toBe(true); - expect(text(result)).toMatch(message); - expect(calls).toHaveLength(0); - } else { - expect(calls[0]!.url.searchParams.get("valueRenderOption")).toBe("FORMATTED_VALUE"); - } + expect(result.isError).toBe(true); + expect(text(result)).toMatch(message); + expect(calls).toHaveLength(0); }); }); diff --git a/server/src/google-workspace-rest-tools/strict-arguments.test.ts b/server/src/google-workspace-rest-tools/strict-arguments.test.ts new file mode 100644 index 00000000000..5c41a9fd1df --- /dev/null +++ b/server/src/google-workspace-rest-tools/strict-arguments.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it } from "vitest"; +import { z } from "zod"; +import { fakeGoogle, json } from "./fixtures/fake-google.js"; +import { GMAIL_TOOLS } from "./gmail/index.js"; +import { CALENDAR_TOOLS } from "./calendar/index.js"; +import { DOCS_TOOLS } from "./docs/index.js"; +import { DRIVE_TOOLS } from "./drive/index.js"; +import { SHEETS_TOOLS } from "./sheets/index.js"; +import { SLIDES_TOOLS } from "./slides/index.js"; +import { defineTool, unmodeledSchemaParts } from "./tool.js"; +import { callGoogleWorkspaceRestTool, GOOGLE_WORKSPACE_REST_SERVICES, listGoogleWorkspaceRestTools } from "./tools.js"; + +type Schema = Record; +const isRecord = (value: unknown): value is Schema => typeof value === "object" && value !== null && !Array.isArray(value); + +function objectNodes(schema: unknown, path = ""): Array<{ path: string; node: Schema }> { + if (!isRecord(schema)) return []; + const own = schema.type === "object" || isRecord(schema.properties) ? [{ path, node: schema }] : []; + const children = isRecord(schema.properties) + ? Object.entries(schema.properties).flatMap(([name, item]) => objectNodes(item, path ? `${path}.${name}` : name)) + : []; + return [...own, ...children, ...objectNodes(schema.items, `${path}[]`)]; +} + +const ALL_TOOLS = GOOGLE_WORKSPACE_REST_SERVICES.flatMap((service) => listGoogleWorkspaceRestTools(service).map((tool) => ({ service, tool }))); +const REST_TOOLS = [...GMAIL_TOOLS, ...CALENDAR_TOOLS, ...DRIVE_TOOLS, ...DOCS_TOOLS, ...SLIDES_TOOLS, ...SHEETS_TOOLS]; +const PASS_THROUGH = ["docs update_doc requests[]", "slides update_presentation requests[]", "sheets update_spreadsheet requests[]"]; + +describe("unknown arguments", () => { + it("covers all 36 tools", () => { + expect(ALL_TOOLS).toHaveLength(36); + expect(REST_TOOLS).toHaveLength(36); + }); + + it("advertises additionalProperties: false on every input object, except Google's pass-through request objects", () => { + const open: string[] = []; + for (const { service, tool } of ALL_TOOLS) { + expect(tool.inputSchema.additionalProperties, tool.name).toBe(false); + for (const { path, node } of objectNodes(tool.inputSchema)) { + if (isRecord(node.properties)) expect(node.additionalProperties, `${tool.name} ${path}`).toBe(false); + else open.push(`${service} ${tool.name} ${path}`); + } + } + expect(open.sort()).toEqual([...PASS_THROUGH].sort()); + }); + + it("validates exactly the arguments each tool advertises, with the same object structure", () => { + for (const tool of REST_TOOLS) { + const parsed = z.toJSONSchema(tool.args, { io: "input", unrepresentable: "any" }); + const keys = (schema: unknown) => Object.fromEntries(objectNodes(schema) + .filter(({ node }) => isRecord(node.properties)) + .map(({ path, node }) => [path || "(top level)", Object.keys(node.properties as Schema).sort()])); + expect(keys(parsed), tool.definition.name).toEqual(keys(tool.definition.inputSchema)); + } + }); + + it("advertises the same types, enums and required fields that each tool validates", () => { + const contract = (schema: unknown) => Object.fromEntries(objectNodes(schema) + .filter(({ node }) => isRecord(node.properties)) + .flatMap(({ path, node }) => Object.entries(node.properties as Record) + .map(([name, item]) => [path ? `${path}.${name}` : name, { type: item.type ?? null, enum: Array.isArray(item.enum) ? [...item.enum].sort() : null }]))); + const required = (schema: unknown) => objectNodes(schema).filter(({ node }) => isRecord(node.properties)) + .flatMap(({ path, node }) => ((node.required as string[] | undefined) ?? []).map((name) => (path ? `${path}.${name}` : name))); + const requiredOnlyInAdvertisedSchema: string[] = []; + for (const tool of REST_TOOLS) { + const parsed = z.toJSONSchema(tool.args, { io: "input", unrepresentable: "any" }); + expect(contract(tool.definition.inputSchema), tool.definition.name).toEqual(contract(parsed)); + const advertised = required(tool.definition.inputSchema); + expect(advertised, tool.definition.name).toEqual(expect.arrayContaining(required(parsed))); + requiredOnlyInAdvertisedSchema.push(...advertised.filter((name) => !required(parsed).includes(name)).map((name) => `${tool.definition.name} ${name}`)); + } + expect(requiredOnlyInAdvertisedSchema.sort()).toEqual([ + "update_doc writeControl", "update_doc writeControl.requiredRevisionId", + "update_presentation writeControl", "update_presentation writeControl.requiredRevisionId", + ]); + }); + + it.each([ + ["docs", "update_doc", { documentId: "doc1", requests: [{ insertText: { text: "Hi", location: { index: 1 } } }] }], + ["slides", "update_presentation", { presentationId: "deck1", requests: [{ createSlide: {} }] }], + ] as const)("%s %s refuses a call without writeControl.requiredRevisionId before sending", async (service, name, args) => { + const { fetch, calls } = fakeGoogle(() => json({})); + for (const call of [args, { ...args, writeControl: {} }]) { + const result = await callGoogleWorkspaceRestTool({ service, name, arguments: call, accessToken: "t", fetch }); + expect(result.isError, JSON.stringify(call)).toBe(true); + expect((result.content as Array<{ text: string }>)[0]!.text).toMatch(/requiredRevisionId/); + } + expect(calls).toHaveLength(0); + }); + + it("refuses at definition time a schema whose parts the check cannot follow", () => { + const base = { name: "probe", annotations: { readOnlyHint: false } }; + const run = async () => ({ content: [] }); + expect(() => defineTool({ definition: { ...base, inputSchema: { type: "object", properties: { a: { anyOf: [{ type: "object", properties: { b: { type: "string" } } }] } } } }, args: z.object({}), run })) + .toThrow("probe: the unknown-argument check cannot follow inputSchema.properties.a.anyOf"); + expect(() => defineTool({ definition: { ...base, inputSchema: { type: "object", properties: { a: { type: "array", items: [{ type: "object" }] } } } }, args: z.object({}), run })) + .toThrow("inputSchema.properties.a.items (tuple)"); + expect(() => defineTool({ definition: { ...base, inputSchema: { type: "object", properties: { a: { type: "string" } }, additionalProperties: { type: "string" } } }, args: z.object({}), run })) + .toThrow("inputSchema.additionalProperties (open beside properties)"); + expect(() => defineTool({ definition: { ...base, inputSchema: { type: "object", properties: { a: { type: "string" } }, additionalProperties: true } }, args: z.object({}), run })) + .toThrow("inputSchema.additionalProperties (open beside properties)"); + for (const { tool } of ALL_TOOLS) expect(unmodeledSchemaParts(tool.inputSchema, tool.name)).toEqual([]); + }); + + it.each(ALL_TOOLS.map(({ service, tool }) => [`${service}__${tool.name}`, service, tool] as const))( + "%s refuses an unknown argument by name, lists the accepted ones, and sends nothing to Google", + async (_label, service, tool) => { + const { fetch, calls } = fakeGoogle(() => json({})); + const result = await callGoogleWorkspaceRestTool({ service, name: tool.name, arguments: { unexpectedArgument: "x" }, accessToken: "t", fetch }); + const accepted = Object.keys(tool.inputSchema.properties ?? {}).join(", "); + expect(result).toEqual({ + isError: true, + content: [{ type: "text", text: `Invalid arguments for ${tool.name}: unknown argument "unexpectedArgument". Accepted arguments: ${accepted}. Nothing was sent to Google.` }], + }); + expect(calls).toHaveLength(0); + }, + ); + + it("names every unknown argument in one error", async () => { + const { fetch, calls } = fakeGoogle(() => json({})); + const result = await callGoogleWorkspaceRestTool({ service: "gmail", name: "search_messages", arguments: { q: "x", filter: "y", pageSize: 5 }, accessToken: "t", fetch }); + expect(result.content).toEqual([{ type: "text", text: "Invalid arguments for search_messages: unknown arguments \"q\", \"filter\". Accepted arguments: pageSize, pageToken, query, includeTrash, messageFormat. Nothing was sent to Google." }]); + expect(calls).toHaveLength(0); + }); + + it("refuses unknown fields inside structured inputs, with their path", async () => { + const { fetch, calls } = fakeGoogle(() => json({})); + const event = await callGoogleWorkspaceRestTool({ + service: "calendar", name: "create_event", accessToken: "t", fetch, + arguments: { summary: "Plan", startTime: "2026-11-24T10:00:00Z", endTime: "2026-11-24T10:30:00Z", attendees: [{ email: "sam@example.test", role: "owner" }] }, + }); + expect(event.isError).toBe(true); + expect((event.content as Array<{ text: string }>)[0]!.text).toMatch(/^Invalid arguments for create_event: unknown argument "role" in attendees\[0\]\. Accepted in attendees\[0\]: id, email, .+\. Nothing was sent to Google\.$/); + const doc = await callGoogleWorkspaceRestTool({ + service: "docs", name: "update_doc", accessToken: "t", fetch, + arguments: { documentId: "doc1", requests: [{ insertText: { text: "Hi", location: { index: 1 } } }], writeControl: { requiredRevisionId: "rev-1", force: true } }, + }); + expect((doc.content as Array<{ text: string }>)[0]!.text).toMatch(/unknown argument "force" in writeControl\. Accepted in writeControl: requiredRevisionId/); + expect(calls).toHaveLength(0); + }); + + it("passes Google's request objects through unchanged", async () => { + const { fetch, calls } = fakeGoogle(() => json({ documentId: "doc1", replies: [{}], writeControl: { requiredRevisionId: "rev-2" } })); + const request = { insertText: { text: "Hi", location: { index: 1, tabId: "t.0" } } }; + const result = await callGoogleWorkspaceRestTool({ + service: "docs", name: "update_doc", accessToken: "t", fetch, + arguments: { documentId: "doc1", requests: [request], writeControl: { requiredRevisionId: "rev-1" } }, + }); + expect(result.isError).toBeFalsy(); + expect(calls).toHaveLength(1); + expect((calls[0]!.body as { requests: unknown[] }).requests).toEqual([request]); + }); +}); diff --git a/server/src/google-workspace-rest-tools/tool.ts b/server/src/google-workspace-rest-tools/tool.ts index 6284f823bbe..96d8bd64e6e 100644 --- a/server/src/google-workspace-rest-tools/tool.ts +++ b/server/src/google-workspace-rest-tools/tool.ts @@ -20,6 +20,7 @@ export interface RestToolSpec { export interface RestTool { definition: Tool; + args: z.ZodType; call(rawArgs: unknown, http: GoogleHttp, limits?: ToolLimits): Promise; } @@ -28,9 +29,19 @@ export function defineTool(spec: RestToolSpec): RestTool { if (readOnly !== (spec.whenTooLarge !== undefined)) { throw new Error(`${spec.definition.name}: a read tool must say how to ask for less, and a write tool must not`); } + const unmodeled = unmodeledSchemaParts(spec.definition.inputSchema, "inputSchema"); + if (unmodeled.length > 0) { + throw new Error(`${spec.definition.name}: the unknown-argument check cannot follow ${unmodeled.join(", ")}`); + } + const definition: Tool = { ...spec.definition, inputSchema: closedObjectSchema(spec.definition.inputSchema) as Tool["inputSchema"] }; return { - definition: spec.definition, + definition, + args: spec.args, async call(rawArgs, http, limits = FALLBACK_TOOL_LIMITS) { + const unknown = unknownArgumentProblems(rawArgs ?? {}, definition.inputSchema, ""); + if (unknown.length > 0) { + return { isError: true, content: [{ type: "text", text: `Invalid arguments for ${spec.definition.name}: ${unknown.join(" ")} Nothing was sent to Google.` }] }; + } const parsed = spec.args.safeParse(rawArgs ?? {}); if (!parsed.success) { const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "arguments"}: ${issue.message}`).join("; "); @@ -49,6 +60,65 @@ export function defineTool(spec: RestToolSpec): RestTool { }; } +type JsonSchemaNode = Record; + +const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); + +function isClosedObjectSchema(schema: JsonSchemaNode): schema is JsonSchemaNode & { properties: Record } { + return isRecord(schema.properties) && (schema.additionalProperties === undefined || schema.additionalProperties === false); +} + +const UNMODELED_KEYWORDS = ["anyOf", "oneOf", "allOf", "not", "$ref", "prefixItems", "patternProperties", "if", "dependentSchemas", "unevaluatedProperties"]; + +export function unmodeledSchemaParts(schema: unknown, path: string): string[] { + if (!isRecord(schema)) return []; + const found = UNMODELED_KEYWORDS.filter((keyword) => keyword in schema).map((keyword) => `${path}.${keyword}`); + if (Array.isArray(schema.items)) found.push(`${path}.items (tuple)`); + if (isRecord(schema.properties) && schema.additionalProperties !== undefined && schema.additionalProperties !== false) { + found.push(`${path}.additionalProperties (open beside properties)`); + } + const properties = isRecord(schema.properties) ? Object.entries(schema.properties) : []; + return [ + ...found, + ...properties.flatMap(([name, item]) => unmodeledSchemaParts(item, `${path}.properties.${name}`)), + ...unmodeledSchemaParts(schema.items, `${path}.items`), + ]; +} + +export function closedObjectSchema(schema: unknown): unknown { + if (Array.isArray(schema)) return schema.map(closedObjectSchema); + if (!isRecord(schema)) return schema; + const copy: JsonSchemaNode = {}; + for (const [key, value] of Object.entries(schema)) { + copy[key] = key === "properties" && isRecord(value) + ? Object.fromEntries(Object.entries(value).map(([name, item]) => [name, closedObjectSchema(item)])) + : key === "items" ? closedObjectSchema(value) : value; + } + if (isClosedObjectSchema(copy)) copy.additionalProperties = false; + return copy; +} + +function unknownArgumentProblems(value: unknown, schema: unknown, path: string): string[] { + if (!isRecord(schema)) return []; + if (Array.isArray(value)) { + return isRecord(schema.items) ? value.flatMap((item, index) => unknownArgumentProblems(item, schema.items, `${path}[${index}]`)) : []; + } + if (!isRecord(value) || !isClosedObjectSchema(schema)) return []; + const accepted = Object.keys(schema.properties); + const unknown = Object.keys(value).filter((key) => value[key] !== undefined && !Object.hasOwn(schema.properties, key)); + const problems: string[] = []; + if (unknown.length > 0) { + const names = unknown.map((key) => JSON.stringify(key)).join(", "); + const where = path ? ` in ${path}` : ""; + const list = accepted.length > 0 ? accepted.join(", ") : "none"; + problems.push(`unknown ${unknown.length === 1 ? "argument" : "arguments"} ${names}${where}. ${path ? `Accepted in ${path}` : "Accepted arguments"}: ${list}.`); + } + for (const key of accepted) { + if (value[key] !== undefined) problems.push(...unknownArgumentProblems(value[key], schema.properties[key], path ? `${path}.${key}` : key)); + } + return problems; +} + export function structuredResult(value: Record): CallToolResult { return { content: [{ type: "text", text: JSON.stringify(value) }], structuredContent: value }; }