@mcp-z/mcp-sheets 2.4.1 → 2.5.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.
Files changed (60) hide show
  1. package/README.md +45 -29
  2. package/dist/cjs/constants.d.cts +2 -0
  3. package/dist/cjs/constants.d.ts +2 -0
  4. package/dist/cjs/constants.js +27 -3
  5. package/dist/cjs/constants.js.map +1 -1
  6. package/dist/cjs/mcp/tools/cells-copy.d.cts +165 -0
  7. package/dist/cjs/mcp/tools/cells-copy.d.ts +165 -0
  8. package/dist/cjs/mcp/tools/cells-copy.js +388 -0
  9. package/dist/cjs/mcp/tools/cells-copy.js.map +1 -0
  10. package/dist/cjs/mcp/tools/csv-get-columns.js +107 -29
  11. package/dist/cjs/mcp/tools/csv-get-columns.js.map +1 -1
  12. package/dist/cjs/mcp/tools/index.d.cts +1 -0
  13. package/dist/cjs/mcp/tools/index.d.ts +1 -0
  14. package/dist/cjs/mcp/tools/index.js +4 -0
  15. package/dist/cjs/mcp/tools/index.js.map +1 -1
  16. package/dist/cjs/schemas/index.d.cts +1 -0
  17. package/dist/cjs/schemas/index.d.ts +1 -0
  18. package/dist/cjs/schemas/index.js +16 -0
  19. package/dist/cjs/schemas/index.js.map +1 -1
  20. package/dist/cjs/setup/config.js +26 -14
  21. package/dist/cjs/setup/config.js.map +1 -1
  22. package/dist/cjs/setup/version-help.js +1 -1
  23. package/dist/cjs/setup/version-help.js.map +1 -1
  24. package/dist/cjs/spreadsheet/data-operations.js +59 -164
  25. package/dist/cjs/spreadsheet/data-operations.js.map +1 -1
  26. package/dist/cjs/spreadsheet/range-operations.d.cts +26 -0
  27. package/dist/cjs/spreadsheet/range-operations.d.ts +26 -0
  28. package/dist/cjs/spreadsheet/range-operations.js +48 -0
  29. package/dist/cjs/spreadsheet/range-operations.js.map +1 -1
  30. package/dist/cjs/spreadsheet/sheet-operations.d.cts +6 -0
  31. package/dist/cjs/spreadsheet/sheet-operations.d.ts +6 -0
  32. package/dist/cjs/spreadsheet/sheet-operations.js +92 -52
  33. package/dist/cjs/spreadsheet/sheet-operations.js.map +1 -1
  34. package/dist/esm/constants.d.ts +2 -0
  35. package/dist/esm/constants.js +14 -0
  36. package/dist/esm/constants.js.map +1 -1
  37. package/dist/esm/mcp/tools/cells-copy.d.ts +165 -0
  38. package/dist/esm/mcp/tools/cells-copy.js +190 -0
  39. package/dist/esm/mcp/tools/cells-copy.js.map +1 -0
  40. package/dist/esm/mcp/tools/csv-get-columns.js +44 -6
  41. package/dist/esm/mcp/tools/csv-get-columns.js.map +1 -1
  42. package/dist/esm/mcp/tools/index.d.ts +1 -0
  43. package/dist/esm/mcp/tools/index.js +1 -0
  44. package/dist/esm/mcp/tools/index.js.map +1 -1
  45. package/dist/esm/schemas/index.d.ts +1 -0
  46. package/dist/esm/schemas/index.js +9 -0
  47. package/dist/esm/schemas/index.js.map +1 -1
  48. package/dist/esm/setup/config.js +26 -14
  49. package/dist/esm/setup/config.js.map +1 -1
  50. package/dist/esm/setup/version-help.js +7 -0
  51. package/dist/esm/setup/version-help.js.map +1 -1
  52. package/dist/esm/spreadsheet/data-operations.js +40 -84
  53. package/dist/esm/spreadsheet/data-operations.js.map +1 -1
  54. package/dist/esm/spreadsheet/range-operations.d.ts +26 -0
  55. package/dist/esm/spreadsheet/range-operations.js +50 -0
  56. package/dist/esm/spreadsheet/range-operations.js.map +1 -1
  57. package/dist/esm/spreadsheet/sheet-operations.d.ts +6 -0
  58. package/dist/esm/spreadsheet/sheet-operations.js +69 -43
  59. package/dist/esm/spreadsheet/sheet-operations.js.map +1 -1
  60. package/package.json +3 -3
@@ -0,0 +1,388 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: Object.getOwnPropertyDescriptor(all, name).get
9
+ });
10
+ }
11
+ _export(exports, {
12
+ get copyCells () {
13
+ return copyCells;
14
+ },
15
+ get default () {
16
+ return createTool;
17
+ }
18
+ });
19
+ var _sheets = require("@googleapis/sheets");
20
+ var _oauthgoogle = require("@mcp-z/oauth-google");
21
+ var _server = require("@mcp-z/server");
22
+ var _zod = require("zod");
23
+ var _constantsts = require("../../constants.js");
24
+ var _googleauthts = require("../../lib/google-auth.js");
25
+ var _indexts = require("../../schemas/index.js");
26
+ var _rangeoperationsts = require("../../spreadsheet/range-operations.js");
27
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
28
+ try {
29
+ var info = gen[key](arg);
30
+ var value = info.value;
31
+ } catch (error) {
32
+ reject(error);
33
+ return;
34
+ }
35
+ if (info.done) resolve(value);
36
+ else Promise.resolve(value).then(_next, _throw);
37
+ }
38
+ function _async_to_generator(fn) {
39
+ return function() {
40
+ var self = this, args = arguments;
41
+ return new Promise(function(resolve, reject) {
42
+ var gen = fn.apply(self, args);
43
+ function _next(value) {
44
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
45
+ }
46
+ function _throw(err) {
47
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
48
+ }
49
+ _next(undefined);
50
+ });
51
+ };
52
+ }
53
+ function _instanceof(left, right) {
54
+ "@swc/helpers - instanceof";
55
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
56
+ return !!right[Symbol.hasInstance](left);
57
+ } else return left instanceof right;
58
+ }
59
+ function _ts_generator(thisArg, body) {
60
+ var f, y, t, _ = {
61
+ label: 0,
62
+ sent: function() {
63
+ if (t[0] & 1) throw t[1];
64
+ return t[1];
65
+ },
66
+ trys: [],
67
+ ops: []
68
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
69
+ return d(g, "next", {
70
+ value: verb(0)
71
+ }), d(g, "throw", {
72
+ value: verb(1)
73
+ }), d(g, "return", {
74
+ value: verb(2)
75
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
76
+ value: function() {
77
+ return this;
78
+ }
79
+ }), g;
80
+ function verb(n) {
81
+ return function(v) {
82
+ return step([
83
+ n,
84
+ v
85
+ ]);
86
+ };
87
+ }
88
+ function step(op) {
89
+ if (f) throw new TypeError("Generator is already executing.");
90
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
91
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
92
+ if (y = 0, t) op = [
93
+ op[0] & 2,
94
+ t.value
95
+ ];
96
+ switch(op[0]){
97
+ case 0:
98
+ case 1:
99
+ t = op;
100
+ break;
101
+ case 4:
102
+ _.label++;
103
+ return {
104
+ value: op[1],
105
+ done: false
106
+ };
107
+ case 5:
108
+ _.label++;
109
+ y = op[1];
110
+ op = [
111
+ 0
112
+ ];
113
+ continue;
114
+ case 7:
115
+ op = _.ops.pop();
116
+ _.trys.pop();
117
+ continue;
118
+ default:
119
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
120
+ _ = 0;
121
+ continue;
122
+ }
123
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
124
+ _.label = op[1];
125
+ break;
126
+ }
127
+ if (op[0] === 6 && _.label < t[1]) {
128
+ _.label = t[1];
129
+ t = op;
130
+ break;
131
+ }
132
+ if (t && _.label < t[2]) {
133
+ _.label = t[2];
134
+ _.ops.push(op);
135
+ break;
136
+ }
137
+ if (t[2]) _.ops.pop();
138
+ _.trys.pop();
139
+ continue;
140
+ }
141
+ op = body.call(thisArg, _);
142
+ } catch (e) {
143
+ op = [
144
+ 6,
145
+ e
146
+ ];
147
+ y = 0;
148
+ } finally{
149
+ f = t = 0;
150
+ }
151
+ if (op[0] & 5) throw op[1];
152
+ return {
153
+ value: op[0] ? op[1] : void 0,
154
+ done: true
155
+ };
156
+ }
157
+ }
158
+ var AuthRequiredBranchSchema = _oauthgoogle.schemas.AuthRequiredBranchSchema;
159
+ var inputSchema = _zod.z.object({
160
+ id: _indexts.SpreadsheetIdSchema,
161
+ sourceGid: _indexts.StrictSheetGidSchema.describe('Source sheet ID (from URL gid={gid})'),
162
+ sourceRange: _indexts.A1NotationSchema.describe('Finite sheet-local A1 range to copy (e.g., "A1:C10"; no sheet prefix, no whole rows/columns)'),
163
+ destinationGid: _indexts.StrictSheetGidSchema.describe('Destination sheet ID in the same spreadsheet; may equal sourceGid'),
164
+ destinationRange: _indexts.A1NotationSchema.describe('Top-left cell (e.g., "E1") or a finite range whose height and width are whole multiples of the (oriented) source; a larger range repeats the source to fill it'),
165
+ pasteType: _zod.z.enum(_constantsts.PASTE_TYPES).default('PASTE_NORMAL').describe('What to paste. PASTE_NORMAL (default) = values, formulas, formats and merges; PASTE_VALUES = values only, no formats/formulas/merges; PASTE_FORMAT = format only, excluding data validation; PASTE_NO_BORDERS = like PASTE_NORMAL without borders; PASTE_FORMULA = formulas only; PASTE_DATA_VALIDATION = data validation only; PASTE_CONDITIONAL_FORMATTING = conditional formatting rules only'),
166
+ pasteOrientation: _zod.z.enum(_constantsts.PASTE_ORIENTATIONS).default('NORMAL').describe('NORMAL, or TRANSPOSE (rows become columns and vice versa)')
167
+ });
168
+ var successBranchSchema = _zod.z.object({
169
+ type: _zod.z.literal('success'),
170
+ id: _indexts.SpreadsheetIdOutput,
171
+ spreadsheetTitle: _zod.z.string().describe('Title of the spreadsheet'),
172
+ spreadsheetUrl: _zod.z.string().describe('URL of the spreadsheet'),
173
+ sourceGid: _indexts.SheetGidOutput,
174
+ sourceSheetTitle: _zod.z.string().describe('Title of the source sheet'),
175
+ sourceRange: _zod.z.string().describe('A1 range that was copied'),
176
+ destinationGid: _indexts.SheetGidOutput,
177
+ destinationSheetTitle: _zod.z.string().describe('Title of the destination sheet'),
178
+ destinationRange: _zod.z.string().describe('Destination range as requested'),
179
+ pastedRange: _zod.z.string().describe('A1 range of cells written in the destination sheet'),
180
+ pasteType: _zod.z.enum(_constantsts.PASTE_TYPES).describe('Paste type applied'),
181
+ pasteOrientation: _zod.z.enum(_constantsts.PASTE_ORIENTATIONS).describe('Orientation applied'),
182
+ sheetUrl: _zod.z.string().describe('URL of the destination sheet')
183
+ });
184
+ var outputSchema = _zod.z.discriminatedUnion('type', [
185
+ successBranchSchema,
186
+ AuthRequiredBranchSchema
187
+ ]);
188
+ var config = {
189
+ description: 'Copy a cell range to another range in the same spreadsheet (same or different tab), like Google Sheets copy and paste-special. Default PASTE_NORMAL copies values, formulas (relative references adjust), formats and merges; pasteType selects one native paste-special mode. Cannot copy between spreadsheets: use sheet-copy-to first. To duplicate a whole tab or workbook use sheet-copy, sheet-copy-to or spreadsheet-copy. Use a1-notation prompt for range syntax.',
190
+ inputSchema: inputSchema,
191
+ outputSchema: _zod.z.object({
192
+ result: outputSchema
193
+ })
194
+ };
195
+ function invalid(message) {
196
+ return new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, message);
197
+ }
198
+ /** Validates a finite sheet-local A1 range, converting any failure to InvalidParams. */ function checkRange(label, notation) {
199
+ try {
200
+ (0, _rangeoperationsts.validateA1Notation)(notation);
201
+ return (0, _rangeoperationsts.parseFiniteCellBlock)(notation);
202
+ } catch (error) {
203
+ throw invalid("Invalid ".concat(label, ": ").concat(_instanceof(error, Error) ? error.message : String(error)));
204
+ }
205
+ }
206
+ function copyCells(_0, _1) {
207
+ return _async_to_generator(function(sheets, param) {
208
+ var id, sourceGid, sourceRange, destinationGid, destinationRange, pasteType, pasteOrientation, _destinationSheet_sheetId, _ref, _spreadsheetData_spreadsheetUrl, _sourceSheet_title, _destinationSheet_title, _spreadsheetData_properties, source, pasted, spreadsheetResponse, spreadsheetData, findSheet, sourceSheet, destinationSheet, gridSize, sourceGrid, destinationGrid, fits, destinationSheetId;
209
+ return _ts_generator(this, function(_state) {
210
+ switch(_state.label){
211
+ case 0:
212
+ id = param.id, sourceGid = param.sourceGid, sourceRange = param.sourceRange, destinationGid = param.destinationGid, destinationRange = param.destinationRange, pasteType = param.pasteType, pasteOrientation = param.pasteOrientation;
213
+ // All range checks happen before any network call
214
+ source = checkRange('sourceRange', sourceRange);
215
+ checkRange('destinationRange', destinationRange);
216
+ try {
217
+ pasted = (0, _rangeoperationsts.calculatePasteRange)(sourceRange, destinationRange, pasteOrientation);
218
+ } catch (error) {
219
+ throw invalid(_instanceof(error, Error) ? error.message : String(error));
220
+ }
221
+ return [
222
+ 4,
223
+ sheets.spreadsheets.get({
224
+ spreadsheetId: id,
225
+ fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties'
226
+ })
227
+ ];
228
+ case 1:
229
+ spreadsheetResponse = _state.sent();
230
+ spreadsheetData = spreadsheetResponse.data;
231
+ findSheet = function findSheet(gid) {
232
+ var _spreadsheetData_sheets_find, _spreadsheetData_sheets;
233
+ return (_spreadsheetData_sheets = spreadsheetData.sheets) === null || _spreadsheetData_sheets === void 0 ? void 0 : (_spreadsheetData_sheets_find = _spreadsheetData_sheets.find(function(s) {
234
+ var _s_properties;
235
+ return String((_s_properties = s.properties) === null || _s_properties === void 0 ? void 0 : _s_properties.sheetId) === gid;
236
+ })) === null || _spreadsheetData_sheets_find === void 0 ? void 0 : _spreadsheetData_sheets_find.properties;
237
+ };
238
+ sourceSheet = findSheet(sourceGid);
239
+ if (!sourceSheet) throw invalid("Sheet not found: ".concat(sourceGid));
240
+ destinationSheet = findSheet(destinationGid);
241
+ if (!destinationSheet) throw invalid("Sheet not found: ".concat(destinationGid));
242
+ gridSize = function gridSize(sheet) {
243
+ var _sheet_title;
244
+ var _sheet_gridProperties, _sheet_gridProperties1;
245
+ var rows = (_sheet_gridProperties = sheet.gridProperties) === null || _sheet_gridProperties === void 0 ? void 0 : _sheet_gridProperties.rowCount;
246
+ var columns = (_sheet_gridProperties1 = sheet.gridProperties) === null || _sheet_gridProperties1 === void 0 ? void 0 : _sheet_gridProperties1.columnCount;
247
+ if (typeof rows !== 'number' || typeof columns !== 'number') throw new Error('Could not read the grid size of sheet "'.concat((_sheet_title = sheet.title) !== null && _sheet_title !== void 0 ? _sheet_title : sheet.sheetId, '"'));
248
+ return {
249
+ rows: rows,
250
+ columns: columns
251
+ };
252
+ };
253
+ sourceGrid = gridSize(sourceSheet);
254
+ destinationGrid = gridSize(destinationSheet);
255
+ fits = function fits(grid, endRow, endColumn) {
256
+ return endRow <= grid.rows && endColumn <= grid.columns;
257
+ };
258
+ if (!fits(sourceGrid, source.endRow, source.endColumn)) {
259
+ throw invalid("Source range ".concat(sourceRange, ' is outside the grid of "').concat(sourceSheet.title, '" (').concat(sourceGrid.rows, " rows x ").concat(sourceGrid.columns, " columns)"));
260
+ }
261
+ if (!fits(destinationGrid, pasted.endRow, pasted.endColumn)) {
262
+ throw invalid("Pasting ".concat(sourceRange, " at ").concat(destinationRange, " would write ").concat((0, _rangeoperationsts.cellBlockToA1)(pasted), ', outside the grid of "').concat(destinationSheet.title, '" (').concat(destinationGrid.rows, " rows x ").concat(destinationGrid.columns, " columns)"));
263
+ }
264
+ // pasteType is always sent explicitly; there is no fallback path
265
+ return [
266
+ 4,
267
+ sheets.spreadsheets.batchUpdate({
268
+ spreadsheetId: id,
269
+ requestBody: {
270
+ requests: [
271
+ {
272
+ copyPaste: {
273
+ source: (0, _rangeoperationsts.rangeReferenceToGridRange)((0, _rangeoperationsts.parseA1Notation)(sourceRange), Number(sourceGid)),
274
+ destination: (0, _rangeoperationsts.rangeReferenceToGridRange)((0, _rangeoperationsts.parseA1Notation)(destinationRange), Number(destinationGid)),
275
+ pasteType: pasteType,
276
+ pasteOrientation: pasteOrientation
277
+ }
278
+ }
279
+ ]
280
+ }
281
+ })
282
+ ];
283
+ case 2:
284
+ _state.sent();
285
+ destinationSheetId = (_destinationSheet_sheetId = destinationSheet.sheetId) !== null && _destinationSheet_sheetId !== void 0 ? _destinationSheet_sheetId : Number(destinationGid);
286
+ return [
287
+ 2,
288
+ {
289
+ type: 'success',
290
+ id: id,
291
+ spreadsheetTitle: (_ref = (_spreadsheetData_properties = spreadsheetData.properties) === null || _spreadsheetData_properties === void 0 ? void 0 : _spreadsheetData_properties.title) !== null && _ref !== void 0 ? _ref : '',
292
+ spreadsheetUrl: (_spreadsheetData_spreadsheetUrl = spreadsheetData.spreadsheetUrl) !== null && _spreadsheetData_spreadsheetUrl !== void 0 ? _spreadsheetData_spreadsheetUrl : '',
293
+ sourceGid: sourceGid,
294
+ sourceSheetTitle: (_sourceSheet_title = sourceSheet.title) !== null && _sourceSheet_title !== void 0 ? _sourceSheet_title : sourceGid,
295
+ sourceRange: sourceRange,
296
+ destinationGid: destinationGid,
297
+ destinationSheetTitle: (_destinationSheet_title = destinationSheet.title) !== null && _destinationSheet_title !== void 0 ? _destinationSheet_title : destinationGid,
298
+ destinationRange: destinationRange,
299
+ pastedRange: (0, _rangeoperationsts.cellBlockToA1)(pasted),
300
+ pasteType: pasteType,
301
+ pasteOrientation: pasteOrientation,
302
+ sheetUrl: "https://docs.google.com/spreadsheets/d/".concat(id, "/edit#gid=").concat(destinationSheetId)
303
+ }
304
+ ];
305
+ }
306
+ });
307
+ }).apply(this, arguments);
308
+ }
309
+ function handler(input, extra) {
310
+ return _async_to_generator(function() {
311
+ var logger, id, sourceGid, destinationGid, pasteType, pasteOrientation, sheets, result, error, message;
312
+ return _ts_generator(this, function(_state) {
313
+ switch(_state.label){
314
+ case 0:
315
+ logger = extra.logger;
316
+ id = input.id, sourceGid = input.sourceGid, destinationGid = input.destinationGid, pasteType = input.pasteType, pasteOrientation = input.pasteOrientation;
317
+ logger.info('sheets.cells.copy called', {
318
+ id: id,
319
+ sourceGid: sourceGid,
320
+ destinationGid: destinationGid,
321
+ pasteType: pasteType,
322
+ pasteOrientation: pasteOrientation
323
+ });
324
+ _state.label = 1;
325
+ case 1:
326
+ _state.trys.push([
327
+ 1,
328
+ 3,
329
+ ,
330
+ 4
331
+ ]);
332
+ sheets = (0, _sheets.sheets)({
333
+ version: 'v4',
334
+ auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
335
+ });
336
+ return [
337
+ 4,
338
+ copyCells(sheets, input)
339
+ ];
340
+ case 2:
341
+ result = _state.sent();
342
+ logger.info('sheets.cells.copy completed successfully', {
343
+ id: id,
344
+ pastedRange: result.type === 'success' ? result.pastedRange : undefined
345
+ });
346
+ return [
347
+ 2,
348
+ {
349
+ content: [
350
+ {
351
+ type: 'text',
352
+ text: JSON.stringify(result)
353
+ }
354
+ ],
355
+ structuredContent: {
356
+ result: result
357
+ }
358
+ }
359
+ ];
360
+ case 3:
361
+ error = _state.sent();
362
+ if (_instanceof(error, _server.ProtocolError)) throw error;
363
+ message = _instanceof(error, Error) ? error.message : String(error);
364
+ logger.error('Copy cells failed', {
365
+ id: id,
366
+ sourceGid: sourceGid,
367
+ destinationGid: destinationGid,
368
+ error: message
369
+ });
370
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error copying cells: ".concat(message), {
371
+ stack: _instanceof(error, Error) ? error.stack : undefined
372
+ });
373
+ case 4:
374
+ return [
375
+ 2
376
+ ];
377
+ }
378
+ });
379
+ })();
380
+ }
381
+ function createTool() {
382
+ return {
383
+ name: 'cells-copy',
384
+ config: config,
385
+ handler: handler
386
+ };
387
+ }
388
+ /* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/cells-copy.ts"],"sourcesContent":["import type { sheets_v4 } from '@googleapis/sheets';\nimport { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { PASTE_ORIENTATIONS, PASTE_TYPES } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetGidOutput, SpreadsheetIdOutput, SpreadsheetIdSchema, StrictSheetGidSchema } from '../../schemas/index.ts';\nimport { calculatePasteRange, cellBlockToA1, parseA1Notation, parseFiniteCellBlock, rangeReferenceToGridRange, validateA1Notation } from '../../spreadsheet/range-operations.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n sourceGid: StrictSheetGidSchema.describe('Source sheet ID (from URL gid={gid})'),\n sourceRange: A1NotationSchema.describe('Finite sheet-local A1 range to copy (e.g., \"A1:C10\"; no sheet prefix, no whole rows/columns)'),\n destinationGid: StrictSheetGidSchema.describe('Destination sheet ID in the same spreadsheet; may equal sourceGid'),\n destinationRange: A1NotationSchema.describe('Top-left cell (e.g., \"E1\") or a finite range whose height and width are whole multiples of the (oriented) source; a larger range repeats the source to fill it'),\n pasteType: z\n .enum(PASTE_TYPES)\n .default('PASTE_NORMAL')\n .describe(\n 'What to paste. PASTE_NORMAL (default) = values, formulas, formats and merges; PASTE_VALUES = values only, no formats/formulas/merges; PASTE_FORMAT = format only, excluding data validation; PASTE_NO_BORDERS = like PASTE_NORMAL without borders; PASTE_FORMULA = formulas only; PASTE_DATA_VALIDATION = data validation only; PASTE_CONDITIONAL_FORMATTING = conditional formatting rules only'\n ),\n pasteOrientation: z.enum(PASTE_ORIENTATIONS).default('NORMAL').describe('NORMAL, or TRANSPOSE (rows become columns and vice versa)'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n spreadsheetTitle: z.string().describe('Title of the spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the spreadsheet'),\n sourceGid: SheetGidOutput,\n sourceSheetTitle: z.string().describe('Title of the source sheet'),\n sourceRange: z.string().describe('A1 range that was copied'),\n destinationGid: SheetGidOutput,\n destinationSheetTitle: z.string().describe('Title of the destination sheet'),\n destinationRange: z.string().describe('Destination range as requested'),\n pastedRange: z.string().describe('A1 range of cells written in the destination sheet'),\n pasteType: z.enum(PASTE_TYPES).describe('Paste type applied'),\n pasteOrientation: z.enum(PASTE_ORIENTATIONS).describe('Orientation applied'),\n sheetUrl: z.string().describe('URL of the destination sheet'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description:\n 'Copy a cell range to another range in the same spreadsheet (same or different tab), like Google Sheets copy and paste-special. Default PASTE_NORMAL copies values, formulas (relative references adjust), formats and merges; pasteType selects one native paste-special mode. Cannot copy between spreadsheets: use sheet-copy-to first. To duplicate a whole tab or workbook use sheet-copy, sheet-copy-to or spreadsheet-copy. Use a1-notation prompt for range syntax.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\ntype SuccessOutput = z.infer<typeof successBranchSchema>;\n\n/** The slice of the Sheets client this tool uses; tests pass a plain fake. */\nexport interface CellsCopySheets {\n spreadsheets: {\n get(params: { spreadsheetId: string; fields: string }): Promise<{ data: sheets_v4.Schema$Spreadsheet }>;\n batchUpdate(params: { spreadsheetId: string; requestBody: sheets_v4.Schema$BatchUpdateSpreadsheetRequest }): Promise<unknown>;\n };\n}\n\nfunction invalid(message: string): ProtocolError {\n return new ProtocolError(ProtocolErrorCode.InvalidParams, message);\n}\n\n/** Validates a finite sheet-local A1 range, converting any failure to InvalidParams. */\nfunction checkRange(label: string, notation: string) {\n try {\n validateA1Notation(notation);\n return parseFiniteCellBlock(notation);\n } catch (error) {\n throw invalid(`Invalid ${label}: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nexport async function copyCells(sheets: CellsCopySheets, { id, sourceGid, sourceRange, destinationGid, destinationRange, pasteType, pasteOrientation }: Input): Promise<SuccessOutput> {\n // All range checks happen before any network call\n const source = checkRange('sourceRange', sourceRange);\n checkRange('destinationRange', destinationRange);\n let pasted: ReturnType<typeof calculatePasteRange>;\n try {\n pasted = calculatePasteRange(sourceRange, destinationRange, pasteOrientation);\n } catch (error) {\n throw invalid(error instanceof Error ? error.message : String(error));\n }\n\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\n });\n const spreadsheetData = spreadsheetResponse.data;\n const findSheet = (gid: string) => spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid)?.properties;\n const sourceSheet = findSheet(sourceGid);\n if (!sourceSheet) throw invalid(`Sheet not found: ${sourceGid}`);\n const destinationSheet = findSheet(destinationGid);\n if (!destinationSheet) throw invalid(`Sheet not found: ${destinationGid}`);\n\n const gridSize = (sheet: sheets_v4.Schema$SheetProperties) => {\n const rows = sheet.gridProperties?.rowCount;\n const columns = sheet.gridProperties?.columnCount;\n if (typeof rows !== 'number' || typeof columns !== 'number') throw new Error(`Could not read the grid size of sheet \"${sheet.title ?? sheet.sheetId}\"`);\n return { rows, columns };\n };\n const sourceGrid = gridSize(sourceSheet);\n const destinationGrid = gridSize(destinationSheet);\n const fits = (grid: { rows: number; columns: number }, endRow: number, endColumn: number) => endRow <= grid.rows && endColumn <= grid.columns;\n if (!fits(sourceGrid, source.endRow, source.endColumn)) {\n throw invalid(`Source range ${sourceRange} is outside the grid of \"${sourceSheet.title}\" (${sourceGrid.rows} rows x ${sourceGrid.columns} columns)`);\n }\n if (!fits(destinationGrid, pasted.endRow, pasted.endColumn)) {\n throw invalid(`Pasting ${sourceRange} at ${destinationRange} would write ${cellBlockToA1(pasted)}, outside the grid of \"${destinationSheet.title}\" (${destinationGrid.rows} rows x ${destinationGrid.columns} columns)`);\n }\n\n // pasteType is always sent explicitly; there is no fallback path\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: [\n {\n copyPaste: {\n source: rangeReferenceToGridRange(parseA1Notation(sourceRange), Number(sourceGid)),\n destination: rangeReferenceToGridRange(parseA1Notation(destinationRange), Number(destinationGid)),\n pasteType,\n pasteOrientation,\n },\n },\n ],\n },\n });\n\n const destinationSheetId = destinationSheet.sheetId ?? Number(destinationGid);\n return {\n type: 'success' as const,\n id,\n spreadsheetTitle: spreadsheetData.properties?.title ?? '',\n spreadsheetUrl: spreadsheetData.spreadsheetUrl ?? '',\n sourceGid,\n sourceSheetTitle: sourceSheet.title ?? sourceGid,\n sourceRange,\n destinationGid,\n destinationSheetTitle: destinationSheet.title ?? destinationGid,\n destinationRange,\n pastedRange: cellBlockToA1(pasted),\n pasteType,\n pasteOrientation,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${destinationSheetId}`,\n };\n}\n\nasync function handler(input: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n const { id, sourceGid, destinationGid, pasteType, pasteOrientation } = input;\n logger.info('sheets.cells.copy called', { id, sourceGid, destinationGid, pasteType, pasteOrientation });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n const result: Output = await copyCells(sheets as unknown as CellsCopySheets, input);\n logger.info('sheets.cells.copy completed successfully', { id, pastedRange: result.type === 'success' ? result.pastedRange : undefined });\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n if (error instanceof ProtocolError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Copy cells failed', { id, sourceGid, destinationGid, error: message });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error copying cells: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'cells-copy',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["copyCells","createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","SpreadsheetIdSchema","sourceGid","StrictSheetGidSchema","describe","sourceRange","A1NotationSchema","destinationGid","destinationRange","pasteType","enum","PASTE_TYPES","default","pasteOrientation","PASTE_ORIENTATIONS","successBranchSchema","type","literal","SpreadsheetIdOutput","spreadsheetTitle","string","spreadsheetUrl","SheetGidOutput","sourceSheetTitle","destinationSheetTitle","pastedRange","sheetUrl","outputSchema","discriminatedUnion","config","description","result","invalid","message","ProtocolError","ProtocolErrorCode","InvalidParams","checkRange","label","notation","validateA1Notation","parseFiniteCellBlock","error","Error","String","sheets","destinationSheet","spreadsheetData","sourceSheet","source","pasted","spreadsheetResponse","findSheet","gridSize","sourceGrid","destinationGrid","fits","destinationSheetId","calculatePasteRange","spreadsheets","get","spreadsheetId","fields","data","gid","find","s","properties","sheetId","sheet","rows","gridProperties","rowCount","columns","columnCount","title","grid","endRow","endColumn","cellBlockToA1","batchUpdate","requestBody","requests","copyPaste","rangeReferenceToGridRange","parseA1Notation","Number","destination","handler","input","extra","logger","info","sheetsApi","version","auth","googleAuth","authContext","undefined","content","text","JSON","stringify","structuredContent","InternalError","stack","name"],"mappings":";;;;;;;;;;;QAoFsBA;eAAAA;;QAiGtB;eAAwBC;;;sBApLY;2BAEZ;sBAKyB;mBAC/B;2BAC8B;4BACrB;uBACsF;iCACwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARzI,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,WAAWC,6BAAoB,CAACC,QAAQ,CAAC;IACzCC,aAAaC,yBAAgB,CAACF,QAAQ,CAAC;IACvCG,gBAAgBJ,6BAAoB,CAACC,QAAQ,CAAC;IAC9CI,kBAAkBF,yBAAgB,CAACF,QAAQ,CAAC;IAC5CK,WAAWX,MAAC,CACTY,I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AC1FwE,OAAO/D,AAAK,YAALA,OAAiBC,SAAQD,MAAM+D,KAAK,GAAGP;oBAChD;;;;;;;IAEJ;;AAEe,SAASxG;IACtB,OAAO;QACLgH,MAAM;QACN7E,QAAAA;QACA2D,SAAAA;IACF;AACF"}
@@ -14,6 +14,14 @@ var _csvparse = require("csv-parse");
14
14
  var _promises = require("stream/promises");
15
15
  var _zod = require("zod");
16
16
  var _csvstreamingts = require("../../spreadsheet/csv-streaming.js");
17
+ function _array_like_to_array(arr, len) {
18
+ if (len == null || len > arr.length) len = arr.length;
19
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
20
+ return arr2;
21
+ }
22
+ function _array_without_holes(arr) {
23
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
24
+ }
17
25
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
18
26
  try {
19
27
  var info = gen[key](arg);
@@ -46,6 +54,17 @@ function _instanceof(left, right) {
46
54
  return !!right[Symbol.hasInstance](left);
47
55
  } else return left instanceof right;
48
56
  }
57
+ function _iterable_to_array(iter) {
58
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
59
+ return Array.from(iter);
60
+ }
61
+ }
62
+ function _non_iterable_spread() {
63
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
64
+ }
65
+ function _to_consumable_array(arr) {
66
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
67
+ }
49
68
  function _ts_generator(thisArg, body) {
50
69
  var f, y, t, _ = {
51
70
  label: 0,
@@ -145,6 +164,14 @@ function _ts_generator(thisArg, body) {
145
164
  };
146
165
  }
147
166
  }
167
+ function _unsupported_iterable_to_array(o, minLen) {
168
+ if (!o) return;
169
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
170
+ var n = Object.prototype.toString.call(o).slice(8, -1);
171
+ if (n === "Object" && o.constructor) n = o.constructor.name;
172
+ if (n === "Map" || n === "Set") return Array.from(n);
173
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
174
+ }
148
175
  var AuthRequiredBranchSchema = _oauthgoogle.schemas.AuthRequiredBranchSchema;
149
176
  var inputSchema = _zod.z.object({
150
177
  sourceUri: _zod.z.string().trim().min(1).describe('CSV file URI (file://, http://, https://)')
@@ -168,7 +195,7 @@ var config = {
168
195
  };
169
196
  function handler(_0, _1) {
170
197
  return _async_to_generator(function(param, extra) {
171
- var sourceUri, _logger_debug, logger, _logger_info, parser, readStream, firstRowRead, completed, firstRow, rowCount, record, error, pipelineError, columns, isEmpty, result, error1, _logger_error, message;
198
+ var sourceUri, _logger_debug, logger, _logger_info, parser, firstRowRead, streamErrors, onError, parserClosed, readStream, sourceClosed, completed, failed, primaryError, firstRow, rowCount, record, pipelineError, error, pipelineError1, failures, message, columns, isEmpty, result, error1, _logger_error, message1;
172
199
  return _ts_generator(this, function(_state) {
173
200
  switch(_state.label){
174
201
  case 0:
@@ -181,9 +208,9 @@ function handler(_0, _1) {
181
208
  case 1:
182
209
  _state.trys.push([
183
210
  1,
184
- 9,
211
+ 11,
185
212
  ,
186
- 10
213
+ 12
187
214
  ]);
188
215
  parser = (0, _csvparse.parse)({
189
216
  columns: false,
@@ -192,28 +219,41 @@ function handler(_0, _1) {
192
219
  cast: true,
193
220
  relax_column_count: true
194
221
  });
222
+ firstRowRead = new Error('First CSV row read');
223
+ streamErrors = [];
224
+ onError = function onError(error) {
225
+ return streamErrors.push(error);
226
+ };
227
+ parser.on('error', onError);
228
+ parserClosed = new Promise(function(resolve) {
229
+ return parser.once('close', resolve);
230
+ });
231
+ failed = false;
232
+ firstRow = [];
233
+ rowCount = 0;
234
+ _state.label = 2;
235
+ case 2:
236
+ _state.trys.push([
237
+ 2,
238
+ 6,
239
+ 7,
240
+ 10
241
+ ]);
195
242
  return [
196
243
  4,
197
244
  (0, _csvstreamingts.getCsvReadStream)(sourceUri)
198
245
  ];
199
- case 2:
246
+ case 3:
200
247
  readStream = _state.sent();
201
- firstRowRead = new Error('First CSV row read');
248
+ readStream.on('error', onError);
249
+ sourceClosed = readStream.closed ? Promise.resolve() : new Promise(function(resolve) {
250
+ return readStream === null || readStream === void 0 ? void 0 : readStream.once('close', resolve);
251
+ });
202
252
  completed = (0, _promises.pipeline)(readStream, parser).then(function() {
203
253
  return undefined;
204
254
  }, function(error) {
205
255
  return error;
206
256
  });
207
- firstRow = [];
208
- rowCount = 0;
209
- _state.label = 3;
210
- case 3:
211
- _state.trys.push([
212
- 3,
213
- 5,
214
- ,
215
- 7
216
- ]);
217
257
  return [
218
258
  4,
219
259
  parser[Symbol.asyncIterator]().next()
@@ -226,26 +266,64 @@ function handler(_0, _1) {
226
266
  parser.destroy(firstRowRead);
227
267
  }
228
268
  return [
229
- 3,
230
- 7
269
+ 4,
270
+ completed
231
271
  ];
232
272
  case 5:
233
- error = _state.sent();
273
+ pipelineError = _state.sent();
274
+ if (pipelineError !== undefined && pipelineError !== firstRowRead) throw pipelineError;
234
275
  return [
235
- 4,
236
- completed
276
+ 3,
277
+ 10
237
278
  ];
238
279
  case 6:
239
- _state.sent();
240
- throw error;
280
+ error = _state.sent();
281
+ failed = true;
282
+ primaryError = error;
283
+ return [
284
+ 3,
285
+ 10
286
+ ];
241
287
  case 7:
288
+ readStream === null || readStream === void 0 ? void 0 : readStream.destroy();
289
+ parser.destroy();
242
290
  return [
243
291
  4,
244
292
  completed
245
293
  ];
246
294
  case 8:
247
- pipelineError = _state.sent();
248
- if (pipelineError !== undefined && pipelineError !== firstRowRead) throw pipelineError;
295
+ pipelineError1 = _state.sent();
296
+ if (pipelineError1 !== undefined && pipelineError1 !== firstRowRead) streamErrors.push(pipelineError1);
297
+ return [
298
+ 4,
299
+ Promise.all([
300
+ sourceClosed,
301
+ parserClosed
302
+ ])
303
+ ];
304
+ case 9:
305
+ _state.sent();
306
+ readStream === null || readStream === void 0 ? void 0 : readStream.removeListener('error', onError);
307
+ parser.removeListener('error', onError);
308
+ return [
309
+ 7
310
+ ];
311
+ case 10:
312
+ failures = _to_consumable_array(new Set(_to_consumable_array(failed ? [
313
+ primaryError
314
+ ] : []).concat(_to_consumable_array(streamErrors.filter(function(error) {
315
+ return error !== firstRowRead;
316
+ })))));
317
+ if (failures.length === 1) throw failures[0];
318
+ if (failures.length > 1) {
319
+ message = failures.map(function(error) {
320
+ return _instanceof(error, Error) ? error.message : String(error);
321
+ }).join('; ');
322
+ throw Object.assign(new Error(message), {
323
+ errors: failures,
324
+ primaryError: failures[0]
325
+ });
326
+ }
249
327
  // Convert first row to strings (column names)
250
328
  columns = firstRow.map(function(value) {
251
329
  return String(value !== null && value !== void 0 ? value : '');
@@ -275,16 +353,16 @@ function handler(_0, _1) {
275
353
  }
276
354
  }
277
355
  ];
278
- case 9:
356
+ case 11:
279
357
  error1 = _state.sent();
280
- message = _instanceof(error1, Error) ? error1.message : String(error1);
358
+ message1 = _instanceof(error1, Error) ? error1.message : String(error1);
281
359
  (_logger_error = logger.error) === null || _logger_error === void 0 ? void 0 : _logger_error.call(logger, 'sheets.csv.get-columns error', {
282
- error: message
360
+ error: message1
283
361
  });
284
- throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error getting CSV columns: ".concat(message), {
362
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error getting CSV columns: ".concat(message1), {
285
363
  stack: _instanceof(error1, Error) ? error1.stack : undefined
286
364
  });
287
- case 10:
365
+ case 12:
288
366
  return [
289
367
  2
290
368
  ];