@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.
- package/LICENSE +21 -0
- package/README.md +307 -0
- package/README.ru.md +307 -0
- package/dist/client.js +736 -0
- package/dist/config.js +83 -0
- package/dist/index.js +128 -0
- package/dist/telemetry.js +120 -0
- package/dist/tools/format.js +176 -0
- package/dist/tools/objects.js +127 -0
- package/dist/tools/raw.js +30 -0
- package/dist/tools/rules.js +175 -0
- package/dist/tools/sharing.js +86 -0
- package/dist/tools/sheets.js +79 -0
- package/dist/tools/spreadsheets.js +92 -0
- package/dist/tools/util.js +102 -0
- package/dist/tools/values.js +146 -0
- package/dist/types.js +46 -0
- package/package.json +63 -0
- package/test/dist-smoke.test.js +185 -0
package/dist/config.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/** Default Google Sheets API host. */
|
|
2
|
+
export const DEFAULT_BASE = "https://sheets.googleapis.com";
|
|
3
|
+
/**
|
|
4
|
+
* A malformed environment variable. Thrown instead of exiting on the spot so
|
|
5
|
+
* index.ts can catch it, report the drop-off and start degraded instead of
|
|
6
|
+
* dying; `reason` is the machine-readable code that ships with that ping
|
|
7
|
+
* (never a variable's value).
|
|
8
|
+
*/
|
|
9
|
+
export class ConfigError extends Error {
|
|
10
|
+
reason;
|
|
11
|
+
constructor(message, reason) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "ConfigError";
|
|
14
|
+
this.reason = reason;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* What a tool call without credentials reads. The first sentence is the
|
|
19
|
+
* historical startup error, verbatim — the rest exists because credentials come
|
|
20
|
+
* only from the environment, so the fix is an operator action plus a restart,
|
|
21
|
+
* never a retry.
|
|
22
|
+
*/
|
|
23
|
+
export const MISSING_CREDENTIALS_MESSAGE = "Google OAuth credentials are required: set GOOGLE_SHEETS_CLIENT_ID + " +
|
|
24
|
+
"GOOGLE_SHEETS_CLIENT_SECRET + GOOGLE_SHEETS_REFRESH_TOKEN (recommended), or " +
|
|
25
|
+
"GOOGLE_SHEETS_ACCESS_TOKEN with a short-lived access token. " +
|
|
26
|
+
"This is not a network failure and retrying will not help: the operator must set these " +
|
|
27
|
+
"environment variables in the MCP client's server config and restart the server — they are " +
|
|
28
|
+
"read only at startup.";
|
|
29
|
+
/**
|
|
30
|
+
* Raised when a tool call needs credentials and none were configured. The
|
|
31
|
+
* message is the whole point of the class: it is the only text the calling
|
|
32
|
+
* model reads about the missing setup, so it names the fix (which variables,
|
|
33
|
+
* and that a restart is needed) instead of the failure.
|
|
34
|
+
*/
|
|
35
|
+
export class CredentialsError extends Error {
|
|
36
|
+
constructor(message = MISSING_CREDENTIALS_MESSAGE) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "CredentialsError";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** True when the config carries usable credentials (the full refresh triple or a static token). */
|
|
42
|
+
export function hasCredentials(config) {
|
|
43
|
+
return Boolean(config.accessToken || (config.clientId && config.clientSecret && config.refreshToken));
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Builds the client config from environment variables.
|
|
47
|
+
*
|
|
48
|
+
* Missing credentials are NOT an error here: the server starts anyway and the
|
|
49
|
+
* client raises {@link CredentialsError} on the first tool call, so an
|
|
50
|
+
* unconfigured install completes the MCP handshake and carries the fix into
|
|
51
|
+
* the session instead of dying before it with nothing to read. A malformed
|
|
52
|
+
* setup — the refresh triple set only partially — still throws, because
|
|
53
|
+
* guessing what the user meant is worse.
|
|
54
|
+
*
|
|
55
|
+
* GOOGLE_SHEETS_CLIENT_ID OAuth2 client id (refresh flow, recommended)
|
|
56
|
+
* GOOGLE_SHEETS_CLIENT_SECRET OAuth2 client secret (refresh flow)
|
|
57
|
+
* GOOGLE_SHEETS_REFRESH_TOKEN OAuth2 refresh token (refresh flow)
|
|
58
|
+
* GOOGLE_SHEETS_ACCESS_TOKEN static access token (alternative; expires in ~1h)
|
|
59
|
+
* GOOGLE_SHEETS_API_BASE Sheets API root override (default https://sheets.googleapis.com)
|
|
60
|
+
* GOOGLE_SHEETS_TIMEOUT_MS per-request timeout (default 60000)
|
|
61
|
+
* GOOGLE_SHEETS_MAX_RETRIES retries on transient errors (default 3)
|
|
62
|
+
*/
|
|
63
|
+
export function loadConfig() {
|
|
64
|
+
const clientId = process.env.GOOGLE_SHEETS_CLIENT_ID;
|
|
65
|
+
const clientSecret = process.env.GOOGLE_SHEETS_CLIENT_SECRET;
|
|
66
|
+
const refreshToken = process.env.GOOGLE_SHEETS_REFRESH_TOKEN;
|
|
67
|
+
const accessToken = process.env.GOOGLE_SHEETS_ACCESS_TOKEN;
|
|
68
|
+
const oauthProvided = [clientId, clientSecret, refreshToken].filter(Boolean).length;
|
|
69
|
+
if (oauthProvided > 0 && oauthProvided < 3) {
|
|
70
|
+
throw new ConfigError("GOOGLE_SHEETS_CLIENT_ID, GOOGLE_SHEETS_CLIENT_SECRET and GOOGLE_SHEETS_REFRESH_TOKEN must be set together (OAuth2 refresh flow).", "incomplete_oauth_config");
|
|
71
|
+
}
|
|
72
|
+
const timeoutMs = Number(process.env.GOOGLE_SHEETS_TIMEOUT_MS);
|
|
73
|
+
const maxRetries = Number(process.env.GOOGLE_SHEETS_MAX_RETRIES);
|
|
74
|
+
return {
|
|
75
|
+
clientId,
|
|
76
|
+
clientSecret,
|
|
77
|
+
refreshToken,
|
|
78
|
+
accessToken,
|
|
79
|
+
apiBase: process.env.GOOGLE_SHEETS_API_BASE || DEFAULT_BASE,
|
|
80
|
+
timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 60_000,
|
|
81
|
+
maxRetries: Number.isFinite(maxRetries) && maxRetries >= 0 ? maxRetries : 3,
|
|
82
|
+
};
|
|
83
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
import { GoogleSheetsClient } from "./client.js";
|
|
6
|
+
import { ConfigError, DEFAULT_BASE, hasCredentials, loadConfig } from "./config.js";
|
|
7
|
+
import { instrumentToolCalls, Telemetry } from "./telemetry.js";
|
|
8
|
+
import { registerSpreadsheetTools } from "./tools/spreadsheets.js";
|
|
9
|
+
import { registerValueTools } from "./tools/values.js";
|
|
10
|
+
import { registerSheetTools } from "./tools/sheets.js";
|
|
11
|
+
import { registerFormatTools } from "./tools/format.js";
|
|
12
|
+
import { registerRuleTools } from "./tools/rules.js";
|
|
13
|
+
import { registerObjectTools } from "./tools/objects.js";
|
|
14
|
+
import { registerSharingTools } from "./tools/sharing.js";
|
|
15
|
+
import { registerRawTool } from "./tools/raw.js";
|
|
16
|
+
/**
|
|
17
|
+
* Prose handed to the calling model in the `initialize` result — the only place
|
|
18
|
+
* it learns what the tool list cannot say: which Google product this API is,
|
|
19
|
+
* what the API refuses to do, and the behaviours that make a naive loop
|
|
20
|
+
* expensive, lossy or duplicating.
|
|
21
|
+
*/
|
|
22
|
+
const INSTRUCTIONS = "Google Sheets API v4 reads and edits spreadsheets — not Docs, Slides or arbitrary Drive files. " +
|
|
23
|
+
"Drive is used internally only by search_spreadsheets and manage_permissions; those two need a " +
|
|
24
|
+
"Drive scope on the token and 403 without it, while everything else runs on the spreadsheets " +
|
|
25
|
+
"scope alone. Two addressing schemes coexist and never mix: the values tools take A1 notation " +
|
|
26
|
+
"('Sheet name'!A1:C10), structural tools (sheets, formatting, rules, tables, charts) take the " +
|
|
27
|
+
"numeric sheetId plus 0-based half-open row/column indexes — call get_spreadsheet first to map " +
|
|
28
|
+
"titles to sheetIds (titles change, sheetIds never do). Read formulas with " +
|
|
29
|
+
"value_render_option=FORMULA; on write, USER_ENTERED (the default) parses '=...' as live formulas " +
|
|
30
|
+
"and numbers/dates per the spreadsheet locale, RAW stores strings literally. Quotas are " +
|
|
31
|
+
"per-minute (300 read + 300 write per project, 60 each per user) and one batch call counts once — " +
|
|
32
|
+
"prefer read_values with several ranges and batch_write_values over per-cell loops; a spreadsheet " +
|
|
33
|
+
"tops out at 10 million cells. Deleting sheets, rows or cleared values has no undo through the " +
|
|
34
|
+
"API, and writes are never retried after a 5xx or timeout — re-read state before re-sending. " +
|
|
35
|
+
"Conditional-format rules are addressed by per-sheet index and shift on every add/delete — " +
|
|
36
|
+
"re-read get_spreadsheet between rule mutations. Auth that suddenly breaks usually means the " +
|
|
37
|
+
"OAuth consent screen is still in Testing, where refresh tokens die after 7 days.";
|
|
38
|
+
/**
|
|
39
|
+
* Prepended to INSTRUCTIONS when no credentials are configured. The model reads
|
|
40
|
+
* this before it picks a tool, so an unconfigured session opens with the fix
|
|
41
|
+
* rather than with a failed call. There is no in-chat login here: credentials
|
|
42
|
+
* come only from the environment, so the fix is an operator action + restart.
|
|
43
|
+
*/
|
|
44
|
+
const UNCONFIGURED_PREFIX = "ATTENTION: Google Sheets is not connected yet — no credentials are configured, so every " +
|
|
45
|
+
"tool call will fail. The operator must set GOOGLE_SHEETS_CLIENT_ID + " +
|
|
46
|
+
"GOOGLE_SHEETS_CLIENT_SECRET + GOOGLE_SHEETS_REFRESH_TOKEN (recommended), or " +
|
|
47
|
+
"GOOGLE_SHEETS_ACCESS_TOKEN with a short-lived access token, in the MCP client's " +
|
|
48
|
+
"server config and restart this server — the variables are read only at startup. ";
|
|
49
|
+
/** Reads the package version so the server reports its real version to MCP clients. */
|
|
50
|
+
function readVersion() {
|
|
51
|
+
try {
|
|
52
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
53
|
+
return typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return "0.0.0";
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Loads the config without dying on a bad value. A server that exits here never
|
|
61
|
+
* completes the MCP handshake, so the user sees a dead server and no reason.
|
|
62
|
+
* Instead the problem is carried into the session, where the model can read it
|
|
63
|
+
* and relay it: the config degrades to "no credentials" and every tool call
|
|
64
|
+
* fails with the actionable message.
|
|
65
|
+
*/
|
|
66
|
+
function loadConfigOrDegraded(telemetry) {
|
|
67
|
+
try {
|
|
68
|
+
return { config: loadConfig() };
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
if (!(err instanceof ConfigError))
|
|
72
|
+
throw err;
|
|
73
|
+
console.error(`Error: ${err.message}`);
|
|
74
|
+
// Fire-and-forget now that the process survives: the historical
|
|
75
|
+
// `startup_failed` funnel stays comparable, but nothing blocks startup.
|
|
76
|
+
telemetry.send("startup_failed", { reason: err.reason });
|
|
77
|
+
return {
|
|
78
|
+
config: { apiBase: process.env.GOOGLE_SHEETS_API_BASE || DEFAULT_BASE },
|
|
79
|
+
problem: err,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async function main() {
|
|
84
|
+
// Anonymous usage pings (ids/names/versions only, never data or arguments);
|
|
85
|
+
// opt out with ASKADS_TELEMETRY=0. Built before the config so missing
|
|
86
|
+
// credentials can be reported; wired to the server before tools register.
|
|
87
|
+
const telemetry = new Telemetry(readVersion());
|
|
88
|
+
const { config, problem } = loadConfigOrDegraded(telemetry);
|
|
89
|
+
const client = new GoogleSheetsClient(config);
|
|
90
|
+
// Decided once, at startup: credentials come only from the environment, so
|
|
91
|
+
// "restart after setting the variables" is the accurate advice to give.
|
|
92
|
+
const connected = hasCredentials(config);
|
|
93
|
+
const server = new McpServer({
|
|
94
|
+
name: "mcp-google-sheets",
|
|
95
|
+
version: readVersion(),
|
|
96
|
+
},
|
|
97
|
+
// Surfaces in the initialize result, before the client sees a single tool.
|
|
98
|
+
{
|
|
99
|
+
instructions: connected
|
|
100
|
+
? INSTRUCTIONS
|
|
101
|
+
: UNCONFIGURED_PREFIX + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
|
|
102
|
+
});
|
|
103
|
+
instrumentToolCalls(server, telemetry);
|
|
104
|
+
server.server.oninitialized = () => {
|
|
105
|
+
telemetry.setClientInfo(server.server.getClientVersion());
|
|
106
|
+
// Split on purpose: `server_start` keeps meaning "a usable install started",
|
|
107
|
+
// so the unconfigured case gets its own event instead of inflating that number.
|
|
108
|
+
if (connected)
|
|
109
|
+
telemetry.send("server_start");
|
|
110
|
+
else
|
|
111
|
+
telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
|
|
112
|
+
};
|
|
113
|
+
registerSpreadsheetTools(server, client);
|
|
114
|
+
registerValueTools(server, client);
|
|
115
|
+
registerSheetTools(server, client);
|
|
116
|
+
registerFormatTools(server, client);
|
|
117
|
+
registerRuleTools(server, client);
|
|
118
|
+
registerObjectTools(server, client);
|
|
119
|
+
registerSharingTools(server, client);
|
|
120
|
+
registerRawTool(server, client);
|
|
121
|
+
const transport = new StdioServerTransport();
|
|
122
|
+
await server.connect(transport);
|
|
123
|
+
console.error(`mcp-google-sheets running on stdio${connected ? "" : " (no credentials — set the environment variables and restart)"}`);
|
|
124
|
+
}
|
|
125
|
+
main().catch((err) => {
|
|
126
|
+
console.error("Fatal error starting mcp-google-sheets:", err);
|
|
127
|
+
process.exit(1);
|
|
128
|
+
});
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anonymous usage telemetry — fire-and-forget pings to usage.gistrec.cloud.
|
|
3
|
+
*
|
|
4
|
+
* Privacy contract (mirrored by the receiver): only an anonymous random
|
|
5
|
+
* instance id, event/tool names, a fixed-vocabulary failure reason and
|
|
6
|
+
* environment versions ever leave the machine. The OAuth credentials,
|
|
7
|
+
* spreadsheet data, tool arguments, prompts and the names or values of
|
|
8
|
+
* environment variables are never read, serialized or sent. Sends are capped
|
|
9
|
+
* at 2 s and swallow every error — telemetry must never affect the server's
|
|
10
|
+
* operation. Opt out for every server of this line at once: ASKADS_TELEMETRY=0
|
|
11
|
+
* (also accepts false/off/no).
|
|
12
|
+
*/
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
const ENDPOINT = "https://usage.gistrec.cloud/v1/events";
|
|
18
|
+
const APP = "mcp-google-sheets";
|
|
19
|
+
const SEND_TIMEOUT_MS = 2000;
|
|
20
|
+
export function telemetryEnabled(env = process.env) {
|
|
21
|
+
const value = (env.ASKADS_TELEMETRY ?? "").trim().toLowerCase();
|
|
22
|
+
return !["0", "false", "off", "no"].includes(value);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Stable anonymous installation id, persisted under the user's config dir.
|
|
26
|
+
* Any filesystem failure degrades to an ephemeral id: the ping still counts
|
|
27
|
+
* today's activity, just not installation uniqueness across restarts.
|
|
28
|
+
*/
|
|
29
|
+
function loadInstanceId() {
|
|
30
|
+
try {
|
|
31
|
+
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
32
|
+
const dir = join(base, APP);
|
|
33
|
+
const file = join(dir, "instance-id");
|
|
34
|
+
try {
|
|
35
|
+
const existing = readFileSync(file, "utf8").trim();
|
|
36
|
+
if (/^[0-9a-f]{8}-[0-9a-f-]{27}$/.test(existing))
|
|
37
|
+
return existing;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// first run — fall through and mint one
|
|
41
|
+
}
|
|
42
|
+
const id = randomUUID();
|
|
43
|
+
mkdirSync(dir, { recursive: true });
|
|
44
|
+
writeFileSync(file, `${id}\n`);
|
|
45
|
+
return id;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return randomUUID();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export class Telemetry {
|
|
52
|
+
appVersion;
|
|
53
|
+
enabled;
|
|
54
|
+
fetchImpl;
|
|
55
|
+
instanceId;
|
|
56
|
+
clientInfo;
|
|
57
|
+
constructor(appVersion, enabled = telemetryEnabled(), fetchImpl = fetch) {
|
|
58
|
+
this.appVersion = appVersion;
|
|
59
|
+
this.enabled = enabled;
|
|
60
|
+
this.fetchImpl = fetchImpl;
|
|
61
|
+
this.instanceId = enabled ? loadInstanceId() : "";
|
|
62
|
+
}
|
|
63
|
+
/** The MCP initialize handshake tells us which agent host is on the other side. */
|
|
64
|
+
setClientInfo(info) {
|
|
65
|
+
this.clientInfo = info;
|
|
66
|
+
}
|
|
67
|
+
/** Fire-and-forget: the server's own work never waits on a ping. */
|
|
68
|
+
send(event, fields = {}) {
|
|
69
|
+
void this.post(event, fields);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The same ping, awaited. Only for a caller that exits right after — a
|
|
73
|
+
* fire-and-forget request would die in flight with the process. No startup
|
|
74
|
+
* path needs it anymore (a config problem degrades instead of exiting).
|
|
75
|
+
*/
|
|
76
|
+
async sendBlocking(event, fields = {}) {
|
|
77
|
+
await this.post(event, fields);
|
|
78
|
+
}
|
|
79
|
+
async post(event, fields) {
|
|
80
|
+
if (!this.enabled)
|
|
81
|
+
return;
|
|
82
|
+
const body = JSON.stringify({
|
|
83
|
+
app: APP,
|
|
84
|
+
event,
|
|
85
|
+
instance_id: this.instanceId,
|
|
86
|
+
app_version: this.appVersion,
|
|
87
|
+
client_name: this.clientInfo?.name,
|
|
88
|
+
client_version: this.clientInfo?.version,
|
|
89
|
+
tool: fields.tool,
|
|
90
|
+
reason: fields.reason,
|
|
91
|
+
node_version: process.version,
|
|
92
|
+
os: process.platform,
|
|
93
|
+
});
|
|
94
|
+
try {
|
|
95
|
+
await this.fetchImpl(ENDPOINT, {
|
|
96
|
+
method: "POST",
|
|
97
|
+
headers: { "Content-Type": "application/json" },
|
|
98
|
+
body,
|
|
99
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
// network failure, timeout abort or a synchronous throw — all silent
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Count every tool invocation by name. Wraps registerTool once, before the
|
|
109
|
+
* domain modules register their tools, so no per-tool wiring is needed.
|
|
110
|
+
* Only the tool *name* is recorded — arguments never reach telemetry.
|
|
111
|
+
*/
|
|
112
|
+
export function instrumentToolCalls(server, telemetry) {
|
|
113
|
+
const original = server.registerTool.bind(server);
|
|
114
|
+
// registerTool's generic signature does not survive a wrapper; the runtime
|
|
115
|
+
// shape (name, config, callback) is stable per SDK contract.
|
|
116
|
+
server.registerTool = ((name, config, callback) => original(name, config, ((...args) => {
|
|
117
|
+
telemetry.send("tool_call", { tool: name });
|
|
118
|
+
return callback(...args);
|
|
119
|
+
})));
|
|
120
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { DESTRUCTIVE, fail, gridRangeSchema, hexColorSchema, ok, sheetIdSchema, spreadsheetIdSchema, toGridRange, UPDATE, } from "./util.js";
|
|
3
|
+
/** One border side: line style + optional color. Factory — fresh schema per field. */
|
|
4
|
+
const borderSchema = () => z
|
|
5
|
+
.object({
|
|
6
|
+
style: z
|
|
7
|
+
.enum(["SOLID", "SOLID_MEDIUM", "SOLID_THICK", "DOTTED", "DASHED", "DOUBLE", "NONE"])
|
|
8
|
+
.describe("Line style; NONE removes the border on that side."),
|
|
9
|
+
color: hexColorSchema().optional(),
|
|
10
|
+
})
|
|
11
|
+
.describe("Border line: {style, color?}.");
|
|
12
|
+
export function registerFormatTools(server, client) {
|
|
13
|
+
server.registerTool("format_cells", {
|
|
14
|
+
title: "Format cells",
|
|
15
|
+
annotations: UPDATE,
|
|
16
|
+
description: "Applies cell formatting to a range: background_color, text color/bold/italic/strikethrough/underline/font_size/font_family, horizontal/vertical alignment, wrap_strategy, and number format (number_format_type NUMBER/PERCENT/CURRENCY/DATE/TIME/DATE_TIME/SCIENTIFIC/TEXT with an optional number_format_pattern like \"#,##0.00\" or \"dd.mm.yyyy\"). Only the provided properties are touched — the update mask is computed automatically, so existing formatting outside it survives; at least one formatting field is required. The range is a grid rectangle addressed by sheet_id + 0-based indexes (get sheet_id from get_spreadsheet). Colors are \"#RRGGBB\" hex strings.",
|
|
17
|
+
inputSchema: {
|
|
18
|
+
spreadsheet_id: spreadsheetIdSchema(),
|
|
19
|
+
range: gridRangeSchema(),
|
|
20
|
+
background_color: hexColorSchema().optional(),
|
|
21
|
+
text_color: hexColorSchema().optional().describe('Text color "#RRGGBB".'),
|
|
22
|
+
bold: z.boolean().optional().describe("Bold text."),
|
|
23
|
+
italic: z.boolean().optional().describe("Italic text."),
|
|
24
|
+
strikethrough: z.boolean().optional().describe("Strikethrough text."),
|
|
25
|
+
underline: z.boolean().optional().describe("Underlined text."),
|
|
26
|
+
font_size: z.number().int().min(1).max(400).optional().describe("Font size in points."),
|
|
27
|
+
font_family: z.string().optional().describe('Font family, e.g. "Roboto".'),
|
|
28
|
+
horizontal_alignment: z.enum(["LEFT", "CENTER", "RIGHT"]).optional().describe("Horizontal alignment."),
|
|
29
|
+
vertical_alignment: z.enum(["TOP", "MIDDLE", "BOTTOM"]).optional().describe("Vertical alignment."),
|
|
30
|
+
wrap_strategy: z
|
|
31
|
+
.enum(["OVERFLOW_CELL", "CLIP", "WRAP"])
|
|
32
|
+
.optional()
|
|
33
|
+
.describe("How long text behaves: overflow into empty neighbors, clip at the edge, or wrap."),
|
|
34
|
+
number_format_type: z
|
|
35
|
+
.enum(["TEXT", "NUMBER", "PERCENT", "CURRENCY", "DATE", "TIME", "DATE_TIME", "SCIENTIFIC"])
|
|
36
|
+
.optional()
|
|
37
|
+
.describe("Number format category."),
|
|
38
|
+
number_format_pattern: z
|
|
39
|
+
.string()
|
|
40
|
+
.optional()
|
|
41
|
+
.describe('Format pattern, e.g. "#,##0.00", "0.0%", "dd.mm.yyyy" (requires number_format_type).'),
|
|
42
|
+
},
|
|
43
|
+
}, async (args) => {
|
|
44
|
+
try {
|
|
45
|
+
return ok(await client.formatCells({
|
|
46
|
+
spreadsheetId: args.spreadsheet_id,
|
|
47
|
+
range: toGridRange(args.range),
|
|
48
|
+
backgroundColor: args.background_color,
|
|
49
|
+
textColor: args.text_color,
|
|
50
|
+
bold: args.bold,
|
|
51
|
+
italic: args.italic,
|
|
52
|
+
strikethrough: args.strikethrough,
|
|
53
|
+
underline: args.underline,
|
|
54
|
+
fontSize: args.font_size,
|
|
55
|
+
fontFamily: args.font_family,
|
|
56
|
+
horizontalAlignment: args.horizontal_alignment,
|
|
57
|
+
verticalAlignment: args.vertical_alignment,
|
|
58
|
+
wrapStrategy: args.wrap_strategy,
|
|
59
|
+
numberFormatType: args.number_format_type,
|
|
60
|
+
numberFormatPattern: args.number_format_pattern,
|
|
61
|
+
}));
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
return fail(e);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
server.registerTool("set_frozen", {
|
|
68
|
+
title: "Freeze rows and columns",
|
|
69
|
+
annotations: UPDATE,
|
|
70
|
+
description: "Freezes the first N rows and/or columns of a sheet so they stay visible while scrolling (typical: frozen_rows=1 pins the header). 0 unfreezes. At least one of frozen_rows / frozen_columns is required; the other stays as it is. You cannot freeze all rows or all columns of a sheet — at least one unfrozen row/column must remain.",
|
|
71
|
+
inputSchema: {
|
|
72
|
+
spreadsheet_id: spreadsheetIdSchema(),
|
|
73
|
+
sheet_id: sheetIdSchema(),
|
|
74
|
+
frozen_rows: z.number().int().min(0).optional().describe("How many top rows to freeze (0 = unfreeze)."),
|
|
75
|
+
frozen_columns: z.number().int().min(0).optional().describe("How many left columns to freeze (0 = unfreeze)."),
|
|
76
|
+
},
|
|
77
|
+
}, async ({ spreadsheet_id, sheet_id, frozen_rows, frozen_columns }) => {
|
|
78
|
+
try {
|
|
79
|
+
return ok(await client.setFrozen({
|
|
80
|
+
spreadsheetId: spreadsheet_id,
|
|
81
|
+
sheetId: sheet_id,
|
|
82
|
+
frozenRowCount: frozen_rows,
|
|
83
|
+
frozenColumnCount: frozen_columns,
|
|
84
|
+
}));
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
return fail(e);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
server.registerTool("set_borders", {
|
|
91
|
+
title: "Set cell borders",
|
|
92
|
+
annotations: UPDATE,
|
|
93
|
+
description: "Draws borders around and/or inside a grid range. top/bottom/left/right are the range's outer edges; inner_horizontal/inner_vertical are the grid lines between cells inside it. Each side takes {style, color?} — styles SOLID, SOLID_MEDIUM, SOLID_THICK, DOTTED, DASHED, DOUBLE, or NONE to remove that side's border. Only the provided sides change; at least one is required. Colors are \"#RRGGBB\" hex (default black).",
|
|
94
|
+
inputSchema: {
|
|
95
|
+
spreadsheet_id: spreadsheetIdSchema(),
|
|
96
|
+
range: gridRangeSchema(),
|
|
97
|
+
top: borderSchema().optional(),
|
|
98
|
+
bottom: borderSchema().optional(),
|
|
99
|
+
left: borderSchema().optional(),
|
|
100
|
+
right: borderSchema().optional(),
|
|
101
|
+
inner_horizontal: borderSchema().optional().describe("Horizontal lines between rows inside the range."),
|
|
102
|
+
inner_vertical: borderSchema().optional().describe("Vertical lines between columns inside the range."),
|
|
103
|
+
},
|
|
104
|
+
}, async ({ spreadsheet_id, range, top, bottom, left, right, inner_horizontal, inner_vertical }) => {
|
|
105
|
+
try {
|
|
106
|
+
return ok(await client.setBorders({
|
|
107
|
+
spreadsheetId: spreadsheet_id,
|
|
108
|
+
range: toGridRange(range),
|
|
109
|
+
top,
|
|
110
|
+
bottom,
|
|
111
|
+
left,
|
|
112
|
+
right,
|
|
113
|
+
innerHorizontal: inner_horizontal,
|
|
114
|
+
innerVertical: inner_vertical,
|
|
115
|
+
}));
|
|
116
|
+
}
|
|
117
|
+
catch (e) {
|
|
118
|
+
return fail(e);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
server.registerTool("manage_dimensions", {
|
|
122
|
+
title: "Manage rows and columns",
|
|
123
|
+
// insert/resize/hide are benign, but delete removes rows/columns with
|
|
124
|
+
// their data — annotate for the worst case a call can do.
|
|
125
|
+
annotations: DESTRUCTIVE,
|
|
126
|
+
description: "Row/column operations on a run of rows (dimension=ROWS) or columns (dimension=COLUMNS), addressed by sheet_id + 0-based start_index (inclusive) and end_index (exclusive) — e.g. columns A-C = start 0, end 3. action=resize sets an exact pixel_size; auto_resize fits to content; insert adds empty rows/columns at start_index (inherit_from_before=true copies formatting from the row/column before instead of after); delete removes them WITH their data (irreversible; cell references below/right shift); hide/show toggle visibility without touching data; group/ungroup add or remove a collapsible outline group over the run (groups nest — repeat group on a subrange for a deeper level).",
|
|
127
|
+
inputSchema: {
|
|
128
|
+
spreadsheet_id: spreadsheetIdSchema(),
|
|
129
|
+
action: z
|
|
130
|
+
.enum(["resize", "auto_resize", "insert", "delete", "hide", "show", "group", "ungroup"])
|
|
131
|
+
.describe("What to do with the rows/columns."),
|
|
132
|
+
sheet_id: sheetIdSchema(),
|
|
133
|
+
dimension: z.enum(["ROWS", "COLUMNS"]).describe("Whether the run is rows or columns."),
|
|
134
|
+
start_index: z.number().int().min(0).describe("First row/column of the run, 0-based inclusive."),
|
|
135
|
+
end_index: z.number().int().min(1).describe("End of the run, exclusive (rows 1-3 = start 0, end 3)."),
|
|
136
|
+
pixel_size: z.number().int().min(2).optional().describe("resize: the new size in pixels."),
|
|
137
|
+
inherit_from_before: z
|
|
138
|
+
.boolean()
|
|
139
|
+
.optional()
|
|
140
|
+
.describe("insert: new rows/columns copy formatting from before the insertion point (default: after)."),
|
|
141
|
+
},
|
|
142
|
+
}, async ({ spreadsheet_id, action, sheet_id, dimension, start_index, end_index, pixel_size, inherit_from_before }) => {
|
|
143
|
+
const base = {
|
|
144
|
+
spreadsheetId: spreadsheet_id,
|
|
145
|
+
sheetId: sheet_id,
|
|
146
|
+
dimension,
|
|
147
|
+
startIndex: start_index,
|
|
148
|
+
endIndex: end_index,
|
|
149
|
+
};
|
|
150
|
+
try {
|
|
151
|
+
switch (action) {
|
|
152
|
+
case "resize":
|
|
153
|
+
if (pixel_size === undefined)
|
|
154
|
+
return fail(new Error('action "resize" requires pixel_size.'));
|
|
155
|
+
return ok(await client.resizeDimensions({ ...base, pixelSize: pixel_size }));
|
|
156
|
+
case "auto_resize":
|
|
157
|
+
return ok(await client.autoResizeDimensions(base));
|
|
158
|
+
case "insert":
|
|
159
|
+
return ok(await client.insertDimensions({ ...base, inheritFromBefore: inherit_from_before }));
|
|
160
|
+
case "delete":
|
|
161
|
+
return ok(await client.deleteDimensions(base));
|
|
162
|
+
case "hide":
|
|
163
|
+
return ok(await client.setDimensionsHidden({ ...base, hidden: true }));
|
|
164
|
+
case "show":
|
|
165
|
+
return ok(await client.setDimensionsHidden({ ...base, hidden: false }));
|
|
166
|
+
case "group":
|
|
167
|
+
return ok(await client.groupDimensions(base));
|
|
168
|
+
case "ungroup":
|
|
169
|
+
return ok(await client.ungroupDimensions(base));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch (e) {
|
|
173
|
+
return fail(e);
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { DESTRUCTIVE, fail, gridRangeSchema, ok, sheetIdSchema, spreadsheetIdSchema, toGridRange } from "./util.js";
|
|
3
|
+
export function registerObjectTools(server, client) {
|
|
4
|
+
server.registerTool("manage_tables", {
|
|
5
|
+
title: "Manage tables",
|
|
6
|
+
annotations: DESTRUCTIVE,
|
|
7
|
+
description: "Manages structured tables (the \"Convert to table\" feature: named ranges with per-column types, filters and formatting). action=add creates a table over a grid range whose FIRST ROW becomes the header: name (must be unique in the spreadsheet) + range required; column_properties optionally types the columns — a list of raw TableColumnProperties objects, e.g. [{\"columnIndex\":0,\"columnName\":\"Task\",\"columnType\":\"TEXT\"},{\"columnIndex\":1,\"columnName\":\"Done\",\"columnType\":\"BOOLEAN\"}] (columnType TEXT/PERCENT/DROPDOWN/DOUBLE/CURRENCY/DATE/TIME/DATE_TIME/BOOLEAN; DROPDOWN adds dataValidationRule). The reply carries the new table with its tableId. action=update renames and/or re-ranges an existing table (table_id + name and/or range; expanding the range grows the table). action=delete removes the TABLE DEFINITION only — the cell data stays; clear the cells separately if needed. Find tableIds via get_spreadsheet (sheets[].tables).",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
spreadsheet_id: spreadsheetIdSchema(),
|
|
10
|
+
action: z.enum(["add", "update", "delete"]).describe("What to do with the tables."),
|
|
11
|
+
name: z.string().min(1).optional().describe("add (required) / update: the table's unique name."),
|
|
12
|
+
range: gridRangeSchema().optional().describe("add (required) / update: the table's cells incl. the header row."),
|
|
13
|
+
column_properties: z
|
|
14
|
+
.array(z.record(z.any()))
|
|
15
|
+
.optional()
|
|
16
|
+
.describe('add: raw TableColumnProperties list, e.g. [{"columnIndex":0,"columnName":"Task","columnType":"TEXT"}].'),
|
|
17
|
+
table_id: z.string().optional().describe("update/delete: the tableId from get_spreadsheet or the add reply."),
|
|
18
|
+
},
|
|
19
|
+
}, async ({ spreadsheet_id, action, name, range, column_properties, table_id }) => {
|
|
20
|
+
try {
|
|
21
|
+
switch (action) {
|
|
22
|
+
case "add":
|
|
23
|
+
if (!name || !range)
|
|
24
|
+
return fail(new Error('action "add" requires name and range.'));
|
|
25
|
+
return ok(await client.addTable({
|
|
26
|
+
spreadsheetId: spreadsheet_id,
|
|
27
|
+
name,
|
|
28
|
+
range: toGridRange(range),
|
|
29
|
+
columnProperties: column_properties,
|
|
30
|
+
}));
|
|
31
|
+
case "update":
|
|
32
|
+
if (!table_id)
|
|
33
|
+
return fail(new Error('action "update" requires table_id.'));
|
|
34
|
+
return ok(await client.updateTable({
|
|
35
|
+
spreadsheetId: spreadsheet_id,
|
|
36
|
+
tableId: table_id,
|
|
37
|
+
name,
|
|
38
|
+
range: range ? toGridRange(range) : undefined,
|
|
39
|
+
}));
|
|
40
|
+
case "delete":
|
|
41
|
+
if (!table_id)
|
|
42
|
+
return fail(new Error('action "delete" requires table_id.'));
|
|
43
|
+
return ok(await client.deleteTable(spreadsheet_id, table_id));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
catch (e) {
|
|
47
|
+
return fail(e);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
server.registerTool("manage_charts", {
|
|
51
|
+
title: "Manage charts",
|
|
52
|
+
annotations: DESTRUCTIVE,
|
|
53
|
+
description: "Manages embedded charts. action=add builds a chart from chart_type (COLUMN/BAR/LINE/AREA/STEPPED_AREA/SCATTER/PIE), domain_range (x-axis labels / pie labels), series_ranges (one grid range per data series; PIE takes exactly one) and optional title/legend_position/header_count (rows of the ranges treated as headers, default 1) — place it with anchor {sheet_id,row_index,column_index} (the cell under the chart's top-left corner) or new_sheet=true for its own chart sheet; the reply carries the new chartId. Ranges should be single columns (or rows) including the header cell. For chart kinds beyond the basic set (combo, waterfall, histogram, org …) pass a raw Sheets API ChartSpec via spec instead — it overrides the simplified fields. action=update REPLACES the whole spec of an existing chart (chart_id + the same spec-building fields; there is no partial chart update). action=delete removes the chart by chart_id. Find chartIds via get_spreadsheet (sheets[].charts).",
|
|
54
|
+
inputSchema: {
|
|
55
|
+
spreadsheet_id: spreadsheetIdSchema(),
|
|
56
|
+
action: z.enum(["add", "update", "delete"]).describe("What to do with the charts."),
|
|
57
|
+
chart_id: z.number().int().optional().describe("update/delete: the chartId from get_spreadsheet or the add reply."),
|
|
58
|
+
chart_type: z
|
|
59
|
+
.enum(["COLUMN", "BAR", "LINE", "AREA", "STEPPED_AREA", "SCATTER", "PIE"])
|
|
60
|
+
.optional()
|
|
61
|
+
.describe("add/update: the chart kind (required unless spec is given)."),
|
|
62
|
+
title: z.string().optional().describe("Chart title."),
|
|
63
|
+
domain_range: gridRangeSchema().optional().describe("The x-axis (or pie label) values, incl. header cell."),
|
|
64
|
+
series_ranges: z
|
|
65
|
+
.array(gridRangeSchema())
|
|
66
|
+
.optional()
|
|
67
|
+
.describe("One range per data series, incl. header cells (PIE: exactly one)."),
|
|
68
|
+
legend_position: z
|
|
69
|
+
.string()
|
|
70
|
+
.optional()
|
|
71
|
+
.describe("BOTTOM_LEGEND, LEFT_LEGEND, RIGHT_LEGEND, TOP_LEGEND or NO_LEGEND (default: API's choice)."),
|
|
72
|
+
header_count: z
|
|
73
|
+
.number()
|
|
74
|
+
.int()
|
|
75
|
+
.min(0)
|
|
76
|
+
.optional()
|
|
77
|
+
.describe("How many leading rows of the ranges are headers (default 1)."),
|
|
78
|
+
spec: z
|
|
79
|
+
.record(z.any())
|
|
80
|
+
.optional()
|
|
81
|
+
.describe("Raw Sheets API ChartSpec — full control; overrides the simplified fields above."),
|
|
82
|
+
anchor: z
|
|
83
|
+
.object({
|
|
84
|
+
sheet_id: sheetIdSchema(),
|
|
85
|
+
row_index: z.number().int().min(0).describe("0-based row of the anchor cell."),
|
|
86
|
+
column_index: z.number().int().min(0).describe("0-based column of the anchor cell."),
|
|
87
|
+
})
|
|
88
|
+
.optional()
|
|
89
|
+
.describe("add: place the chart over the grid, top-left at this cell."),
|
|
90
|
+
new_sheet: z.boolean().optional().describe("add: put the chart on its own new chart sheet instead."),
|
|
91
|
+
},
|
|
92
|
+
}, async (args) => {
|
|
93
|
+
const specParams = {
|
|
94
|
+
chartType: args.chart_type,
|
|
95
|
+
title: args.title,
|
|
96
|
+
domainRange: args.domain_range ? toGridRange(args.domain_range) : undefined,
|
|
97
|
+
seriesRanges: args.series_ranges?.map(toGridRange),
|
|
98
|
+
legendPosition: args.legend_position,
|
|
99
|
+
headerCount: args.header_count,
|
|
100
|
+
spec: args.spec,
|
|
101
|
+
};
|
|
102
|
+
try {
|
|
103
|
+
switch (args.action) {
|
|
104
|
+
case "add":
|
|
105
|
+
return ok(await client.addChart({
|
|
106
|
+
spreadsheetId: args.spreadsheet_id,
|
|
107
|
+
...specParams,
|
|
108
|
+
anchor: args.anchor
|
|
109
|
+
? { sheetId: args.anchor.sheet_id, rowIndex: args.anchor.row_index, columnIndex: args.anchor.column_index }
|
|
110
|
+
: undefined,
|
|
111
|
+
newSheet: args.new_sheet,
|
|
112
|
+
}));
|
|
113
|
+
case "update":
|
|
114
|
+
if (args.chart_id === undefined)
|
|
115
|
+
return fail(new Error('action "update" requires chart_id.'));
|
|
116
|
+
return ok(await client.updateChart({ spreadsheetId: args.spreadsheet_id, chartId: args.chart_id, ...specParams }));
|
|
117
|
+
case "delete":
|
|
118
|
+
if (args.chart_id === undefined)
|
|
119
|
+
return fail(new Error('action "delete" requires chart_id.'));
|
|
120
|
+
return ok(await client.deleteChart(args.spreadsheet_id, args.chart_id));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
catch (e) {
|
|
124
|
+
return fail(e);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
}
|