@mcp-z/mcp-sheets 1.0.7 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/README.md +3 -2
  2. package/dist/cjs/constants.js.map +1 -1
  3. package/dist/cjs/index.js.map +1 -1
  4. package/dist/cjs/lib/create-store.js.map +1 -1
  5. package/dist/cjs/mcp/index.js.map +1 -1
  6. package/dist/cjs/mcp/prompts/a1-notation.js +1 -1
  7. package/dist/cjs/mcp/prompts/a1-notation.js.map +1 -1
  8. package/dist/cjs/mcp/prompts/index.js.map +1 -1
  9. package/dist/cjs/mcp/resources/index.js.map +1 -1
  10. package/dist/cjs/mcp/resources/spreadsheet.js +1 -1
  11. package/dist/cjs/mcp/resources/spreadsheet.js.map +1 -1
  12. package/dist/cjs/mcp/tools/cells-format.js +4 -2
  13. package/dist/cjs/mcp/tools/cells-format.js.map +1 -1
  14. package/dist/cjs/mcp/tools/chart-create.js +4 -2
  15. package/dist/cjs/mcp/tools/chart-create.js.map +1 -1
  16. package/dist/cjs/mcp/tools/columns-get.js +1 -0
  17. package/dist/cjs/mcp/tools/columns-get.js.map +1 -1
  18. package/dist/cjs/mcp/tools/columns-update.js +1 -0
  19. package/dist/cjs/mcp/tools/columns-update.js.map +1 -1
  20. package/dist/cjs/mcp/tools/csv-get-columns.js +1 -0
  21. package/dist/cjs/mcp/tools/csv-get-columns.js.map +1 -1
  22. package/dist/cjs/mcp/tools/dimensions-batch-update.js +1 -0
  23. package/dist/cjs/mcp/tools/dimensions-batch-update.js.map +1 -1
  24. package/dist/cjs/mcp/tools/dimensions-move.js +1 -0
  25. package/dist/cjs/mcp/tools/dimensions-move.js.map +1 -1
  26. package/dist/cjs/mcp/tools/index.d.cts +1 -0
  27. package/dist/cjs/mcp/tools/index.d.ts +1 -0
  28. package/dist/cjs/mcp/tools/index.js +4 -0
  29. package/dist/cjs/mcp/tools/index.js.map +1 -1
  30. package/dist/cjs/mcp/tools/lib/dimension-operations.d.cts +2 -2
  31. package/dist/cjs/mcp/tools/lib/dimension-operations.d.ts +2 -2
  32. package/dist/cjs/mcp/tools/lib/dimension-operations.js.map +1 -1
  33. package/dist/cjs/mcp/tools/rows-append.js +1 -0
  34. package/dist/cjs/mcp/tools/rows-append.js.map +1 -1
  35. package/dist/cjs/mcp/tools/rows-csv-append.js +2 -1
  36. package/dist/cjs/mcp/tools/rows-csv-append.js.map +1 -1
  37. package/dist/cjs/mcp/tools/rows-get.js +1 -0
  38. package/dist/cjs/mcp/tools/rows-get.js.map +1 -1
  39. package/dist/cjs/mcp/tools/sheet-copy-to.js +1 -0
  40. package/dist/cjs/mcp/tools/sheet-copy-to.js.map +1 -1
  41. package/dist/cjs/mcp/tools/sheet-copy.js +1 -0
  42. package/dist/cjs/mcp/tools/sheet-copy.js.map +1 -1
  43. package/dist/cjs/mcp/tools/sheet-create.js +1 -0
  44. package/dist/cjs/mcp/tools/sheet-create.js.map +1 -1
  45. package/dist/cjs/mcp/tools/sheet-delete.js +1 -0
  46. package/dist/cjs/mcp/tools/sheet-delete.js.map +1 -1
  47. package/dist/cjs/mcp/tools/sheet-find.js +1 -0
  48. package/dist/cjs/mcp/tools/sheet-find.js.map +1 -1
  49. package/dist/cjs/mcp/tools/sheet-rename.js +1 -0
  50. package/dist/cjs/mcp/tools/sheet-rename.js.map +1 -1
  51. package/dist/cjs/mcp/tools/spreadsheet-copy.js +1 -0
  52. package/dist/cjs/mcp/tools/spreadsheet-copy.js.map +1 -1
  53. package/dist/cjs/mcp/tools/spreadsheet-create.js +1 -0
  54. package/dist/cjs/mcp/tools/spreadsheet-create.js.map +1 -1
  55. package/dist/cjs/mcp/tools/spreadsheet-find.js +1 -0
  56. package/dist/cjs/mcp/tools/spreadsheet-find.js.map +1 -1
  57. package/dist/cjs/mcp/tools/spreadsheet-rename.js +1 -0
  58. package/dist/cjs/mcp/tools/spreadsheet-rename.js.map +1 -1
  59. package/dist/cjs/mcp/tools/validation-set.js +1 -0
  60. package/dist/cjs/mcp/tools/validation-set.js.map +1 -1
  61. package/dist/cjs/mcp/tools/values-batch-update.d.cts +1 -1
  62. package/dist/cjs/mcp/tools/values-batch-update.d.ts +1 -1
  63. package/dist/cjs/mcp/tools/values-batch-update.js +2 -1
  64. package/dist/cjs/mcp/tools/values-batch-update.js.map +1 -1
  65. package/dist/cjs/mcp/tools/values-clear.js +1 -0
  66. package/dist/cjs/mcp/tools/values-clear.js.map +1 -1
  67. package/dist/cjs/mcp/tools/values-csv-update.js +1 -0
  68. package/dist/cjs/mcp/tools/values-csv-update.js.map +1 -1
  69. package/dist/cjs/mcp/tools/values-markdown-update.d.cts +76 -0
  70. package/dist/cjs/mcp/tools/values-markdown-update.d.ts +76 -0
  71. package/dist/cjs/mcp/tools/values-markdown-update.js +413 -0
  72. package/dist/cjs/mcp/tools/values-markdown-update.js.map +1 -0
  73. package/dist/cjs/mcp/tools/values-replace.js +1 -0
  74. package/dist/cjs/mcp/tools/values-replace.js.map +1 -1
  75. package/dist/cjs/mcp/tools/values-search.js +2 -1
  76. package/dist/cjs/mcp/tools/values-search.js.map +1 -1
  77. package/dist/cjs/schemas/index.js.map +1 -1
  78. package/dist/cjs/setup/config.js.map +1 -1
  79. package/dist/cjs/setup/http.js +1 -1
  80. package/dist/cjs/setup/http.js.map +1 -1
  81. package/dist/cjs/setup/index.js.map +1 -1
  82. package/dist/cjs/setup/oauth-google.js +3 -2
  83. package/dist/cjs/setup/oauth-google.js.map +1 -1
  84. package/dist/cjs/setup/runtime.d.cts +1 -1
  85. package/dist/cjs/setup/runtime.d.ts +1 -1
  86. package/dist/cjs/setup/runtime.js +1 -1
  87. package/dist/cjs/setup/runtime.js.map +1 -1
  88. package/dist/cjs/setup/stdio.js +1 -1
  89. package/dist/cjs/setup/stdio.js.map +1 -1
  90. package/dist/cjs/spreadsheet/column-utilities.js.map +1 -1
  91. package/dist/cjs/spreadsheet/csv-streaming.js.map +1 -1
  92. package/dist/cjs/spreadsheet/data-operations.js +4 -3
  93. package/dist/cjs/spreadsheet/data-operations.js.map +1 -1
  94. package/dist/cjs/spreadsheet/deduplication-utils.js.map +1 -1
  95. package/dist/cjs/spreadsheet/markdown-runs.d.cts +67 -0
  96. package/dist/cjs/spreadsheet/markdown-runs.d.ts +67 -0
  97. package/dist/cjs/spreadsheet/markdown-runs.js +441 -0
  98. package/dist/cjs/spreadsheet/markdown-runs.js.map +1 -0
  99. package/dist/cjs/spreadsheet/range-operations.d.cts +1 -1
  100. package/dist/cjs/spreadsheet/range-operations.d.ts +1 -1
  101. package/dist/cjs/spreadsheet/range-operations.js.map +1 -1
  102. package/dist/cjs/spreadsheet/sheet-operations.d.cts +1 -1
  103. package/dist/cjs/spreadsheet/sheet-operations.d.ts +1 -1
  104. package/dist/cjs/spreadsheet/sheet-operations.js +1 -1
  105. package/dist/cjs/spreadsheet/sheet-operations.js.map +1 -1
  106. package/dist/cjs/spreadsheet/spreadsheet-management.d.cts +8 -8
  107. package/dist/cjs/spreadsheet/spreadsheet-management.d.ts +8 -8
  108. package/dist/cjs/spreadsheet/spreadsheet-management.js.map +1 -1
  109. package/dist/esm/constants.js.map +1 -1
  110. package/dist/esm/index.js.map +1 -1
  111. package/dist/esm/lib/create-store.js.map +1 -1
  112. package/dist/esm/mcp/index.js.map +1 -1
  113. package/dist/esm/mcp/prompts/a1-notation.js.map +1 -1
  114. package/dist/esm/mcp/prompts/index.js.map +1 -1
  115. package/dist/esm/mcp/resources/index.js.map +1 -1
  116. package/dist/esm/mcp/resources/spreadsheet.js.map +1 -1
  117. package/dist/esm/mcp/tools/cells-format.js +3 -2
  118. package/dist/esm/mcp/tools/cells-format.js.map +1 -1
  119. package/dist/esm/mcp/tools/chart-create.js +3 -2
  120. package/dist/esm/mcp/tools/chart-create.js.map +1 -1
  121. package/dist/esm/mcp/tools/columns-get.js.map +1 -1
  122. package/dist/esm/mcp/tools/columns-update.js.map +1 -1
  123. package/dist/esm/mcp/tools/csv-get-columns.js.map +1 -1
  124. package/dist/esm/mcp/tools/dimensions-batch-update.js.map +1 -1
  125. package/dist/esm/mcp/tools/dimensions-move.js.map +1 -1
  126. package/dist/esm/mcp/tools/index.d.ts +1 -0
  127. package/dist/esm/mcp/tools/index.js +1 -0
  128. package/dist/esm/mcp/tools/index.js.map +1 -1
  129. package/dist/esm/mcp/tools/lib/dimension-operations.d.ts +2 -2
  130. package/dist/esm/mcp/tools/lib/dimension-operations.js.map +1 -1
  131. package/dist/esm/mcp/tools/rows-append.js.map +1 -1
  132. package/dist/esm/mcp/tools/rows-csv-append.js.map +1 -1
  133. package/dist/esm/mcp/tools/rows-get.js.map +1 -1
  134. package/dist/esm/mcp/tools/sheet-copy-to.js.map +1 -1
  135. package/dist/esm/mcp/tools/sheet-copy.js.map +1 -1
  136. package/dist/esm/mcp/tools/sheet-create.js.map +1 -1
  137. package/dist/esm/mcp/tools/sheet-delete.js.map +1 -1
  138. package/dist/esm/mcp/tools/sheet-find.js.map +1 -1
  139. package/dist/esm/mcp/tools/sheet-rename.js.map +1 -1
  140. package/dist/esm/mcp/tools/spreadsheet-copy.js.map +1 -1
  141. package/dist/esm/mcp/tools/spreadsheet-create.js.map +1 -1
  142. package/dist/esm/mcp/tools/spreadsheet-find.js.map +1 -1
  143. package/dist/esm/mcp/tools/spreadsheet-rename.js.map +1 -1
  144. package/dist/esm/mcp/tools/validation-set.js.map +1 -1
  145. package/dist/esm/mcp/tools/values-batch-update.d.ts +1 -1
  146. package/dist/esm/mcp/tools/values-batch-update.js +1 -1
  147. package/dist/esm/mcp/tools/values-batch-update.js.map +1 -1
  148. package/dist/esm/mcp/tools/values-clear.js.map +1 -1
  149. package/dist/esm/mcp/tools/values-csv-update.js.map +1 -1
  150. package/dist/esm/mcp/tools/values-markdown-update.d.ts +76 -0
  151. package/dist/esm/mcp/tools/values-markdown-update.js +216 -0
  152. package/dist/esm/mcp/tools/values-markdown-update.js.map +1 -0
  153. package/dist/esm/mcp/tools/values-replace.js.map +1 -1
  154. package/dist/esm/mcp/tools/values-search.js.map +1 -1
  155. package/dist/esm/schemas/index.js.map +1 -1
  156. package/dist/esm/setup/config.js.map +1 -1
  157. package/dist/esm/setup/http.js.map +1 -1
  158. package/dist/esm/setup/index.js.map +1 -1
  159. package/dist/esm/setup/oauth-google.js.map +1 -1
  160. package/dist/esm/setup/runtime.d.ts +1 -1
  161. package/dist/esm/setup/runtime.js.map +1 -1
  162. package/dist/esm/setup/stdio.js.map +1 -1
  163. package/dist/esm/spreadsheet/column-utilities.js.map +1 -1
  164. package/dist/esm/spreadsheet/csv-streaming.js.map +1 -1
  165. package/dist/esm/spreadsheet/data-operations.js.map +1 -1
  166. package/dist/esm/spreadsheet/deduplication-utils.js.map +1 -1
  167. package/dist/esm/spreadsheet/markdown-runs.d.ts +67 -0
  168. package/dist/esm/spreadsheet/markdown-runs.js +325 -0
  169. package/dist/esm/spreadsheet/markdown-runs.js.map +1 -0
  170. package/dist/esm/spreadsheet/range-operations.d.ts +1 -1
  171. package/dist/esm/spreadsheet/range-operations.js.map +1 -1
  172. package/dist/esm/spreadsheet/sheet-operations.d.ts +1 -1
  173. package/dist/esm/spreadsheet/sheet-operations.js.map +1 -1
  174. package/dist/esm/spreadsheet/spreadsheet-management.d.ts +8 -8
  175. package/dist/esm/spreadsheet/spreadsheet-management.js.map +1 -1
  176. package/dist/esm/types.js.map +1 -1
  177. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/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 type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { parse } from 'csv-parse';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\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 = google.sheets({ version: 'v4', auth: 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 McpError(ErrorCode.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 McpError(ErrorCode.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 McpError(ErrorCode.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":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","parse","google","z","A1NotationSchema","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","getCsvReadStream","BATCH_SIZE","inputSchema","object","id","gid","sourceUri","string","trim","min","describe","startRange","default","valueInputOption","enum","sourceHasHeaders","boolean","successBranchSchema","type","literal","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRange","updatedRows","number","updatedColumns","updatedCells","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","sheet","spreadsheetData","batchUpdateResponse","sheets","version","auth","authContext","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","title","sourceHeaders","allRows","totalCols","readStream","parser","pipe","columns","skip_empty_lines","cast","relax_column_count","record","length","Object","keys","row","map","header","push","dataToWrite","batchRequests","currentRow","match","currentRowNum","Number","parseInt","i","batchData","slice","batchRange","range","values","totalBatches","batchSize","batchUpdate","requestBody","totalUpdatedCells","totalUpdatedRows","totalUpdatedColumns","firstUpdatedRange","responses","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","stack","undefined","createTool","name"],"mappings":"AAAA,gFAAgF,GAGhF,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAIrC,SAASE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AACzE,SAASC,KAAK,QAAQ,YAAY;AAClC,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,gBAA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IAAI;YAChGkB;YACAC,UAAU,CAAC,uCAAuC,EAAEnB,GAAG,UAAU,EAAEkC,MAAMgB,UAAU,CAACC,OAAO,EAAE;YAC7F/B,cAAcwE;YACdvE,aAAaqE;YACbnE,gBAAgBoE;YAChBnE,cAAciE;QAChB;QAEA,OAAO;YACLK,SAAS;gBAAC;oBAAEhF,MAAM;oBAAiBiF,MAAMC,KAAKC,SAAS,CAACpE;gBAAQ;aAAE;YAClEqE,mBAAmB;gBAAErE;YAAO;QAC9B;IACF,EAAE,OAAOsE,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGnD,OAAOkD;QAChEnE,OAAOmE,KAAK,CAAC,kCAAkC;YAAEA,OAAOC;QAAQ;QAEhE,MAAM,IAAIjH,SAASD,UAAUoH,aAAa,EAAE,CAAC,gCAAgC,EAAEF,SAAS,EAAE;YACxFG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACN/E;QACAG;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/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 type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { parse } from 'csv-parse';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\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 = google.sheets({ version: 'v4', auth: 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 McpError(ErrorCode.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 McpError(ErrorCode.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 McpError(ErrorCode.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":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","parse","google","z","A1NotationSchema","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","getCsvReadStream","BATCH_SIZE","inputSchema","object","id","gid","sourceUri","string","trim","min","describe","startRange","default","valueInputOption","enum","sourceHasHeaders","boolean","successBranchSchema","type","literal","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRange","updatedRows","number","updatedColumns","updatedCells","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","sheet","spreadsheetData","batchUpdateResponse","sheets","version","auth","authContext","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","title","sourceHeaders","allRows","totalCols","readStream","parser","pipe","columns","skip_empty_lines","cast","relax_column_count","record","length","Object","keys","row","map","header","push","dataToWrite","batchRequests","currentRow","match","currentRowNum","Number","parseInt","i","batchData","slice","batchRange","range","values","totalBatches","batchSize","batchUpdate","requestBody","totalUpdatedCells","totalUpdatedRows","totalUpdatedColumns","firstUpdatedRange","responses","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","stack","undefined","createTool","name"],"mappings":"AAAA,gFAAgF,GAGhF,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAIrC,SAASE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AACzE,SAASC,KAAK,QAAQ,YAAY;AAClC,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AACpI,SAASC,gBAAgB,QAAQ,qCAAqC;AAEtE,gGAAgG,GAChG,MAAMC,aAAa;AAEnB,MAAMC,cAAcR,EAAES,MAAM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,OAAO;YACLK,SAAS;gBAAC;oBAAEhF,MAAM;oBAAiBiF,MAAMC,KAAKC,SAAS,CAACpE;gBAAQ;aAAE;YAClEqE,mBAAmB;gBAAErE;YAAO;QAC9B;IACF,EAAE,OAAOsE,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGnD,OAAOkD;QAChEnE,OAAOmE,KAAK,CAAC,kCAAkC;YAAEA,OAAOC;QAAQ;QAEhE,MAAM,IAAIjH,SAASD,UAAUoH,aAAa,EAAE,CAAC,gCAAgC,EAAEF,SAAS,EAAE;YACxFG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACN/E;QACAG;IACF;AACF"}
@@ -0,0 +1,76 @@
1
+ import type { EnrichedExtra } from '@mcp-z/oauth-google';
2
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
3
+ import { z } from 'zod';
4
+ declare const inputSchema: z.ZodObject<{
5
+ id: z.ZodString;
6
+ gid: z.ZodCoercedString<unknown>;
7
+ requests: z.ZodArray<z.ZodObject<{
8
+ cell: z.ZodString;
9
+ text: z.ZodString;
10
+ }, z.core.$strip>>;
11
+ }, z.core.$strip>;
12
+ declare const outputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
13
+ type: z.ZodLiteral<"success">;
14
+ id: z.ZodString;
15
+ gid: z.ZodString;
16
+ sheetTitle: z.ZodString;
17
+ sheetUrl: z.ZodString;
18
+ successCount: z.ZodNumber;
19
+ cells: z.ZodArray<z.ZodObject<{
20
+ cell: z.ZodString;
21
+ text: z.ZodString;
22
+ linkCount: z.ZodNumber;
23
+ }, z.core.$strip>>;
24
+ failedCells: z.ZodOptional<z.ZodArray<z.ZodObject<{
25
+ cell: z.ZodString;
26
+ error: z.ZodString;
27
+ }, z.core.$strip>>>;
28
+ }, z.core.$strip>, z.ZodObject<{
29
+ type: z.ZodLiteral<"auth_required">;
30
+ provider: z.ZodString;
31
+ message: z.ZodString;
32
+ url: z.ZodOptional<z.ZodString>;
33
+ }, z.core.$strip>], "type">;
34
+ export type Input = z.infer<typeof inputSchema>;
35
+ export type Output = z.infer<typeof outputSchema>;
36
+ declare function handler({ id, gid, requests }: Input, extra: EnrichedExtra): Promise<CallToolResult>;
37
+ export default function createTool(): {
38
+ name: string;
39
+ config: {
40
+ readonly description: "Replace cell content with text parsed from inline markdown. Supports [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~ — the only way to put MULTIPLE clickable links in one cell. Block syntax (headers, lists, tables) and other unsupported markdown is written as literal text. Writes text cells only — no formula or number coercion. For whole-cell formatting (colors, borders, number formats) use cells-format.";
41
+ readonly inputSchema: z.ZodObject<{
42
+ id: z.ZodString;
43
+ gid: z.ZodCoercedString<unknown>;
44
+ requests: z.ZodArray<z.ZodObject<{
45
+ cell: z.ZodString;
46
+ text: z.ZodString;
47
+ }, z.core.$strip>>;
48
+ }, z.core.$strip>;
49
+ readonly outputSchema: z.ZodObject<{
50
+ result: z.ZodDiscriminatedUnion<[z.ZodObject<{
51
+ type: z.ZodLiteral<"success">;
52
+ id: z.ZodString;
53
+ gid: z.ZodString;
54
+ sheetTitle: z.ZodString;
55
+ sheetUrl: z.ZodString;
56
+ successCount: z.ZodNumber;
57
+ cells: z.ZodArray<z.ZodObject<{
58
+ cell: z.ZodString;
59
+ text: z.ZodString;
60
+ linkCount: z.ZodNumber;
61
+ }, z.core.$strip>>;
62
+ failedCells: z.ZodOptional<z.ZodArray<z.ZodObject<{
63
+ cell: z.ZodString;
64
+ error: z.ZodString;
65
+ }, z.core.$strip>>>;
66
+ }, z.core.$strip>, z.ZodObject<{
67
+ type: z.ZodLiteral<"auth_required">;
68
+ provider: z.ZodString;
69
+ message: z.ZodString;
70
+ url: z.ZodOptional<z.ZodString>;
71
+ }, z.core.$strip>], "type">;
72
+ }, z.core.$strip>;
73
+ };
74
+ handler: typeof handler;
75
+ };
76
+ export {};
@@ -0,0 +1,216 @@
1
+ import { schemas } from '@mcp-z/oauth-google';
2
+ const { AuthRequiredBranchSchema } = schemas;
3
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
4
+ import { google } from 'googleapis';
5
+ import { z } from 'zod';
6
+ import { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.js';
7
+ import { buildTextFormatRuns, parseInlineMarkdown } from '../../spreadsheet/markdown-runs.js';
8
+ import { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.js';
9
+ // Input schema for a single markdown-cell request
10
+ const MarkdownCellRequestSchema = z.object({
11
+ cell: z.string().min(1).describe('Single-cell A1 reference (e.g., "I2"). Multi-cell ranges (e.g., "A1:B2") are rejected as a per-request failure.'),
12
+ text: z.string().describe('Cell content as inline markdown: [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~. Block syntax and other unsupported markdown is written as literal text.')
13
+ });
14
+ const inputSchema = z.object({
15
+ id: SpreadsheetIdSchema,
16
+ gid: SheetGidSchema,
17
+ requests: z.array(MarkdownCellRequestSchema).min(1).max(50).describe('Array of cell markdown requests. Batch multiple cells for efficiency.')
18
+ });
19
+ const successBranchSchema = z.object({
20
+ type: z.literal('success'),
21
+ id: SpreadsheetIdOutput,
22
+ gid: SheetGidOutput,
23
+ sheetTitle: z.string().describe('Title of the updated sheet'),
24
+ sheetUrl: z.string().describe('URL of the updated sheet'),
25
+ successCount: z.number().int().nonnegative().describe('Number of cells successfully written'),
26
+ cells: z.array(z.object({
27
+ cell: z.string().describe('A1 reference of the cell that was written'),
28
+ text: z.string().describe('Resolved plain text written to the cell (markdown syntax stripped/literalized)'),
29
+ linkCount: z.number().int().nonnegative().describe('Number of clickable links written into the cell')
30
+ })).describe('Cells successfully written'),
31
+ failedCells: z.array(z.object({
32
+ cell: z.string().describe('A1 reference that failed'),
33
+ error: z.string().describe('Why the cell failed (e.g., not a single-cell reference)')
34
+ })).optional().describe('Only populated if some cells failed')
35
+ });
36
+ const outputSchema = z.discriminatedUnion('type', [
37
+ successBranchSchema,
38
+ AuthRequiredBranchSchema
39
+ ]);
40
+ const config = {
41
+ description: 'Replace cell content with text parsed from inline markdown. Supports [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~ — the only way to put MULTIPLE clickable links in one cell. Block syntax (headers, lists, tables) and other unsupported markdown is written as literal text. Writes text cells only — no formula or number coercion. For whole-cell formatting (colors, borders, number formats) use cells-format.',
42
+ inputSchema,
43
+ outputSchema: z.object({
44
+ result: outputSchema
45
+ })
46
+ };
47
+ async function handler({ id, gid, requests }, extra) {
48
+ const logger = extra.logger;
49
+ logger.info('sheets.values.markdownUpdate called', {
50
+ id,
51
+ gid,
52
+ requestCount: requests.length
53
+ });
54
+ try {
55
+ var _sheet_properties_title, _sheet_properties_sheetId;
56
+ var _spreadsheetResponse_data_sheets;
57
+ const sheets = google.sheets({
58
+ version: 'v4',
59
+ auth: extra.authContext.auth
60
+ });
61
+ // Get spreadsheet and sheet info in single API call
62
+ const spreadsheetResponse = await sheets.spreadsheets.get({
63
+ spreadsheetId: id,
64
+ fields: 'sheets.properties.sheetId,sheets.properties.title'
65
+ });
66
+ // Find sheet by gid
67
+ const sheet = (_spreadsheetResponse_data_sheets = spreadsheetResponse.data.sheets) === null || _spreadsheetResponse_data_sheets === void 0 ? void 0 : _spreadsheetResponse_data_sheets.find((s)=>{
68
+ var _s_properties;
69
+ return String((_s_properties = s.properties) === null || _s_properties === void 0 ? void 0 : _s_properties.sheetId) === gid;
70
+ });
71
+ if (!(sheet === null || sheet === void 0 ? void 0 : sheet.properties)) {
72
+ logger.info('Sheet not found for markdown update', {
73
+ id,
74
+ gid,
75
+ requestCount: requests.length
76
+ });
77
+ throw new McpError(ErrorCode.InvalidParams, `Sheet not found: ${gid}`);
78
+ }
79
+ const sheetTitle = (_sheet_properties_title = sheet.properties.title) !== null && _sheet_properties_title !== void 0 ? _sheet_properties_title : gid;
80
+ // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).
81
+ const sheetId = (_sheet_properties_sheetId = sheet.properties.sheetId) !== null && _sheet_properties_sheetId !== void 0 ? _sheet_properties_sheetId : 0;
82
+ const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;
83
+ // Build one updateCells request per cell
84
+ const batchRequests = [];
85
+ const cells = [];
86
+ const failedCells = [];
87
+ for (const request of requests){
88
+ try {
89
+ // Parse A1 notation and reject anything that isn't a single cell
90
+ const rangeRef = parseA1Notation(request.cell);
91
+ if (rangeRef.type !== 'cell') {
92
+ throw new Error(`Not a single-cell reference: "${request.cell}"`);
93
+ }
94
+ const gridRange = rangeReferenceToGridRange(rangeRef, sheetId);
95
+ const parsed = parseInlineMarkdown(request.text);
96
+ const runs = buildTextFormatRuns(parsed);
97
+ batchRequests.push({
98
+ updateCells: {
99
+ range: gridRange,
100
+ rows: [
101
+ {
102
+ values: [
103
+ {
104
+ userEnteredValue: {
105
+ stringValue: parsed.text
106
+ },
107
+ textFormatRuns: runs
108
+ }
109
+ ]
110
+ }
111
+ ],
112
+ fields: 'userEnteredValue,textFormatRuns'
113
+ }
114
+ });
115
+ cells.push({
116
+ cell: request.cell,
117
+ text: parsed.text,
118
+ linkCount: parsed.linkCount
119
+ });
120
+ } catch (error) {
121
+ const message = error instanceof Error ? error.message : String(error);
122
+ logger.info('Failed to parse cell for markdown update', {
123
+ cell: request.cell,
124
+ error: message
125
+ });
126
+ failedCells.push({
127
+ cell: request.cell,
128
+ error: `Failed to parse cell: ${message}`
129
+ });
130
+ }
131
+ }
132
+ // Early return if all cells failed
133
+ if (batchRequests.length === 0) {
134
+ const result = {
135
+ type: 'success',
136
+ id,
137
+ gid: String(sheetId),
138
+ sheetTitle,
139
+ sheetUrl,
140
+ successCount: 0,
141
+ cells: [],
142
+ failedCells: failedCells.length > 0 ? failedCells : undefined
143
+ };
144
+ return {
145
+ content: [
146
+ {
147
+ type: 'text',
148
+ text: JSON.stringify(result)
149
+ }
150
+ ],
151
+ structuredContent: {
152
+ result
153
+ }
154
+ };
155
+ }
156
+ logger.info('sheets.values.markdownUpdate executing batch request', {
157
+ spreadsheetId: id,
158
+ sheetTitle,
159
+ batchRequestsCount: batchRequests.length
160
+ });
161
+ // Execute the batch update
162
+ await sheets.spreadsheets.batchUpdate({
163
+ spreadsheetId: id,
164
+ requestBody: {
165
+ requests: batchRequests
166
+ }
167
+ });
168
+ logger.info('sheets.values.markdownUpdate completed successfully', {
169
+ successCount: cells.length,
170
+ failedCount: failedCells.length
171
+ });
172
+ const result = {
173
+ type: 'success',
174
+ id,
175
+ gid: String(sheetId),
176
+ sheetTitle,
177
+ sheetUrl,
178
+ successCount: cells.length,
179
+ cells,
180
+ failedCells: failedCells.length > 0 ? failedCells : undefined
181
+ };
182
+ return {
183
+ content: [
184
+ {
185
+ type: 'text',
186
+ text: JSON.stringify(result)
187
+ }
188
+ ],
189
+ structuredContent: {
190
+ result
191
+ }
192
+ };
193
+ } catch (error) {
194
+ // Re-throw McpError as-is
195
+ if (error instanceof McpError) {
196
+ throw error;
197
+ }
198
+ const message = error instanceof Error ? error.message : String(error);
199
+ logger.error('Markdown update operation failed', {
200
+ id,
201
+ gid,
202
+ requestCount: requests.length,
203
+ error: message
204
+ });
205
+ throw new McpError(ErrorCode.InternalError, `Error writing markdown to cells: ${message}`, {
206
+ stack: error instanceof Error ? error.stack : undefined
207
+ });
208
+ }
209
+ }
210
+ export default function createTool() {
211
+ return {
212
+ name: 'values-markdown-update',
213
+ config,
214
+ handler
215
+ };
216
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-markdown-update.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google, type sheets_v4 } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { buildTextFormatRuns, parseInlineMarkdown } from '../../spreadsheet/markdown-runs.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\n// Input schema for a single markdown-cell request\nconst MarkdownCellRequestSchema = z.object({\n cell: z.string().min(1).describe('Single-cell A1 reference (e.g., \"I2\"). Multi-cell ranges (e.g., \"A1:B2\") are rejected as a per-request failure.'),\n text: z.string().describe('Cell content as inline markdown: [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~. Block syntax and other unsupported markdown is written as literal text.'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(MarkdownCellRequestSchema).min(1).max(50).describe('Array of cell markdown requests. Batch multiple cells for efficiency.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n successCount: z.number().int().nonnegative().describe('Number of cells successfully written'),\n cells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference of the cell that was written'),\n text: z.string().describe('Resolved plain text written to the cell (markdown syntax stripped/literalized)'),\n linkCount: z.number().int().nonnegative().describe('Number of clickable links written into the cell'),\n })\n )\n .describe('Cells successfully written'),\n failedCells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference that failed'),\n error: z.string().describe('Why the cell failed (e.g., not a single-cell reference)'),\n })\n )\n .optional()\n .describe('Only populated if some cells failed'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description:\n 'Replace cell content with text parsed from inline markdown. Supports [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~ — the only way to put MULTIPLE clickable links in one cell. Block syntax (headers, lists, tables) and other unsupported markdown is written as literal text. Writes text cells only — no formula or number coercion. For whole-cell formatting (colors, borders, number formats) use cells-format.',\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 }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.markdownUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: 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: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for markdown update', { id, gid, requestCount: requests.length });\n throw new McpError(ErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).\n const sheetId = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Build one updateCells request per cell\n const batchRequests: sheets_v4.Schema$Request[] = [];\n const cells: Array<{ cell: string; text: string; linkCount: number }> = [];\n const failedCells: Array<{ cell: string; error: string }> = [];\n\n for (const request of requests) {\n try {\n // Parse A1 notation and reject anything that isn't a single cell\n const rangeRef = parseA1Notation(request.cell);\n if (rangeRef.type !== 'cell') {\n throw new Error(`Not a single-cell reference: \"${request.cell}\"`);\n }\n\n const gridRange = rangeReferenceToGridRange(rangeRef, sheetId);\n const parsed = parseInlineMarkdown(request.text);\n const runs = buildTextFormatRuns(parsed);\n\n batchRequests.push({\n updateCells: {\n range: gridRange,\n rows: [\n {\n values: [\n {\n userEnteredValue: { stringValue: parsed.text },\n textFormatRuns: runs,\n },\n ],\n },\n ],\n fields: 'userEnteredValue,textFormatRuns',\n },\n });\n cells.push({ cell: request.cell, text: parsed.text, linkCount: parsed.linkCount });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse cell for markdown update', {\n cell: request.cell,\n error: message,\n });\n failedCells.push({\n cell: request.cell,\n error: `Failed to parse cell: ${message}`,\n });\n }\n }\n\n // Early return if all cells failed\n if (batchRequests.length === 0) {\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: 0,\n cells: [],\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n }\n\n logger.info('sheets.values.markdownUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchRequestsCount: batchRequests.length,\n });\n\n // Execute the batch update\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: batchRequests,\n },\n });\n\n logger.info('sheets.values.markdownUpdate completed successfully', {\n successCount: cells.length,\n failedCount: failedCells.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: cells.length,\n cells,\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n // Re-throw McpError as-is\n if (error instanceof McpError) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Markdown update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n error: message,\n });\n\n throw new McpError(ErrorCode.InternalError, `Error writing markdown to cells: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-markdown-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","buildTextFormatRuns","parseInlineMarkdown","parseA1Notation","rangeReferenceToGridRange","MarkdownCellRequestSchema","object","cell","string","min","describe","text","inputSchema","id","gid","requests","array","max","successBranchSchema","type","literal","sheetTitle","sheetUrl","successCount","number","int","nonnegative","cells","linkCount","failedCells","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","requestCount","length","sheet","spreadsheetResponse","sheets","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","title","batchRequests","request","rangeRef","Error","gridRange","parsed","runs","push","updateCells","range","rows","values","userEnteredValue","stringValue","textFormatRuns","message","undefined","content","JSON","stringify","structuredContent","batchRequestsCount","batchUpdate","requestBody","failedCount","InternalError","stack","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAIrC,SAASE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AACzE,SAASC,MAAM,QAAwB,aAAa;AACpD,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AAClH,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,qCAAqC;AAC9F,SAASC,eAAe,EAAEC,yBAAyB,QAAQ,wCAAwC;AAEnG,kDAAkD;AAClD,MAAMC,4BAA4BT,EAAEU,MAAM,CAAC;IACzCC,MAAMX,EAAEY,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACjCC,MAAMf,EAAEY,MAAM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mcp-z/mcp-sheets/src/mcp/tools/values-replace.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google, type sheets_v4 } from 'googleapis';\nimport { z } from 'zod';\nimport { A1NotationSchema, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\nconst inputSchema = z\n .object({\n id: SpreadsheetIdSchema,\n find: z.string().min(1).describe('Text or regex pattern to find'),\n replacement: z.string().describe('Replacement text. Use $1, $2 for regex capture groups. Empty string deletes matches.'),\n\n // Scope - defaults to all sheets if neither specified\n gid: SheetGidSchema.optional().describe('Limit to specific sheet. If omitted, searches all sheets.'),\n range: A1NotationSchema.optional().describe('Limit to specific A1 range within the sheet (requires gid)'),\n\n // Match options\n matchCase: z.boolean().optional().describe('Case-sensitive matching'),\n matchEntireCell: z.boolean().optional().describe('Only match entire cell content'),\n searchByRegex: z.boolean().optional().describe('Treat find as RE2 regex'),\n includeFormulas: z.boolean().optional().describe('Search within formula text'),\n })\n .refine((data) => !(data.range && !data.gid), { message: 'range requires gid' });\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n spreadsheetUrl: z.string().describe('URL of the spreadsheet'),\n occurrencesChanged: z.number().int().nonnegative().describe('Total replacements made'),\n valuesChanged: z.number().int().nonnegative().describe('Number of non-formula cells changed'),\n formulasChanged: z.number().int().nonnegative().describe('Number of formula cells changed'),\n rowsChanged: z.number().int().nonnegative().describe('Number of rows with replacements'),\n sheetsChanged: z.number().int().nonnegative().describe('Number of sheets with replacements'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Find and replace text across a spreadsheet. Searches all sheets by default, or limit with gid/range. Supports regex with capture groups ($1, $2).',\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, find, replacement, gid, range, matchCase, matchEntireCell, searchByRegex, includeFormulas }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-replace called', { id, find, replacement, gid, range });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Build FindReplaceRequest - only include defined options\n const findReplaceRequest: sheets_v4.Schema$FindReplaceRequest = {\n find,\n replacement,\n ...(matchCase !== undefined && { matchCase }),\n ...(matchEntireCell !== undefined && { matchEntireCell }),\n ...(searchByRegex !== undefined && { searchByRegex }),\n ...(includeFormulas !== undefined && { includeFormulas }),\n };\n\n // Set scope based on gid/range\n if (!gid) {\n // No gid = search all sheets\n findReplaceRequest.allSheets = true;\n } else {\n // Need to resolve sheet to get numeric sheetId\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 if (!sheet) {\n throw new McpError(ErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n // Note: sheetId can be 0 which is falsy, so check explicitly for undefined/null\n const sheetId = sheet.properties?.sheetId;\n if (sheetId === undefined || sheetId === null) {\n throw new McpError(ErrorCode.InternalError, 'Sheet properties not available');\n }\n\n if (!range) {\n // gid but no range = search specific sheet\n findReplaceRequest.sheetId = sheetId;\n } else {\n // gid + range = search specific range\n const rangeRef = parseA1Notation(range);\n findReplaceRequest.range = rangeReferenceToGridRange(rangeRef, sheetId);\n }\n }\n\n // Execute batchUpdate\n const response = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: [{ findReplace: findReplaceRequest }],\n },\n });\n\n const findReplaceResponse = response.data.replies?.[0]?.findReplace;\n const spreadsheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit`;\n\n logger.info('sheets.values-replace completed', {\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n spreadsheetUrl,\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n valuesChanged: findReplaceResponse?.valuesChanged ?? 0,\n formulasChanged: findReplaceResponse?.formulasChanged ?? 0,\n rowsChanged: findReplaceResponse?.rowsChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Replace operation failed', {\n id,\n find,\n replacement,\n gid,\n range,\n error: message,\n });\n\n throw new McpError(ErrorCode.InternalError, `Error replacing values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-replace',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","A1NotationSchema","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","parseA1Notation","rangeReferenceToGridRange","inputSchema","object","id","find","string","min","describe","replacement","gid","optional","range","matchCase","boolean","matchEntireCell","searchByRegex","includeFormulas","refine","data","message","successBranchSchema","type","literal","spreadsheetUrl","occurrencesChanged","number","int","nonnegative","valuesChanged","formulasChanged","rowsChanged","sheetsChanged","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","response","sheets","version","auth","authContext","findReplaceRequest","undefined","allSheets","spreadsheetResponse","sheet","spreadsheets","get","spreadsheetId","fields","s","String","properties","sheetId","InvalidParams","InternalError","rangeRef","batchUpdate","requestBody","requests","findReplace","findReplaceResponse","replies","content","text","JSON","stringify","structuredContent","error","Error","stack","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAIrC,SAASE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AACzE,SAASC,MAAM,QAAwB,aAAa;AACpD,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AACpH,SAASC,eAAe,EAAEC,yBAAyB,QAAQ,wCAAwC;AAEnG,MAAMC,cAAcP,EACjBQ,MAAM,CAAC;IACNC,IAAIL;IACJM,MAAMV,EAAEW,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACjCC,aAAad,EAAEW,MAAM,GAAGE,QAAQ,CAAC;IAEjC,sDAAsD;IACtDE,KAAKb,eAAec,QAAQ,GAAGH,QAAQ,CAAC;IACxCI,OAAOhB,iBAAiBe,QAAQ,GAAGH,QAAQ,CAAC;IAE5C,gBAAgB;IAChBK,WAAWlB,EAAEmB,OAAO,GAAGH,QAAQ,GAAGH,QAAQ,CAAC;IAC3CO,iBAAiBpB,EAAEmB,OAAO,GAAGH,QAAQ,GAAGH,QAAQ,CAAC;IACjDQ,eAAerB,EAAEmB,OAAO,GAAGH,QAAQ,GAAGH,QAAQ,CAAC;IAC/CS,iBAAiBtB,EAAEmB,OAAO,GAAGH,QAAQ,GAAGH,QAAQ,CAAC;AACnD,GACCU,MAAM,CAAC,CAACC,OAAS,CAAEA,CAAAA,KAAKP,KAAK,IAAI,CAACO,KAAKT,GAAG,AAAD,GAAI;IAAEU,SAAS;AAAqB;AAEhF,MAAMC,sBAAsB1B,EAAEQ,MAAM,CAAC;IACnCmB,MAAM3B,EAAE4B,O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AS6B;IACtB,OAAO;QACLC,MAAM;QACN3C;QACAG;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-replace.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google, type sheets_v4 } from 'googleapis';\nimport { z } from 'zod';\nimport { A1NotationSchema, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\nconst inputSchema = z\n .object({\n id: SpreadsheetIdSchema,\n find: z.string().min(1).describe('Text or regex pattern to find'),\n replacement: z.string().describe('Replacement text. Use $1, $2 for regex capture groups. Empty string deletes matches.'),\n\n // Scope - defaults to all sheets if neither specified\n gid: SheetGidSchema.optional().describe('Limit to specific sheet. If omitted, searches all sheets.'),\n range: A1NotationSchema.optional().describe('Limit to specific A1 range within the sheet (requires gid)'),\n\n // Match options\n matchCase: z.boolean().optional().describe('Case-sensitive matching'),\n matchEntireCell: z.boolean().optional().describe('Only match entire cell content'),\n searchByRegex: z.boolean().optional().describe('Treat find as RE2 regex'),\n includeFormulas: z.boolean().optional().describe('Search within formula text'),\n })\n .refine((data) => !(data.range && !data.gid), { message: 'range requires gid' });\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n spreadsheetUrl: z.string().describe('URL of the spreadsheet'),\n occurrencesChanged: z.number().int().nonnegative().describe('Total replacements made'),\n valuesChanged: z.number().int().nonnegative().describe('Number of non-formula cells changed'),\n formulasChanged: z.number().int().nonnegative().describe('Number of formula cells changed'),\n rowsChanged: z.number().int().nonnegative().describe('Number of rows with replacements'),\n sheetsChanged: z.number().int().nonnegative().describe('Number of sheets with replacements'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Find and replace text across a spreadsheet. Searches all sheets by default, or limit with gid/range. Supports regex with capture groups ($1, $2).',\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, find, replacement, gid, range, matchCase, matchEntireCell, searchByRegex, includeFormulas }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-replace called', { id, find, replacement, gid, range });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Build FindReplaceRequest - only include defined options\n const findReplaceRequest: sheets_v4.Schema$FindReplaceRequest = {\n find,\n replacement,\n ...(matchCase !== undefined && { matchCase }),\n ...(matchEntireCell !== undefined && { matchEntireCell }),\n ...(searchByRegex !== undefined && { searchByRegex }),\n ...(includeFormulas !== undefined && { includeFormulas }),\n };\n\n // Set scope based on gid/range\n if (!gid) {\n // No gid = search all sheets\n findReplaceRequest.allSheets = true;\n } else {\n // Need to resolve sheet to get numeric sheetId\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 if (!sheet) {\n throw new McpError(ErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n // Note: sheetId can be 0 which is falsy, so check explicitly for undefined/null\n const sheetId = sheet.properties?.sheetId;\n if (sheetId === undefined || sheetId === null) {\n throw new McpError(ErrorCode.InternalError, 'Sheet properties not available');\n }\n\n if (!range) {\n // gid but no range = search specific sheet\n findReplaceRequest.sheetId = sheetId;\n } else {\n // gid + range = search specific range\n const rangeRef = parseA1Notation(range);\n findReplaceRequest.range = rangeReferenceToGridRange(rangeRef, sheetId);\n }\n }\n\n // Execute batchUpdate\n const response = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: [{ findReplace: findReplaceRequest }],\n },\n });\n\n const findReplaceResponse = response.data.replies?.[0]?.findReplace;\n const spreadsheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit`;\n\n logger.info('sheets.values-replace completed', {\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n spreadsheetUrl,\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n valuesChanged: findReplaceResponse?.valuesChanged ?? 0,\n formulasChanged: findReplaceResponse?.formulasChanged ?? 0,\n rowsChanged: findReplaceResponse?.rowsChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Replace operation failed', {\n id,\n find,\n replacement,\n gid,\n range,\n error: message,\n });\n\n throw new McpError(ErrorCode.InternalError, `Error replacing values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-replace',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","A1NotationSchema","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","parseA1Notation","rangeReferenceToGridRange","inputSchema","object","id","find","string","min","describe","replacement","gid","optional","range","matchCase","boolean","matchEntireCell","searchByRegex","includeFormulas","refine","data","message","successBranchSchema","type","literal","spreadsheetUrl","occurrencesChanged","number","int","nonnegative","valuesChanged","formulasChanged","rowsChanged","sheetsChanged","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","response","sheets","version","auth","authContext","findReplaceRequest","undefined","allSheets","spreadsheetResponse","sheet","spreadsheets","get","spreadsheetId","fields","s","String","properties","sheetId","InvalidParams","InternalError","rangeRef","batchUpdate","requestBody","requests","findReplace","findReplaceResponse","replies","content","text","JSON","stringify","structuredContent","error","Error","stack","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAIrC,SAASE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AACzE,SAASC,MAAM,QAAwB,aAAa;AACpD,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AACpH,SAASC,eAAe,EAAEC,yBAAyB,QAAQ,wCAAwC;AAEnG,MAAMC,cAAcP,EACjBQ,MAAM,CAAC;IACNC,IAAIL;IACJM,MAAMV,EAAEW,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACjCC,aAAad,EAAEW,MAAM,GAAGE,QAAQ,CAAC;IAEjC,sDAAsD;IACtDE,KAAKb,eAAec,QAAQ,GAAGH,QAAQ,CAAC;IACxCI,OAAOhB,iBAAiBe,QAAQ,GAAGH,QAAQ,CAAC;IAE5C,gBAAgB;IAChBK,WAAWlB,EAAEmB,OAAO,GAAGH,QAAQ,GAAGH,QAAQ,CAAC;IAC3CO,iBAAiBpB,EAAEmB,OAAO,GAAGH,QAAQ,GAAGH,QAAQ,CAAC;IACjDQ,eAAerB,EAAEmB,OAAO,GAAGH,QAAQ,GAAGH,QAAQ,CAAC;IAC/CS,iBAAiBtB,EAAEmB,OAAO,GAAGH,QAAQ,GAAGH,QAAQ,CAAC;AACnD,GACCU,MAAM,CAAC,CAACC,OAAS,CAAEA,CAAAA,KAAKP,KAAK,IAAI,CAACO,KAAKT,GAAG,AAAD,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zC,SAAS,EAAE;YAChFwD,OAAOF,iBAAiBC,QAAQD,MAAME,KAAK,GAAG5B;QAChD;IACF;AACF;AAEA,eAAe,SAAS6B;IACtB,OAAO;QACLC,MAAM;QACN3C;QACAG;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\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 = google.sheets({ version: 'v4', auth: 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 McpError(ErrorCode.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 McpError(ErrorCode.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":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","SheetCellSchema","SheetGidSchema","SpreadsheetIdSchema","columnIndexToLetter","index","letter","num","remainder","String","fromCharCode","Math","floor","inputSchema","object","id","gid","query","coerce","string","trim","optional","describe","select","enum","values","boolean","a1s","render","matchCase","successBranchSchema","type","literal","count","number","int","nonnegative","array","union","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","spreadsheetResponse","sheet","sheets","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","properties","sheetId","InvalidParams","sheetTitle","title","rowCount","gridProperties","columnCount","endColumn","fullRange","debug","response","range","valueRenderOption","res","allRows","Array","isArray","searchQuery","toLowerCase","a1Array","valuesArray","cellMatches","cell","cellValue","includes","rowIdx","length","row","colIdx","colLetter","rowNum","push","matchingRows","matches","some","colEnd","max","headerRow","matchingCols","header","columnValues","map","undefined","hasA1s","hasValues","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","stack","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAIrC,SAASE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AACzE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,eAAe,EAAEC,cAAc,EAAEC,mBAAmB,QAAQ,yBAAyB;AAE9F,gEAAgE;AAChE,SAASC,oBAAoBC,KAAa;IACxC,IAAIC,SAAS;IACb,IAAIC,MAAMF,QAAQ;IAClB,MAAOE,MAAM,EAAG;QACd,MAAMC,YAAY,AAACD,CAAAA,MAAM,CAAA,IAAK;QAC9BD,SAASG,OAAOC,YAAY,CAAC,KAAKF,aAAaF;QAC/CC,MAAMI,KAAKC,KAAK,CAAC,AAACL,CAAAA,MAAM,CAAA,IAAK;IAC/B;IACA,OAAOD;AACT;AAEA,MAAMO,cAAcb,EAAEc,MAAM,CAAC;IAC3BC,IAAIZ;IACJa,KAAKd;IACLe,OAAOjB,EAAEkB,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,QAAQ,GAAGC,QAAQ,CAAC;IACpDC,QAAQvB,EAAEwB,IAAI,CAAC;QAAC;QAAS;QAAQ;KAAU,EAAEF,QAAQ,CAAC;IACtDG,QAAQzB,EAAE0B,OAAO,GAAGL,QAAQ,GAAGC,QAAQ,CAAC;IACxCK,KAAK3B,EAAE0B,OAAO,GAAGL,QAAQ,GAAGC,QAAQ,CAAC;IACrCM,QAAQ5B,EAAEwB,IAAI,CAAC;QAAC;QAAmB;QAAqB;KAAU,EAAEH,QAAQ,GAAGC,QAAQ,CAAC;IACxFO,WAAW7B,EAAE0B,OAAO,GAAGL,QAAQ,GAAGC,QAAQ,CAAC;AAC7C;AAEA,MAAMQ,sBAAsB9B,EAAEc,MAAM,CAAC;IACnCiB,MAAM/B,EAAEgC,OAAO,CAAC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;aAAE;YAClEoE,mBAAmB;gBAAEpE;YAAO;QAC9B;IACF,EAAE,OAAOqE,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGxG,OAAOuG;QAChElE,OAAOkE,KAAK,CAAC,8BAA8B;YAAEA,OAAOC;QAAQ;QAE5D,MAAM,IAAInH,SAASD,UAAUsH,aAAa,EAAE,CAAC,6BAA6B,EAAEF,SAAS,EAAE;YACrFG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGZ;QAChD;IACF;AACF;AAEA,eAAe,SAASa;IACtB,OAAO;QACLC,MAAM;QACN7E;QACAG;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\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 = google.sheets({ version: 'v4', auth: 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 McpError(ErrorCode.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 McpError(ErrorCode.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":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","SheetCellSchema","SheetGidSchema","SpreadsheetIdSchema","columnIndexToLetter","index","letter","num","remainder","String","fromCharCode","Math","floor","inputSchema","object","id","gid","query","coerce","string","trim","optional","describe","select","enum","values","boolean","a1s","render","matchCase","successBranchSchema","type","literal","count","number","int","nonnegative","array","union","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","spreadsheetResponse","sheet","sheets","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","properties","sheetId","InvalidParams","sheetTitle","title","rowCount","gridProperties","columnCount","endColumn","fullRange","debug","response","range","valueRenderOption","res","allRows","Array","isArray","searchQuery","toLowerCase","a1Array","valuesArray","cellMatches","cell","cellValue","includes","rowIdx","length","row","colIdx","colLetter","rowNum","push","matchingRows","matches","some","colEnd","max","headerRow","matchingCols","header","columnValues","map","undefined","hasA1s","hasValues","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","stack","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAIrC,SAASE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AACzE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,eAAe,EAAEC,cAAc,EAAEC,mBAAmB,QAAQ,yBAAyB;AAE9F,gEAAgE;AAChE,SAASC,oBAAoBC,KAAa;IACxC,IAAIC,SAAS;IACb,IAAIC,MAAMF,QAAQ;IAClB,MAAOE,MAAM,EAAG;QACd,MAAMC,YAAY,AAACD,CAAAA,MAAM,CAAA,IAAK;QAC9BD,SAASG,OAAOC,YAAY,CAAC,KAAKF,aAAaF;QAC/CC,MAAMI,KAAKC,KAAK,CAAC,AAACL,CAAAA,MAAM,CAAA,IAAK;IAC/B;IACA,OAAOD;AACT;AAEA,MAAMO,cAAcb,EAAEc,MAAM,CAAC;IAC3BC,IAAIZ;IACJa,KAAKd;IACLe,OAAOjB,EAAEkB,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,QAAQ,GAAGC,QAAQ,CAAC;IACpDC,QAAQvB,EAAEwB,IAAI,CAAC;QAAC;QAAS;QAAQ;KAAU,EAAEF,QAAQ,CAAC;IACtDG,QAAQzB,EAAE0B,OAAO,GAAGL,QAAQ,GAAGC,QAAQ,CAAC;IACxCK,KAAK3B,EAAE0B,OAAO,GAAGL,QAAQ,GAAGC,QAAQ,CAA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YACA,GAAIN,OAAOsD,QAAQO,MAAM,GAAG,KAAK;gBAAE7D,KAAKsD;YAAQ,CAAC;YACjD,GAAIxD,UAAUyD,YAAYM,MAAM,GAAG,KAAK;gBAAE/D,QAAQyD;YAAY,CAAC;QACjE;QAEA,OAAO;YACLyB,SAAS;gBAAC;oBAAE5E,MAAM;oBAAiB6E,MAAMC,KAAKC,SAAS,CAACnE;gBAAQ;aAAE;YAClEoE,mBAAmB;gBAAEpE;YAAO;QAC9B;IACF,EAAE,OAAOqE,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGxG,OAAOuG;QAChElE,OAAOkE,KAAK,CAAC,8BAA8B;YAAEA,OAAOC;QAAQ;QAE5D,MAAM,IAAInH,SAASD,UAAUsH,aAAa,EAAE,CAAC,6BAA6B,EAAEF,SAAS,EAAE;YACrFG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGZ;QAChD;IACF;AACF;AAEA,eAAe,SAASa;IACtB,OAAO;QACLC,MAAM;QACN7E;QACAG;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-sheets/src/schemas/index.ts"],"sourcesContent":["import { z } from 'zod';\n\n// Spreadsheet and sheet reference schemas\nexport const SpreadsheetRefSchema = z.string().min(1).describe('Spreadsheet reference: full URL, exact name, or partial name (not ID - use spreadsheet-find to get ID)');\n\nexport const SheetRefSchema = z.string().min(1).describe('Sheet reference: exact title or partial name match (not ID - use sheet-find to get ID)');\n\n// Shared descriptions for consistency\nconst SPREADSHEET_ID_DESC = 'Spreadsheet ID (from URL d/{id})';\nconst SHEET_ID_DESC = 'Sheet ID (from URL gid={gid})';\n\n// Input schemas (with validation)\n// Note: z.coerce.string() converts numbers to strings, handling cases where MCP clients\n// pass gid: 0 (number) instead of gid: \"0\" (string). This is critical for gid=0 which\n// is the default sheet ID in new spreadsheets.\nexport const SpreadsheetIdSchema = z.string().min(1).describe(SPREADSHEET_ID_DESC);\nexport const SheetGidSchema = z.coerce.string().min(1).describe(SHEET_ID_DESC);\n\n// Output schemas (for use in output/response schemas)\nexport const SpreadsheetIdOutput = z.string().describe(SPREADSHEET_ID_DESC);\nexport const SheetGidOutput = z.string().describe(SHEET_ID_DESC);\n\n// Schema for individual sheet cells (can be string, number, boolean, or null)\n// null represents empty cells - JSON cannot represent undefined, and Google API uses null for empty cells\n// Infinity values are allowed as Google Sheets can contain them, but NaN is still rejected\nexport const SheetCellSchema = z.union([z.string(), z.number(), z.literal(Infinity), z.literal(-Infinity), z.boolean(), z.null()]);\n\n// Schema for a row in a sheet search result\nexport const SheetRowSchema = z.object({\n rowIndex: z.number().int().positive().describe('1-based row number in the sheet'),\n values: z.array(SheetCellSchema).optional().describe('Cell values for this row (included when includeData=true)'),\n range: z.string().optional().describe('A1 notation range for this row (e.g., A5:D5)'),\n});\n\n// A1 notation validation - simplified for zod compatibility\nexport const A1NotationSchema = z.string().min(1).describe('A1 notation for cell range (e.g., A1, A1:B2, A:B, 1:2)');\n"],"names":["z","SpreadsheetRefSchema","string","min","describe","SheetRefSchema","SPREADSHEET_ID_DESC","SHEET_ID_DESC","SpreadsheetIdSchema","SheetGidSchema","coerce","SpreadsheetIdOutput","SheetGidOutput","SheetCellSchema","union","number","literal","Infinity","boolean","null","SheetRowSchema","object","rowIndex","int","positive","values","array","optional","range","A1NotationSchema"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAM;AAExB,0CAA0C;AAC1C,OAAO,MAAMC,uBAAuBD,EAAEE,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC,0GAA0G;AAEzK,OAAO,MAAMC,iBAAiBL,EAAEE,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC,0FAA0F;AAEnJ,sCAAsC;AACtC,MAAME,sBAAsB;AAC5B,MAAMC,gBAAgB;AAEtB,kCAAkC;AAClC,wFAAwF;AACxF,sFAAsF;AACtF,+CAA+C;AAC/C,OAAO,MAAMC,sBAAsBR,EAAEE,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAACE,qBAAqB;AACnF,OAAO,MAAMG,iBAAiBT,EAAEU,MAAM,CAACR,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAACG,eAAe;AAE/E,sDAAsD;AACtD,OAAO,MAAMI,sBAAsBX,EAAEE,MAAM,GAAGE,QAAQ,CAACE,qBAAqB;AAC5E,OAAO,MAAMM,iBAAiBZ,EAAEE,MAAM,GAAGE,QAAQ,CAACG,eAAe;AAEjE,8EAA8E;AAC9E,0GAA0G;AAC1G,2FAA2F;AAC3F,OAAO,MAAMM,kBAAkBb,EAAEc,KAAK,CAAC;IAACd,EAAEE,MAAM;IAAIF,EAAEe,MAAM;IAAIf,EAAEgB,OAAO,CAACC;IAAWjB,EAAEgB,OAAO,CAAC,CAACC;IAAWjB,EAAEkB,OAAO;IAAIlB,EAAEmB,IAAI;CAAG,EAAE;AAEnI,4CAA4C;AAC5C,OAAO,MAAMC,iBAAiBpB,EAAEqB,MAAM,CAAC;IACrCC,UAAUtB,EAAEe,MAAM,GAAGQ,GAAG,GAAGC,QAAQ,GAAGpB,QAAQ,CAAC;IAC/CqB,QAAQzB,EAAE0B,KAAK,CAACb,iBAAiBc,QAAQ,GAAGvB,QAAQ,CAAC;IACrDwB,OAAO5B,EAAEE,MAAM,GAAGyB,QAAQ,GAAGvB,QAAQ,CAAC;AACxC,GAAG;AAEH,4DAA4D;AAC5D,OAAO,MAAMyB,mBAAmB7B,EAAEE,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC,0DAA0D"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/schemas/index.ts"],"sourcesContent":["import { z } from 'zod';\n\n// Spreadsheet and sheet reference schemas\nexport const SpreadsheetRefSchema = z.string().min(1).describe('Spreadsheet reference: full URL, exact name, or partial name (not ID - use spreadsheet-find to get ID)');\n\nexport const SheetRefSchema = z.string().min(1).describe('Sheet reference: exact title or partial name match (not ID - use sheet-find to get ID)');\n\n// Shared descriptions for consistency\nconst SPREADSHEET_ID_DESC = 'Spreadsheet ID (from URL d/{id})';\nconst SHEET_ID_DESC = 'Sheet ID (from URL gid={gid})';\n\n// Input schemas (with validation)\n// Note: z.coerce.string() converts numbers to strings, handling cases where MCP clients\n// pass gid: 0 (number) instead of gid: \"0\" (string). This is critical for gid=0 which\n// is the default sheet ID in new spreadsheets.\nexport const SpreadsheetIdSchema = z.string().min(1).describe(SPREADSHEET_ID_DESC);\nexport const SheetGidSchema = z.coerce.string().min(1).describe(SHEET_ID_DESC);\n\n// Output schemas (for use in output/response schemas)\nexport const SpreadsheetIdOutput = z.string().describe(SPREADSHEET_ID_DESC);\nexport const SheetGidOutput = z.string().describe(SHEET_ID_DESC);\n\n// Schema for individual sheet cells (can be string, number, boolean, or null)\n// null represents empty cells - JSON cannot represent undefined, and Google API uses null for empty cells\n// Infinity values are allowed as Google Sheets can contain them, but NaN is still rejected\nexport const SheetCellSchema = z.union([z.string(), z.number(), z.literal(Infinity), z.literal(-Infinity), z.boolean(), z.null()]);\n\n// Schema for a row in a sheet search result\nexport const SheetRowSchema = z.object({\n rowIndex: z.number().int().positive().describe('1-based row number in the sheet'),\n values: z.array(SheetCellSchema).optional().describe('Cell values for this row (included when includeData=true)'),\n range: z.string().optional().describe('A1 notation range for this row (e.g., A5:D5)'),\n});\n\n// A1 notation validation - simplified for zod compatibility\nexport const A1NotationSchema = z.string().min(1).describe('A1 notation for cell range (e.g., A1, A1:B2, A:B, 1:2)');\n"],"names":["z","SpreadsheetRefSchema","string","min","describe","SheetRefSchema","SPREADSHEET_ID_DESC","SHEET_ID_DESC","SpreadsheetIdSchema","SheetGidSchema","coerce","SpreadsheetIdOutput","SheetGidOutput","SheetCellSchema","union","number","literal","Infinity","boolean","null","SheetRowSchema","object","rowIndex","int","positive","values","array","optional","range","A1NotationSchema"],"mappings":"AAAA,SAASA,CAAC,QAA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