@a1-x-tech/mcp-google-sheets 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ import { z } from "zod";
2
+ import { DESTRUCTIVE, fail, ok } from "./util.js";
3
+ export function registerRawTool(server, client) {
4
+ server.registerTool("raw_request", {
5
+ title: "Raw Google Sheets API call",
6
+ // Full API surface incl. batchUpdate deletions — annotate for the worst
7
+ // case a call can do, not the average.
8
+ annotations: DESTRUCTIVE,
9
+ description: 'Escape hatch to call any Google Sheets API v4 path directly, for requests the typed tools don\'t cover — e.g. a batchUpdate with mergeCells, named ranges, banding, basic filters, slicers, sortRange, findReplace, gradient conditional-format rules, developer metadata, or several requests in one atomic call: path "v4/spreadsheets/<spreadsheetId>:batchUpdate", method POST, body {"requests":[...]}. The path may carry a query string. The Bearer token is added automatically; the method defaults to GET (values updates use PUT). Sheets API paths only — Drive paths are not reachable here.',
10
+ inputSchema: {
11
+ path: z
12
+ .string()
13
+ .min(1)
14
+ .describe('API path relative to https://sheets.googleapis.com, e.g. "v4/spreadsheets/<id>:batchUpdate".'),
15
+ method: z
16
+ .enum(["GET", "POST", "PUT"])
17
+ .optional()
18
+ .describe("HTTP method (the Sheets API uses only these three). Defaults to GET."),
19
+ body: z.record(z.any()).optional().describe("JSON request body (POST/PUT only)."),
20
+ },
21
+ }, async ({ path, method, body }) => {
22
+ try {
23
+ const m = (method ?? "GET");
24
+ return ok(await client.request(m, path, body));
25
+ }
26
+ catch (e) {
27
+ return fail(e);
28
+ }
29
+ });
30
+ }
@@ -0,0 +1,175 @@
1
+ import { z } from "zod";
2
+ import { DESTRUCTIVE, fail, gridRangeSchema, hexColorSchema, ok, sheetIdSchema, spreadsheetIdSchema, toGridRange, UPDATE, } from "./util.js";
3
+ /**
4
+ * A Sheets API BooleanCondition type, passed through to the wire. Kept as a
5
+ * string (not an enum) because the vocabulary is long and still growing; the
6
+ * description lists the common values so the model can pick without guessing.
7
+ */
8
+ const conditionTypeSchema = () => z
9
+ .string()
10
+ .min(1)
11
+ .describe("Sheets API condition type, e.g. ONE_OF_LIST, ONE_OF_RANGE, NUMBER_GREATER, NUMBER_LESS, NUMBER_BETWEEN, NUMBER_EQ, TEXT_CONTAINS, TEXT_STARTS_WITH, TEXT_EQ, TEXT_IS_EMAIL, DATE_AFTER, DATE_BEFORE, DATE_BETWEEN, DATE_IS_VALID, BLANK, NOT_BLANK, BOOLEAN, CUSTOM_FORMULA.");
12
+ const conditionValuesSchema = () => z
13
+ .array(z.string())
14
+ .optional()
15
+ .describe('Condition arguments: list items for ONE_OF_LIST (["Yes","No"]), one number for NUMBER_GREATER (["100"]), two for NUMBER_BETWEEN, "=A1>B1"-style formula for CUSTOM_FORMULA and ONE_OF_RANGE ("=Sheet1!A1:A10"), relative dates as values. Omit for BLANK / NOT_BLANK / DATE_IS_VALID.');
16
+ export function registerRuleTools(server, client) {
17
+ server.registerTool("set_data_validation", {
18
+ title: "Set data validation",
19
+ annotations: UPDATE,
20
+ description: "Sets — or clears — a data-validation rule on a grid range. With condition_type set, every cell in the range gets the rule: ONE_OF_LIST with condition_values plus show_custom_ui=true is the classic in-cell dropdown; ONE_OF_RANGE takes a \"=Sheet1!A1:A10\" formula; NUMBER_/TEXT_/DATE_ conditions restrict input; CUSTOM_FORMULA takes a formula evaluated per cell. strict=true rejects invalid input outright, strict=false only shows a warning; input_message is the help text shown on the cell. OMIT condition_type (and the other rule fields) to REMOVE validation from the range. Overwrites any previous rule on the range — one rule per cell.",
21
+ inputSchema: {
22
+ spreadsheet_id: spreadsheetIdSchema(),
23
+ range: gridRangeSchema(),
24
+ condition_type: conditionTypeSchema().optional(),
25
+ condition_values: conditionValuesSchema(),
26
+ input_message: z.string().optional().describe("Help text shown when the cell is selected."),
27
+ strict: z.boolean().optional().describe("true rejects invalid input; false (default) shows a warning."),
28
+ show_custom_ui: z
29
+ .boolean()
30
+ .optional()
31
+ .describe("Show a dropdown UI for ONE_OF_LIST / ONE_OF_RANGE conditions."),
32
+ },
33
+ }, async ({ spreadsheet_id, range, condition_type, condition_values, input_message, strict, show_custom_ui }) => {
34
+ try {
35
+ return ok(await client.setDataValidation({
36
+ spreadsheetId: spreadsheet_id,
37
+ range: toGridRange(range),
38
+ conditionType: condition_type,
39
+ conditionValues: condition_values,
40
+ inputMessage: input_message,
41
+ strict,
42
+ showCustomUi: show_custom_ui,
43
+ }));
44
+ }
45
+ catch (e) {
46
+ return fail(e);
47
+ }
48
+ });
49
+ server.registerTool("manage_protected_ranges", {
50
+ title: "Manage protected ranges",
51
+ // add/update are guard rails, but delete removes a protection outright —
52
+ // annotate for the worst case.
53
+ annotations: DESTRUCTIVE,
54
+ description: "Manages protections that stop other editors from changing cells. action=add protects a grid range (or a named range via named_range_id; a range with only sheet_id protects the whole sheet): warning_only=true merely warns before edits, otherwise only the listed editor_users/editor_groups (emails) plus the owner may edit — note the calling user is NOT added automatically. Returns the new protectedRangeId in the replies. action=update changes description/warning_only/editors of an existing protection (protected_range_id required; provided fields replace the old values). action=delete removes the protection — the cells and data stay, but anyone with edit access can change them again. Find existing protectedRangeIds via get_spreadsheet.",
55
+ inputSchema: {
56
+ spreadsheet_id: spreadsheetIdSchema(),
57
+ action: z.enum(["add", "update", "delete"]).describe("What to do with the protections."),
58
+ range: gridRangeSchema().optional().describe("add: the cells to protect."),
59
+ named_range_id: z.string().optional().describe("add: protect a named range instead of a grid range."),
60
+ description: z.string().optional().describe("Label shown in the Sheets UI protections list."),
61
+ warning_only: z
62
+ .boolean()
63
+ .optional()
64
+ .describe("true = anyone can still edit after a warning; false = only the listed editors."),
65
+ editor_users: z
66
+ .array(z.string().email())
67
+ .optional()
68
+ .describe("Emails of users allowed to edit the protected cells."),
69
+ editor_groups: z.array(z.string().email()).optional().describe("Emails of Google Groups allowed to edit."),
70
+ protected_range_id: z
71
+ .number()
72
+ .int()
73
+ .optional()
74
+ .describe("update/delete: the protection's id from get_spreadsheet or the add reply."),
75
+ },
76
+ }, async (args) => {
77
+ try {
78
+ switch (args.action) {
79
+ case "add":
80
+ return ok(await client.addProtectedRange({
81
+ spreadsheetId: args.spreadsheet_id,
82
+ range: args.range ? toGridRange(args.range) : undefined,
83
+ namedRangeId: args.named_range_id,
84
+ description: args.description,
85
+ warningOnly: args.warning_only,
86
+ editorUsers: args.editor_users,
87
+ editorGroups: args.editor_groups,
88
+ }));
89
+ case "update":
90
+ if (args.protected_range_id === undefined) {
91
+ return fail(new Error('action "update" requires protected_range_id.'));
92
+ }
93
+ return ok(await client.updateProtectedRange({
94
+ spreadsheetId: args.spreadsheet_id,
95
+ protectedRangeId: args.protected_range_id,
96
+ description: args.description,
97
+ warningOnly: args.warning_only,
98
+ editorUsers: args.editor_users,
99
+ editorGroups: args.editor_groups,
100
+ }));
101
+ case "delete":
102
+ if (args.protected_range_id === undefined) {
103
+ return fail(new Error('action "delete" requires protected_range_id.'));
104
+ }
105
+ return ok(await client.deleteProtectedRange(args.spreadsheet_id, args.protected_range_id));
106
+ }
107
+ }
108
+ catch (e) {
109
+ return fail(e);
110
+ }
111
+ });
112
+ server.registerTool("manage_conditional_formats", {
113
+ title: "Manage conditional formatting",
114
+ annotations: DESTRUCTIVE,
115
+ description: "Manages conditional-format rules that style cells when a condition holds (boolean rules; gradient color scales need raw_request). Rules are addressed by SHEET + INDEX in that sheet's rule list — get current rules and indexes from get_spreadsheet (sheets[].conditionalFormats), and re-read after every mutation because add/delete shift later indexes. action=add inserts a rule at index (default 0 = highest priority; rules are evaluated in order and the first match wins): needs ranges, condition_type (+condition_values; CUSTOM_FORMULA with a \"=...\" formula is the most flexible) and at least one format field (background_color, text_color, bold, italic). action=update replaces the ENTIRE rule at sheet_id+index with the newly provided one. action=delete removes the rule at sheet_id+index.",
116
+ inputSchema: {
117
+ spreadsheet_id: spreadsheetIdSchema(),
118
+ action: z.enum(["add", "update", "delete"]).describe("What to do with the rules."),
119
+ sheet_id: sheetIdSchema().optional().describe("update/delete: the sheet whose rule list is addressed."),
120
+ index: z
121
+ .number()
122
+ .int()
123
+ .min(0)
124
+ .optional()
125
+ .describe("Rule position in the sheet's list. add: insert position (default 0); update/delete: required."),
126
+ ranges: z.array(gridRangeSchema()).optional().describe("add/update: the cells the rule applies to."),
127
+ condition_type: conditionTypeSchema().optional(),
128
+ condition_values: conditionValuesSchema(),
129
+ background_color: hexColorSchema().optional().describe('Fill for matching cells, "#RRGGBB".'),
130
+ text_color: hexColorSchema().optional().describe('Text color for matching cells, "#RRGGBB".'),
131
+ bold: z.boolean().optional().describe("Bold text for matching cells."),
132
+ italic: z.boolean().optional().describe("Italic text for matching cells."),
133
+ },
134
+ }, async (args) => {
135
+ try {
136
+ switch (args.action) {
137
+ case "add":
138
+ case "update": {
139
+ if (!args.ranges || !args.condition_type) {
140
+ return fail(new Error(`action "${args.action}" requires ranges and condition_type.`));
141
+ }
142
+ const rule = {
143
+ ranges: args.ranges.map(toGridRange),
144
+ conditionType: args.condition_type,
145
+ conditionValues: args.condition_values,
146
+ backgroundColor: args.background_color,
147
+ textColor: args.text_color,
148
+ bold: args.bold,
149
+ italic: args.italic,
150
+ };
151
+ if (args.action === "add") {
152
+ return ok(await client.addConditionalFormat({ spreadsheetId: args.spreadsheet_id, index: args.index, ...rule }));
153
+ }
154
+ if (args.sheet_id === undefined || args.index === undefined) {
155
+ return fail(new Error('action "update" requires sheet_id and index.'));
156
+ }
157
+ return ok(await client.updateConditionalFormat({
158
+ spreadsheetId: args.spreadsheet_id,
159
+ sheetId: args.sheet_id,
160
+ index: args.index,
161
+ ...rule,
162
+ }));
163
+ }
164
+ case "delete":
165
+ if (args.sheet_id === undefined || args.index === undefined) {
166
+ return fail(new Error('action "delete" requires sheet_id and index.'));
167
+ }
168
+ return ok(await client.deleteConditionalFormat(args.spreadsheet_id, args.sheet_id, args.index));
169
+ }
170
+ }
171
+ catch (e) {
172
+ return fail(e);
173
+ }
174
+ });
175
+ }
@@ -0,0 +1,86 @@
1
+ import { z } from "zod";
2
+ import { DESTRUCTIVE, fail, ok, spreadsheetIdSchema } from "./util.js";
3
+ export function registerSharingTools(server, client) {
4
+ server.registerTool("manage_permissions", {
5
+ title: "Manage spreadsheet access",
6
+ // list is a read, but grant/revoke change who can reach the data and
7
+ // revoke removes access outright — annotate for the worst case.
8
+ annotations: DESTRUCTIVE,
9
+ description: "Shares the spreadsheet (Drive permissions on the file — the OAuth token needs a Drive scope; the spreadsheets scope alone gets 403 here while every Sheets tool still works). action=list shows who has access: id, type, role, emailAddress/domain per permission; one page per call (shared-drive files cap a page at 100) — when the reply carries nextPageToken, pass it back as page_token for the rest. action=grant gives role reader/commenter/writer to type user/group (email_address required), domain (domain required, e.g. \"example.com\") or anyone (makes the link public — use deliberately); send_notification_email (default true for users) and email_message control the notification, allow_file_discovery lets domain/anyone grants surface in search. action=update changes an existing permission's role (permission_id + role). action=revoke removes a permission (permission_id) — the person loses access immediately. Ownership transfer is not supported by this server. Protecting individual ranges from co-editors is manage_protected_ranges, not this tool.",
10
+ inputSchema: {
11
+ spreadsheet_id: spreadsheetIdSchema(),
12
+ action: z.enum(["list", "grant", "update", "revoke"]).describe("What to do with the file's permissions."),
13
+ page_size: z
14
+ .number()
15
+ .int()
16
+ .min(1)
17
+ .max(100)
18
+ .optional()
19
+ .describe("list: max permissions per page (1..100; shared-drive files default to 100)."),
20
+ page_token: z.string().optional().describe("list: nextPageToken from the previous page."),
21
+ role: z
22
+ .enum(["reader", "commenter", "writer"])
23
+ .optional()
24
+ .describe("grant/update: the access level to give."),
25
+ type: z
26
+ .enum(["user", "group", "domain", "anyone"])
27
+ .optional()
28
+ .describe("grant: who the grantee is."),
29
+ email_address: z.string().email().optional().describe("grant (user/group): the grantee's email."),
30
+ domain: z.string().optional().describe('grant (domain): the domain, e.g. "example.com".'),
31
+ allow_file_discovery: z
32
+ .boolean()
33
+ .optional()
34
+ .describe("grant (domain/anyone): let the file appear in search results (default false)."),
35
+ send_notification_email: z
36
+ .boolean()
37
+ .optional()
38
+ .describe("grant: send the standard sharing notification (default true for users/groups)."),
39
+ email_message: z.string().optional().describe("grant: custom text for the notification email."),
40
+ permission_id: z
41
+ .string()
42
+ .optional()
43
+ .describe("update/revoke: the permission's id from action=list (or the grant reply)."),
44
+ },
45
+ }, async (args) => {
46
+ try {
47
+ switch (args.action) {
48
+ case "list":
49
+ return ok(await client.listPermissions({
50
+ spreadsheetId: args.spreadsheet_id,
51
+ pageSize: args.page_size,
52
+ pageToken: args.page_token,
53
+ }));
54
+ case "grant":
55
+ if (!args.role || !args.type)
56
+ return fail(new Error('action "grant" requires role and type.'));
57
+ return ok(await client.grantPermission({
58
+ spreadsheetId: args.spreadsheet_id,
59
+ role: args.role,
60
+ type: args.type,
61
+ emailAddress: args.email_address,
62
+ domain: args.domain,
63
+ allowFileDiscovery: args.allow_file_discovery,
64
+ sendNotificationEmail: args.send_notification_email,
65
+ emailMessage: args.email_message,
66
+ }));
67
+ case "update":
68
+ if (!args.permission_id || !args.role) {
69
+ return fail(new Error('action "update" requires permission_id and role.'));
70
+ }
71
+ return ok(await client.updatePermission({
72
+ spreadsheetId: args.spreadsheet_id,
73
+ permissionId: args.permission_id,
74
+ role: args.role,
75
+ }));
76
+ case "revoke":
77
+ if (!args.permission_id)
78
+ return fail(new Error('action "revoke" requires permission_id.'));
79
+ return ok(await client.revokePermission(args.spreadsheet_id, args.permission_id));
80
+ }
81
+ }
82
+ catch (e) {
83
+ return fail(e);
84
+ }
85
+ });
86
+ }
@@ -0,0 +1,79 @@
1
+ import { z } from "zod";
2
+ import { DESTRUCTIVE, fail, ok, sheetIdSchema, spreadsheetIdSchema } from "./util.js";
3
+ export function registerSheetTools(server, client) {
4
+ server.registerTool("manage_sheets", {
5
+ title: "Manage sheets",
6
+ // One tool covers add/duplicate/rename/delete/copy_to; delete removes a
7
+ // whole tab with its data, so the tool carries the destructive hints.
8
+ annotations: DESTRUCTIVE,
9
+ description: "Manages the sheets (tabs) of a spreadsheet. action=add creates a tab (title required; optional index position and row_count/column_count — default 1000×26). action=duplicate copies a tab within the same spreadsheet (sheet_id; optional title for the copy and index). action=rename changes a tab's title (sheet_id + title; the numeric sheetId never changes, so other tools keep working). action=delete removes the tab AND all its data — irreversible through the API, and deleting the last remaining sheet fails. action=copy_to copies a tab into ANOTHER spreadsheet (sheet_id + destination_spreadsheet_id; the copy arrives named \"Copy of ...\" — rename it there). Get sheet_id values from get_spreadsheet; every action except add returns batchUpdate replies with the affected sheet's properties.",
10
+ inputSchema: {
11
+ spreadsheet_id: spreadsheetIdSchema(),
12
+ action: z.enum(["add", "duplicate", "rename", "delete", "copy_to"]).describe("What to do with the sheets."),
13
+ sheet_id: sheetIdSchema().optional().describe("duplicate/rename/delete/copy_to: the target sheet."),
14
+ title: z
15
+ .string()
16
+ .min(1)
17
+ .optional()
18
+ .describe("add: the new tab's title (required). rename: the new title (required). duplicate: the copy's title."),
19
+ index: z
20
+ .number()
21
+ .int()
22
+ .min(0)
23
+ .optional()
24
+ .describe("add/duplicate: 0-based tab position for the new sheet (omit = after the existing tabs)."),
25
+ row_count: z.number().int().min(1).optional().describe("add: grid rows for the new sheet (default 1000)."),
26
+ column_count: z.number().int().min(1).optional().describe("add: grid columns for the new sheet (default 26)."),
27
+ destination_spreadsheet_id: z
28
+ .string()
29
+ .min(1)
30
+ .optional()
31
+ .describe("copy_to: the spreadsheet to copy the sheet into."),
32
+ },
33
+ }, async ({ spreadsheet_id, action, sheet_id, title, index, row_count, column_count, destination_spreadsheet_id }) => {
34
+ try {
35
+ switch (action) {
36
+ case "add":
37
+ if (!title)
38
+ return fail(new Error('action "add" requires title.'));
39
+ return ok(await client.addSheet({
40
+ spreadsheetId: spreadsheet_id,
41
+ title,
42
+ index,
43
+ rowCount: row_count,
44
+ columnCount: column_count,
45
+ }));
46
+ case "duplicate":
47
+ if (sheet_id === undefined)
48
+ return fail(new Error('action "duplicate" requires sheet_id.'));
49
+ return ok(await client.duplicateSheet({
50
+ spreadsheetId: spreadsheet_id,
51
+ sheetId: sheet_id,
52
+ newTitle: title,
53
+ insertIndex: index,
54
+ }));
55
+ case "rename":
56
+ if (sheet_id === undefined || !title) {
57
+ return fail(new Error('action "rename" requires sheet_id and title.'));
58
+ }
59
+ return ok(await client.renameSheet({ spreadsheetId: spreadsheet_id, sheetId: sheet_id, title }));
60
+ case "delete":
61
+ if (sheet_id === undefined)
62
+ return fail(new Error('action "delete" requires sheet_id.'));
63
+ return ok(await client.deleteSheet(spreadsheet_id, sheet_id));
64
+ case "copy_to":
65
+ if (sheet_id === undefined || !destination_spreadsheet_id) {
66
+ return fail(new Error('action "copy_to" requires sheet_id and destination_spreadsheet_id.'));
67
+ }
68
+ return ok(await client.copySheetTo({
69
+ spreadsheetId: spreadsheet_id,
70
+ sheetId: sheet_id,
71
+ destinationSpreadsheetId: destination_spreadsheet_id,
72
+ }));
73
+ }
74
+ }
75
+ catch (e) {
76
+ return fail(e);
77
+ }
78
+ });
79
+ }
@@ -0,0 +1,92 @@
1
+ import { z } from "zod";
2
+ import { a1RangeSchema, fail, ok, READ_ONLY, spreadsheetIdSchema, WRITE } from "./util.js";
3
+ export function registerSpreadsheetTools(server, client) {
4
+ server.registerTool("create_spreadsheet", {
5
+ title: "Create a spreadsheet",
6
+ annotations: WRITE,
7
+ description: "Creates a new Google Sheets spreadsheet and returns it: spreadsheetId, spreadsheetUrl, properties (title, locale, timeZone) and sheets[] with each sheet's numeric sheetId. sheet_titles creates one tab per title in order (omitted = a single default \"Sheet1\"). The file lands in the authorized user's My Drive root — moving it into a folder needs the Drive API, which this server does not cover. Save the returned spreadsheetId: the Sheets API has no list endpoint of its own (search_spreadsheets exists, but it needs a Drive scope on the token).",
8
+ inputSchema: {
9
+ title: z.string().min(1).describe("The spreadsheet title (also the Drive file name)."),
10
+ sheet_titles: z
11
+ .array(z.string().min(1))
12
+ .optional()
13
+ .describe('Tab titles to create, in order, e.g. ["Data","Summary"]. Omitted = one default sheet.'),
14
+ locale: z
15
+ .string()
16
+ .optional()
17
+ .describe('Spreadsheet locale as ISO code, e.g. "en_US" or "ru_RU" (affects number/date parsing).'),
18
+ time_zone: z
19
+ .string()
20
+ .optional()
21
+ .describe('Time zone in CLDR format, e.g. "Europe/Moscow" (affects NOW()/TODAY()).'),
22
+ },
23
+ }, async ({ title, sheet_titles, locale, time_zone }) => {
24
+ try {
25
+ return ok(await client.createSpreadsheet({ title, sheetTitles: sheet_titles, locale, timeZone: time_zone }));
26
+ }
27
+ catch (e) {
28
+ return fail(e);
29
+ }
30
+ });
31
+ server.registerTool("get_spreadsheet", {
32
+ title: "Get spreadsheet metadata",
33
+ annotations: READ_ONLY,
34
+ description: "Returns the spreadsheet's structure: properties (title, locale, timeZone), sheets[] with properties (sheetId, title, index, gridProperties incl. rowCount/columnCount and frozenRowCount/frozenColumnCount), plus each sheet's protectedRanges, conditionalFormats, tables and charts, and the spreadsheet's namedRanges. Call this FIRST whenever a structural tool needs a sheetId, protectedRangeId, tableId, chartId or a conditional-format rule index — titles are not addresses. By default no cell data is returned; include_grid_data=true (optionally limited to ranges) embeds cells but is heavy — prefer read_values for data. fields is a partial-response mask to trim the payload, e.g. \"sheets.properties\".",
35
+ inputSchema: {
36
+ spreadsheet_id: spreadsheetIdSchema(),
37
+ ranges: z
38
+ .array(a1RangeSchema())
39
+ .optional()
40
+ .describe("Limit the returned sheets/grid data to these A1 ranges."),
41
+ include_grid_data: z
42
+ .boolean()
43
+ .optional()
44
+ .describe("Embed cell data (values, formats) in the response. Heavy — prefer read_values."),
45
+ fields: z
46
+ .string()
47
+ .optional()
48
+ .describe('Partial-response field mask, e.g. "sheets.properties" or "namedRanges".'),
49
+ },
50
+ }, async ({ spreadsheet_id, ranges, include_grid_data, fields }) => {
51
+ try {
52
+ return ok(await client.getSpreadsheet({
53
+ spreadsheetId: spreadsheet_id,
54
+ ranges,
55
+ includeGridData: include_grid_data,
56
+ fields,
57
+ }));
58
+ }
59
+ catch (e) {
60
+ return fail(e);
61
+ }
62
+ });
63
+ server.registerTool("search_spreadsheets", {
64
+ title: "Search spreadsheets",
65
+ annotations: READ_ONLY,
66
+ description: "Finds Google Sheets spreadsheets the authorized user can open (own files and shared drives; trashed files are excluded): id, name, createdTime, modifiedTime, owners and webViewLink per file, newest-modified first by default. name_contains filters by name substring; omit it to list everything. Paginate with page_token from nextPageToken. This is the one read that goes through the Drive API internally, so the OAuth token needs a Drive scope (drive, drive.readonly or drive.file for app-created files) — with only the spreadsheets scope it fails with 403 while every other tool still works.",
67
+ inputSchema: {
68
+ name_contains: z
69
+ .string()
70
+ .optional()
71
+ .describe("Case-insensitive name substring to filter by (omit to list all spreadsheets)."),
72
+ page_size: z.number().int().min(1).max(1000).optional().describe("Max files per page (1..1000; default 100)."),
73
+ page_token: z.string().optional().describe("nextPageToken from the previous page."),
74
+ order_by: z
75
+ .string()
76
+ .optional()
77
+ .describe('Drive sort key, e.g. "modifiedTime desc" (default), "name", "createdTime desc", "viewedByMeTime desc".'),
78
+ },
79
+ }, async ({ name_contains, page_size, page_token, order_by }) => {
80
+ try {
81
+ return ok(await client.searchSpreadsheets({
82
+ nameContains: name_contains,
83
+ pageSize: page_size,
84
+ pageToken: page_token,
85
+ orderBy: order_by,
86
+ }));
87
+ }
88
+ catch (e) {
89
+ return fail(e);
90
+ }
91
+ });
92
+ }
@@ -0,0 +1,102 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Schema factories, not shared consts: reusing one zod object across two fields
4
+ * makes zod-to-json-schema dedupe them into a `$ref`, which some tool-schema
5
+ * consumers (OpenAI Apps review) don't dereference and flag as `any`. A fresh
6
+ * object per field keeps each one inlined with its type + pattern.
7
+ */
8
+ export const spreadsheetIdSchema = () => z
9
+ .string()
10
+ .min(1)
11
+ .describe("The spreadsheet id — the long id from the URL (docs.google.com/spreadsheets/d/<spreadsheetId>/edit) or from create_spreadsheet / search_spreadsheets output.");
12
+ /** An A1-notation range — the addressing scheme of the values endpoints. */
13
+ export const a1RangeSchema = () => z
14
+ .string()
15
+ .min(1)
16
+ .describe("A1-notation range, e.g. \"Sheet1!A1:C10\", \"'My sheet'!B2:D\" (quote titles with spaces) or a bare sheet title for the whole sheet.");
17
+ /** The numeric sheetId — the stable address of a tab (titles change, ids never do). */
18
+ export const sheetIdSchema = () => z
19
+ .number()
20
+ .int()
21
+ .min(0)
22
+ .describe("The numeric sheetId (NOT the title) from get_spreadsheet sheets[].properties.sheetId; the first sheet of a new spreadsheet is 0.");
23
+ /**
24
+ * The batchUpdate cell rectangle: 0-based, start inclusive, end exclusive; an
25
+ * omitted edge extends to the sheet's bound. Fresh object per call (factory).
26
+ */
27
+ export const gridRangeSchema = () => z
28
+ .object({
29
+ sheet_id: z.number().int().min(0).describe("The numeric sheetId from get_spreadsheet (not the title)."),
30
+ start_row_index: z.number().int().min(0).optional().describe("First row, 0-based inclusive (omit = from the top)."),
31
+ end_row_index: z.number().int().min(0).optional().describe("End row, exclusive (omit = to the last row)."),
32
+ start_column_index: z.number().int().min(0).optional().describe("First column, 0-based inclusive (A=0)."),
33
+ end_column_index: z.number().int().min(0).optional().describe("End column, exclusive (omit = to the last column)."),
34
+ })
35
+ .describe("Cell rectangle in grid coordinates: rows 1-10 × columns A-B = {start_row_index:0, end_row_index:10, start_column_index:0, end_column_index:2}.");
36
+ /** Maps the snake_case grid-range argument to the client's normalized params. */
37
+ export function toGridRange(range) {
38
+ return {
39
+ sheetId: range.sheet_id,
40
+ startRowIndex: range.start_row_index,
41
+ endRowIndex: range.end_row_index,
42
+ startColumnIndex: range.start_column_index,
43
+ endColumnIndex: range.end_column_index,
44
+ };
45
+ }
46
+ /** A "#RRGGBB" hex color; the client converts it to the API's float RGB. */
47
+ export const hexColorSchema = () => z
48
+ .string()
49
+ .regex(/^#[0-9a-fA-F]{6}$/, 'Must be "#RRGGBB", e.g. "#1A73E8"')
50
+ .describe('Hex color "#RRGGBB", e.g. "#FF0000".');
51
+ /** A 2-D matrix of cell values (outer array = rows by default). */
52
+ export const valuesSchema = () => z
53
+ .array(z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])))
54
+ .min(1)
55
+ .describe("2-D array of cell values, outer array = rows: [[\"Name\",\"Score\"],[\"Ada\",42]]. null leaves the existing cell untouched.");
56
+ /** Wraps a value as a compact-JSON tool result (compact: the consumer is an LLM). */
57
+ export function ok(data) {
58
+ const text = typeof data === "string" ? data : JSON.stringify(data);
59
+ return { content: [{ type: "text", text: text ?? "null" }] };
60
+ }
61
+ export function fail(err) {
62
+ let message = err instanceof Error ? err.message : String(err);
63
+ // Surface the underlying cause (e.g. the network error behind a timeout) — no
64
+ // secrets live in cause, and it makes failures far easier to diagnose.
65
+ if (err instanceof Error && err.cause instanceof Error)
66
+ message += ` (${err.cause.message})`;
67
+ return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
68
+ }
69
+ /**
70
+ * MCP tool annotations — hints the consuming client can use to gate or label a
71
+ * tool. All four hints are set explicitly on every tool: some clients (OpenAI
72
+ * Apps review) require readOnlyHint, destructiveHint and openWorldHint on each.
73
+ *
74
+ * The Sheets API mixes reads and writes, so each tool picks one of four presets:
75
+ * READ_ONLY (pure reads), WRITE (creates new state; replaying duplicates it),
76
+ * UPDATE (overwrites existing fields; replaying the same update converges) and
77
+ * DESTRUCTIVE (removes existing state; replaying hits different targets).
78
+ */
79
+ export const READ_ONLY = {
80
+ readOnlyHint: true,
81
+ destructiveHint: false,
82
+ idempotentHint: true,
83
+ openWorldHint: true,
84
+ };
85
+ export const WRITE = {
86
+ readOnlyHint: false,
87
+ destructiveHint: false,
88
+ idempotentHint: false,
89
+ openWorldHint: true,
90
+ };
91
+ export const UPDATE = {
92
+ readOnlyHint: false,
93
+ destructiveHint: true,
94
+ idempotentHint: true,
95
+ openWorldHint: true,
96
+ };
97
+ export const DESTRUCTIVE = {
98
+ readOnlyHint: false,
99
+ destructiveHint: true,
100
+ idempotentHint: false,
101
+ openWorldHint: true,
102
+ };