@mcp-z/mcp-sheets 2.5.0 → 2.6.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 (106) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/constants.d.cts +24 -0
  3. package/dist/cjs/constants.d.ts +24 -0
  4. package/dist/cjs/constants.js +56 -0
  5. package/dist/cjs/constants.js.map +1 -1
  6. package/dist/cjs/lib/create-store.d.cts +2 -1
  7. package/dist/cjs/lib/create-store.d.ts +2 -1
  8. package/dist/cjs/lib/create-store.js +82 -7
  9. package/dist/cjs/lib/create-store.js.map +1 -1
  10. package/dist/cjs/mcp/tools/cells-format.d.cts +3 -3
  11. package/dist/cjs/mcp/tools/cells-format.d.ts +3 -3
  12. package/dist/cjs/mcp/tools/cells-format.js +3 -2
  13. package/dist/cjs/mcp/tools/cells-format.js.map +1 -1
  14. package/dist/cjs/mcp/tools/columns-get.d.cts +2 -2
  15. package/dist/cjs/mcp/tools/columns-get.d.ts +2 -2
  16. package/dist/cjs/mcp/tools/columns-get.js +2 -1
  17. package/dist/cjs/mcp/tools/columns-get.js.map +1 -1
  18. package/dist/cjs/mcp/tools/columns-update.d.cts +1 -1
  19. package/dist/cjs/mcp/tools/columns-update.d.ts +1 -1
  20. package/dist/cjs/mcp/tools/columns-update.js +3 -2
  21. package/dist/cjs/mcp/tools/columns-update.js.map +1 -1
  22. package/dist/cjs/mcp/tools/csv-get-columns.js +1 -1
  23. package/dist/cjs/mcp/tools/lib/dimension-operations.js +1 -1
  24. package/dist/cjs/mcp/tools/rows-append.d.cts +1 -1
  25. package/dist/cjs/mcp/tools/rows-append.d.ts +1 -1
  26. package/dist/cjs/mcp/tools/rows-append.js +2 -1
  27. package/dist/cjs/mcp/tools/rows-append.js.map +1 -1
  28. package/dist/cjs/mcp/tools/rows-csv-append.d.cts +1 -1
  29. package/dist/cjs/mcp/tools/rows-csv-append.d.ts +1 -1
  30. package/dist/cjs/mcp/tools/rows-csv-append.js +3 -2
  31. package/dist/cjs/mcp/tools/rows-csv-append.js.map +1 -1
  32. package/dist/cjs/mcp/tools/rows-get.d.cts +2 -2
  33. package/dist/cjs/mcp/tools/rows-get.d.ts +2 -2
  34. package/dist/cjs/mcp/tools/rows-get.js +2 -1
  35. package/dist/cjs/mcp/tools/rows-get.js.map +1 -1
  36. package/dist/cjs/mcp/tools/values-batch-update.d.cts +1 -1
  37. package/dist/cjs/mcp/tools/values-batch-update.d.ts +1 -1
  38. package/dist/cjs/mcp/tools/values-batch-update.js +3 -2
  39. package/dist/cjs/mcp/tools/values-batch-update.js.map +1 -1
  40. package/dist/cjs/mcp/tools/values-csv-update.d.cts +1 -1
  41. package/dist/cjs/mcp/tools/values-csv-update.d.ts +1 -1
  42. package/dist/cjs/mcp/tools/values-csv-update.js +3 -2
  43. package/dist/cjs/mcp/tools/values-csv-update.js.map +1 -1
  44. package/dist/cjs/mcp/tools/values-search.d.cts +2 -2
  45. package/dist/cjs/mcp/tools/values-search.d.ts +2 -2
  46. package/dist/cjs/mcp/tools/values-search.js +2 -1
  47. package/dist/cjs/mcp/tools/values-search.js.map +1 -1
  48. package/dist/cjs/setup/http.js +1 -1
  49. package/dist/cjs/setup/runtime.d.cts +2 -2
  50. package/dist/cjs/setup/runtime.d.ts +2 -2
  51. package/dist/cjs/setup/runtime.js +6 -6
  52. package/dist/cjs/setup/runtime.js.map +1 -1
  53. package/dist/cjs/setup/stdio.js +1 -1
  54. package/dist/cjs/spreadsheet/data-operations.js +2 -18
  55. package/dist/cjs/spreadsheet/data-operations.js.map +1 -1
  56. package/dist/cjs/spreadsheet/markdown-runs.js +1 -1
  57. package/dist/cjs/spreadsheet/range-operations.d.cts +1 -5
  58. package/dist/cjs/spreadsheet/range-operations.d.ts +1 -5
  59. package/dist/cjs/spreadsheet/range-operations.js +1 -29
  60. package/dist/cjs/spreadsheet/range-operations.js.map +1 -1
  61. package/dist/cjs/spreadsheet/sheet-operations.js +25 -75
  62. package/dist/cjs/spreadsheet/sheet-operations.js.map +1 -1
  63. package/dist/esm/constants.d.ts +24 -0
  64. package/dist/esm/constants.js +41 -0
  65. package/dist/esm/constants.js.map +1 -1
  66. package/dist/esm/lib/create-store.d.ts +2 -1
  67. package/dist/esm/lib/create-store.js +22 -4
  68. package/dist/esm/lib/create-store.js.map +1 -1
  69. package/dist/esm/mcp/tools/cells-format.d.ts +3 -3
  70. package/dist/esm/mcp/tools/cells-format.js +3 -2
  71. package/dist/esm/mcp/tools/cells-format.js.map +1 -1
  72. package/dist/esm/mcp/tools/columns-get.d.ts +2 -2
  73. package/dist/esm/mcp/tools/columns-get.js +2 -1
  74. package/dist/esm/mcp/tools/columns-get.js.map +1 -1
  75. package/dist/esm/mcp/tools/columns-update.d.ts +1 -1
  76. package/dist/esm/mcp/tools/columns-update.js +3 -2
  77. package/dist/esm/mcp/tools/columns-update.js.map +1 -1
  78. package/dist/esm/mcp/tools/rows-append.d.ts +1 -1
  79. package/dist/esm/mcp/tools/rows-append.js +2 -1
  80. package/dist/esm/mcp/tools/rows-append.js.map +1 -1
  81. package/dist/esm/mcp/tools/rows-csv-append.d.ts +1 -1
  82. package/dist/esm/mcp/tools/rows-csv-append.js +2 -1
  83. package/dist/esm/mcp/tools/rows-csv-append.js.map +1 -1
  84. package/dist/esm/mcp/tools/rows-get.d.ts +2 -2
  85. package/dist/esm/mcp/tools/rows-get.js +2 -1
  86. package/dist/esm/mcp/tools/rows-get.js.map +1 -1
  87. package/dist/esm/mcp/tools/values-batch-update.d.ts +1 -1
  88. package/dist/esm/mcp/tools/values-batch-update.js +3 -2
  89. package/dist/esm/mcp/tools/values-batch-update.js.map +1 -1
  90. package/dist/esm/mcp/tools/values-csv-update.d.ts +1 -1
  91. package/dist/esm/mcp/tools/values-csv-update.js +3 -2
  92. package/dist/esm/mcp/tools/values-csv-update.js.map +1 -1
  93. package/dist/esm/mcp/tools/values-search.d.ts +2 -2
  94. package/dist/esm/mcp/tools/values-search.js +2 -1
  95. package/dist/esm/mcp/tools/values-search.js.map +1 -1
  96. package/dist/esm/setup/runtime.d.ts +2 -2
  97. package/dist/esm/setup/runtime.js +6 -6
  98. package/dist/esm/setup/runtime.js.map +1 -1
  99. package/dist/esm/spreadsheet/data-operations.js +7 -11
  100. package/dist/esm/spreadsheet/data-operations.js.map +1 -1
  101. package/dist/esm/spreadsheet/range-operations.d.ts +1 -5
  102. package/dist/esm/spreadsheet/range-operations.js +0 -27
  103. package/dist/esm/spreadsheet/range-operations.js.map +1 -1
  104. package/dist/esm/spreadsheet/sheet-operations.js +19 -36
  105. package/dist/esm/spreadsheet/sheet-operations.js.map +1 -1
  106. package/package.json +7 -7
@@ -3,6 +3,7 @@ import { schemas } from '@mcp-z/oauth-google';
3
3
  const { AuthRequiredBranchSchema } = schemas;
4
4
  import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
5
5
  import { z } from 'zod';
6
+ import { NATIVE_DATE_GUIDANCE } from '../../constants.js';
6
7
  import { googleAuth } from '../../lib/google-auth.js';
7
8
  import { A1NotationSchema, SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.js';
8
9
  // Input schema for values batch update requests
@@ -21,7 +22,7 @@ const inputSchema = z.object({
21
22
  valueInputOption: z.enum([
22
23
  'RAW',
23
24
  'USER_ENTERED'
24
- ]).describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input)'),
25
+ ]).describe('How input data should be interpreted (required; no default is applied by the schema). RAW = exact values: date strings stay text, numeric serials stay numbers. USER_ENTERED = parsed like user input: date strings may become native dates per the workbook locale.'),
25
26
  includeData: z.boolean().describe('Whether to include updated cell values in the response')
26
27
  });
27
28
  const successBranchSchema = z.object({
@@ -50,7 +51,7 @@ const outputSchema = z.discriminatedUnion('type', [
50
51
  AuthRequiredBranchSchema
51
52
  ]);
52
53
  const config = {
53
- description: 'Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update.',
54
+ description: `Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update. ${NATIVE_DATE_GUIDANCE}`,
54
55
  inputSchema,
55
56
  outputSchema: z.object({
56
57
  result: outputSchema
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-batch-update.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Types for updated data response\ninterface UpdatedDataItem {\n range: string;\n majorDimension: 'ROWS' | 'COLUMNS';\n values?: (string | number | boolean | null)[][];\n}\n\n// Input schema for values batch update requests\nconst ValuesBatchUpdateRequestSchema = z.object({\n range: A1NotationSchema.describe('A1 notation range defining the bounded target area. Data dimensions must match range dimensions. Example: D1:D100 requires exactly 100 rows of data. Use open-ended ranges like D1:D to write any number of rows.'),\n values: z.array(z.array(SheetCellSchema)).min(1).describe('2D array of values. Row count must match range height, column count must match range width. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether values represent rows or columns'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(ValuesBatchUpdateRequestSchema).min(1).describe('Array of value update requests'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input)'),\n includeData: z.boolean().describe('Whether to include updated cell values in the response'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Title of the updated spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the updated spreadsheet'),\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n totalUpdatedRows: z.number().int().nonnegative().describe('Total number of rows updated across all requests'),\n totalUpdatedColumns: z.number().int().nonnegative().describe('Total number of columns updated across all requests'),\n totalUpdatedCells: z.number().int().nonnegative().describe('Total number of cells updated across all requests'),\n updatedRanges: z.array(z.string()).describe('A1 notation ranges that were updated'),\n updatedData: z\n .array(\n z.object({\n range: z.string().describe('A1 notation range that was updated'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension of the updated data'),\n values: z.array(z.array(SheetCellSchema)).optional().describe('Updated values (if includeData was true)'),\n })\n )\n .optional()\n .describe('Detailed information about updated data (if includeData was true)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests, valueInputOption = 'USER_ENTERED', includeData = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n includeData,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n const spreadsheetTitle = spreadsheetData.properties?.title ?? '';\n const spreadsheetUrl = spreadsheetData.spreadsheetUrl ?? '';\n\n // Find sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for batch update', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n const sheetGid = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetGid}`;\n\n // Build batch update request with prefixed ranges\n const batchUpdateData = requests.map((req) => ({\n range: `${sheetTitle}!${req.range}`,\n values: req.values,\n majorDimension: req.majorDimension || 'ROWS',\n }));\n\n logger.info('sheets.values.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchUpdateDataCount: batchUpdateData.length,\n });\n\n // Execute the batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchUpdateData,\n includeValuesInResponse: includeData,\n responseDateTimeRenderOption: 'FORMATTED_STRING',\n responseValueRenderOption: 'FORMATTED_VALUE',\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Validate batch operation results and detect partial failures\n const responses = updateResult.responses || [];\n const expectedCount = requests.length;\n const actualCount = responses.length;\n\n if (actualCount !== expectedCount) {\n logger.error('Partial batch failure detected', {\n expectedOperations: expectedCount,\n completedOperations: actualCount,\n spreadsheetId: id,\n sheetTitle,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation partially failed: ${actualCount}/${expectedCount} operations completed`);\n }\n\n // Check for any failed operations (empty or null responses)\n const failedOperations = responses.filter((response, index) => {\n if (!response || !response.updatedRange) {\n logger.error('Failed operation detected', {\n operationIndex: index,\n requestedRange: requests[index]?.range,\n spreadsheetId: id,\n sheetTitle,\n });\n return true;\n }\n return false;\n });\n\n if (failedOperations.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, `${failedOperations.length} operations failed to update ranges`);\n }\n\n // Extract updated ranges and calculate totals\n const updatedRanges = responses.map((response) => response.updatedRange || '').filter((range) => range);\n const totalUpdatedRows = updateResult.totalUpdatedRows || 0;\n const totalUpdatedColumns = updateResult.totalUpdatedColumns || 0;\n const totalUpdatedCells = updateResult.totalUpdatedCells || 0;\n\n // Build updated data response if requested\n let updatedData: UpdatedDataItem[] | undefined;\n if (includeData && updateResult.responses) {\n updatedData = updateResult.responses\n .filter((response) => response.updatedData)\n .map((response) => {\n const item: UpdatedDataItem = {\n range: response.updatedRange || '',\n majorDimension: (response.updatedData?.majorDimension as 'ROWS' | 'COLUMNS' | undefined) || 'ROWS',\n };\n const values = response.updatedData?.values as (string | number | boolean | null | undefined)[][] | undefined;\n if (values !== undefined) {\n // Map undefined values to null for JSON Schema compatibility\n item.values = values.map((row) => row.map((cell) => (cell === undefined ? null : cell)));\n }\n return item;\n });\n }\n\n logger.info('sheets.values.batchUpdate completed successfully', {\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRangesCount: updatedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetGid),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRanges,\n updatedData,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Batch update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","z","googleAuth","A1NotationSchema","SheetCellSchema","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","ValuesBatchUpdateRequestSchema","object","range","describe","values","array","min","majorDimension","enum","inputSchema","id","gid","requests","valueInputOption","includeData","boolean","successBranchSchema","type","literal","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalUpdatedRows","number","int","nonnegative","totalUpdatedColumns","totalUpdatedCells","updatedRanges","updatedData","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","requestCount","length","spreadsheetData","sheet","version","auth","authContext","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","InvalidParams","sheetGid","batchUpdateData","map","req","batchUpdateDataCount","batchUpdateResponse","batchUpdate","requestBody","includeValuesInResponse","responseDateTimeRenderOption","responseValueRenderOption","updateResult","responses","expectedCount","actualCount","error","expectedOperations","completedOperations","InternalError","failedOperations","filter","response","index","updatedRange","operationIndex","requestedRange","item","undefined","row","cell","updatedRangesCount","content","text","JSON","stringify","structuredContent","message","Error","stack","createTool","name"],"mappings":"AAAA,SAASA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzD,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,gBAAgB,EAAEC,eAAe,EAAEC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EA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vB,iBAAiBsB,QAAQtB,MAAMuB,KAAK,GAAGX;QAChD;IACF;AACF;AAEA,eAAe,SAASY;IACtB,OAAO;QACLC,MAAM;QACNnE;QACAG;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-batch-update.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { NATIVE_DATE_GUIDANCE } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Types for updated data response\ninterface UpdatedDataItem {\n range: string;\n majorDimension: 'ROWS' | 'COLUMNS';\n values?: (string | number | boolean | null)[][];\n}\n\n// Input schema for values batch update requests\nconst ValuesBatchUpdateRequestSchema = z.object({\n range: A1NotationSchema.describe('A1 notation range defining the bounded target area. Data dimensions must match range dimensions. Example: D1:D100 requires exactly 100 rows of data. Use open-ended ranges like D1:D to write any number of rows.'),\n values: z.array(z.array(SheetCellSchema)).min(1).describe('2D array of values. Row count must match range height, column count must match range width. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether values represent rows or columns'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(ValuesBatchUpdateRequestSchema).min(1).describe('Array of value update requests'),\n valueInputOption: z\n .enum(['RAW', 'USER_ENTERED'])\n .describe('How input data should be interpreted (required; no default is applied by the schema). RAW = exact values: date strings stay text, numeric serials stay numbers. USER_ENTERED = parsed like user input: date strings may become native dates per the workbook locale.'),\n includeData: z.boolean().describe('Whether to include updated cell values in the response'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Title of the updated spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the updated spreadsheet'),\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n totalUpdatedRows: z.number().int().nonnegative().describe('Total number of rows updated across all requests'),\n totalUpdatedColumns: z.number().int().nonnegative().describe('Total number of columns updated across all requests'),\n totalUpdatedCells: z.number().int().nonnegative().describe('Total number of cells updated across all requests'),\n updatedRanges: z.array(z.string()).describe('A1 notation ranges that were updated'),\n updatedData: z\n .array(\n z.object({\n range: z.string().describe('A1 notation range that was updated'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension of the updated data'),\n values: z.array(z.array(SheetCellSchema)).optional().describe('Updated values (if includeData was true)'),\n })\n )\n .optional()\n .describe('Detailed information about updated data (if includeData was true)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: `Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update. ${NATIVE_DATE_GUIDANCE}`,\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests, valueInputOption = 'USER_ENTERED', includeData = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n includeData,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n const spreadsheetTitle = spreadsheetData.properties?.title ?? '';\n const spreadsheetUrl = spreadsheetData.spreadsheetUrl ?? '';\n\n // Find sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for batch update', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n const sheetGid = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetGid}`;\n\n // Build batch update request with prefixed ranges\n const batchUpdateData = requests.map((req) => ({\n range: `${sheetTitle}!${req.range}`,\n values: req.values,\n majorDimension: req.majorDimension || 'ROWS',\n }));\n\n logger.info('sheets.values.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchUpdateDataCount: batchUpdateData.length,\n });\n\n // Execute the batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchUpdateData,\n includeValuesInResponse: includeData,\n responseDateTimeRenderOption: 'FORMATTED_STRING',\n responseValueRenderOption: 'FORMATTED_VALUE',\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Validate batch operation results and detect partial failures\n const responses = updateResult.responses || [];\n const expectedCount = requests.length;\n const actualCount = responses.length;\n\n if (actualCount !== expectedCount) {\n logger.error('Partial batch failure detected', {\n expectedOperations: expectedCount,\n completedOperations: actualCount,\n spreadsheetId: id,\n sheetTitle,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation partially failed: ${actualCount}/${expectedCount} operations completed`);\n }\n\n // Check for any failed operations (empty or null responses)\n const failedOperations = responses.filter((response, index) => {\n if (!response || !response.updatedRange) {\n logger.error('Failed operation detected', {\n operationIndex: index,\n requestedRange: requests[index]?.range,\n spreadsheetId: id,\n sheetTitle,\n });\n return true;\n }\n return false;\n });\n\n if (failedOperations.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, `${failedOperations.length} operations failed to update ranges`);\n }\n\n // Extract updated ranges and calculate totals\n const updatedRanges = responses.map((response) => response.updatedRange || '').filter((range) => range);\n const totalUpdatedRows = updateResult.totalUpdatedRows || 0;\n const totalUpdatedColumns = updateResult.totalUpdatedColumns || 0;\n const totalUpdatedCells = updateResult.totalUpdatedCells || 0;\n\n // Build updated data response if requested\n let updatedData: UpdatedDataItem[] | undefined;\n if (includeData && updateResult.responses) {\n updatedData = updateResult.responses\n .filter((response) => response.updatedData)\n .map((response) => {\n const item: UpdatedDataItem = {\n range: response.updatedRange || '',\n majorDimension: (response.updatedData?.majorDimension as 'ROWS' | 'COLUMNS' | undefined) || 'ROWS',\n };\n const values = response.updatedData?.values as (string | number | boolean | null | undefined)[][] | undefined;\n if (values !== undefined) {\n // Map undefined values to null for JSON Schema compatibility\n item.values = values.map((row) => row.map((cell) => (cell === undefined ? null : cell)));\n }\n return item;\n });\n }\n\n logger.info('sheets.values.batchUpdate completed successfully', {\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRangesCount: updatedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetGid),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRanges,\n updatedData,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Batch update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","z","NATIVE_DATE_GUIDANCE","googleAuth","A1NotationSchema","SheetCellSchema","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","ValuesBatchUpdateRequestSchema","object","range","describe","values","array","min","majorDimension","enum","inputSchema","id","gid","requests","valueInputOption","includeData","boolean","successBranchSchema","type","literal","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalUpdatedRows","number","int","nonnegative","totalUpdatedColumns","totalUpdatedCells","updatedRanges","updatedData","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","requestCount","length","spreadsheetData","sheet","version","auth","authContext","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","InvalidParams","sheetGid","batchUpdateData","map","req","batchUpdateDataCount","batchUpdateResponse","batchUpdate","requestBody","includeValuesInResponse","responseDateTimeRenderOption","responseValueRenderOption","updateResult","responses","expectedCount","actualCount","error","expectedOperations","completedOperations","InternalError","failedOperations","filter","response","index","updatedRange","operationIndex","requestedRange","item","undefined","row","cell","updatedRangesCount","content","text","JSON","stringify","structuredContent","message","Error","stack","createTool","name"],"mappings":"AAAA,SAASA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzD,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,oBAAoB,QAAQ,qBAAqB;AAC1D,SAASC,UAAU,QAAQ,2BAA2B;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YACAgE,OAAOqB;QACT;QAEA,MAAM,IAAI7G,cAAcC,kBAAkB0F,aAAa,EAAE,CAAC,6BAA6B,EAAEkB,SAAS,EAAE;YAClGE,OAAOvB,iBAAiBsB,QAAQtB,MAAMuB,KAAK,GAAGX;QAChD;IACF;AACF;AAEA,eAAe,SAASY;IACtB,OAAO;QACLC,MAAM;QACNnE;QACAG;IACF;AACF"}
@@ -37,7 +37,7 @@ declare function handler({ id, gid, sourceUri, startRange, valueInputOption, sou
37
37
  export default function createTool(): {
38
38
  name: string;
39
39
  config: {
40
- readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.";
40
+ readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. Dates: a date-looking string is not necessarily a native date. See values-batch-update for the native-date write, format and read-back steps.";
41
41
  readonly inputSchema: z.ZodObject<{
42
42
  id: z.ZodString;
43
43
  gid: z.ZodCoercedString<unknown>;
@@ -4,6 +4,7 @@ const { AuthRequiredBranchSchema } = schemas;
4
4
  import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
5
5
  import { parse } from 'csv-parse';
6
6
  import { z } from 'zod';
7
+ import { NATIVE_DATE_POINTER } from '../../constants.js';
7
8
  import { googleAuth } from '../../lib/google-auth.js';
8
9
  import { A1NotationSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.js';
9
10
  import { getCsvReadStream } from '../../spreadsheet/csv-streaming.js';
@@ -16,7 +17,7 @@ const inputSchema = z.object({
16
17
  valueInputOption: z.enum([
17
18
  'RAW',
18
19
  'USER_ENTERED'
19
- ]).default('USER_ENTERED').describe('How to interpret values (RAW = exact, USER_ENTERED = parse formulas/dates)'),
20
+ ]).default('USER_ENTERED').describe('How to interpret values (default USER_ENTERED = parse formulas/dates per the workbook locale; RAW = exact, date-looking CSV text stays text)'),
20
21
  sourceHasHeaders: z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.')
21
22
  });
22
23
  const successBranchSchema = z.object({
@@ -37,7 +38,7 @@ const outputSchema = z.discriminatedUnion('type', [
37
38
  AuthRequiredBranchSchema
38
39
  ]);
39
40
  const config = {
40
- description: 'Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.',
41
+ description: `Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. ${NATIVE_DATE_POINTER}`,
41
42
  inputSchema,
42
43
  outputSchema: z.object({
43
44
  result: outputSchema
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-csv-update.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with range-based update (no deduplication) */\n\nimport { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { parse } from 'csv-parse';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\n\n/** Batch size for Sheets API calls (1000 rows × avg 10 cols = 10K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n sourceUri: z.string().trim().min(1).describe('CSV file URI (file://, http://, https://)'),\n startRange: A1NotationSchema.default('A1').describe('Top-left cell where CSV data starts (default: A1)'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How to interpret values (RAW = exact, USER_ENTERED = parse formulas/dates)'),\n sourceHasHeaders: z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Spreadsheet title'),\n spreadsheetUrl: z.string().describe('Spreadsheet URL'),\n sheetTitle: z.string().describe('Sheet title'),\n sheetUrl: z.string().describe('Sheet URL'),\n updatedRange: z.string().describe('A1 notation range that was updated'),\n updatedRows: z.number().describe('Number of rows updated'),\n updatedColumns: z.number().describe('Number of columns updated'),\n updatedCells: z.number().describe('Number of cells updated'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, sourceUri, startRange, valueInputOption = 'USER_ENTERED', sourceHasHeaders }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.csv-update called', { id, gid, sourceUri, startRange, valueInputOption, sourceHasHeaders });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n\n // Find the sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? '';\n\n // Streaming CSV processing state\n let sourceHeaders: string[] = [];\n const allRows: (string | number | boolean | null)[][] = [];\n let totalCols = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser with native streaming\n const parser = readStream.pipe(\n parse({\n columns: !!sourceHasHeaders, // Parse first row as column names if source has headers\n skip_empty_lines: true,\n trim: true,\n cast: true, // Auto-convert numbers/booleans\n relax_column_count: true,\n })\n );\n\n // Stream and collect all rows (with batching for very large files)\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders.length === 0) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n totalCols = sourceHeaders.length;\n logger.info('sheets.values.csv-update source headers', { sourceHeaders, totalCols });\n }\n\n // Convert record to row array (exclude source headers from data range)\n // CSV values are strings/numbers/booleans/nulls from the parser\n const row = sourceHeaders.map((header) => (record as Record<string, string | number | boolean | null>)[header] ?? null);\n allRows.push(row);\n } else {\n // sourceHasHeaders=false: record is an array, include all rows (including first row)\n const row = record as (string | number | boolean | null)[];\n allRows.push(row);\n\n if (totalCols === 0) {\n totalCols = row.length;\n }\n }\n }\n\n if (allRows.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'CSV file is empty');\n }\n\n // Prepare data for update (all rows)\n const dataToWrite: (string | number | boolean | null)[][] = allRows;\n\n // For large datasets, use batchUpdate to write in chunks\n // This respects the 40K cell limit per request\n const batchRequests = [];\n const currentRow = startRange.match(/[A-Z]+(\\d+)/)?.[1] || '1';\n let currentRowNum = Number.parseInt(currentRow, 10);\n\n for (let i = 0; i < dataToWrite.length; i += BATCH_SIZE) {\n const batchData = dataToWrite.slice(i, i + BATCH_SIZE);\n const batchRange = `${sheetTitle}!${startRange.match(/[A-Z]+/)?.[0]}${currentRowNum}`;\n\n batchRequests.push({\n range: batchRange,\n values: batchData,\n });\n\n currentRowNum += batchData.length;\n }\n\n logger.info('sheets.values.csv-update batching', { totalBatches: batchRequests.length, batchSize: BATCH_SIZE });\n\n // Execute batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchRequests,\n },\n });\n\n const totalUpdatedCells = batchUpdateResponse.data.totalUpdatedCells || 0;\n const totalUpdatedRows = batchUpdateResponse.data.totalUpdatedRows || 0;\n const totalUpdatedColumns = batchUpdateResponse.data.totalUpdatedColumns || 0;\n const firstUpdatedRange = batchUpdateResponse.data.responses?.[0]?.updatedRange || `${sheetTitle}!${startRange}`;\n\n logger.info('sheets.values.csv-update completed', { id, gid: sheet.properties.sheetId, updatedRange: firstUpdatedRange, updatedRows: totalUpdatedRows, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheet.properties.sheetId ?? ''),\n spreadsheetTitle: spreadsheetData.properties?.title ?? '',\n spreadsheetUrl: spreadsheetData.spreadsheetUrl ?? `https://docs.google.com/spreadsheets/d/${id}`,\n sheetTitle,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheet.properties.sheetId}`,\n updatedRange: firstUpdatedRange,\n updatedRows: totalUpdatedRows,\n updatedColumns: totalUpdatedColumns,\n updatedCells: totalUpdatedCells,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values.csv-update error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error updating values from CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-csv-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","parse","z","googleAuth","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","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,GAEhF,SAASA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzD,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,KAAK,QAAQ,YAAY;AAClC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AACpI,SAASC,gBAAgB,QAAQ,qCAAqC;AAEtE,gGAAgG,GAChG,MAAMC,aAAa;AAEnB,MAAMC,cAAcT,EAAEU,MAAM,CAAC;IAC3BC,IAAIL;IACJM,KAAKR;IACLS,WAAWb,EAAEc,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,YAAYhB,iBAAiBiB,OAAO,CAAC,MAAMF,QAAQ,CAAC;IACpDG,kBAAkBpB,EAAEqB,IA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,OAAO,GAAGnD,OAAOkD;QAChElE,OAAOkE,KAAK,CAAC,kCAAkC;YAAEA,OAAOC;QAAQ;QAEhE,MAAM,IAAIjH,cAAcC,kBAAkBkH,aAAa,EAAE,CAAC,gCAAgC,EAAEF,SAAS,EAAE;YACrGG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACN9E;QACAG;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-csv-update.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with range-based update (no deduplication) */\n\nimport { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { parse } from 'csv-parse';\nimport { z } from 'zod';\nimport { NATIVE_DATE_POINTER } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\n\n/** Batch size for Sheets API calls (1000 rows × avg 10 cols = 10K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n sourceUri: z.string().trim().min(1).describe('CSV file URI (file://, http://, https://)'),\n startRange: A1NotationSchema.default('A1').describe('Top-left cell where CSV data starts (default: A1)'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How to interpret values (default USER_ENTERED = parse formulas/dates per the workbook locale; RAW = exact, date-looking CSV text stays text)'),\n sourceHasHeaders: z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Spreadsheet title'),\n spreadsheetUrl: z.string().describe('Spreadsheet URL'),\n sheetTitle: z.string().describe('Sheet title'),\n sheetUrl: z.string().describe('Sheet URL'),\n updatedRange: z.string().describe('A1 notation range that was updated'),\n updatedRows: z.number().describe('Number of rows updated'),\n updatedColumns: z.number().describe('Number of columns updated'),\n updatedCells: z.number().describe('Number of cells updated'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: `Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. ${NATIVE_DATE_POINTER}`,\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, sourceUri, startRange, valueInputOption = 'USER_ENTERED', sourceHasHeaders }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.csv-update called', { id, gid, sourceUri, startRange, valueInputOption, sourceHasHeaders });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n\n // Find the sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? '';\n\n // Streaming CSV processing state\n let sourceHeaders: string[] = [];\n const allRows: (string | number | boolean | null)[][] = [];\n let totalCols = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser with native streaming\n const parser = readStream.pipe(\n parse({\n columns: !!sourceHasHeaders, // Parse first row as column names if source has headers\n skip_empty_lines: true,\n trim: true,\n cast: true, // Auto-convert numbers/booleans\n relax_column_count: true,\n })\n );\n\n // Stream and collect all rows (with batching for very large files)\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders.length === 0) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n totalCols = sourceHeaders.length;\n logger.info('sheets.values.csv-update source headers', { sourceHeaders, totalCols });\n }\n\n // Convert record to row array (exclude source headers from data range)\n // CSV values are strings/numbers/booleans/nulls from the parser\n const row = sourceHeaders.map((header) => (record as Record<string, string | number | boolean | null>)[header] ?? null);\n allRows.push(row);\n } else {\n // sourceHasHeaders=false: record is an array, include all rows (including first row)\n const row = record as (string | number | boolean | null)[];\n allRows.push(row);\n\n if (totalCols === 0) {\n totalCols = row.length;\n }\n }\n }\n\n if (allRows.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'CSV file is empty');\n }\n\n // Prepare data for update (all rows)\n const dataToWrite: (string | number | boolean | null)[][] = allRows;\n\n // For large datasets, use batchUpdate to write in chunks\n // This respects the 40K cell limit per request\n const batchRequests = [];\n const currentRow = startRange.match(/[A-Z]+(\\d+)/)?.[1] || '1';\n let currentRowNum = Number.parseInt(currentRow, 10);\n\n for (let i = 0; i < dataToWrite.length; i += BATCH_SIZE) {\n const batchData = dataToWrite.slice(i, i + BATCH_SIZE);\n const batchRange = `${sheetTitle}!${startRange.match(/[A-Z]+/)?.[0]}${currentRowNum}`;\n\n batchRequests.push({\n range: batchRange,\n values: batchData,\n });\n\n currentRowNum += batchData.length;\n }\n\n logger.info('sheets.values.csv-update batching', { totalBatches: batchRequests.length, batchSize: BATCH_SIZE });\n\n // Execute batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchRequests,\n },\n });\n\n const totalUpdatedCells = batchUpdateResponse.data.totalUpdatedCells || 0;\n const totalUpdatedRows = batchUpdateResponse.data.totalUpdatedRows || 0;\n const totalUpdatedColumns = batchUpdateResponse.data.totalUpdatedColumns || 0;\n const firstUpdatedRange = batchUpdateResponse.data.responses?.[0]?.updatedRange || `${sheetTitle}!${startRange}`;\n\n logger.info('sheets.values.csv-update completed', { id, gid: sheet.properties.sheetId, updatedRange: firstUpdatedRange, updatedRows: totalUpdatedRows, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheet.properties.sheetId ?? ''),\n spreadsheetTitle: spreadsheetData.properties?.title ?? '',\n spreadsheetUrl: spreadsheetData.spreadsheetUrl ?? `https://docs.google.com/spreadsheets/d/${id}`,\n sheetTitle,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheet.properties.sheetId}`,\n updatedRange: firstUpdatedRange,\n updatedRows: totalUpdatedRows,\n updatedColumns: totalUpdatedColumns,\n updatedCells: totalUpdatedCells,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values.csv-update error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error updating values from CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-csv-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","parse","z","NATIVE_DATE_POINTER","googleAuth","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","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,GAEhF,SAASA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzD,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,KAAK,QAAQ,YAAY;AAClC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,mBAAmB,QAAQ,qBAAqB;AACzD,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AACpI,SAASC,gBAAgB,QAAQ,qCAAqC;AAEtE,gGAAgG,GAChG,MAAMC,aAAa;AAEnB,MAAMC,cAAcV,EAAEW,MAAM,CAAC;IAC3BC,IAAIL;IACJM,KAAKR;IACLS,WAAWd,EAAEe,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,YAAYhB,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EoE,mBAAmB;gBAAEpE;YAAO;QAC9B;IACF,EAAE,OAAOqE,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGnD,OAAOkD;QAChElE,OAAOkE,KAAK,CAAC,kCAAkC;YAAEA,OAAOC;QAAQ;QAEhE,MAAM,IAAIlH,cAAcC,kBAAkBmH,aAAa,EAAE,CAAC,gCAAgC,EAAEF,SAAS,EAAE;YACrGG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACN9E;QACAG;IACF;AACF"}
@@ -13,8 +13,8 @@ declare const inputSchema: z.ZodObject<{
13
13
  values: z.ZodOptional<z.ZodBoolean>;
14
14
  a1s: z.ZodOptional<z.ZodBoolean>;
15
15
  render: z.ZodOptional<z.ZodEnum<{
16
- FORMATTED_VALUE: "FORMATTED_VALUE";
17
16
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
17
+ FORMATTED_VALUE: "FORMATTED_VALUE";
18
18
  FORMULA: "FORMULA";
19
19
  }>>;
20
20
  matchCase: z.ZodOptional<z.ZodBoolean>;
@@ -49,8 +49,8 @@ export default function createTool(): {
49
49
  values: z.ZodOptional<z.ZodBoolean>;
50
50
  a1s: z.ZodOptional<z.ZodBoolean>;
51
51
  render: z.ZodOptional<z.ZodEnum<{
52
- FORMATTED_VALUE: "FORMATTED_VALUE";
53
52
  UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
53
+ FORMATTED_VALUE: "FORMATTED_VALUE";
54
54
  FORMULA: "FORMULA";
55
55
  }>>;
56
56
  matchCase: z.ZodOptional<z.ZodBoolean>;
@@ -3,6 +3,7 @@ import { schemas } from '@mcp-z/oauth-google';
3
3
  const { AuthRequiredBranchSchema } = schemas;
4
4
  import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
5
5
  import { z } from 'zod';
6
+ import { RENDER_DESCRIPTION } from '../../constants.js';
6
7
  import { googleAuth } from '../../lib/google-auth.js';
7
8
  import { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.js';
8
9
  // Helper to convert column index to letter (0 = A, 1 = B, etc.)
@@ -31,7 +32,7 @@ const inputSchema = z.object({
31
32
  'FORMATTED_VALUE',
32
33
  'UNFORMATTED_VALUE',
33
34
  'FORMULA'
34
- ]).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.'),
35
+ ]).optional().describe(RENDER_DESCRIPTION),
35
36
  matchCase: z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).')
36
37
  });
37
38
  const successBranchSchema = z.object({
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Helper to convert column index to letter (0 = A, 1 = B, etc.)\nfunction columnIndexToLetter(index: number): string {\n let letter = '';\n let num = index + 1;\n while (num > 0) {\n const remainder = (num - 1) % 26;\n letter = String.fromCharCode(65 + remainder) + letter;\n num = Math.floor((num - 1) / 26);\n }\n return letter;\n}\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n query: z.coerce.string().trim().optional().describe('Text to search for in sheet cells. If empty, returns all data at specified granularity.'),\n select: z.enum(['cells', 'rows', 'columns']).describe('Granularity: cells (individual matches), rows (full matching rows), columns (columns with matching headers)'),\n values: z.boolean().optional().describe('Include cell values in response'),\n a1s: z.boolean().optional().describe('Include A1 notation references in response'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.'),\n matchCase: z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n count: z.number().int().nonnegative().describe('Number of matches found'),\n a1s: z.array(z.string()).optional().describe('A1 notation references for matches (e.g., \"B5\", \"A5:D5\", \"B:B\")'),\n values: z\n .array(z.union([z.array(SheetCellSchema), SheetCellSchema]))\n .optional()\n .describe('Cell values for matches (arrays for rows/columns, single values for cells)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search spreadsheet and return matches at cell, row, or column granularity. Use a1-notation prompt for range syntax.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, query, select, values = false, a1s = false, render, matchCase = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-search called', { id, gid, query, select, values, a1s, render, matchCase });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details including grid dimensions\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.values-search sheet not found', { id, gid, query });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Use actual sheet dimensions from gridProperties, with sensible defaults\n // Google Sheets default for new sheets is 1000 rows x 26 columns\n const rowCount = sheet.properties?.gridProperties?.rowCount ?? 1000;\n const columnCount = sheet.properties?.gridProperties?.columnCount ?? 26;\n const endColumn = columnIndexToLetter(columnCount - 1);\n const fullRange = `${sheetTitle}!A1:${endColumn}${rowCount}`;\n\n logger.debug?.('sheets.values-search fetching range', { fullRange, rowCount, columnCount });\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n const res = response.data;\n const allRows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n // Prepare query for matching (case-insensitive by default)\n const searchQuery = query ? (matchCase ? query : query.toLowerCase()) : null;\n\n let count = 0;\n const a1Array: string[] = [];\n const valuesArray: (string | number | boolean | null | (string | number | boolean | null)[])[] = [];\n\n // Helper to check if a cell matches the query\n const cellMatches = (cell: string | number | boolean | null): boolean => {\n if (!searchQuery) return true; // If no query, match all\n if (typeof cell !== 'string') return false;\n const cellValue = matchCase ? cell : cell.toLowerCase();\n return cellValue.includes(searchQuery);\n };\n\n if (select === 'cells') {\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n for (let colIdx = 0; colIdx < row.length; colIdx++) {\n const cell = row[colIdx];\n if (cellMatches(cell)) {\n count++;\n if (a1s) {\n const colLetter = columnIndexToLetter(colIdx);\n const rowNum = rowIdx + 1;\n a1Array.push(`${colLetter}${rowNum}`);\n }\n if (values) {\n valuesArray.push(cell ?? null);\n }\n }\n }\n }\n } else if (select === 'rows') {\n const matchingRows: number[] = [];\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n const matches = row.some((cell) => cellMatches(cell));\n if (matches) {\n matchingRows.push(rowIdx);\n }\n }\n\n count = matchingRows.length;\n for (const rowIdx of matchingRows) {\n const row = allRows[rowIdx];\n if (!row) continue; // Skip if row is undefined\n const rowNum = rowIdx + 1;\n\n if (a1s) {\n const colEnd = columnIndexToLetter(Math.max(0, row.length - 1));\n a1Array.push(`A${rowNum}:${colEnd}${rowNum}`);\n }\n if (values) {\n valuesArray.push(row);\n }\n }\n } else if (select === 'columns') {\n const headerRow = allRows[0] || [];\n const matchingCols: number[] = [];\n\n for (let colIdx = 0; colIdx < headerRow.length; colIdx++) {\n const header = headerRow[colIdx];\n if (cellMatches(header)) {\n matchingCols.push(colIdx);\n }\n }\n\n count = matchingCols.length;\n for (const colIdx of matchingCols) {\n const colLetter = columnIndexToLetter(colIdx);\n\n if (a1s) {\n a1Array.push(`${colLetter}:${colLetter}`);\n }\n if (values) {\n const columnValues = allRows.map((row) => (row && row[colIdx] !== undefined ? row[colIdx] : null));\n valuesArray.push(columnValues);\n }\n }\n }\n\n logger.info('sheets.values-search results', { count, select, hasA1s: a1s, hasValues: values });\n\n const result: Output = {\n type: 'success' as const,\n count,\n ...(a1s && a1Array.length > 0 && { a1s: a1Array }),\n ...(values && valuesArray.length > 0 && { values: valuesArray }),\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values-search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching spreadsheet: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","z","googleAuth","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","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":"AAAA,SAASA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzD,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,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,cAAcd,EAAEe,MAAM,CAAC;IAC3BC,IAAIZ;IACJa,KAAKd;IACLe,OAAOlB,EAAEmB,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,QAAQ,GAAGC,QAAQ,CAAC;IACpDC,QAAQxB,EAAEyB,IAAI,CAAC;QAAC;QAAS;QAAQ;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,CAACS;gBACnB;YACF;QACF;QAEAvD,OAAOC,IAAI,CAAC,gCAAgC;YAAEd;YAAOV;YAAQiF,QAAQ7E;YAAK8E,WAAWhF;QAAO;QAE5F,MAAMkB,SAAiB;YACrBZ,MAAM;YACNE;YACA,GAAIN,OAAOqD,QAAQO,MAAM,GAAG,KAAK;gBAAE5D,KAAKqD;YAAQ,CAAC;YACjD,GAAIvD,UAAUwD,YAAYM,MAAM,GAAG,KAAK;gBAAE9D,QAAQwD;YAAY,CAAC;QACjE;QAEA,OAAO;YACLyB,SAAS;gBAAC;oBAAE3E,MAAM;oBAAiB4E,MAAMC,KAAKC,SAAS,CAAClE;gBAAQ;aAAE;YAClEmE,mBAAmB;gBAAEnE;YAAO;QAC9B;IACF,EAAE,OAAOoE,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGvG,OAAOsG;QAChEjE,OAAOiE,KAAK,CAAC,8BAA8B;YAAEA,OAAOC;QAAQ;QAE5D,MAAM,IAAInH,cAAcC,kBAAkBoH,aAAa,EAAE,CAAC,6BAA6B,EAAEF,SAAS,EAAE;YAClGG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGZ;QAChD;IACF;AACF;AAEA,eAAe,SAASa;IACtB,OAAO;QACLC,MAAM;QACN5E;QACAG;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { RENDER_DESCRIPTION } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Helper to convert column index to letter (0 = A, 1 = B, etc.)\nfunction columnIndexToLetter(index: number): string {\n let letter = '';\n let num = index + 1;\n while (num > 0) {\n const remainder = (num - 1) % 26;\n letter = String.fromCharCode(65 + remainder) + letter;\n num = Math.floor((num - 1) / 26);\n }\n return letter;\n}\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n query: z.coerce.string().trim().optional().describe('Text to search for in sheet cells. If empty, returns all data at specified granularity.'),\n select: z.enum(['cells', 'rows', 'columns']).describe('Granularity: cells (individual matches), rows (full matching rows), columns (columns with matching headers)'),\n values: z.boolean().optional().describe('Include cell values in response'),\n a1s: z.boolean().optional().describe('Include A1 notation references in response'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe(RENDER_DESCRIPTION),\n matchCase: z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n count: z.number().int().nonnegative().describe('Number of matches found'),\n a1s: z.array(z.string()).optional().describe('A1 notation references for matches (e.g., \"B5\", \"A5:D5\", \"B:B\")'),\n values: z\n .array(z.union([z.array(SheetCellSchema), SheetCellSchema]))\n .optional()\n .describe('Cell values for matches (arrays for rows/columns, single values for cells)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search spreadsheet and return matches at cell, row, or column granularity. Use a1-notation prompt for range syntax.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, query, select, values = false, a1s = false, render, matchCase = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-search called', { id, gid, query, select, values, a1s, render, matchCase });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details including grid dimensions\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.values-search sheet not found', { id, gid, query });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Use actual sheet dimensions from gridProperties, with sensible defaults\n // Google Sheets default for new sheets is 1000 rows x 26 columns\n const rowCount = sheet.properties?.gridProperties?.rowCount ?? 1000;\n const columnCount = sheet.properties?.gridProperties?.columnCount ?? 26;\n const endColumn = columnIndexToLetter(columnCount - 1);\n const fullRange = `${sheetTitle}!A1:${endColumn}${rowCount}`;\n\n logger.debug?.('sheets.values-search fetching range', { fullRange, rowCount, columnCount });\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n const res = response.data;\n const allRows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n // Prepare query for matching (case-insensitive by default)\n const searchQuery = query ? (matchCase ? query : query.toLowerCase()) : null;\n\n let count = 0;\n const a1Array: string[] = [];\n const valuesArray: (string | number | boolean | null | (string | number | boolean | null)[])[] = [];\n\n // Helper to check if a cell matches the query\n const cellMatches = (cell: string | number | boolean | null): boolean => {\n if (!searchQuery) return true; // If no query, match all\n if (typeof cell !== 'string') return false;\n const cellValue = matchCase ? cell : cell.toLowerCase();\n return cellValue.includes(searchQuery);\n };\n\n if (select === 'cells') {\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n for (let colIdx = 0; colIdx < row.length; colIdx++) {\n const cell = row[colIdx];\n if (cellMatches(cell)) {\n count++;\n if (a1s) {\n const colLetter = columnIndexToLetter(colIdx);\n const rowNum = rowIdx + 1;\n a1Array.push(`${colLetter}${rowNum}`);\n }\n if (values) {\n valuesArray.push(cell ?? null);\n }\n }\n }\n }\n } else if (select === 'rows') {\n const matchingRows: number[] = [];\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n const matches = row.some((cell) => cellMatches(cell));\n if (matches) {\n matchingRows.push(rowIdx);\n }\n }\n\n count = matchingRows.length;\n for (const rowIdx of matchingRows) {\n const row = allRows[rowIdx];\n if (!row) continue; // Skip if row is undefined\n const rowNum = rowIdx + 1;\n\n if (a1s) {\n const colEnd = columnIndexToLetter(Math.max(0, row.length - 1));\n a1Array.push(`A${rowNum}:${colEnd}${rowNum}`);\n }\n if (values) {\n valuesArray.push(row);\n }\n }\n } else if (select === 'columns') {\n const headerRow = allRows[0] || [];\n const matchingCols: number[] = [];\n\n for (let colIdx = 0; colIdx < headerRow.length; colIdx++) {\n const header = headerRow[colIdx];\n if (cellMatches(header)) {\n matchingCols.push(colIdx);\n }\n }\n\n count = matchingCols.length;\n for (const colIdx of matchingCols) {\n const colLetter = columnIndexToLetter(colIdx);\n\n if (a1s) {\n a1Array.push(`${colLetter}:${colLetter}`);\n }\n if (values) {\n const columnValues = allRows.map((row) => (row && row[colIdx] !== undefined ? row[colIdx] : null));\n valuesArray.push(columnValues);\n }\n }\n }\n\n logger.info('sheets.values-search results', { count, select, hasA1s: a1s, hasValues: values });\n\n const result: Output = {\n type: 'success' as const,\n count,\n ...(a1s && a1Array.length > 0 && { a1s: a1Array }),\n ...(values && valuesArray.length > 0 && { values: valuesArray }),\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values-search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching spreadsheet: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","z","RENDER_DESCRIPTION","googleAuth","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","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":"AAAA,SAASA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzD,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,kBAAkB,QAAQ,qBAAqB;AACxD,SAASC,UAAU,QAAQ,2BAA2B;AACtD,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,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-3,8 +3,8 @@ import type { Logger, MiddlewareLayer } from '@mcp-z/server';
3
3
  import type { CommonRuntime, RuntimeOverrides, ServerConfig } from '../types.js';
4
4
  import { type OAuthAdapters } from './oauth-google.js';
5
5
  export declare function createLogger(config: ServerConfig): Logger;
6
- export declare function createTokenStore(baseDir: string): Promise<import("keyv").Keyv<CachedToken>>;
7
- export declare function createDcrStore(baseDir: string, required: boolean): Promise<import("keyv").Keyv<unknown> | undefined>;
6
+ export declare function createTokenStore(baseDir: string, logger?: Logger): Promise<import("keyv").Keyv<CachedToken>>;
7
+ export declare function createDcrStore(baseDir: string, required: boolean, logger?: Logger): Promise<import("keyv").Keyv<unknown> | undefined>;
8
8
  export declare function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer;
9
9
  export declare function createLoggingLayer(logger: Logger): MiddlewareLayer;
10
10
  export declare function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime>;
@@ -22,14 +22,14 @@ export function createLogger(config) {
22
22
  sync: false
23
23
  }) : pino.destination(1));
24
24
  }
25
- export async function createTokenStore(baseDir) {
25
+ export async function createTokenStore(baseDir, logger) {
26
26
  const tokenStoreUri = process.env.TOKEN_STORE_URI || pathToFileURL(path.join(baseDir, 'tokens.json')).href;
27
- return createStore(tokenStoreUri);
27
+ return createStore(tokenStoreUri, logger);
28
28
  }
29
- export async function createDcrStore(baseDir, required) {
29
+ export async function createDcrStore(baseDir, required, logger) {
30
30
  if (!required) return undefined;
31
31
  const dcrStoreUri = process.env.DCR_STORE_URI || pathToFileURL(path.join(baseDir, 'dcr.json')).href;
32
- return createStore(dcrStoreUri);
32
+ return createStore(dcrStoreUri, logger);
33
33
  }
34
34
  export function createAuthLayer(authMiddleware) {
35
35
  return {
@@ -52,9 +52,9 @@ export async function createDefaultRuntime(config, overrides) {
52
52
  var _config_baseUrl, _ref, _ref1;
53
53
  if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');
54
54
  const logger = createLogger(config);
55
- const tokenStore = await createTokenStore(config.baseDir);
55
+ const tokenStore = await createTokenStore(config.baseDir, logger);
56
56
  const baseUrl = (_config_baseUrl = config.baseUrl) !== null && _config_baseUrl !== void 0 ? _config_baseUrl : config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined;
57
- const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr');
57
+ const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr', logger);
58
58
  const oauthAdapters = await createOAuthAdapters(config, {
59
59
  logger,
60
60
  tokenStore,
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/setup/runtime.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url';\nimport { sanitizeForLoggingFormatter } from '@mcp-z/oauth';\nimport type { CachedToken } from '@mcp-z/oauth-google';\nimport type { Logger, MiddlewareLayer } from '@mcp-z/server';\nimport { createLoggingMiddleware } from '@mcp-z/server';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport pino from 'pino';\nimport createStore from '../lib/create-store.ts';\nimport * as mcp from '../mcp/index.ts';\nimport type { CommonRuntime, RuntimeDeps, RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createOAuthAdapters, type OAuthAdapters } from './oauth-google.ts';\n\nexport function createLogger(config: ServerConfig): Logger {\n const hasStdio = config.transport.type === 'stdio';\n const logsPath = path.join(config.baseDir, 'logs', `${config.name}.log`);\n if (hasStdio) fs.mkdirSync(path.dirname(logsPath), { recursive: true });\n return pino({ level: config.logLevel ?? 'info', formatters: sanitizeForLoggingFormatter() }, hasStdio ? pino.destination({ dest: logsPath, sync: false }) : pino.destination(1));\n}\n\nexport async function createTokenStore(baseDir: string) {\n const tokenStoreUri = process.env.TOKEN_STORE_URI || pathToFileURL(path.join(baseDir, 'tokens.json')).href;\n return createStore<CachedToken>(tokenStoreUri);\n}\n\nexport async function createDcrStore(baseDir: string, required: boolean) {\n if (!required) return undefined;\n const dcrStoreUri = process.env.DCR_STORE_URI || pathToFileURL(path.join(baseDir, 'dcr.json')).href;\n return createStore<unknown>(dcrStoreUri);\n}\n\nexport function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer {\n return {\n withTool: authMiddleware.withToolAuth,\n withResource: authMiddleware.withResourceAuth,\n withPrompt: authMiddleware.withPromptAuth,\n };\n}\n\nexport function createLoggingLayer(logger: Logger): MiddlewareLayer {\n const logging = createLoggingMiddleware({ logger });\n return {\n withTool: logging.withToolLogging,\n withResource: logging.withResourceLogging,\n withPrompt: logging.withPromptLogging,\n };\n}\n\nexport async function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime> {\n if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');\n\n const logger = createLogger(config);\n const tokenStore = await createTokenStore(config.baseDir);\n const baseUrl = config.baseUrl ?? (config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined);\n const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr');\n const oauthAdapters = await createOAuthAdapters(config, { logger, tokenStore, dcrStore }, baseUrl);\n const deps: RuntimeDeps = { config, logger, tokenStore, oauthAdapters, baseUrl };\n const createDomainModules =\n overrides?.createDomainModules ??\n (() => ({\n tools: Object.values(mcp.toolFactories).map((factory) => factory()),\n resources: Object.values(mcp.resourceFactories).map((factory) => factory()),\n prompts: Object.values(mcp.promptFactories).map((factory) => factory()),\n }));\n const middlewareFactories = overrides?.middlewareFactories ?? [() => createAuthLayer(oauthAdapters.middleware), () => createLoggingLayer(logger)];\n\n return {\n deps,\n middlewareFactories,\n createDomainModules,\n close: async () => {},\n };\n}\n"],"names":["pathToFileURL","sanitizeForLoggingFormatter","createLoggingMiddleware","fs","path","pino","createStore","mcp","createOAuthAdapters","createLogger","config","hasStdio","transport","type","logsPath","join","baseDir","name","mkdirSync","dirname","recursive","level","logLevel","formatters","destination","dest","sync","createTokenStore","tokenStoreUri","process","env","TOKEN_STORE_URI","href","createDcrStore","required","undefined","dcrStoreUri","DCR_STORE_URI","createAuthLayer","authMiddleware","withTool","withToolAuth","withResource","withResourceAuth","withPrompt","withPromptAuth","createLoggingLayer","logger","logging","withToolLogging","withResourceLogging","withPromptLogging","createDefaultRuntime","overrides","auth","Error","tokenStore","baseUrl","port","dcrStore","oauthAdapters","deps","createDomainModules","tools","Object","values","toolFactories","map","factory","resources","resourceFactories","prompts","promptFactories","middlewareFactories","middleware","close"],"mappings":"AAAA,SAASA,aAAa,QAAQ,WAAW;AACzC,SAASC,2BAA2B,QAAQ,eAAe;AAG3D,SAASC,uBAAuB,QAAQ,gBAAgB;AACxD,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAC7B,OAAOC,UAAU,OAAO;AACxB,OAAOC,iBAAiB,yBAAyB;AACjD,YAAYC,SAAS,kBAAkB;AAEvC,SAASC,mBAAmB,QAA4B,oBAAoB;AAE5E,OAAO,SAASC,aAAaC,MAAoB;QAI1BA;IAHrB,MAAMC,WAAWD,OAAOE,SAAS,CAACC,IAAI,KAAK;IAC3C,MAAMC,WAAWV,KAAKW,IAAI,CAACL,OAAOM,OAAO,EAAE,QAAQ,GAAGN,OAAOO,IAAI,CAAC,IAAI,CAAC;IACvE,IAAIN,UAAUR,GAAGe,SAAS,CAACd,KAAKe,OAAO,CAACL,WAAW;QAAEM,WAAW;IAAK;IACrE,OAAOf,KAAK;QAAEgB,KAAK,GAAEX,mBAAAA,OAAOY,QAAQ,cAAfZ,8BAAAA,mBAAmB;QAAQa,YAAYtB;IAA8B,GAAGU,WAAWN,KAAKmB,WAAW,CAAC;QAAEC,MAAMX;QAAUY,MAAM;IAAM,KAAKrB,KAAKmB,WAAW,CAAC;AAC/K;AAEA,OAAO,eAAeG,iBAAiBX,OAAe;IACpD,MAAMY,gBAAgBC,QAAQC,GAAG,CAACC,eAAe,IAAI/B,cAAcI,KAAKW,IAAI,CAACC,SAAS,gB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AAEnD;QAAQqC;QAAQS;QAAYI;QAAeH;IAAQ;IAC/E,MAAMK,8BACJT,sBAAAA,gCAAAA,UAAWS,mBAAmB,uCAC7B,IAAO,CAAA;YACNC,OAAOC,OAAOC,MAAM,CAAC1D,IAAI2D,aAAa,EAAEC,GAAG,CAAC,CAACC,UAAYA;YACzDC,WAAWL,OAAOC,MAAM,CAAC1D,IAAI+D,iBAAiB,EAAEH,GAAG,CAAC,CAACC,UAAYA;YACjEG,SAASP,OAAOC,MAAM,CAAC1D,IAAIiE,eAAe,EAAEL,GAAG,CAAC,CAACC,UAAYA;QAC/D,CAAA;IACF,MAAMK,+BAAsBpB,sBAAAA,gCAAAA,UAAWoB,mBAAmB,yCAAI;QAAC,IAAMnC,gBAAgBsB,cAAcc,UAAU;QAAG,IAAM5B,mBAAmBC;KAAQ;IAEjJ,OAAO;QACLc;QACAY;QACAX;QACAa,OAAO,WAAa;IACtB;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/setup/runtime.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url';\nimport { sanitizeForLoggingFormatter } from '@mcp-z/oauth';\nimport type { CachedToken } from '@mcp-z/oauth-google';\nimport type { Logger, MiddlewareLayer } from '@mcp-z/server';\nimport { createLoggingMiddleware } from '@mcp-z/server';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport pino from 'pino';\nimport createStore from '../lib/create-store.ts';\nimport * as mcp from '../mcp/index.ts';\nimport type { CommonRuntime, RuntimeDeps, RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createOAuthAdapters, type OAuthAdapters } from './oauth-google.ts';\n\nexport function createLogger(config: ServerConfig): Logger {\n const hasStdio = config.transport.type === 'stdio';\n const logsPath = path.join(config.baseDir, 'logs', `${config.name}.log`);\n if (hasStdio) fs.mkdirSync(path.dirname(logsPath), { recursive: true });\n return pino({ level: config.logLevel ?? 'info', formatters: sanitizeForLoggingFormatter() }, hasStdio ? pino.destination({ dest: logsPath, sync: false }) : pino.destination(1));\n}\n\nexport async function createTokenStore(baseDir: string, logger?: Logger) {\n const tokenStoreUri = process.env.TOKEN_STORE_URI || pathToFileURL(path.join(baseDir, 'tokens.json')).href;\n return createStore<CachedToken>(tokenStoreUri, logger);\n}\n\nexport async function createDcrStore(baseDir: string, required: boolean, logger?: Logger) {\n if (!required) return undefined;\n const dcrStoreUri = process.env.DCR_STORE_URI || pathToFileURL(path.join(baseDir, 'dcr.json')).href;\n return createStore<unknown>(dcrStoreUri, logger);\n}\n\nexport function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer {\n return {\n withTool: authMiddleware.withToolAuth,\n withResource: authMiddleware.withResourceAuth,\n withPrompt: authMiddleware.withPromptAuth,\n };\n}\n\nexport function createLoggingLayer(logger: Logger): MiddlewareLayer {\n const logging = createLoggingMiddleware({ logger });\n return {\n withTool: logging.withToolLogging,\n withResource: logging.withResourceLogging,\n withPrompt: logging.withPromptLogging,\n };\n}\n\nexport async function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime> {\n if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');\n\n const logger = createLogger(config);\n const tokenStore = await createTokenStore(config.baseDir, logger);\n const baseUrl = config.baseUrl ?? (config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined);\n const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr', logger);\n const oauthAdapters = await createOAuthAdapters(config, { logger, tokenStore, dcrStore }, baseUrl);\n const deps: RuntimeDeps = { config, logger, tokenStore, oauthAdapters, baseUrl };\n const createDomainModules =\n overrides?.createDomainModules ??\n (() => ({\n tools: Object.values(mcp.toolFactories).map((factory) => factory()),\n resources: Object.values(mcp.resourceFactories).map((factory) => factory()),\n prompts: Object.values(mcp.promptFactories).map((factory) => factory()),\n }));\n const middlewareFactories = overrides?.middlewareFactories ?? [() => createAuthLayer(oauthAdapters.middleware), () => createLoggingLayer(logger)];\n\n return {\n deps,\n middlewareFactories,\n createDomainModules,\n close: async () => {},\n };\n}\n"],"names":["pathToFileURL","sanitizeForLoggingFormatter","createLoggingMiddleware","fs","path","pino","createStore","mcp","createOAuthAdapters","createLogger","config","hasStdio","transport","type","logsPath","join","baseDir","name","mkdirSync","dirname","recursive","level","logLevel","formatters","destination","dest","sync","createTokenStore","logger","tokenStoreUri","process","env","TOKEN_STORE_URI","href","createDcrStore","required","undefined","dcrStoreUri","DCR_STORE_URI","createAuthLayer","authMiddleware","withTool","withToolAuth","withResource","withResourceAuth","withPrompt","withPromptAuth","createLoggingLayer","logging","withToolLogging","withResourceLogging","withPromptLogging","createDefaultRuntime","overrides","auth","Error","tokenStore","baseUrl","port","dcrStore","oauthAdapters","deps","createDomainModules","tools","Object","values","toolFactories","map","factory","resources","resourceFactories","prompts","promptFactories","middlewareFactories","middleware","close"],"mappings":"AAAA,SAASA,aAAa,QAAQ,WAAW;AACzC,SAASC,2BAA2B,QAAQ,eAAe;AAG3D,SAASC,uBAAuB,QAAQ,gBAAgB;AACxD,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAC7B,OAAOC,UAAU,OAAO;AACxB,OAAOC,iBAAiB,yBAAyB;AACjD,YAAYC,SAAS,kBAAkB;AAEvC,SAASC,mBAAmB,QAA4B,oBAAoB;AAE5E,OAAO,SAASC,aAAaC,MAAoB;QAI1BA;IAHrB,MAAMC,WAAWD,OAAOE,SAAS,CAACC,IAAI,KAAK;IAC3C,MAAMC,WAAWV,KAAKW,IAAI,CAACL,OAAOM,OAAO,EAAE,QAAQ,GAAGN,OAAOO,IAAI,CAAC,IAAI,CAAC;IACvE,IAAIN,UAAUR,GAAGe,SAAS,CAACd,KAAKe,OAAO,CAACL,WAAW;QAAEM,WAAW;IAAK;IACrE,OAAOf,KAAK;QAAEgB,KAAK,GAAEX,mBAAAA,OAAOY,QAAQ,cAAfZ,8BAAAA,mBAAmB;QAAQa,YAAYtB;IAA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UH,OAAOE,SAAS,CAAC8C,IAAI,GAAG,CAAC,iBAAiB,EAAEhD,OAAOE,SAAS,CAAC8C,IAAI,EAAE,GAAGtB;IAC7I,MAAMuB,WAAW,MAAMzB,eAAexB,OAAOM,OAAO,EAAEN,OAAO4C,IAAI,KAAK,OAAO1B;IAC7E,MAAMgC,gBAAgB,MAAMpD,oBAAoBE,QAAQ;QAAEkB;QAAQ4B;QAAYG;IAAS,GAAGF;IAC1F,MAAMI,OAAoB;QAAEnD;QAAQkB;QAAQ4B;QAAYI;QAAeH;IAAQ;IAC/E,MAAMK,8BACJT,sBAAAA,gCAAAA,UAAWS,mBAAmB,uCAC7B,IAAO,CAAA;YACNC,OAAOC,OAAOC,MAAM,CAAC1D,IAAI2D,aAAa,EAAEC,GAAG,CAAC,CAACC,UAAYA;YACzDC,WAAWL,OAAOC,MAAM,CAAC1D,IAAI+D,iBAAiB,EAAEH,GAAG,CAAC,CAACC,UAAYA;YACjEG,SAASP,OAAOC,MAAM,CAAC1D,IAAIiE,eAAe,EAAEL,GAAG,CAAC,CAACC,UAAYA;QAC/D,CAAA;IACF,MAAMK,+BAAsBpB,sBAAAA,gCAAAA,UAAWoB,mBAAmB,yCAAI;QAAC,IAAMlC,gBAAgBqB,cAAcc,UAAU;QAAG,IAAM3B,mBAAmBnB;KAAQ;IAEjJ,OAAO;QACLiC;QACAY;QACAX;QACAa,OAAO,WAAa;IACtB;AACF"}
@@ -1,17 +1,13 @@
1
1
  import { a1Col } from './column-utilities.js';
2
2
  import { findSheetByRef, scanKeyColumnRows } from './sheet-operations.js';
3
3
  export async function discoverHeader(sheets, spreadsheetId, sheetTitle) {
4
- try {
5
- var _response_data;
6
- const response = await sheets.spreadsheets.values.get({
7
- spreadsheetId,
8
- range: `${sheetTitle}!1:1`,
9
- majorDimension: 'ROWS'
10
- });
11
- return (((_response_data = response.data) === null || _response_data === void 0 ? void 0 : _response_data.values) || [])[0] || [];
12
- } catch {
13
- return [];
14
- }
4
+ var _response_data;
5
+ const response = await sheets.spreadsheets.values.get({
6
+ spreadsheetId,
7
+ range: `${sheetTitle}!1:1`,
8
+ majorDimension: 'ROWS'
9
+ });
10
+ return (((_response_data = response.data) === null || _response_data === void 0 ? void 0 : _response_data.values) || [])[0] || [];
15
11
  }
16
12
  export function validateAndMapHeaders(sheetHeaders, canonicalHeaders, requiredColumns = []) {
17
13
  const normalizeColumn = (col)=>String(col !== null && col !== void 0 ? col : '').toLowerCase().replace(/[^a-z0-9]/g, '');