@mcp-z/mcp-sheets 2.4.2 → 2.5.1

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 (119) hide show
  1. package/README.md +45 -29
  2. package/dist/cjs/constants.d.cts +26 -0
  3. package/dist/cjs/constants.d.ts +26 -0
  4. package/dist/cjs/constants.js +83 -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/cells-format.d.cts +3 -3
  11. package/dist/cjs/mcp/tools/cells-format.d.ts +3 -3
  12. package/dist/cjs/mcp/tools/cells-format.js +3 -2
  13. package/dist/cjs/mcp/tools/cells-format.js.map +1 -1
  14. package/dist/cjs/mcp/tools/columns-get.d.cts +2 -2
  15. package/dist/cjs/mcp/tools/columns-get.d.ts +2 -2
  16. package/dist/cjs/mcp/tools/columns-get.js +2 -1
  17. package/dist/cjs/mcp/tools/columns-get.js.map +1 -1
  18. package/dist/cjs/mcp/tools/columns-update.d.cts +1 -1
  19. package/dist/cjs/mcp/tools/columns-update.d.ts +1 -1
  20. package/dist/cjs/mcp/tools/columns-update.js +3 -2
  21. package/dist/cjs/mcp/tools/columns-update.js.map +1 -1
  22. package/dist/cjs/mcp/tools/index.d.cts +1 -0
  23. package/dist/cjs/mcp/tools/index.d.ts +1 -0
  24. package/dist/cjs/mcp/tools/index.js +4 -0
  25. package/dist/cjs/mcp/tools/index.js.map +1 -1
  26. package/dist/cjs/mcp/tools/rows-append.d.cts +1 -1
  27. package/dist/cjs/mcp/tools/rows-append.d.ts +1 -1
  28. package/dist/cjs/mcp/tools/rows-append.js +2 -1
  29. package/dist/cjs/mcp/tools/rows-append.js.map +1 -1
  30. package/dist/cjs/mcp/tools/rows-csv-append.d.cts +1 -1
  31. package/dist/cjs/mcp/tools/rows-csv-append.d.ts +1 -1
  32. package/dist/cjs/mcp/tools/rows-csv-append.js +2 -1
  33. package/dist/cjs/mcp/tools/rows-csv-append.js.map +1 -1
  34. package/dist/cjs/mcp/tools/rows-get.d.cts +2 -2
  35. package/dist/cjs/mcp/tools/rows-get.d.ts +2 -2
  36. package/dist/cjs/mcp/tools/rows-get.js +2 -1
  37. package/dist/cjs/mcp/tools/rows-get.js.map +1 -1
  38. package/dist/cjs/mcp/tools/values-batch-update.d.cts +1 -1
  39. package/dist/cjs/mcp/tools/values-batch-update.d.ts +1 -1
  40. package/dist/cjs/mcp/tools/values-batch-update.js +3 -2
  41. package/dist/cjs/mcp/tools/values-batch-update.js.map +1 -1
  42. package/dist/cjs/mcp/tools/values-csv-update.d.cts +1 -1
  43. package/dist/cjs/mcp/tools/values-csv-update.d.ts +1 -1
  44. package/dist/cjs/mcp/tools/values-csv-update.js +3 -2
  45. package/dist/cjs/mcp/tools/values-csv-update.js.map +1 -1
  46. package/dist/cjs/mcp/tools/values-search.d.cts +2 -2
  47. package/dist/cjs/mcp/tools/values-search.d.ts +2 -2
  48. package/dist/cjs/mcp/tools/values-search.js +2 -1
  49. package/dist/cjs/mcp/tools/values-search.js.map +1 -1
  50. package/dist/cjs/schemas/index.d.cts +1 -0
  51. package/dist/cjs/schemas/index.d.ts +1 -0
  52. package/dist/cjs/schemas/index.js +16 -0
  53. package/dist/cjs/schemas/index.js.map +1 -1
  54. package/dist/cjs/setup/config.js +26 -14
  55. package/dist/cjs/setup/config.js.map +1 -1
  56. package/dist/cjs/setup/version-help.js +1 -1
  57. package/dist/cjs/setup/version-help.js.map +1 -1
  58. package/dist/cjs/spreadsheet/data-operations.js +60 -181
  59. package/dist/cjs/spreadsheet/data-operations.js.map +1 -1
  60. package/dist/cjs/spreadsheet/range-operations.d.cts +27 -5
  61. package/dist/cjs/spreadsheet/range-operations.d.ts +27 -5
  62. package/dist/cjs/spreadsheet/range-operations.js +48 -28
  63. package/dist/cjs/spreadsheet/range-operations.js.map +1 -1
  64. package/dist/cjs/spreadsheet/sheet-operations.d.cts +6 -0
  65. package/dist/cjs/spreadsheet/sheet-operations.d.ts +6 -0
  66. package/dist/cjs/spreadsheet/sheet-operations.js +114 -124
  67. package/dist/cjs/spreadsheet/sheet-operations.js.map +1 -1
  68. package/dist/esm/constants.d.ts +26 -0
  69. package/dist/esm/constants.js +55 -0
  70. package/dist/esm/constants.js.map +1 -1
  71. package/dist/esm/mcp/tools/cells-copy.d.ts +165 -0
  72. package/dist/esm/mcp/tools/cells-copy.js +190 -0
  73. package/dist/esm/mcp/tools/cells-copy.js.map +1 -0
  74. package/dist/esm/mcp/tools/cells-format.d.ts +3 -3
  75. package/dist/esm/mcp/tools/cells-format.js +3 -2
  76. package/dist/esm/mcp/tools/cells-format.js.map +1 -1
  77. package/dist/esm/mcp/tools/columns-get.d.ts +2 -2
  78. package/dist/esm/mcp/tools/columns-get.js +2 -1
  79. package/dist/esm/mcp/tools/columns-get.js.map +1 -1
  80. package/dist/esm/mcp/tools/columns-update.d.ts +1 -1
  81. package/dist/esm/mcp/tools/columns-update.js +3 -2
  82. package/dist/esm/mcp/tools/columns-update.js.map +1 -1
  83. package/dist/esm/mcp/tools/index.d.ts +1 -0
  84. package/dist/esm/mcp/tools/index.js +1 -0
  85. package/dist/esm/mcp/tools/index.js.map +1 -1
  86. package/dist/esm/mcp/tools/rows-append.d.ts +1 -1
  87. package/dist/esm/mcp/tools/rows-append.js +2 -1
  88. package/dist/esm/mcp/tools/rows-append.js.map +1 -1
  89. package/dist/esm/mcp/tools/rows-csv-append.d.ts +1 -1
  90. package/dist/esm/mcp/tools/rows-csv-append.js +2 -1
  91. package/dist/esm/mcp/tools/rows-csv-append.js.map +1 -1
  92. package/dist/esm/mcp/tools/rows-get.d.ts +2 -2
  93. package/dist/esm/mcp/tools/rows-get.js +2 -1
  94. package/dist/esm/mcp/tools/rows-get.js.map +1 -1
  95. package/dist/esm/mcp/tools/values-batch-update.d.ts +1 -1
  96. package/dist/esm/mcp/tools/values-batch-update.js +3 -2
  97. package/dist/esm/mcp/tools/values-batch-update.js.map +1 -1
  98. package/dist/esm/mcp/tools/values-csv-update.d.ts +1 -1
  99. package/dist/esm/mcp/tools/values-csv-update.js +3 -2
  100. package/dist/esm/mcp/tools/values-csv-update.js.map +1 -1
  101. package/dist/esm/mcp/tools/values-search.d.ts +2 -2
  102. package/dist/esm/mcp/tools/values-search.js +2 -1
  103. package/dist/esm/mcp/tools/values-search.js.map +1 -1
  104. package/dist/esm/schemas/index.d.ts +1 -0
  105. package/dist/esm/schemas/index.js +9 -0
  106. package/dist/esm/schemas/index.js.map +1 -1
  107. package/dist/esm/setup/config.js +26 -14
  108. package/dist/esm/setup/config.js.map +1 -1
  109. package/dist/esm/setup/version-help.js +7 -0
  110. package/dist/esm/setup/version-help.js.map +1 -1
  111. package/dist/esm/spreadsheet/data-operations.js +47 -95
  112. package/dist/esm/spreadsheet/data-operations.js.map +1 -1
  113. package/dist/esm/spreadsheet/range-operations.d.ts +27 -5
  114. package/dist/esm/spreadsheet/range-operations.js +50 -27
  115. package/dist/esm/spreadsheet/range-operations.js.map +1 -1
  116. package/dist/esm/spreadsheet/sheet-operations.d.ts +6 -0
  117. package/dist/esm/spreadsheet/sheet-operations.js +88 -79
  118. package/dist/esm/spreadsheet/sheet-operations.js.map +1 -1
  119. package/package.json +3 -3
@@ -6,8 +6,8 @@ declare const inputSchema: z.ZodObject<{
6
6
  gid: z.ZodCoercedString<unknown>;
7
7
  range: z.ZodString;
8
8
  render: z.ZodOptional<z.ZodEnum<{
9
- FORMATTED_VALUE: "FORMATTED_VALUE";
10
9
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
10
+ FORMATTED_VALUE: "FORMATTED_VALUE";
11
11
  FORMULA: "FORMULA";
12
12
  }>>;
13
13
  }, z.core.$strip>;
@@ -33,8 +33,8 @@ export default function createTool(): {
33
33
  gid: z.ZodCoercedString<unknown>;
34
34
  range: z.ZodString;
35
35
  render: z.ZodOptional<z.ZodEnum<{
36
- FORMATTED_VALUE: "FORMATTED_VALUE";
37
36
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
37
+ FORMATTED_VALUE: "FORMATTED_VALUE";
38
38
  FORMULA: "FORMULA";
39
39
  }>>;
40
40
  }, z.core.$strip>;
@@ -6,8 +6,8 @@ declare const inputSchema: z.ZodObject<{
6
6
  gid: z.ZodCoercedString<unknown>;
7
7
  range: z.ZodString;
8
8
  render: z.ZodOptional<z.ZodEnum<{
9
- FORMATTED_VALUE: "FORMATTED_VALUE";
10
9
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
10
+ FORMATTED_VALUE: "FORMATTED_VALUE";
11
11
  FORMULA: "FORMULA";
12
12
  }>>;
13
13
  }, z.core.$strip>;
@@ -33,8 +33,8 @@ export default function createTool(): {
33
33
  gid: z.ZodCoercedString<unknown>;
34
34
  range: z.ZodString;
35
35
  render: z.ZodOptional<z.ZodEnum<{
36
- FORMATTED_VALUE: "FORMATTED_VALUE";
37
36
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
37
+ FORMATTED_VALUE: "FORMATTED_VALUE";
38
38
  FORMULA: "FORMULA";
39
39
  }>>;
40
40
  }, z.core.$strip>;
@@ -12,6 +12,7 @@ var _sheets = require("@googleapis/sheets");
12
12
  var _oauthgoogle = require("@mcp-z/oauth-google");
13
13
  var _server = require("@mcp-z/server");
14
14
  var _zod = require("zod");
15
+ var _constantsts = require("../../constants.js");
15
16
  var _googleauthts = require("../../lib/google-auth.js");
16
17
  var _indexts = require("../../schemas/index.js");
17
18
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
@@ -154,7 +155,7 @@ var inputSchema = _zod.z.object({
154
155
  'FORMATTED_VALUE',
155
156
  'UNFORMATTED_VALUE',
156
157
  'FORMULA'
157
- ]).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.')
158
+ ]).optional().describe(_constantsts.RENDER_DESCRIPTION)
158
159
  });
159
160
  // Success branch schema - uses rows: for consistency with standard vocabulary
160
161
  var successBranchSchema = _zod.z.object({
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/rows-get.ts"],"sourcesContent":["import { 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 { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n range: z.string().min(1).describe('A1 notation range to fetch (e.g., \"B5\", \"A5:D5\", \"B:B\", \"5:5\")'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.'),\n});\n\n// Success branch schema - uses rows: for consistency with standard vocabulary\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n range: z.string().describe('The A1 notation range that was retrieved'),\n rows: z.array(z.array(SheetCellSchema)).describe('2D array of row data (each inner array is a row)'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Fetch row data from a specific range in A1 notation. Best used after values-search to get surrounding context. Use a1-notation prompt for syntax reference.',\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>;\n\nasync function handler({ id, gid, range, render }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.rows.get called', { id, gid, range, render });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details using the gid to get sheet title\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.rows.get sheet not found', { id, gid, range });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Construct full range with sheet title\n const fullRange = `${sheetTitle}!${range}`;\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n\n const res = response.data;\n const rows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n logger.info('sheets.rows.get success', { id, gid, range, rowCount: rows.length });\n\n const result: Output = {\n type: 'success' as const,\n range: res.range || fullRange,\n rows,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.rows.get error', { error: message });\n\n // Throw ProtocolError for proper MCP error handling\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting rows: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'rows-get',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","range","string","min","describe","render","enum","optional","successBranchSchema","type","literal","rows","array","SheetCellSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetResponse","sheet","sheets","sheetTitle","fullRange","response","res","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","values","valueRenderOption","Array","isArray","rowCount","length","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":";;;;+BAiGA;;;eAAwBA;;;sBAjGY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBAC0C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AANrE,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,OAAON,MAAC,CAACO,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAClCC,QAAQV,MAAC,CAACW,IAAI,CAAC;QAAC;QAAmB;QAAqB;KAAU,EAAEC,QAAQ,GAAGH,QAAQ,CAAC;AAC1F;AAEA,8EAA8E;AAC9E,IAAMI,sBAAsBb,MAAC,CAACC,MAAM,CAAC;IACnCa,MAAMd,MAAC,CAACe,OAAO,CAAC;IAChBT,OAAON,MAAC,CAACO,MAAM,GAAGE,QAAQ,CAAC;IAC3BO,MAAMhB,MAAC,CAACiB,KAAK,CAACjB,MAAC,CAACiB,KAAK,CAACC,wBAAe,GAAGT,QAAQ,CAAC;AACnD;AAEA,2CAA2C;AAC3C,IAAMU,eAAenB,MAAC,CAACoB,kBAAkB,CAAC,QAAQ;IAACP;IAAqBhB;CAAyB;AAEjG,IAAMwB,SAAS;IACbC,aAAa;IACbvB,aAAAA;IACAoB,cAAcnB,MAAC,CAACC,MAAM,CAAC;QAC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AAMuB,OAAOa,YAAY,CAACc,MAAM,CAACb,GAAG,CAAC;4BACpDC,eAAe1C;4BACfI,OAAOyB;4BACP0B,mBAAmB/C,UAAU;wBAC/B;;;oBAJMsB,WAAW;oBAMXC,MAAMD,SAASc,IAAI;oBACnB9B,OAAO0C,MAAMC,OAAO,CAAC1B,IAAIuB,MAAM,IAAKvB,IAAIuB,MAAM;oBAEpD9B,OAAOU,IAAI,CAAC,2BAA2B;wBAAElC,IAAAA;wBAAIE,KAAAA;wBAAKE,OAAAA;wBAAOsD,UAAU5C,KAAK6C,MAAM;oBAAC;oBAEzEtC,SAAiB;wBACrBT,MAAM;wBACNR,OAAO2B,IAAI3B,KAAK,IAAIyB;wBACpBf,MAAAA;oBACF;oBAEA;;wBAAO;4BACL8C,OAAO;gCAAG;oCAAEhD,MAAM;oCAAiBiD,MAAMC,KAAKC,SAAS,CAAC1C;gCAAQ;;4BAChE2C,mBAAmB;gCAAE3C,QAAAA;4BAAO;wBAC9B;;;oBACOW;oBACDC,UAAUD,AAAK,YAALA,OAAiBiC,SAAQjC,MAAMC,OAAO,GAAGc,OAAOf;oBAChER,OAAOQ,KAAK,CAAC,yBAAyB;wBAAEA,OAAOC;oBAAQ;oBAEvD,oDAAoD;oBACpD,MAAM,IAAIiB,qBAAa,CAACC,yBAAiB,CAACe,aAAa,EAAE,AAAC,uBAA8B,OAARjC,UAAW;wBACzFkC,OAAOnC,AAAK,YAALA,OAAiBiC,SAAQjC,MAAMmC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1E;IACtB,OAAO;QACL2E,MAAM;QACNlD,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/rows-get.ts"],"sourcesContent":["import { 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 { RENDER_DESCRIPTION } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n range: z.string().min(1).describe('A1 notation range to fetch (e.g., \"B5\", \"A5:D5\", \"B:B\", \"5:5\")'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe(RENDER_DESCRIPTION),\n});\n\n// Success branch schema - uses rows: for consistency with standard vocabulary\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n range: z.string().describe('The A1 notation range that was retrieved'),\n rows: z.array(z.array(SheetCellSchema)).describe('2D array of row data (each inner array is a row)'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Fetch row data from a specific range in A1 notation. Best used after values-search to get surrounding context. Use a1-notation prompt for syntax reference.',\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>;\n\nasync function handler({ id, gid, range, render }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.rows.get called', { id, gid, range, render });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details using the gid to get sheet title\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.rows.get sheet not found', { id, gid, range });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Construct full range with sheet title\n const fullRange = `${sheetTitle}!${range}`;\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n\n const res = response.data;\n const rows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n logger.info('sheets.rows.get success', { id, gid, range, rowCount: rows.length });\n\n const result: Output = {\n type: 'success' as const,\n range: res.range || fullRange,\n rows,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.rows.get error', { error: message });\n\n // Throw ProtocolError for proper MCP error handling\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting rows: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'rows-get',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","range","string","min","describe","render","enum","optional","RENDER_DESCRIPTION","successBranchSchema","type","literal","rows","array","SheetCellSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetResponse","sheet","sheets","sheetTitle","fullRange","response","res","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","values","valueRenderOption","Array","isArray","rowCount","length","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":";;;;+BAkGA;;;eAAwBA;;;sBAlGY;2BAEZ;sBAKyB;mBAC/B;2BACiB;4BACR;uBAC0C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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K6C,MAAM;oBAAC;oBAEzEtC,SAAiB;wBACrBT,MAAM;wBACNT,OAAO4B,IAAI5B,KAAK,IAAI0B;wBACpBf,MAAAA;oBACF;oBAEA;;wBAAO;4BACL8C,OAAO;gCAAG;oCAAEhD,MAAM;oCAAiBiD,MAAMC,KAAKC,SAAS,CAAC1C;gCAAQ;;4BAChE2C,mBAAmB;gCAAE3C,QAAAA;4BAAO;wBAC9B;;;oBACOW;oBACDC,UAAUD,AAAK,YAALA,OAAiBiC,SAAQjC,MAAMC,OAAO,GAAGc,OAAOf;oBAChER,OAAOQ,KAAK,CAAC,yBAAyB;wBAAEA,OAAOC;oBAAQ;oBAEvD,oDAAoD;oBACpD,MAAM,IAAIiB,qBAAa,CAACC,yBAAiB,CAACe,aAAa,EAAE,AAAC,uBAA8B,OAARjC,UAAW;wBACzFkC,OAAOnC,AAAK,YAALA,OAAiBiC,SAAQjC,MAAMmC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS3E;IACtB,OAAO;QACL4E,MAAM;QACNlD,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -50,7 +50,7 @@ declare function handler({ id, gid, requests, valueInputOption, includeData }: I
50
50
  export default function createTool(): {
51
51
  name: string;
52
52
  config: {
53
- readonly description: "Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update.";
53
+ readonly description: `Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update. ${string}`;
54
54
  readonly inputSchema: z.ZodObject<{
55
55
  id: z.ZodString;
56
56
  gid: z.ZodCoercedString<unknown>;
@@ -50,7 +50,7 @@ declare function handler({ id, gid, requests, valueInputOption, includeData }: I
50
50
  export default function createTool(): {
51
51
  name: string;
52
52
  config: {
53
- readonly description: "Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update.";
53
+ readonly description: `Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update. ${string}`;
54
54
  readonly inputSchema: z.ZodObject<{
55
55
  id: z.ZodString;
56
56
  gid: z.ZodCoercedString<unknown>;
@@ -12,6 +12,7 @@ var _sheets = require("@googleapis/sheets");
12
12
  var _oauthgoogle = require("@mcp-z/oauth-google");
13
13
  var _server = require("@mcp-z/server");
14
14
  var _zod = require("zod");
15
+ var _constantsts = require("../../constants.js");
15
16
  var _googleauthts = require("../../lib/google-auth.js");
16
17
  var _indexts = require("../../schemas/index.js");
17
18
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
@@ -162,7 +163,7 @@ var inputSchema = _zod.z.object({
162
163
  valueInputOption: _zod.z.enum([
163
164
  'RAW',
164
165
  'USER_ENTERED'
165
- ]).describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input)'),
166
+ ]).describe('How input data should be interpreted (required; no default is applied by the schema). RAW = exact values: date strings stay text, numeric serials stay numbers. USER_ENTERED = parsed like user input: date strings may become native dates per the workbook locale.'),
166
167
  includeData: _zod.z.boolean().describe('Whether to include updated cell values in the response')
167
168
  });
168
169
  var successBranchSchema = _zod.z.object({
@@ -191,7 +192,7 @@ var outputSchema = _zod.z.discriminatedUnion('type', [
191
192
  AuthRequiredBranchSchema
192
193
  ]);
193
194
  var config = {
194
- description: 'Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update.',
195
+ description: "Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update. ".concat(_constantsts.NATIVE_DATE_GUIDANCE),
195
196
  inputSchema: inputSchema,
196
197
  outputSchema: _zod.z.object({
197
198
  result: outputSchema
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-batch-update.ts"],"sourcesContent":["import { 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 { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Types for updated data response\ninterface UpdatedDataItem {\n range: string;\n majorDimension: 'ROWS' | 'COLUMNS';\n values?: (string | number | boolean | null)[][];\n}\n\n// Input schema for values batch update requests\nconst ValuesBatchUpdateRequestSchema = z.object({\n range: A1NotationSchema.describe('A1 notation range defining the bounded target area. Data dimensions must match range dimensions. Example: D1:D100 requires exactly 100 rows of data. Use open-ended ranges like D1:D to write any number of rows.'),\n values: z.array(z.array(SheetCellSchema)).min(1).describe('2D array of values. Row count must match range height, column count must match range width. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether values represent rows or columns'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(ValuesBatchUpdateRequestSchema).min(1).describe('Array of value update requests'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input)'),\n includeData: z.boolean().describe('Whether to include updated cell values in the response'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Title of the updated spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the updated spreadsheet'),\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n totalUpdatedRows: z.number().int().nonnegative().describe('Total number of rows updated across all requests'),\n totalUpdatedColumns: z.number().int().nonnegative().describe('Total number of columns updated across all requests'),\n totalUpdatedCells: z.number().int().nonnegative().describe('Total number of cells updated across all requests'),\n updatedRanges: z.array(z.string()).describe('A1 notation ranges that were updated'),\n updatedData: z\n .array(\n z.object({\n range: z.string().describe('A1 notation range that was updated'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension of the updated data'),\n values: z.array(z.array(SheetCellSchema)).optional().describe('Updated values (if includeData was true)'),\n })\n )\n .optional()\n .describe('Detailed information about updated data (if includeData was true)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update.',\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>;\n\nasync function handler({ id, gid, requests, valueInputOption = 'USER_ENTERED', includeData = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n includeData,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n const spreadsheetTitle = spreadsheetData.properties?.title ?? '';\n const spreadsheetUrl = spreadsheetData.spreadsheetUrl ?? '';\n\n // Find sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for batch update', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n const sheetGid = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetGid}`;\n\n // Build batch update request with prefixed ranges\n const batchUpdateData = requests.map((req) => ({\n range: `${sheetTitle}!${req.range}`,\n values: req.values,\n majorDimension: req.majorDimension || 'ROWS',\n }));\n\n logger.info('sheets.values.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchUpdateDataCount: batchUpdateData.length,\n });\n\n // Execute the batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchUpdateData,\n includeValuesInResponse: includeData,\n responseDateTimeRenderOption: 'FORMATTED_STRING',\n responseValueRenderOption: 'FORMATTED_VALUE',\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Validate batch operation results and detect partial failures\n const responses = updateResult.responses || [];\n const expectedCount = requests.length;\n const actualCount = responses.length;\n\n if (actualCount !== expectedCount) {\n logger.error('Partial batch failure detected', {\n expectedOperations: expectedCount,\n completedOperations: actualCount,\n spreadsheetId: id,\n sheetTitle,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation partially failed: ${actualCount}/${expectedCount} operations completed`);\n }\n\n // Check for any failed operations (empty or null responses)\n const failedOperations = responses.filter((response, index) => {\n if (!response || !response.updatedRange) {\n logger.error('Failed operation detected', {\n operationIndex: index,\n requestedRange: requests[index]?.range,\n spreadsheetId: id,\n sheetTitle,\n });\n return true;\n }\n return false;\n });\n\n if (failedOperations.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, `${failedOperations.length} operations failed to update ranges`);\n }\n\n // Extract updated ranges and calculate totals\n const updatedRanges = responses.map((response) => response.updatedRange || '').filter((range) => range);\n const totalUpdatedRows = updateResult.totalUpdatedRows || 0;\n const totalUpdatedColumns = updateResult.totalUpdatedColumns || 0;\n const totalUpdatedCells = updateResult.totalUpdatedCells || 0;\n\n // Build updated data response if requested\n let updatedData: UpdatedDataItem[] | undefined;\n if (includeData && updateResult.responses) {\n updatedData = updateResult.responses\n .filter((response) => response.updatedData)\n .map((response) => {\n const item: UpdatedDataItem = {\n range: response.updatedRange || '',\n majorDimension: (response.updatedData?.majorDimension as 'ROWS' | 'COLUMNS' | undefined) || 'ROWS',\n };\n const values = response.updatedData?.values as (string | number | boolean | null | undefined)[][] | undefined;\n if (values !== undefined) {\n // Map undefined values to null for JSON Schema compatibility\n item.values = values.map((row) => row.map((cell) => (cell === undefined ? null : cell)));\n }\n return item;\n });\n }\n\n logger.info('sheets.values.batchUpdate completed successfully', {\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRangesCount: updatedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetGid),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRanges,\n updatedData,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Batch update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","ValuesBatchUpdateRequestSchema","z","object","range","A1NotationSchema","describe","values","array","SheetCellSchema","min","majorDimension","enum","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","valueInputOption","includeData","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalUpdatedRows","number","int","nonnegative","totalUpdatedColumns","totalUpdatedCells","updatedRanges","updatedData","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetData","sheet","sheets","spreadsheetResponse","sheetGid","batchUpdateData","batchUpdateResponse","updateResult","responses","expectedCount","actualCount","failedOperations","error","message","info","requestCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","map","req","batchUpdateDataCount","batchUpdate","requestBody","includeValuesInResponse","responseDateTimeRenderOption","responseValueRenderOption","expectedOperations","completedOperations","InternalError","filter","response","index","updatedRange","operationIndex","requestedRange","item","undefined","row","cell","updatedRangesCount","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BAyOA;;;eAAwBA;;;sBAzOY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBACiG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN5H,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAeR,gDAAgD;AAChD,IAAME,iCAAiCC,MAAC,CAACC,MAAM,CAAC;IAC9CC,OAAOC,yBAAgB,CAACC,QAAQ,CAAC;IACjCC,QAAQL,MAAC,CAACM,KAAK,CAACN,MAAC,CAACM,KAAK,CAACC,wBAAe,GAAGC,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IAC1DK,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iBqF,MAAMC,KAAKC,SAAS,CAACjE;gCAAQ;;4BAChEkE,mBAAmB;gCAAElE,QAAAA;4BAAO;wBAC9B;;;oBACOgB;oBACDC,UAAUD,AAAK,YAALA,OAAiBmD,SAAQnD,MAAMC,OAAO,GAAGkB,OAAOnB;oBAChEb,OAAOa,KAAK,CAAC,iCAAiC;wBAC5C/C,IAAAA;wBACAE,KAAAA;wBACAgD,cAAc9C,SAAS+C,MAAM;wBAC7B9C,kBAAAA;wBACA0C,OAAOC;oBACT;oBAEA,MAAM,IAAIoB,qBAAa,CAACC,yBAAiB,CAACY,aAAa,EAAE,AAAC,gCAAuC,OAARjC,UAAW;wBAClGmD,OAAOpD,AAAK,YAALA,OAAiBmD,SAAQnD,MAAMoD,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASzG;IACtB,OAAO;QACLoH,MAAM;QACNvE,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-batch-update.ts"],"sourcesContent":["import { 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 { NATIVE_DATE_GUIDANCE } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Types for updated data response\ninterface UpdatedDataItem {\n range: string;\n majorDimension: 'ROWS' | 'COLUMNS';\n values?: (string | number | boolean | null)[][];\n}\n\n// Input schema for values batch update requests\nconst ValuesBatchUpdateRequestSchema = z.object({\n range: A1NotationSchema.describe('A1 notation range defining the bounded target area. Data dimensions must match range dimensions. Example: D1:D100 requires exactly 100 rows of data. Use open-ended ranges like D1:D to write any number of rows.'),\n values: z.array(z.array(SheetCellSchema)).min(1).describe('2D array of values. Row count must match range height, column count must match range width. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether values represent rows or columns'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(ValuesBatchUpdateRequestSchema).min(1).describe('Array of value update requests'),\n valueInputOption: z\n .enum(['RAW', 'USER_ENTERED'])\n .describe('How input data should be interpreted (required; no default is applied by the schema). RAW = exact values: date strings stay text, numeric serials stay numbers. USER_ENTERED = parsed like user input: date strings may become native dates per the workbook locale.'),\n includeData: z.boolean().describe('Whether to include updated cell values in the response'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Title of the updated spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the updated spreadsheet'),\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n totalUpdatedRows: z.number().int().nonnegative().describe('Total number of rows updated across all requests'),\n totalUpdatedColumns: z.number().int().nonnegative().describe('Total number of columns updated across all requests'),\n totalUpdatedCells: z.number().int().nonnegative().describe('Total number of cells updated across all requests'),\n updatedRanges: z.array(z.string()).describe('A1 notation ranges that were updated'),\n updatedData: z\n .array(\n z.object({\n range: z.string().describe('A1 notation range that was updated'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension of the updated data'),\n values: z.array(z.array(SheetCellSchema)).optional().describe('Updated values (if includeData was true)'),\n })\n )\n .optional()\n .describe('Detailed information about updated data (if includeData was true)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: `Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update. ${NATIVE_DATE_GUIDANCE}`,\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>;\n\nasync function handler({ id, gid, requests, valueInputOption = 'USER_ENTERED', includeData = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n includeData,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n const spreadsheetTitle = spreadsheetData.properties?.title ?? '';\n const spreadsheetUrl = spreadsheetData.spreadsheetUrl ?? '';\n\n // Find sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for batch update', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n const sheetGid = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetGid}`;\n\n // Build batch update request with prefixed ranges\n const batchUpdateData = requests.map((req) => ({\n range: `${sheetTitle}!${req.range}`,\n values: req.values,\n majorDimension: req.majorDimension || 'ROWS',\n }));\n\n logger.info('sheets.values.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchUpdateDataCount: batchUpdateData.length,\n });\n\n // Execute the batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchUpdateData,\n includeValuesInResponse: includeData,\n responseDateTimeRenderOption: 'FORMATTED_STRING',\n responseValueRenderOption: 'FORMATTED_VALUE',\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Validate batch operation results and detect partial failures\n const responses = updateResult.responses || [];\n const expectedCount = requests.length;\n const actualCount = responses.length;\n\n if (actualCount !== expectedCount) {\n logger.error('Partial batch failure detected', {\n expectedOperations: expectedCount,\n completedOperations: actualCount,\n spreadsheetId: id,\n sheetTitle,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation partially failed: ${actualCount}/${expectedCount} operations completed`);\n }\n\n // Check for any failed operations (empty or null responses)\n const failedOperations = responses.filter((response, index) => {\n if (!response || !response.updatedRange) {\n logger.error('Failed operation detected', {\n operationIndex: index,\n requestedRange: requests[index]?.range,\n spreadsheetId: id,\n sheetTitle,\n });\n return true;\n }\n return false;\n });\n\n if (failedOperations.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, `${failedOperations.length} operations failed to update ranges`);\n }\n\n // Extract updated ranges and calculate totals\n const updatedRanges = responses.map((response) => response.updatedRange || '').filter((range) => range);\n const totalUpdatedRows = updateResult.totalUpdatedRows || 0;\n const totalUpdatedColumns = updateResult.totalUpdatedColumns || 0;\n const totalUpdatedCells = updateResult.totalUpdatedCells || 0;\n\n // Build updated data response if requested\n let updatedData: UpdatedDataItem[] | undefined;\n if (includeData && updateResult.responses) {\n updatedData = updateResult.responses\n .filter((response) => response.updatedData)\n .map((response) => {\n const item: UpdatedDataItem = {\n range: response.updatedRange || '',\n majorDimension: (response.updatedData?.majorDimension as 'ROWS' | 'COLUMNS' | undefined) || 'ROWS',\n };\n const values = response.updatedData?.values as (string | number | boolean | null | undefined)[][] | undefined;\n if (values !== undefined) {\n // Map undefined values to null for JSON Schema compatibility\n item.values = values.map((row) => row.map((cell) => (cell === undefined ? null : cell)));\n }\n return item;\n });\n }\n\n logger.info('sheets.values.batchUpdate completed successfully', {\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRangesCount: updatedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetGid),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRanges,\n updatedData,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Batch update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","ValuesBatchUpdateRequestSchema","z","object","range","A1NotationSchema","describe","values","array","SheetCellSchema","min","majorDimension","enum","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","valueInputOption","includeData","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalUpdatedRows","number","int","nonnegative","totalUpdatedColumns","totalUpdatedCells","updatedRanges","updatedData","optional","outputSchema","discriminatedUnion","config","description","NATIVE_DATE_GUIDANCE","result","handler","extra","logger","spreadsheetData","sheet","sheets","spreadsheetResponse","sheetGid","batchUpdateData","batchUpdateResponse","updateResult","responses","expectedCount","actualCount","failedOperations","error","message","info","requestCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","map","req","batchUpdateDataCount","batchUpdate","requestBody","includeValuesInResponse","responseDateTimeRenderOption","responseValueRenderOption","expectedOperations","completedOperations","InternalError","filter","response","index","updatedRange","operationIndex","requestedRange","item","undefined","row","cell","updatedRangesCount","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BA4OA;;;eAAwBA;;;sBA5OY;2BAEZ;sBAKyB;mBAC/B;2BACmB;4BACV;uBACiG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAP5H,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAgBR,gDAAgD;AAChD,IAAME,iCAAiCC,MAAC,CAACC,MAAM,CAAC;IAC9CC,OAAOC,yBAAgB,CAACC,QAAQ,CAAC;IACjCC,QAAQL,MAAC,CAACM,KAAK,CAACN,MAAC,CAACM,KAAK,CAACC,wBAAe,GAAGC,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IAC1DK,gBAAgBT,MAAC,CAACU,IAAI,CAAC;QAAC;QAAQ;KAAU,EAAEN,QAAQ,CAAC;AACvD;AAEA,IAAMO,cAAcX,MAAC,CAACC,MAAM,CAAC;IAC3BW,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,UAAUhB,MAAC,CAACM,KAAK,CAACP,gCAAgCS,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IAClEa,kBAAkBjB,MAAC,CAChBU,IAAI,CAAC;QAAC;QAAO;KAAe,EAC5BN,QAAQ,CAAC;IACZc,aAAalB,MAAC,CAACmB,OAAO,GAAGf,QAAQ,CAAC;AACpC;AAEA,IAAMgB,sBAAsBpB,MAAC,CAACC,MAAM,CAAC;IACnCoB,MAAMrB,MAAC,CAACsB,OAAO,CAAC;IAChBV,IAAIW,4BAAmB;IACvBT,KAAKU,uBAAc;IACnBC,kBAAkBz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LqH,MAAM;QACNxE,QAAAA;QACAI,SAAAA;IACF;AACF"}
@@ -37,7 +37,7 @@ declare function handler({ id, gid, sourceUri, startRange, valueInputOption, sou
37
37
  export default function createTool(): {
38
38
  name: string;
39
39
  config: {
40
- readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.";
40
+ readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. Dates: a date-looking string is not necessarily a native date. See values-batch-update for the native-date write, format and read-back steps.";
41
41
  readonly inputSchema: z.ZodObject<{
42
42
  id: z.ZodString;
43
43
  gid: z.ZodCoercedString<unknown>;
@@ -37,7 +37,7 @@ declare function handler({ id, gid, sourceUri, startRange, valueInputOption, sou
37
37
  export default function createTool(): {
38
38
  name: string;
39
39
  config: {
40
- readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.";
40
+ readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. Dates: a date-looking string is not necessarily a native date. See values-batch-update for the native-date write, format and read-back steps.";
41
41
  readonly inputSchema: z.ZodObject<{
42
42
  id: z.ZodString;
43
43
  gid: z.ZodCoercedString<unknown>;
@@ -13,6 +13,7 @@ var _oauthgoogle = require("@mcp-z/oauth-google");
13
13
  var _server = require("@mcp-z/server");
14
14
  var _csvparse = require("csv-parse");
15
15
  var _zod = require("zod");
16
+ var _constantsts = require("../../constants.js");
16
17
  var _googleauthts = require("../../lib/google-auth.js");
17
18
  var _indexts = require("../../schemas/index.js");
18
19
  var _csvstreamingts = require("../../spreadsheet/csv-streaming.js");
@@ -198,7 +199,7 @@ var inputSchema = _zod.z.object({
198
199
  valueInputOption: _zod.z.enum([
199
200
  'RAW',
200
201
  'USER_ENTERED'
201
- ]).default('USER_ENTERED').describe('How to interpret values (RAW = exact, USER_ENTERED = parse formulas/dates)'),
202
+ ]).default('USER_ENTERED').describe('How to interpret values (default USER_ENTERED = parse formulas/dates per the workbook locale; RAW = exact, date-looking CSV text stays text)'),
202
203
  sourceHasHeaders: _zod.z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.')
203
204
  });
204
205
  var successBranchSchema = _zod.z.object({
@@ -219,7 +220,7 @@ var outputSchema = _zod.z.discriminatedUnion('type', [
219
220
  AuthRequiredBranchSchema
220
221
  ]);
221
222
  var config = {
222
- description: 'Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.',
223
+ description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. ".concat(_constantsts.NATIVE_DATE_POINTER),
223
224
  inputSchema: inputSchema,
224
225
  outputSchema: _zod.z.object({
225
226
  result: outputSchema
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-csv-update.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with range-based update (no deduplication) */\n\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 { parse } from 'csv-parse';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\n\n/** Batch size for Sheets API calls (1000 rows × avg 10 cols = 10K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n sourceUri: z.string().trim().min(1).describe('CSV file URI (file://, http://, https://)'),\n startRange: A1NotationSchema.default('A1').describe('Top-left cell where CSV data starts (default: A1)'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How to interpret values (RAW = exact, USER_ENTERED = parse formulas/dates)'),\n sourceHasHeaders: z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Spreadsheet title'),\n spreadsheetUrl: z.string().describe('Spreadsheet URL'),\n sheetTitle: z.string().describe('Sheet title'),\n sheetUrl: z.string().describe('Sheet URL'),\n updatedRange: z.string().describe('A1 notation range that was updated'),\n updatedRows: z.number().describe('Number of rows updated'),\n updatedColumns: z.number().describe('Number of columns updated'),\n updatedCells: z.number().describe('Number of cells updated'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.',\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>;\n\nasync function handler({ id, gid, sourceUri, startRange, valueInputOption = 'USER_ENTERED', sourceHasHeaders }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.csv-update called', { id, gid, sourceUri, startRange, valueInputOption, sourceHasHeaders });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n\n // Find the sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? '';\n\n // Streaming CSV processing state\n let sourceHeaders: string[] = [];\n const allRows: (string | number | boolean | null)[][] = [];\n let totalCols = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser with native streaming\n const parser = readStream.pipe(\n parse({\n columns: !!sourceHasHeaders, // Parse first row as column names if source has headers\n skip_empty_lines: true,\n trim: true,\n cast: true, // Auto-convert numbers/booleans\n relax_column_count: true,\n })\n );\n\n // Stream and collect all rows (with batching for very large files)\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders.length === 0) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n totalCols = sourceHeaders.length;\n logger.info('sheets.values.csv-update source headers', { sourceHeaders, totalCols });\n }\n\n // Convert record to row array (exclude source headers from data range)\n // CSV values are strings/numbers/booleans/nulls from the parser\n const row = sourceHeaders.map((header) => (record as Record<string, string | number | boolean | null>)[header] ?? null);\n allRows.push(row);\n } else {\n // sourceHasHeaders=false: record is an array, include all rows (including first row)\n const row = record as (string | number | boolean | null)[];\n allRows.push(row);\n\n if (totalCols === 0) {\n totalCols = row.length;\n }\n }\n }\n\n if (allRows.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'CSV file is empty');\n }\n\n // Prepare data for update (all rows)\n const dataToWrite: (string | number | boolean | null)[][] = allRows;\n\n // For large datasets, use batchUpdate to write in chunks\n // This respects the 40K cell limit per request\n const batchRequests = [];\n const currentRow = startRange.match(/[A-Z]+(\\d+)/)?.[1] || '1';\n let currentRowNum = Number.parseInt(currentRow, 10);\n\n for (let i = 0; i < dataToWrite.length; i += BATCH_SIZE) {\n const batchData = dataToWrite.slice(i, i + BATCH_SIZE);\n const batchRange = `${sheetTitle}!${startRange.match(/[A-Z]+/)?.[0]}${currentRowNum}`;\n\n batchRequests.push({\n range: batchRange,\n values: batchData,\n });\n\n currentRowNum += batchData.length;\n }\n\n logger.info('sheets.values.csv-update batching', { totalBatches: batchRequests.length, batchSize: BATCH_SIZE });\n\n // Execute batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchRequests,\n },\n });\n\n const totalUpdatedCells = batchUpdateResponse.data.totalUpdatedCells || 0;\n const totalUpdatedRows = batchUpdateResponse.data.totalUpdatedRows || 0;\n const totalUpdatedColumns = batchUpdateResponse.data.totalUpdatedColumns || 0;\n const firstUpdatedRange = batchUpdateResponse.data.responses?.[0]?.updatedRange || `${sheetTitle}!${startRange}`;\n\n logger.info('sheets.values.csv-update completed', { id, gid: sheet.properties.sheetId, updatedRange: firstUpdatedRange, updatedRows: totalUpdatedRows, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheet.properties.sheetId ?? ''),\n spreadsheetTitle: spreadsheetData.properties?.title ?? '',\n spreadsheetUrl: spreadsheetData.spreadsheetUrl ?? `https://docs.google.com/spreadsheets/d/${id}`,\n sheetTitle,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheet.properties.sheetId}`,\n updatedRange: firstUpdatedRange,\n updatedRows: totalUpdatedRows,\n updatedColumns: totalUpdatedColumns,\n updatedCells: totalUpdatedCells,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values.csv-update error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error updating values from CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-csv-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","BATCH_SIZE","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","sourceUri","string","trim","min","describe","startRange","A1NotationSchema","default","valueInputOption","enum","sourceHasHeaders","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRange","updatedRows","number","updatedColumns","updatedCells","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","sheet","spreadsheetData","batchUpdateResponse","sheets","spreadsheetResponse","sourceHeaders","allRows","totalCols","readStream","parser","dataToWrite","batchRequests","currentRow","currentRowNum","i","batchData","batchRange","totalUpdatedCells","totalUpdatedRows","totalUpdatedColumns","firstUpdatedRange","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","getCsvReadStream","pipe","parse","columns","skip_empty_lines","cast","relax_column_count","record","length","Object","keys","row","map","header","push","match","Number","parseInt","slice","range","values","totalBatches","batchSize","batchUpdate","requestBody","responses","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":"AAAA,gFAAgF;;;;+BAiMhF;;;eAAwBA;;;sBA/LY;2BAEZ;sBAKyB;wBAC3B;mBACJ;4BACS;uBACgF;8BAC1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,gGAAgG,GAChG,IAAME,aAAa;AAEnB,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,WAAWN,MAAC,CAACO,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,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AiB;wBACrBjB,MAAM;wBACNjB,IAAAA;wBACAE,KAAKwE,QAAOpC,4BAAAA,MAAMqC,UAAU,CAACC,OAAO,cAAxBtC,uCAAAA,4BAA4B;wBACxCjB,gBAAgB,WAAEkB,8BAAAA,gBAAgBoC,UAAU,cAA1BpC,kDAAAA,4BAA4ByC,KAAK,uCAAI;wBACvD1D,cAAc,GAAEiB,kCAAAA,gBAAgBjB,cAAc,cAA9BiB,6CAAAA,kCAAkC,AAAC,0CAA4C,OAAHvC;wBAC5FuB,YAAAA;wBACAC,UAAU,AAAC,0CAAwDc,OAAftC,IAAG,cAAqC,OAAzBsC,MAAMqC,UAAU,CAACC,OAAO;wBAC3FnD,cAAciC;wBACdhC,aAAa8B;wBACb5B,gBAAgB6B;wBAChB5B,cAAc0B;oBAChB;oBAEA;;wBAAO;4BACLoD,OAAO;gCAAG;oCAAE1F,MAAM;oCAAiB2F,MAAMC,KAAKC,SAAS,CAAC5E;gCAAQ;;4BAChE6E,mBAAmB;gCAAE7E,QAAAA;4BAAO;wBAC9B;;;oBACOyB;oBACDC,UAAUD,AAAK,YAALA,OAAiBqD,SAAQrD,MAAMC,OAAO,GAAGc,OAAOf;oBAChEtB,OAAOsB,KAAK,CAAC,kCAAkC;wBAAEA,OAAOC;oBAAQ;oBAEhE,MAAM,IAAIiB,qBAAa,CAACC,yBAAiB,CAACmC,aAAa,EAAE,AAAC,mCAA0C,OAARrD,UAAW;wBACrGsD,OAAOvD,AAAK,YAALA,OAAiBqD,SAAQrD,MAAMuD,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1H;IACtB,OAAO;QACL2H,MAAM;QACNpF,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-csv-update.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with range-based update (no deduplication) */\n\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 { parse } from 'csv-parse';\nimport { z } from 'zod';\nimport { NATIVE_DATE_POINTER } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\n\n/** Batch size for Sheets API calls (1000 rows × avg 10 cols = 10K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n sourceUri: z.string().trim().min(1).describe('CSV file URI (file://, http://, https://)'),\n startRange: A1NotationSchema.default('A1').describe('Top-left cell where CSV data starts (default: A1)'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How to interpret values (default USER_ENTERED = parse formulas/dates per the workbook locale; RAW = exact, date-looking CSV text stays text)'),\n sourceHasHeaders: z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Spreadsheet title'),\n spreadsheetUrl: z.string().describe('Spreadsheet URL'),\n sheetTitle: z.string().describe('Sheet title'),\n sheetUrl: z.string().describe('Sheet URL'),\n updatedRange: z.string().describe('A1 notation range that was updated'),\n updatedRows: z.number().describe('Number of rows updated'),\n updatedColumns: z.number().describe('Number of columns updated'),\n updatedCells: z.number().describe('Number of cells updated'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: `Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. ${NATIVE_DATE_POINTER}`,\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>;\n\nasync function handler({ id, gid, sourceUri, startRange, valueInputOption = 'USER_ENTERED', sourceHasHeaders }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.csv-update called', { id, gid, sourceUri, startRange, valueInputOption, sourceHasHeaders });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n\n // Find the sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? '';\n\n // Streaming CSV processing state\n let sourceHeaders: string[] = [];\n const allRows: (string | number | boolean | null)[][] = [];\n let totalCols = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser with native streaming\n const parser = readStream.pipe(\n parse({\n columns: !!sourceHasHeaders, // Parse first row as column names if source has headers\n skip_empty_lines: true,\n trim: true,\n cast: true, // Auto-convert numbers/booleans\n relax_column_count: true,\n })\n );\n\n // Stream and collect all rows (with batching for very large files)\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders.length === 0) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n totalCols = sourceHeaders.length;\n logger.info('sheets.values.csv-update source headers', { sourceHeaders, totalCols });\n }\n\n // Convert record to row array (exclude source headers from data range)\n // CSV values are strings/numbers/booleans/nulls from the parser\n const row = sourceHeaders.map((header) => (record as Record<string, string | number | boolean | null>)[header] ?? null);\n allRows.push(row);\n } else {\n // sourceHasHeaders=false: record is an array, include all rows (including first row)\n const row = record as (string | number | boolean | null)[];\n allRows.push(row);\n\n if (totalCols === 0) {\n totalCols = row.length;\n }\n }\n }\n\n if (allRows.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'CSV file is empty');\n }\n\n // Prepare data for update (all rows)\n const dataToWrite: (string | number | boolean | null)[][] = allRows;\n\n // For large datasets, use batchUpdate to write in chunks\n // This respects the 40K cell limit per request\n const batchRequests = [];\n const currentRow = startRange.match(/[A-Z]+(\\d+)/)?.[1] || '1';\n let currentRowNum = Number.parseInt(currentRow, 10);\n\n for (let i = 0; i < dataToWrite.length; i += BATCH_SIZE) {\n const batchData = dataToWrite.slice(i, i + BATCH_SIZE);\n const batchRange = `${sheetTitle}!${startRange.match(/[A-Z]+/)?.[0]}${currentRowNum}`;\n\n batchRequests.push({\n range: batchRange,\n values: batchData,\n });\n\n currentRowNum += batchData.length;\n }\n\n logger.info('sheets.values.csv-update batching', { totalBatches: batchRequests.length, batchSize: BATCH_SIZE });\n\n // Execute batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchRequests,\n },\n });\n\n const totalUpdatedCells = batchUpdateResponse.data.totalUpdatedCells || 0;\n const totalUpdatedRows = batchUpdateResponse.data.totalUpdatedRows || 0;\n const totalUpdatedColumns = batchUpdateResponse.data.totalUpdatedColumns || 0;\n const firstUpdatedRange = batchUpdateResponse.data.responses?.[0]?.updatedRange || `${sheetTitle}!${startRange}`;\n\n logger.info('sheets.values.csv-update completed', { id, gid: sheet.properties.sheetId, updatedRange: firstUpdatedRange, updatedRows: totalUpdatedRows, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheet.properties.sheetId ?? ''),\n spreadsheetTitle: spreadsheetData.properties?.title ?? '',\n spreadsheetUrl: spreadsheetData.spreadsheetUrl ?? `https://docs.google.com/spreadsheets/d/${id}`,\n sheetTitle,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheet.properties.sheetId}`,\n updatedRange: firstUpdatedRange,\n updatedRows: totalUpdatedRows,\n updatedColumns: totalUpdatedColumns,\n updatedCells: totalUpdatedCells,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values.csv-update error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error updating values from CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-csv-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","BATCH_SIZE","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","sourceUri","string","trim","min","describe","startRange","A1NotationSchema","default","valueInputOption","enum","sourceHasHeaders","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRange","updatedRows","number","updatedColumns","updatedCells","outputSchema","discriminatedUnion","config","description","NATIVE_DATE_POINTER","result","handler","extra","logger","sheet","spreadsheetData","batchUpdateResponse","sheets","spreadsheetResponse","sourceHeaders","allRows","totalCols","readStream","parser","dataToWrite","batchRequests","currentRow","currentRowNum","i","batchData","batchRange","totalUpdatedCells","totalUpdatedRows","totalUpdatedColumns","firstUpdatedRange","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","getCsvReadStream","pipe","parse","columns","skip_empty_lines","cast","relax_column_count","record","length","Object","keys","row","map","header","push","match","Number","parseInt","slice","range","values","totalBatches","batchSize","batchUpdate","requestBody","responses","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":"AAAA,gFAAgF;;;;+BAkMhF;;;eAAwBA;;;sBAhMY;2BAEZ;sBAKyB;wBAC3B;mBACJ;2BACkB;4BACT;uBACgF;8BAC1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AATjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAWR,gGAAgG,GAChG,IAAME,aAAa;AAEnB,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,WAAWN,MAAC,CAACO,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,YAAYC,yBAAgB,CAACC,OAAO,CAAC,MAAMH,QAAQ,CAAC;IACpDI,kBAAkBd,MAAC,CAACe,IAAI,CAAC;QAAC;QAAO;KAAe,EAAEF,OAAO,CAAC,gBAAgBH,QAAQ,CAAC;IACnFM,kBAAkBhB,MAAC,CAACiB,OAAO,GAAGJ,OAAO,CAAC,MAAMH,QAAQ,CAAC;AACvD;AAEA,IAAMQ,sBAAsBlB,MAAC,CAACC,MAAM,CAAC;IACnCkB,MAAMnB,MAAC,CAACoB,OAAO,CAAC;IAChBlB,IAAImB,4BAAmB;IACvBjB,KAAKkB,uBAAc;IACnBC,kBAAkBvB,MAAC,CAACO,MAAM,GAAGG,QAAQ,CAAC;IACtCc,gBAAgBxB,MAAC,CAACO,MAAM,GAAGG,QAAQ,CAAC;IACpCe,YAAYzB,MAAC,CAACO,MAAM,GAAGG,QAAQ,CAAC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;gCAAG;oCAAE3F,MAAM;oCAAiB4F,MAAMC,KAAKC,SAAS,CAAC5E;gCAAQ;;4BAChE6E,mBAAmB;gCAAE7E,QAAAA;4BAAO;wBAC9B;;;oBACOyB;oBACDC,UAAUD,AAAK,YAALA,OAAiBqD,SAAQrD,MAAMC,OAAO,GAAGc,OAAOf;oBAChEtB,OAAOsB,KAAK,CAAC,kCAAkC;wBAAEA,OAAOC;oBAAQ;oBAEhE,MAAM,IAAIiB,qBAAa,CAACC,yBAAiB,CAACmC,aAAa,EAAE,AAAC,mCAA0C,OAARrD,UAAW;wBACrGsD,OAAOvD,AAAK,YAALA,OAAiBqD,SAAQrD,MAAMuD,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS3H;IACtB,OAAO;QACL4H,MAAM;QACNrF,QAAAA;QACAI,SAAAA;IACF;AACF"}
@@ -13,8 +13,8 @@ declare const inputSchema: z.ZodObject<{
13
13
  values: z.ZodOptional<z.ZodBoolean>;
14
14
  a1s: z.ZodOptional<z.ZodBoolean>;
15
15
  render: z.ZodOptional<z.ZodEnum<{
16
- FORMATTED_VALUE: "FORMATTED_VALUE";
17
16
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
17
+ FORMATTED_VALUE: "FORMATTED_VALUE";
18
18
  FORMULA: "FORMULA";
19
19
  }>>;
20
20
  matchCase: z.ZodOptional<z.ZodBoolean>;
@@ -49,8 +49,8 @@ export default function createTool(): {
49
49
  values: z.ZodOptional<z.ZodBoolean>;
50
50
  a1s: z.ZodOptional<z.ZodBoolean>;
51
51
  render: z.ZodOptional<z.ZodEnum<{
52
- FORMATTED_VALUE: "FORMATTED_VALUE";
53
52
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
53
+ FORMATTED_VALUE: "FORMATTED_VALUE";
54
54
  FORMULA: "FORMULA";
55
55
  }>>;
56
56
  matchCase: z.ZodOptional<z.ZodBoolean>;
@@ -13,8 +13,8 @@ declare const inputSchema: z.ZodObject<{
13
13
  values: z.ZodOptional<z.ZodBoolean>;
14
14
  a1s: z.ZodOptional<z.ZodBoolean>;
15
15
  render: z.ZodOptional<z.ZodEnum<{
16
- FORMATTED_VALUE: "FORMATTED_VALUE";
17
16
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
17
+ FORMATTED_VALUE: "FORMATTED_VALUE";
18
18
  FORMULA: "FORMULA";
19
19
  }>>;
20
20
  matchCase: z.ZodOptional<z.ZodBoolean>;
@@ -49,8 +49,8 @@ export default function createTool(): {
49
49
  values: z.ZodOptional<z.ZodBoolean>;
50
50
  a1s: z.ZodOptional<z.ZodBoolean>;
51
51
  render: z.ZodOptional<z.ZodEnum<{
52
- FORMATTED_VALUE: "FORMATTED_VALUE";
53
52
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
53
+ FORMATTED_VALUE: "FORMATTED_VALUE";
54
54
  FORMULA: "FORMULA";
55
55
  }>>;
56
56
  matchCase: z.ZodOptional<z.ZodBoolean>;
@@ -12,6 +12,7 @@ var _sheets = require("@googleapis/sheets");
12
12
  var _oauthgoogle = require("@mcp-z/oauth-google");
13
13
  var _server = require("@mcp-z/server");
14
14
  var _zod = require("zod");
15
+ var _constantsts = require("../../constants.js");
15
16
  var _googleauthts = require("../../lib/google-auth.js");
16
17
  var _indexts = require("../../schemas/index.js");
17
18
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
@@ -198,7 +199,7 @@ var inputSchema = _zod.z.object({
198
199
  'FORMATTED_VALUE',
199
200
  'UNFORMATTED_VALUE',
200
201
  'FORMULA'
201
- ]).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.'),
202
+ ]).optional().describe(_constantsts.RENDER_DESCRIPTION),
202
203
  matchCase: _zod.z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).')
203
204
  });
204
205
  var successBranchSchema = _zod.z.object({
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import { 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 { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Helper to convert column index to letter (0 = A, 1 = B, etc.)\nfunction columnIndexToLetter(index: number): string {\n let letter = '';\n let num = index + 1;\n while (num > 0) {\n const remainder = (num - 1) % 26;\n letter = String.fromCharCode(65 + remainder) + letter;\n num = Math.floor((num - 1) / 26);\n }\n return letter;\n}\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n query: z.coerce.string().trim().optional().describe('Text to search for in sheet cells. If empty, returns all data at specified granularity.'),\n select: z.enum(['cells', 'rows', 'columns']).describe('Granularity: cells (individual matches), rows (full matching rows), columns (columns with matching headers)'),\n values: z.boolean().optional().describe('Include cell values in response'),\n a1s: z.boolean().optional().describe('Include A1 notation references in response'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.'),\n matchCase: z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n count: z.number().int().nonnegative().describe('Number of matches found'),\n a1s: z.array(z.string()).optional().describe('A1 notation references for matches (e.g., \"B5\", \"A5:D5\", \"B:B\")'),\n values: z\n .array(z.union([z.array(SheetCellSchema), SheetCellSchema]))\n .optional()\n .describe('Cell values for matches (arrays for rows/columns, single values for cells)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search spreadsheet and return matches at cell, row, or column granularity. 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>;\n\nasync function handler({ id, gid, query, select, values = false, a1s = false, render, matchCase = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-search called', { id, gid, query, select, values, a1s, render, matchCase });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details including grid dimensions\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.values-search sheet not found', { id, gid, query });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Use actual sheet dimensions from gridProperties, with sensible defaults\n // Google Sheets default for new sheets is 1000 rows x 26 columns\n const rowCount = sheet.properties?.gridProperties?.rowCount ?? 1000;\n const columnCount = sheet.properties?.gridProperties?.columnCount ?? 26;\n const endColumn = columnIndexToLetter(columnCount - 1);\n const fullRange = `${sheetTitle}!A1:${endColumn}${rowCount}`;\n\n logger.debug?.('sheets.values-search fetching range', { fullRange, rowCount, columnCount });\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n const res = response.data;\n const allRows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n // Prepare query for matching (case-insensitive by default)\n const searchQuery = query ? (matchCase ? query : query.toLowerCase()) : null;\n\n let count = 0;\n const a1Array: string[] = [];\n const valuesArray: (string | number | boolean | null | (string | number | boolean | null)[])[] = [];\n\n // Helper to check if a cell matches the query\n const cellMatches = (cell: string | number | boolean | null): boolean => {\n if (!searchQuery) return true; // If no query, match all\n if (typeof cell !== 'string') return false;\n const cellValue = matchCase ? cell : cell.toLowerCase();\n return cellValue.includes(searchQuery);\n };\n\n if (select === 'cells') {\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n for (let colIdx = 0; colIdx < row.length; colIdx++) {\n const cell = row[colIdx];\n if (cellMatches(cell)) {\n count++;\n if (a1s) {\n const colLetter = columnIndexToLetter(colIdx);\n const rowNum = rowIdx + 1;\n a1Array.push(`${colLetter}${rowNum}`);\n }\n if (values) {\n valuesArray.push(cell ?? null);\n }\n }\n }\n }\n } else if (select === 'rows') {\n const matchingRows: number[] = [];\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n const matches = row.some((cell) => cellMatches(cell));\n if (matches) {\n matchingRows.push(rowIdx);\n }\n }\n\n count = matchingRows.length;\n for (const rowIdx of matchingRows) {\n const row = allRows[rowIdx];\n if (!row) continue; // Skip if row is undefined\n const rowNum = rowIdx + 1;\n\n if (a1s) {\n const colEnd = columnIndexToLetter(Math.max(0, row.length - 1));\n a1Array.push(`A${rowNum}:${colEnd}${rowNum}`);\n }\n if (values) {\n valuesArray.push(row);\n }\n }\n } else if (select === 'columns') {\n const headerRow = allRows[0] || [];\n const matchingCols: number[] = [];\n\n for (let colIdx = 0; colIdx < headerRow.length; colIdx++) {\n const header = headerRow[colIdx];\n if (cellMatches(header)) {\n matchingCols.push(colIdx);\n }\n }\n\n count = matchingCols.length;\n for (const colIdx of matchingCols) {\n const colLetter = columnIndexToLetter(colIdx);\n\n if (a1s) {\n a1Array.push(`${colLetter}:${colLetter}`);\n }\n if (values) {\n const columnValues = allRows.map((row) => (row && row[colIdx] !== undefined ? row[colIdx] : null));\n valuesArray.push(columnValues);\n }\n }\n }\n\n logger.info('sheets.values-search results', { count, select, hasA1s: a1s, hasValues: values });\n\n const result: Output = {\n type: 'success' as const,\n count,\n ...(a1s && a1Array.length > 0 && { a1s: a1Array }),\n ...(values && valuesArray.length > 0 && { values: valuesArray }),\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values-search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching spreadsheet: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","columnIndexToLetter","index","letter","num","remainder","String","fromCharCode","Math","floor","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","query","coerce","string","trim","optional","describe","select","enum","values","boolean","a1s","render","matchCase","successBranchSchema","type","literal","count","number","int","nonnegative","array","union","SheetCellSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetResponse","sheet","sheets","sheetTitle","rowCount","columnCount","endColumn","fullRange","response","res","allRows","searchQuery","a1Array","valuesArray","cellMatches","rowIdx","row","colIdx","cell","colLetter","rowNum","matchingRows","matches","colEnd","headerRow","matchingCols","header","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","gridProperties","debug","range","valueRenderOption","Array","isArray","toLowerCase","cellValue","includes","length","push","some","max","columnValues","map","undefined","hasA1s","hasValues","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","name"],"mappings":";;;;+BA8MA;;;eAAwBA;;;sBA9MY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBA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e,SAASjH;IACtB,OAAO;QACL4H,MAAM;QACNhF,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import { 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 { RENDER_DESCRIPTION } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Helper to convert column index to letter (0 = A, 1 = B, etc.)\nfunction columnIndexToLetter(index: number): string {\n let letter = '';\n let num = index + 1;\n while (num > 0) {\n const remainder = (num - 1) % 26;\n letter = String.fromCharCode(65 + remainder) + letter;\n num = Math.floor((num - 1) / 26);\n }\n return letter;\n}\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n query: z.coerce.string().trim().optional().describe('Text to search for in sheet cells. If empty, returns all data at specified granularity.'),\n select: z.enum(['cells', 'rows', 'columns']).describe('Granularity: cells (individual matches), rows (full matching rows), columns (columns with matching headers)'),\n values: z.boolean().optional().describe('Include cell values in response'),\n a1s: z.boolean().optional().describe('Include A1 notation references in response'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe(RENDER_DESCRIPTION),\n matchCase: z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n count: z.number().int().nonnegative().describe('Number of matches found'),\n a1s: z.array(z.string()).optional().describe('A1 notation references for matches (e.g., \"B5\", \"A5:D5\", \"B:B\")'),\n values: z\n .array(z.union([z.array(SheetCellSchema), SheetCellSchema]))\n .optional()\n .describe('Cell values for matches (arrays for rows/columns, single values for cells)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search spreadsheet and return matches at cell, row, or column granularity. 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>;\n\nasync function handler({ id, gid, query, select, values = false, a1s = false, render, matchCase = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-search called', { id, gid, query, select, values, a1s, render, matchCase });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details including grid dimensions\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.values-search sheet not found', { id, gid, query });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Use actual sheet dimensions from gridProperties, with sensible defaults\n // Google Sheets default for new sheets is 1000 rows x 26 columns\n const rowCount = sheet.properties?.gridProperties?.rowCount ?? 1000;\n const columnCount = sheet.properties?.gridProperties?.columnCount ?? 26;\n const endColumn = columnIndexToLetter(columnCount - 1);\n const fullRange = `${sheetTitle}!A1:${endColumn}${rowCount}`;\n\n logger.debug?.('sheets.values-search fetching range', { fullRange, rowCount, columnCount });\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n const res = response.data;\n const allRows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n // Prepare query for matching (case-insensitive by default)\n const searchQuery = query ? (matchCase ? query : query.toLowerCase()) : null;\n\n let count = 0;\n const a1Array: string[] = [];\n const valuesArray: (string | number | boolean | null | (string | number | boolean | null)[])[] = [];\n\n // Helper to check if a cell matches the query\n const cellMatches = (cell: string | number | boolean | null): boolean => {\n if (!searchQuery) return true; // If no query, match all\n if (typeof cell !== 'string') return false;\n const cellValue = matchCase ? cell : cell.toLowerCase();\n return cellValue.includes(searchQuery);\n };\n\n if (select === 'cells') {\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n for (let colIdx = 0; colIdx < row.length; colIdx++) {\n const cell = row[colIdx];\n if (cellMatches(cell)) {\n count++;\n if (a1s) {\n const colLetter = columnIndexToLetter(colIdx);\n const rowNum = rowIdx + 1;\n a1Array.push(`${colLetter}${rowNum}`);\n }\n if (values) {\n valuesArray.push(cell ?? null);\n }\n }\n }\n }\n } else if (select === 'rows') {\n const matchingRows: number[] = [];\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n const matches = row.some((cell) => cellMatches(cell));\n if (matches) {\n matchingRows.push(rowIdx);\n }\n }\n\n count = matchingRows.length;\n for (const rowIdx of matchingRows) {\n const row = allRows[rowIdx];\n if (!row) continue; // Skip if row is undefined\n const rowNum = rowIdx + 1;\n\n if (a1s) {\n const colEnd = columnIndexToLetter(Math.max(0, row.length - 1));\n a1Array.push(`A${rowNum}:${colEnd}${rowNum}`);\n }\n if (values) {\n valuesArray.push(row);\n }\n }\n } else if (select === 'columns') {\n const headerRow = allRows[0] || [];\n const matchingCols: number[] = [];\n\n for (let colIdx = 0; colIdx < headerRow.length; colIdx++) {\n const header = headerRow[colIdx];\n if (cellMatches(header)) {\n matchingCols.push(colIdx);\n }\n }\n\n count = matchingCols.length;\n for (const colIdx of matchingCols) {\n const colLetter = columnIndexToLetter(colIdx);\n\n if (a1s) {\n a1Array.push(`${colLetter}:${colLetter}`);\n }\n if (values) {\n const columnValues = allRows.map((row) => (row && row[colIdx] !== undefined ? row[colIdx] : null));\n valuesArray.push(columnValues);\n }\n }\n }\n\n logger.info('sheets.values-search results', { count, select, hasA1s: a1s, hasValues: values });\n\n const result: Output = {\n type: 'success' as const,\n count,\n ...(a1s && a1Array.length > 0 && { a1s: a1Array }),\n ...(values && valuesArray.length > 0 && { values: valuesArray }),\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values-search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching spreadsheet: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","columnIndexToLetter","index","letter","num","remainder","String","fromCharCode","Math","floor","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","query","coerce","string","trim","optional","describe","select","enum","values","boolean","a1s","render","RENDER_DESCRIPTION","matchCase","successBranchSchema","type","literal","count","number","int","nonnegative","array","union","SheetCellSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetResponse","sheet","sheets","sheetTitle","rowCount","columnCount","endColumn","fullRange","response","res","allRows","searchQuery","a1Array","valuesArray","cellMatches","rowIdx","row","colIdx","cell","colLetter","rowNum","matchingRows","matches","colEnd","headerRow","matchingCols","header","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","gridProperties","debug","range","valueRenderOption","Array","isArray","toLowerCase","cellValue","includes","length","push","some","max","columnValues","map","undefined","hasA1s","hasValues","content","text","JSON","stringify","structuredContent","Error","InternalError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wBAClG6C,OAAO9C,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAM8C,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASlH;IACtB,OAAO;QACL6H,MAAM;QACNhF,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -3,6 +3,7 @@ export declare const SpreadsheetRefSchema: z.ZodString;
3
3
  export declare const SheetRefSchema: z.ZodString;
4
4
  export declare const SpreadsheetIdSchema: z.ZodString;
5
5
  export declare const SheetGidSchema: z.ZodCoercedString<unknown>;
6
+ export declare const StrictSheetGidSchema: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<string, string | number>>;
6
7
  export declare const SpreadsheetIdOutput: z.ZodString;
7
8
  export declare const SheetGidOutput: z.ZodString;
8
9
  export declare const SheetCellSchema: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodLiteral<number>, z.ZodLiteral<number>, z.ZodBoolean, z.ZodNull]>;
@@ -3,6 +3,7 @@ export declare const SpreadsheetRefSchema: z.ZodString;
3
3
  export declare const SheetRefSchema: z.ZodString;
4
4
  export declare const SpreadsheetIdSchema: z.ZodString;
5
5
  export declare const SheetGidSchema: z.ZodCoercedString<unknown>;
6
+ export declare const StrictSheetGidSchema: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<string, string | number>>;
6
7
  export declare const SpreadsheetIdOutput: z.ZodString;
7
8
  export declare const SheetGidOutput: z.ZodString;
8
9
  export declare const SheetCellSchema: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodLiteral<number>, z.ZodLiteral<number>, z.ZodBoolean, z.ZodNull]>;
@@ -35,6 +35,9 @@ _export(exports, {
35
35
  },
36
36
  get SpreadsheetRefSchema () {
37
37
  return SpreadsheetRefSchema;
38
+ },
39
+ get StrictSheetGidSchema () {
40
+ return StrictSheetGidSchema;
38
41
  }
39
42
  });
40
43
  var _zod = require("zod");
@@ -45,6 +48,19 @@ var SPREADSHEET_ID_DESC = 'Spreadsheet ID (from URL d/{id})';
45
48
  var SHEET_ID_DESC = 'Sheet ID (from URL gid={gid})';
46
49
  var SpreadsheetIdSchema = _zod.z.string().min(1).describe(SPREADSHEET_ID_DESC);
47
50
  var SheetGidSchema = _zod.z.coerce.string().min(1).describe(SHEET_ID_DESC);
51
+ // Strict sheet ID: a non-negative integer number or a string of digits (gid 0 and "0" both work).
52
+ // Unlike SheetGidSchema it does not coerce, so null, undefined, booleans, negatives, decimals and
53
+ // non-digit strings are rejected instead of becoming "null", "undefined", "true", etc.
54
+ // Sheet IDs are int32, so values above 2147483647 are rejected (keeps Number(gid) exact).
55
+ var MAX_SHEET_GID = 2147483647;
56
+ var StrictSheetGidSchema = _zod.z.union([
57
+ _zod.z.number().int().nonnegative().max(MAX_SHEET_GID),
58
+ _zod.z.string().regex(/^\d+$/, 'Sheet ID must be a non-negative integer').refine(function(value) {
59
+ return Number(value) <= MAX_SHEET_GID;
60
+ }, "Sheet ID must be at most ".concat(MAX_SHEET_GID))
61
+ ]).transform(function(value) {
62
+ return String(typeof value === 'number' ? value : Number(value));
63
+ }).describe(SHEET_ID_DESC);
48
64
  var SpreadsheetIdOutput = _zod.z.string().describe(SPREADSHEET_ID_DESC);
49
65
  var SheetGidOutput = _zod.z.string().describe(SHEET_ID_DESC);
50
66
  var SheetCellSchema = _zod.z.union([