@mcp-z/mcp-sheets 2.3.1 → 2.4.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 (142) hide show
  1. package/README.md +32 -27
  2. package/dist/cjs/constants.js.map +1 -1
  3. package/dist/cjs/index.js.map +1 -1
  4. package/dist/cjs/lib/create-store.js.map +1 -1
  5. package/dist/cjs/lib/google-auth.js.map +1 -1
  6. package/dist/cjs/mcp/index.js.map +1 -1
  7. package/dist/cjs/mcp/prompts/a1-notation.js.map +1 -1
  8. package/dist/cjs/mcp/prompts/index.js.map +1 -1
  9. package/dist/cjs/mcp/resources/index.js.map +1 -1
  10. package/dist/cjs/mcp/resources/spreadsheet.js.map +1 -1
  11. package/dist/cjs/mcp/tools/cells-format.js.map +1 -1
  12. package/dist/cjs/mcp/tools/cells-metadata-get.d.cts +95 -0
  13. package/dist/cjs/mcp/tools/cells-metadata-get.d.ts +95 -0
  14. package/dist/cjs/mcp/tools/cells-metadata-get.js +331 -0
  15. package/dist/cjs/mcp/tools/cells-metadata-get.js.map +1 -0
  16. package/dist/cjs/mcp/tools/chart-create.js.map +1 -1
  17. package/dist/cjs/mcp/tools/columns-get.js.map +1 -1
  18. package/dist/cjs/mcp/tools/columns-update.js.map +1 -1
  19. package/dist/cjs/mcp/tools/csv-get-columns.js.map +1 -1
  20. package/dist/cjs/mcp/tools/dimensions-batch-update.js.map +1 -1
  21. package/dist/cjs/mcp/tools/dimensions-move.js.map +1 -1
  22. package/dist/cjs/mcp/tools/index.d.cts +2 -0
  23. package/dist/cjs/mcp/tools/index.d.ts +2 -0
  24. package/dist/cjs/mcp/tools/index.js +8 -0
  25. package/dist/cjs/mcp/tools/index.js.map +1 -1
  26. package/dist/cjs/mcp/tools/lib/dimension-operations.js.map +1 -1
  27. package/dist/cjs/mcp/tools/rows-append.js.map +1 -1
  28. package/dist/cjs/mcp/tools/rows-csv-append.js.map +1 -1
  29. package/dist/cjs/mcp/tools/rows-get.js.map +1 -1
  30. package/dist/cjs/mcp/tools/sheet-copy-to.js.map +1 -1
  31. package/dist/cjs/mcp/tools/sheet-copy.js.map +1 -1
  32. package/dist/cjs/mcp/tools/sheet-create.js.map +1 -1
  33. package/dist/cjs/mcp/tools/sheet-delete.js.map +1 -1
  34. package/dist/cjs/mcp/tools/sheet-find.js.map +1 -1
  35. package/dist/cjs/mcp/tools/sheet-rename.js.map +1 -1
  36. package/dist/cjs/mcp/tools/spreadsheet-copy.js.map +1 -1
  37. package/dist/cjs/mcp/tools/spreadsheet-create.js.map +1 -1
  38. package/dist/cjs/mcp/tools/spreadsheet-find.js.map +1 -1
  39. package/dist/cjs/mcp/tools/spreadsheet-metadata-get.d.cts +59 -0
  40. package/dist/cjs/mcp/tools/spreadsheet-metadata-get.d.ts +59 -0
  41. package/dist/cjs/mcp/tools/spreadsheet-metadata-get.js +259 -0
  42. package/dist/cjs/mcp/tools/spreadsheet-metadata-get.js.map +1 -0
  43. package/dist/cjs/mcp/tools/spreadsheet-rename.js.map +1 -1
  44. package/dist/cjs/mcp/tools/validation-set.js.map +1 -1
  45. package/dist/cjs/mcp/tools/values-batch-update.js.map +1 -1
  46. package/dist/cjs/mcp/tools/values-clear.js.map +1 -1
  47. package/dist/cjs/mcp/tools/values-csv-update.js.map +1 -1
  48. package/dist/cjs/mcp/tools/values-markdown-update.js.map +1 -1
  49. package/dist/cjs/mcp/tools/values-replace.js.map +1 -1
  50. package/dist/cjs/mcp/tools/values-search.js.map +1 -1
  51. package/dist/cjs/schemas/index.js.map +1 -1
  52. package/dist/cjs/setup/config.js +5 -4
  53. package/dist/cjs/setup/config.js.map +1 -1
  54. package/dist/cjs/setup/http.d.cts +1 -1
  55. package/dist/cjs/setup/http.d.ts +1 -1
  56. package/dist/cjs/setup/http.js.map +1 -1
  57. package/dist/cjs/setup/index.js.map +1 -1
  58. package/dist/cjs/setup/oauth-google.js.map +1 -1
  59. package/dist/cjs/setup/runtime.js +3 -2
  60. package/dist/cjs/setup/runtime.js.map +1 -1
  61. package/dist/cjs/setup/stdio.js.map +1 -1
  62. package/dist/cjs/setup/version-help.js.map +1 -1
  63. package/dist/cjs/spreadsheet/column-utilities.js.map +1 -1
  64. package/dist/cjs/spreadsheet/csv-streaming.js.map +1 -1
  65. package/dist/cjs/spreadsheet/data-operations.js.map +1 -1
  66. package/dist/cjs/spreadsheet/deduplication-utils.js.map +1 -1
  67. package/dist/cjs/spreadsheet/markdown-runs.js.map +1 -1
  68. package/dist/cjs/spreadsheet/range-operations.d.cts +2 -1
  69. package/dist/cjs/spreadsheet/range-operations.d.ts +2 -1
  70. package/dist/cjs/spreadsheet/range-operations.js +12 -0
  71. package/dist/cjs/spreadsheet/range-operations.js.map +1 -1
  72. package/dist/cjs/spreadsheet/sheet-operations.js.map +1 -1
  73. package/dist/cjs/spreadsheet/spreadsheet-management.js.map +1 -1
  74. package/dist/esm/constants.js.map +1 -1
  75. package/dist/esm/index.js.map +1 -1
  76. package/dist/esm/lib/create-store.js.map +1 -1
  77. package/dist/esm/lib/google-auth.js.map +1 -1
  78. package/dist/esm/mcp/index.js.map +1 -1
  79. package/dist/esm/mcp/prompts/a1-notation.js.map +1 -1
  80. package/dist/esm/mcp/prompts/index.js.map +1 -1
  81. package/dist/esm/mcp/resources/index.js.map +1 -1
  82. package/dist/esm/mcp/resources/spreadsheet.js.map +1 -1
  83. package/dist/esm/mcp/tools/cells-format.js.map +1 -1
  84. package/dist/esm/mcp/tools/cells-metadata-get.d.ts +95 -0
  85. package/dist/esm/mcp/tools/cells-metadata-get.js +155 -0
  86. package/dist/esm/mcp/tools/cells-metadata-get.js.map +1 -0
  87. package/dist/esm/mcp/tools/chart-create.js.map +1 -1
  88. package/dist/esm/mcp/tools/columns-get.js.map +1 -1
  89. package/dist/esm/mcp/tools/columns-update.js.map +1 -1
  90. package/dist/esm/mcp/tools/csv-get-columns.js.map +1 -1
  91. package/dist/esm/mcp/tools/dimensions-batch-update.js.map +1 -1
  92. package/dist/esm/mcp/tools/dimensions-move.js.map +1 -1
  93. package/dist/esm/mcp/tools/index.d.ts +2 -0
  94. package/dist/esm/mcp/tools/index.js +2 -0
  95. package/dist/esm/mcp/tools/index.js.map +1 -1
  96. package/dist/esm/mcp/tools/lib/dimension-operations.js.map +1 -1
  97. package/dist/esm/mcp/tools/rows-append.js.map +1 -1
  98. package/dist/esm/mcp/tools/rows-csv-append.js.map +1 -1
  99. package/dist/esm/mcp/tools/rows-get.js.map +1 -1
  100. package/dist/esm/mcp/tools/sheet-copy-to.js.map +1 -1
  101. package/dist/esm/mcp/tools/sheet-copy.js.map +1 -1
  102. package/dist/esm/mcp/tools/sheet-create.js.map +1 -1
  103. package/dist/esm/mcp/tools/sheet-delete.js.map +1 -1
  104. package/dist/esm/mcp/tools/sheet-find.js.map +1 -1
  105. package/dist/esm/mcp/tools/sheet-rename.js.map +1 -1
  106. package/dist/esm/mcp/tools/spreadsheet-copy.js.map +1 -1
  107. package/dist/esm/mcp/tools/spreadsheet-create.js.map +1 -1
  108. package/dist/esm/mcp/tools/spreadsheet-find.js.map +1 -1
  109. package/dist/esm/mcp/tools/spreadsheet-metadata-get.d.ts +59 -0
  110. package/dist/esm/mcp/tools/spreadsheet-metadata-get.js +89 -0
  111. package/dist/esm/mcp/tools/spreadsheet-metadata-get.js.map +1 -0
  112. package/dist/esm/mcp/tools/spreadsheet-rename.js.map +1 -1
  113. package/dist/esm/mcp/tools/validation-set.js.map +1 -1
  114. package/dist/esm/mcp/tools/values-batch-update.js.map +1 -1
  115. package/dist/esm/mcp/tools/values-clear.js.map +1 -1
  116. package/dist/esm/mcp/tools/values-csv-update.js.map +1 -1
  117. package/dist/esm/mcp/tools/values-markdown-update.js.map +1 -1
  118. package/dist/esm/mcp/tools/values-replace.js.map +1 -1
  119. package/dist/esm/mcp/tools/values-search.js.map +1 -1
  120. package/dist/esm/schemas/index.js.map +1 -1
  121. package/dist/esm/setup/config.js +4 -3
  122. package/dist/esm/setup/config.js.map +1 -1
  123. package/dist/esm/setup/http.d.ts +1 -1
  124. package/dist/esm/setup/http.js.map +1 -1
  125. package/dist/esm/setup/index.js.map +1 -1
  126. package/dist/esm/setup/oauth-google.js.map +1 -1
  127. package/dist/esm/setup/runtime.js +3 -2
  128. package/dist/esm/setup/runtime.js.map +1 -1
  129. package/dist/esm/setup/stdio.js.map +1 -1
  130. package/dist/esm/setup/version-help.js.map +1 -1
  131. package/dist/esm/spreadsheet/column-utilities.js.map +1 -1
  132. package/dist/esm/spreadsheet/csv-streaming.js.map +1 -1
  133. package/dist/esm/spreadsheet/data-operations.js.map +1 -1
  134. package/dist/esm/spreadsheet/deduplication-utils.js.map +1 -1
  135. package/dist/esm/spreadsheet/markdown-runs.js.map +1 -1
  136. package/dist/esm/spreadsheet/range-operations.d.ts +2 -1
  137. package/dist/esm/spreadsheet/range-operations.js +11 -2
  138. package/dist/esm/spreadsheet/range-operations.js.map +1 -1
  139. package/dist/esm/spreadsheet/sheet-operations.js.map +1 -1
  140. package/dist/esm/spreadsheet/spreadsheet-management.js.map +1 -1
  141. package/dist/esm/types.js.map +1 -1
  142. package/package.json +11 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-batch-update.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Types for updated data response\ninterface UpdatedDataItem {\n range: string;\n majorDimension: 'ROWS' | 'COLUMNS';\n values?: (string | number | boolean | null)[][];\n}\n\n// Input schema for values batch update requests\nconst ValuesBatchUpdateRequestSchema = z.object({\n range: A1NotationSchema.describe('A1 notation range defining the bounded target area. Data dimensions must match range dimensions. Example: D1:D100 requires exactly 100 rows of data. Use open-ended ranges like D1:D to write any number of rows.'),\n values: z.array(z.array(SheetCellSchema)).min(1).describe('2D array of values. Row count must match range height, column count must match range width. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether values represent rows or columns'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(ValuesBatchUpdateRequestSchema).min(1).describe('Array of value update requests'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input)'),\n includeData: z.boolean().describe('Whether to include updated cell values in the response'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Title of the updated spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the updated spreadsheet'),\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n totalUpdatedRows: z.number().int().nonnegative().describe('Total number of rows updated across all requests'),\n totalUpdatedColumns: z.number().int().nonnegative().describe('Total number of columns updated across all requests'),\n totalUpdatedCells: z.number().int().nonnegative().describe('Total number of cells updated across all requests'),\n updatedRanges: z.array(z.string()).describe('A1 notation ranges that were updated'),\n updatedData: z\n .array(\n z.object({\n range: z.string().describe('A1 notation range that was updated'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension of the updated data'),\n values: z.array(z.array(SheetCellSchema)).optional().describe('Updated values (if includeData was true)'),\n })\n )\n .optional()\n .describe('Detailed information about updated data (if includeData was true)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests, valueInputOption = 'USER_ENTERED', includeData = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n includeData,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n const spreadsheetTitle = spreadsheetData.properties?.title ?? '';\n const spreadsheetUrl = spreadsheetData.spreadsheetUrl ?? '';\n\n // Find sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for batch update', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n const sheetGid = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetGid}`;\n\n // Build batch update request with prefixed ranges\n const batchUpdateData = requests.map((req) => ({\n range: `${sheetTitle}!${req.range}`,\n values: req.values,\n majorDimension: req.majorDimension || 'ROWS',\n }));\n\n logger.info('sheets.values.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchUpdateDataCount: batchUpdateData.length,\n });\n\n // Execute the batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchUpdateData,\n includeValuesInResponse: includeData,\n responseDateTimeRenderOption: 'FORMATTED_STRING',\n responseValueRenderOption: 'FORMATTED_VALUE',\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Validate batch operation results and detect partial failures\n const responses = updateResult.responses || [];\n const expectedCount = requests.length;\n const actualCount = responses.length;\n\n if (actualCount !== expectedCount) {\n logger.error('Partial batch failure detected', {\n expectedOperations: expectedCount,\n completedOperations: actualCount,\n spreadsheetId: id,\n sheetTitle,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation partially failed: ${actualCount}/${expectedCount} operations completed`);\n }\n\n // Check for any failed operations (empty or null responses)\n const failedOperations = responses.filter((response, index) => {\n if (!response || !response.updatedRange) {\n logger.error('Failed operation detected', {\n operationIndex: index,\n requestedRange: requests[index]?.range,\n spreadsheetId: id,\n sheetTitle,\n });\n return true;\n }\n return false;\n });\n\n if (failedOperations.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, `${failedOperations.length} operations failed to update ranges`);\n }\n\n // Extract updated ranges and calculate totals\n const updatedRanges = responses.map((response) => response.updatedRange || '').filter((range) => range);\n const totalUpdatedRows = updateResult.totalUpdatedRows || 0;\n const totalUpdatedColumns = updateResult.totalUpdatedColumns || 0;\n const totalUpdatedCells = updateResult.totalUpdatedCells || 0;\n\n // Build updated data response if requested\n let updatedData: UpdatedDataItem[] | undefined;\n if (includeData && updateResult.responses) {\n updatedData = updateResult.responses\n .filter((response) => response.updatedData)\n .map((response) => {\n const item: UpdatedDataItem = {\n range: response.updatedRange || '',\n majorDimension: (response.updatedData?.majorDimension as 'ROWS' | 'COLUMNS' | undefined) || 'ROWS',\n };\n const values = response.updatedData?.values as (string | number | boolean | null | undefined)[][] | undefined;\n if (values !== undefined) {\n // Map undefined values to null for JSON Schema compatibility\n item.values = values.map((row) => row.map((cell) => (cell === undefined ? null : cell)));\n }\n return item;\n });\n }\n\n logger.info('sheets.values.batchUpdate completed successfully', {\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRangesCount: updatedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetGid),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRanges,\n updatedData,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Batch update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","ValuesBatchUpdateRequestSchema","z","object","range","A1NotationSchema","describe","values","array","SheetCellSchema","min","majorDimension","enum","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","valueInputOption","includeData","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalUpdatedRows","number","int","nonnegative","totalUpdatedColumns","totalUpdatedCells","updatedRanges","updatedData","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetData","sheet","sheets","spreadsheetResponse","sheetGid","batchUpdateData","batchUpdateResponse","updateResult","responses","expectedCount","actualCount","failedOperations","error","message","info","requestCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","map","req","batchUpdateDataCount","batchUpdate","requestBody","includeValuesInResponse","responseDateTimeRenderOption","responseValueRenderOption","expectedOperations","completedOperations","InternalError","filter","response","index","updatedRange","operationIndex","requestedRange","item","undefined","row","cell","updatedRangesCount","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BAyOA;;;eAAwBA;;;sBAzOY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBACiG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN5H,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAeR,gDAAgD;AAChD,IAAME,iCAAiCC,MAAC,CAACC,MAAM,CAAC;IAC9CC,OAAOC,yBAAgB,CAACC,QAAQ,CAAC;IACjCC,QAAQL,MAAC,CAACM,KAAK,CAACN,MAAC,CAACM,KAAK,CAACC,wBAAe,GAAGC,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IAC1DK,gBAAgBT,MAAC,CAACU,IAAI,CAAC;QAAC;QAAQ;KAAU,EAAEN,QAAQ,CAAC;AACvD;AAEA,IAAMO,cAAcX,MAAC,CAACC,MAAM,CAAC;IAC3BW,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,UAAUhB,MAAC,CAACM,KAAK,CAACP,gCAAgCS,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IAClEa,kBAAkBjB,MAAC,CAACU,IAAI,CAAC;QAAC;QAAO;KAAe,EAAEN,QAAQ,CAAC;IAC3Dc,aAAalB,MAAC,CAACmB,OAAO,GAAGf,QAAQ,CAAC;AACpC;AAEA,IAAMgB,sBAAsBpB,MAAC,CAACC,MAAM,CAAC;IACnCoB,MAAMrB,MAAC,CAACsB,OAAO,CAAC;IAChBV,IAAIW,4BAAmB;IACvBT,KAAKU,uBAAc;IACnBC,kBAAkBzB,MAAC,CAAC0B,MAAM,GAAGtB,QA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+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-batch-update.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Types for updated data response\ninterface UpdatedDataItem {\n range: string;\n majorDimension: 'ROWS' | 'COLUMNS';\n values?: (string | number | boolean | null)[][];\n}\n\n// Input schema for values batch update requests\nconst ValuesBatchUpdateRequestSchema = z.object({\n range: A1NotationSchema.describe('A1 notation range defining the bounded target area. Data dimensions must match range dimensions. Example: D1:D100 requires exactly 100 rows of data. Use open-ended ranges like D1:D to write any number of rows.'),\n values: z.array(z.array(SheetCellSchema)).min(1).describe('2D array of values. Row count must match range height, column count must match range width. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether values represent rows or columns'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(ValuesBatchUpdateRequestSchema).min(1).describe('Array of value update requests'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input)'),\n includeData: z.boolean().describe('Whether to include updated cell values in the response'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Title of the updated spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the updated spreadsheet'),\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n totalUpdatedRows: z.number().int().nonnegative().describe('Total number of rows updated across all requests'),\n totalUpdatedColumns: z.number().int().nonnegative().describe('Total number of columns updated across all requests'),\n totalUpdatedCells: z.number().int().nonnegative().describe('Total number of cells updated across all requests'),\n updatedRanges: z.array(z.string()).describe('A1 notation ranges that were updated'),\n updatedData: z\n .array(\n z.object({\n range: z.string().describe('A1 notation range that was updated'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension of the updated data'),\n values: z.array(z.array(SheetCellSchema)).optional().describe('Updated values (if includeData was true)'),\n })\n )\n .optional()\n .describe('Detailed information about updated data (if includeData was true)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests, valueInputOption = 'USER_ENTERED', includeData = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n includeData,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n const spreadsheetTitle = spreadsheetData.properties?.title ?? '';\n const spreadsheetUrl = spreadsheetData.spreadsheetUrl ?? '';\n\n // Find sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for batch update', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n const sheetGid = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetGid}`;\n\n // Build batch update request with prefixed ranges\n const batchUpdateData = requests.map((req) => ({\n range: `${sheetTitle}!${req.range}`,\n values: req.values,\n majorDimension: req.majorDimension || 'ROWS',\n }));\n\n logger.info('sheets.values.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchUpdateDataCount: batchUpdateData.length,\n });\n\n // Execute the batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchUpdateData,\n includeValuesInResponse: includeData,\n responseDateTimeRenderOption: 'FORMATTED_STRING',\n responseValueRenderOption: 'FORMATTED_VALUE',\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Validate batch operation results and detect partial failures\n const responses = updateResult.responses || [];\n const expectedCount = requests.length;\n const actualCount = responses.length;\n\n if (actualCount !== expectedCount) {\n logger.error('Partial batch failure detected', {\n expectedOperations: expectedCount,\n completedOperations: actualCount,\n spreadsheetId: id,\n sheetTitle,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation partially failed: ${actualCount}/${expectedCount} operations completed`);\n }\n\n // Check for any failed operations (empty or null responses)\n const failedOperations = responses.filter((response, index) => {\n if (!response || !response.updatedRange) {\n logger.error('Failed operation detected', {\n operationIndex: index,\n requestedRange: requests[index]?.range,\n spreadsheetId: id,\n sheetTitle,\n });\n return true;\n }\n return false;\n });\n\n if (failedOperations.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, `${failedOperations.length} operations failed to update ranges`);\n }\n\n // Extract updated ranges and calculate totals\n const updatedRanges = responses.map((response) => response.updatedRange || '').filter((range) => range);\n const totalUpdatedRows = updateResult.totalUpdatedRows || 0;\n const totalUpdatedColumns = updateResult.totalUpdatedColumns || 0;\n const totalUpdatedCells = updateResult.totalUpdatedCells || 0;\n\n // Build updated data response if requested\n let updatedData: UpdatedDataItem[] | undefined;\n if (includeData && updateResult.responses) {\n updatedData = updateResult.responses\n .filter((response) => response.updatedData)\n .map((response) => {\n const item: UpdatedDataItem = {\n range: response.updatedRange || '',\n majorDimension: (response.updatedData?.majorDimension as 'ROWS' | 'COLUMNS' | undefined) || 'ROWS',\n };\n const values = response.updatedData?.values as (string | number | boolean | null | undefined)[][] | undefined;\n if (values !== undefined) {\n // Map undefined values to null for JSON Schema compatibility\n item.values = values.map((row) => row.map((cell) => (cell === undefined ? null : cell)));\n }\n return item;\n });\n }\n\n logger.info('sheets.values.batchUpdate completed successfully', {\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRangesCount: updatedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetGid),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRanges,\n updatedData,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Batch update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","ValuesBatchUpdateRequestSchema","z","object","range","A1NotationSchema","describe","values","array","SheetCellSchema","min","majorDimension","enum","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","valueInputOption","includeData","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalUpdatedRows","number","int","nonnegative","totalUpdatedColumns","totalUpdatedCells","updatedRanges","updatedData","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetData","sheet","sheets","spreadsheetResponse","sheetGid","batchUpdateData","batchUpdateResponse","updateResult","responses","expectedCount","actualCount","failedOperations","error","message","info","requestCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","map","req","batchUpdateDataCount","batchUpdate","requestBody","includeValuesInResponse","responseDateTimeRenderOption","responseValueRenderOption","expectedOperations","completedOperations","InternalError","filter","response","index","updatedRange","operationIndex","requestedRange","item","undefined","row","cell","updatedRangesCount","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BAyOA;;;eAAwBA;;;sBAzOY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBACiG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN5H,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAeR,gDAAgD;AAChD,IAAME,iCAAiCC,MAAC,CAACC,MAAM,CAAC;IAC9CC,OAAOC,yBAAgB,CAACC,QAAQ,CAAC;IACjCC,QAAQL,MAAC,CAACM,KAAK,CAACN,MAAC,CAACM,KAAK,CAACC,wBAAe,GAAGC,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IAC1DK,gBAAgBT,MAAC,CAACU,IAAI,CAAC;QAAC;QAAQ;KAA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E,mBAAmB;gCAAElE,QAAAA;4BAAO;wBAC9B;;;oBACOgB;oBACDC,UAAUD,AAAK,YAALA,OAAiBmD,SAAQnD,MAAMC,OAAO,GAAGkB,OAAOnB;oBAChEb,OAAOa,KAAK,CAAC,iCAAiC;wBAC5C/C,IAAAA;wBACAE,KAAAA;wBACAgD,cAAc9C,SAAS+C,MAAM;wBAC7B9C,kBAAAA;wBACA0C,OAAOC;oBACT;oBAEA,MAAM,IAAIoB,qBAAa,CAACC,yBAAiB,CAACY,aAAa,EAAE,AAAC,gCAAuC,OAARjC,UAAW;wBAClGmD,OAAOpD,AAAK,YAALA,OAAiBmD,SAAQnD,MAAMoD,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASzG;IACtB,OAAO;QACLoH,MAAM;QACNvE,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-clear.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, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n ranges: z.array(A1NotationSchema).min(1).describe('A1 notation ranges to clear (e.g., [\"A1:B5\", \"D3:D10\"]). Clears values only, preserves formatting.'),\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 spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the spreadsheet'),\n sheetTitle: z.string().describe('Title of the sheet'),\n sheetUrl: z.string().describe('URL of the sheet'),\n clearedRanges: z.array(z.string()).describe('A1 notation ranges that were cleared'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Clear cell values from one or more ranges. Clears values only - preserves formatting, validation, and other cell properties. 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, ranges }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.clear called', { id, gid, rangeCount: ranges.length });\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 clear', { id, gid, rangeCount: ranges.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 // Prefix ranges with sheet title\n const prefixedRanges = ranges.map((range) => `${sheetTitle}!${range}`);\n\n logger.info('sheets.values.clear executing', { spreadsheetId: id, sheetTitle, prefixedRanges });\n\n // Use batchClear for efficiency (works for single or multiple ranges)\n const clearResponse = await sheets.spreadsheets.values.batchClear({\n spreadsheetId: id,\n requestBody: {\n ranges: prefixedRanges,\n },\n });\n\n const clearedRanges = clearResponse.data.clearedRanges || [];\n\n logger.info('sheets.values.clear completed successfully', {\n spreadsheetId: id,\n sheetTitle,\n clearedRangesCount: clearedRanges.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 clearedRanges,\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('Clear operation failed', { id, gid, rangeCount: ranges.length, error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error clearing values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-clear',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","ranges","array","A1NotationSchema","min","describe","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","clearedRanges","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetData","sheet","sheets","spreadsheetResponse","sheetGid","prefixedRanges","clearResponse","error","message","info","rangeCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","map","range","values","batchClear","requestBody","clearedRangesCount","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":";;;;+BAoHA;;;eAAwBA;;;sBApHY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBACgF;;;;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OrC,AAAK,YAALA,OAAiBmC,SAAQnC,MAAMqC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS/E;IACtB,OAAO;QACLgF,MAAM;QACNpD,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-clear.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, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n ranges: z.array(A1NotationSchema).min(1).describe('A1 notation ranges to clear (e.g., [\"A1:B5\", \"D3:D10\"]). Clears values only, preserves formatting.'),\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 spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the spreadsheet'),\n sheetTitle: z.string().describe('Title of the sheet'),\n sheetUrl: z.string().describe('URL of the sheet'),\n clearedRanges: z.array(z.string()).describe('A1 notation ranges that were cleared'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Clear cell values from one or more ranges. Clears values only - preserves formatting, validation, and other cell properties. 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, ranges }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.clear called', { id, gid, rangeCount: ranges.length });\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 clear', { id, gid, rangeCount: ranges.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 // Prefix ranges with sheet title\n const prefixedRanges = ranges.map((range) => `${sheetTitle}!${range}`);\n\n logger.info('sheets.values.clear executing', { spreadsheetId: id, sheetTitle, prefixedRanges });\n\n // Use batchClear for efficiency (works for single or multiple ranges)\n const clearResponse = await sheets.spreadsheets.values.batchClear({\n spreadsheetId: id,\n requestBody: {\n ranges: prefixedRanges,\n },\n });\n\n const clearedRanges = clearResponse.data.clearedRanges || [];\n\n logger.info('sheets.values.clear completed successfully', {\n spreadsheetId: id,\n sheetTitle,\n clearedRangesCount: clearedRanges.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 clearedRanges,\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('Clear operation failed', { id, gid, rangeCount: ranges.length, error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error clearing values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-clear',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","ranges","array","A1NotationSchema","min","describe","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","clearedRanges","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetData","sheet","sheets","spreadsheetResponse","sheetGid","prefixedRanges","clearResponse","error","message","info","rangeCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","map","range","values","batchClear","requestBody","clearedRangesCount","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":";;;;+BAoHA;;;eAAwBA;;;sBApHY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBACgF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3G,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,QAAQN,MAAC,CAACO,KAAK,CAACC,yBAAgB,EAAEC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AACpD;AAEA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gCACX3D,QAAQ6B;4BACV;wBACF;;;oBALMC,gBAAgB;oBAOhBf,gBAAgBe,cAAce,IAAI,CAAC9B,aAAa;oBAEtDQ,OAAOU,IAAI,CAAC,8CAA8C;wBACxDU,eAAe/C;wBACfiB,YAAAA;wBACA+C,oBAAoB7C,cAAcoB,MAAM;oBAC1C;oBAEMf,SAAiB;wBACrBd,MAAM;wBACNV,IAAAA;wBACAE,KAAKoD,OAAOtB;wBACZlB,kBAAkBA,oBAAoB;wBACtCE,gBAAgBA,kBAAkB;wBAClCC,YAAAA;wBACAC,UAAAA;wBACAC,eAAAA;oBACF;oBAEA;;wBAAO;4BACL8C,OAAO;gCAAG;oCAAEvD,MAAM;oCAAiBwD,MAAMC,KAAKC,SAAS,CAAC5C;gCAAQ;;4BAChE6C,mBAAmB;gCAAE7C,QAAAA;4BAAO;wBAC9B;;;oBACOW;oBACDC,UAAUD,AAAK,YAALA,OAAiBmC,SAAQnC,MAAMC,OAAO,GAAGkB,OAAOnB;oBAChER,OAAOQ,KAAK,CAAC,0BAA0B;wBAAEnC,IAAAA;wBAAIE,KAAAA;wBAAKoC,YAAYlC,OAAOmC,MAAM;wBAAEJ,OAAOC;oBAAQ;oBAE5F,MAAM,IAAIoB,qBAAa,CAACC,yBAAiB,CAACc,aAAa,EAAE,AAAC,0BAAiC,OAARnC,UAAW;wBAC5FoC,OAAOrC,AAAK,YAALA,OAAiBmC,SAAQnC,MAAMqC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS/E;IACtB,OAAO;QACLgF,MAAM;QACNpD,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-csv-update.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with range-based update (no deduplication) */\n\nimport { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { parse } from 'csv-parse';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\n\n/** Batch size for Sheets API calls (1000 rows × avg 10 cols = 10K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n sourceUri: z.string().trim().min(1).describe('CSV file URI (file://, http://, https://)'),\n startRange: A1NotationSchema.default('A1').describe('Top-left cell where CSV data starts (default: A1)'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How to interpret values (RAW = exact, USER_ENTERED = parse formulas/dates)'),\n sourceHasHeaders: z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Spreadsheet title'),\n spreadsheetUrl: z.string().describe('Spreadsheet URL'),\n sheetTitle: z.string().describe('Sheet title'),\n sheetUrl: z.string().describe('Sheet URL'),\n updatedRange: z.string().describe('A1 notation range that was updated'),\n updatedRows: z.number().describe('Number of rows updated'),\n updatedColumns: z.number().describe('Number of columns updated'),\n updatedCells: z.number().describe('Number of cells updated'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, sourceUri, startRange, valueInputOption = 'USER_ENTERED', sourceHasHeaders }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.csv-update called', { id, gid, sourceUri, startRange, valueInputOption, sourceHasHeaders });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n\n // Find the sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? '';\n\n // Streaming CSV processing state\n let sourceHeaders: string[] = [];\n const allRows: (string | number | boolean | null)[][] = [];\n let totalCols = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser with native streaming\n const parser = readStream.pipe(\n parse({\n columns: !!sourceHasHeaders, // Parse first row as column names if source has headers\n skip_empty_lines: true,\n trim: true,\n cast: true, // Auto-convert numbers/booleans\n relax_column_count: true,\n })\n );\n\n // Stream and collect all rows (with batching for very large files)\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders.length === 0) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n totalCols = sourceHeaders.length;\n logger.info('sheets.values.csv-update source headers', { sourceHeaders, totalCols });\n }\n\n // Convert record to row array (exclude source headers from data range)\n // CSV values are strings/numbers/booleans/nulls from the parser\n const row = sourceHeaders.map((header) => (record as Record<string, string | number | boolean | null>)[header] ?? null);\n allRows.push(row);\n } else {\n // sourceHasHeaders=false: record is an array, include all rows (including first row)\n const row = record as (string | number | boolean | null)[];\n allRows.push(row);\n\n if (totalCols === 0) {\n totalCols = row.length;\n }\n }\n }\n\n if (allRows.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'CSV file is empty');\n }\n\n // Prepare data for update (all rows)\n const dataToWrite: (string | number | boolean | null)[][] = allRows;\n\n // For large datasets, use batchUpdate to write in chunks\n // This respects the 40K cell limit per request\n const batchRequests = [];\n const currentRow = startRange.match(/[A-Z]+(\\d+)/)?.[1] || '1';\n let currentRowNum = Number.parseInt(currentRow, 10);\n\n for (let i = 0; i < dataToWrite.length; i += BATCH_SIZE) {\n const batchData = dataToWrite.slice(i, i + BATCH_SIZE);\n const batchRange = `${sheetTitle}!${startRange.match(/[A-Z]+/)?.[0]}${currentRowNum}`;\n\n batchRequests.push({\n range: batchRange,\n values: batchData,\n });\n\n currentRowNum += batchData.length;\n }\n\n logger.info('sheets.values.csv-update batching', { totalBatches: batchRequests.length, batchSize: BATCH_SIZE });\n\n // Execute batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchRequests,\n },\n });\n\n const totalUpdatedCells = batchUpdateResponse.data.totalUpdatedCells || 0;\n const totalUpdatedRows = batchUpdateResponse.data.totalUpdatedRows || 0;\n const totalUpdatedColumns = batchUpdateResponse.data.totalUpdatedColumns || 0;\n const firstUpdatedRange = batchUpdateResponse.data.responses?.[0]?.updatedRange || `${sheetTitle}!${startRange}`;\n\n logger.info('sheets.values.csv-update completed', { id, gid: sheet.properties.sheetId, updatedRange: firstUpdatedRange, updatedRows: totalUpdatedRows, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheet.properties.sheetId ?? ''),\n spreadsheetTitle: spreadsheetData.properties?.title ?? '',\n spreadsheetUrl: spreadsheetData.spreadsheetUrl ?? `https://docs.google.com/spreadsheets/d/${id}`,\n sheetTitle,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheet.properties.sheetId}`,\n updatedRange: firstUpdatedRange,\n updatedRows: totalUpdatedRows,\n updatedColumns: totalUpdatedColumns,\n updatedCells: totalUpdatedCells,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values.csv-update error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error updating values from CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-csv-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","BATCH_SIZE","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","sourceUri","string","trim","min","describe","startRange","A1NotationSchema","default","valueInputOption","enum","sourceHasHeaders","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRange","updatedRows","number","updatedColumns","updatedCells","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","sheet","spreadsheetData","batchUpdateResponse","sheets","spreadsheetResponse","sourceHeaders","allRows","totalCols","readStream","parser","dataToWrite","batchRequests","currentRow","currentRowNum","i","batchData","batchRange","totalUpdatedCells","totalUpdatedRows","totalUpdatedColumns","firstUpdatedRange","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","getCsvReadStream","pipe","parse","columns","skip_empty_lines","cast","relax_column_count","record","length","Object","keys","row","map","header","push","match","Number","parseInt","slice","range","values","totalBatches","batchSize","batchUpdate","requestBody","responses","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":"AAAA,gFAAgF;;;;+BAiMhF;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D,MAAMC,OAAO,GAAGc,OAAOf;oBAChEtB,OAAOsB,KAAK,CAAC,kCAAkC;wBAAEA,OAAOC;oBAAQ;oBAEhE,MAAM,IAAIiB,qBAAa,CAACC,yBAAiB,CAACmC,aAAa,EAAE,AAAC,mCAA0C,OAARrD,UAAW;wBACrGsD,OAAOvD,AAAK,YAALA,OAAiBqD,SAAQrD,MAAMuD,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1H;IACtB,OAAO;QACL2H,MAAM;QACNpF,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-csv-update.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with range-based update (no deduplication) */\n\nimport { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { parse } from 'csv-parse';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\n\n/** Batch size for Sheets API calls (1000 rows × avg 10 cols = 10K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n sourceUri: z.string().trim().min(1).describe('CSV file URI (file://, http://, https://)'),\n startRange: A1NotationSchema.default('A1').describe('Top-left cell where CSV data starts (default: A1)'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How to interpret values (RAW = exact, USER_ENTERED = parse formulas/dates)'),\n sourceHasHeaders: z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Spreadsheet title'),\n spreadsheetUrl: z.string().describe('Spreadsheet URL'),\n sheetTitle: z.string().describe('Sheet title'),\n sheetUrl: z.string().describe('Sheet URL'),\n updatedRange: z.string().describe('A1 notation range that was updated'),\n updatedRows: z.number().describe('Number of rows updated'),\n updatedColumns: z.number().describe('Number of columns updated'),\n updatedCells: z.number().describe('Number of cells updated'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, sourceUri, startRange, valueInputOption = 'USER_ENTERED', sourceHasHeaders }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.csv-update called', { id, gid, sourceUri, startRange, valueInputOption, sourceHasHeaders });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n\n // Find the sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? '';\n\n // Streaming CSV processing state\n let sourceHeaders: string[] = [];\n const allRows: (string | number | boolean | null)[][] = [];\n let totalCols = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser with native streaming\n const parser = readStream.pipe(\n parse({\n columns: !!sourceHasHeaders, // Parse first row as column names if source has headers\n skip_empty_lines: true,\n trim: true,\n cast: true, // Auto-convert numbers/booleans\n relax_column_count: true,\n })\n );\n\n // Stream and collect all rows (with batching for very large files)\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders.length === 0) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n totalCols = sourceHeaders.length;\n logger.info('sheets.values.csv-update source headers', { sourceHeaders, totalCols });\n }\n\n // Convert record to row array (exclude source headers from data range)\n // CSV values are strings/numbers/booleans/nulls from the parser\n const row = sourceHeaders.map((header) => (record as Record<string, string | number | boolean | null>)[header] ?? null);\n allRows.push(row);\n } else {\n // sourceHasHeaders=false: record is an array, include all rows (including first row)\n const row = record as (string | number | boolean | null)[];\n allRows.push(row);\n\n if (totalCols === 0) {\n totalCols = row.length;\n }\n }\n }\n\n if (allRows.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'CSV file is empty');\n }\n\n // Prepare data for update (all rows)\n const dataToWrite: (string | number | boolean | null)[][] = allRows;\n\n // For large datasets, use batchUpdate to write in chunks\n // This respects the 40K cell limit per request\n const batchRequests = [];\n const currentRow = startRange.match(/[A-Z]+(\\d+)/)?.[1] || '1';\n let currentRowNum = Number.parseInt(currentRow, 10);\n\n for (let i = 0; i < dataToWrite.length; i += BATCH_SIZE) {\n const batchData = dataToWrite.slice(i, i + BATCH_SIZE);\n const batchRange = `${sheetTitle}!${startRange.match(/[A-Z]+/)?.[0]}${currentRowNum}`;\n\n batchRequests.push({\n range: batchRange,\n values: batchData,\n });\n\n currentRowNum += batchData.length;\n }\n\n logger.info('sheets.values.csv-update batching', { totalBatches: batchRequests.length, batchSize: BATCH_SIZE });\n\n // Execute batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchRequests,\n },\n });\n\n const totalUpdatedCells = batchUpdateResponse.data.totalUpdatedCells || 0;\n const totalUpdatedRows = batchUpdateResponse.data.totalUpdatedRows || 0;\n const totalUpdatedColumns = batchUpdateResponse.data.totalUpdatedColumns || 0;\n const firstUpdatedRange = batchUpdateResponse.data.responses?.[0]?.updatedRange || `${sheetTitle}!${startRange}`;\n\n logger.info('sheets.values.csv-update completed', { id, gid: sheet.properties.sheetId, updatedRange: firstUpdatedRange, updatedRows: totalUpdatedRows, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheet.properties.sheetId ?? ''),\n spreadsheetTitle: spreadsheetData.properties?.title ?? '',\n spreadsheetUrl: spreadsheetData.spreadsheetUrl ?? `https://docs.google.com/spreadsheets/d/${id}`,\n sheetTitle,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheet.properties.sheetId}`,\n updatedRange: firstUpdatedRange,\n updatedRows: totalUpdatedRows,\n updatedColumns: totalUpdatedColumns,\n updatedCells: totalUpdatedCells,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values.csv-update error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error updating values from CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-csv-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","BATCH_SIZE","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","sourceUri","string","trim","min","describe","startRange","A1NotationSchema","default","valueInputOption","enum","sourceHasHeaders","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRange","updatedRows","number","updatedColumns","updatedCells","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","sheet","spreadsheetData","batchUpdateResponse","sheets","spreadsheetResponse","sourceHeaders","allRows","totalCols","readStream","parser","dataToWrite","batchRequests","currentRow","currentRowNum","i","batchData","batchRange","totalUpdatedCells","totalUpdatedRows","totalUpdatedColumns","firstUpdatedRange","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","getCsvReadStream","pipe","parse","columns","skip_empty_lines","cast","relax_column_count","record","length","Object","keys","row","map","header","push","match","Number","parseInt","slice","range","values","totalBatches","batchSize","batchUpdate","requestBody","responses","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":"AAAA,gFAAgF;;;;+BAiMhF;;;eAAwBA;;;sBA/LY;2BAEZ;sBAKyB;wBAC3B;mBACJ;4BACS;uBACgF;8BAC1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,gGAAgG,GAChG,IAAME,aAAa;AAEnB,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,WAAWN,MAAC,CAACO,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,YAAYC,yBAAgB,CAACC,OAAO,CAAC,MAAMH,QAAQ,CAAC;IACpDI,kBAAkBd,MAAC,CAACe,IAAI,CAAC;QAAC;QAAO;KAAe,EAAEF,O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gB,WAAEkB,8BAAAA,gBAAgBoC,UAAU,cAA1BpC,kDAAAA,4BAA4ByC,KAAK,uCAAI;wBACvD1D,cAAc,GAAEiB,kCAAAA,gBAAgBjB,cAAc,cAA9BiB,6CAAAA,kCAAkC,AAAC,0CAA4C,OAAHvC;wBAC5FuB,YAAAA;wBACAC,UAAU,AAAC,0CAAwDc,OAAftC,IAAG,cAAqC,OAAzBsC,MAAMqC,UAAU,CAACC,OAAO;wBAC3FnD,cAAciC;wBACdhC,aAAa8B;wBACb5B,gBAAgB6B;wBAChB5B,cAAc0B;oBAChB;oBAEA;;wBAAO;4BACLoD,OAAO;gCAAG;oCAAE1F,MAAM;oCAAiB2F,MAAMC,KAAKC,SAAS,CAAC5E;gCAAQ;;4BAChE6E,mBAAmB;gCAAE7E,QAAAA;4BAAO;wBAC9B;;;oBACOyB;oBACDC,UAAUD,AAAK,YAALA,OAAiBqD,SAAQrD,MAAMC,OAAO,GAAGc,OAAOf;oBAChEtB,OAAOsB,KAAK,CAAC,kCAAkC;wBAAEA,OAAOC;oBAAQ;oBAEhE,MAAM,IAAIiB,qBAAa,CAACC,yBAAiB,CAACmC,aAAa,EAAE,AAAC,mCAA0C,OAARrD,UAAW;wBACrGsD,OAAOvD,AAAK,YAALA,OAAiBqD,SAAQrD,MAAMuD,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1H;IACtB,OAAO;QACL2H,MAAM;QACNpF,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-markdown-update.ts"],"sourcesContent":["import { type sheets_v4, 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 { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { buildTextFormatRuns, parseInlineMarkdown } from '../../spreadsheet/markdown-runs.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\n// Input schema for a single markdown-cell request\nconst MarkdownCellRequestSchema = z.object({\n cell: z.string().min(1).describe('Single-cell A1 reference (e.g., \"I2\"). Multi-cell ranges (e.g., \"A1:B2\") are rejected as a per-request failure.'),\n text: z.string().describe('Cell content as inline markdown: [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~. Block syntax and other unsupported markdown is written as literal text.'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(MarkdownCellRequestSchema).min(1).max(50).describe('Array of cell markdown requests. Batch multiple cells for efficiency.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n successCount: z.number().int().nonnegative().describe('Number of cells successfully written'),\n cells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference of the cell that was written'),\n text: z.string().describe('Resolved plain text written to the cell (markdown syntax stripped/literalized)'),\n linkCount: z.number().int().nonnegative().describe('Number of clickable links written into the cell'),\n })\n )\n .describe('Cells successfully written'),\n failedCells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference that failed'),\n error: z.string().describe('Why the cell failed (e.g., not a single-cell reference)'),\n })\n )\n .optional()\n .describe('Only populated if some cells failed'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description:\n 'Replace cell content with text parsed from inline markdown. Supports [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~ — the only way to put MULTIPLE clickable links in one cell. Block syntax (headers, lists, tables) and other unsupported markdown is written as literal text. Writes text cells only — no formula or number coercion. For whole-cell formatting (colors, borders, number formats) use cells-format.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.markdownUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n });\n\n try {\n const sheets = 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: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for markdown update', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).\n const sheetId = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Build one updateCells request per cell\n const batchRequests: sheets_v4.Schema$Request[] = [];\n const cells: Array<{ cell: string; text: string; linkCount: number }> = [];\n const failedCells: Array<{ cell: string; error: string }> = [];\n\n for (const request of requests) {\n try {\n // Parse A1 notation and reject anything that isn't a single cell\n const rangeRef = parseA1Notation(request.cell);\n if (rangeRef.type !== 'cell') {\n throw new Error(`Not a single-cell reference: \"${request.cell}\"`);\n }\n\n const gridRange = rangeReferenceToGridRange(rangeRef, sheetId);\n const parsed = parseInlineMarkdown(request.text);\n const runs = buildTextFormatRuns(parsed);\n\n batchRequests.push({\n updateCells: {\n range: gridRange,\n rows: [\n {\n values: [\n {\n userEnteredValue: { stringValue: parsed.text },\n textFormatRuns: runs,\n },\n ],\n },\n ],\n fields: 'userEnteredValue,textFormatRuns',\n },\n });\n cells.push({ cell: request.cell, text: parsed.text, linkCount: parsed.linkCount });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse cell for markdown update', {\n cell: request.cell,\n error: message,\n });\n failedCells.push({\n cell: request.cell,\n error: `Failed to parse cell: ${message}`,\n });\n }\n }\n\n // Early return if all cells failed\n if (batchRequests.length === 0) {\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: 0,\n cells: [],\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n }\n\n logger.info('sheets.values.markdownUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchRequestsCount: batchRequests.length,\n });\n\n // Execute the batch update\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: batchRequests,\n },\n });\n\n logger.info('sheets.values.markdownUpdate completed successfully', {\n successCount: cells.length,\n failedCount: failedCells.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: cells.length,\n cells,\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n // Re-throw ProtocolError as-is\n if (error instanceof ProtocolError) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Markdown update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error writing markdown to cells: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-markdown-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","MarkdownCellRequestSchema","z","object","cell","string","min","describe","text","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","array","max","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","sheetTitle","sheetUrl","successCount","number","int","nonnegative","cells","linkCount","failedCells","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","sheet","spreadsheetResponse","sheets","sheetId","batchRequests","request","rangeRef","gridRange","parsed","runs","message","info","requestCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","ProtocolError","ProtocolErrorCode","InvalidParams","title","parseA1Notation","Error","rangeReferenceToGridRange","parseInlineMarkdown","buildTextFormatRuns","push","updateCells","range","rows","values","userEnteredValue","stringValue","textFormatRuns","undefined","content","JSON","stringify","structuredContent","batchRequestsCount","batchUpdate","requestBody","failedCount","InternalError","stack","name"],"mappings":";;;;+BAwNA;;;eAAwBA;;;sBAxN4B;2BAE5B;sBAKyB;mBAC/B;4BACS;uBAC8D;8BAChC;iCACE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAR3D,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,kDAAkD;AAClD,IAAME,4BAA4BC,MAAC,CAACC,MAAM,CAAC;IACzCC,MAAMF,MAAC,CAACG,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACjCC,MAAMN,MAAC,CAACG,MAAM,GAAGE,QAAQ,CAAC;AAC5B;AAEA,IAAME,cAAcP,MAAC,CAACC,MAAM,CAAC;IAC3BO,IAAIC,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/B,IAAIA,AAAK,YAALA,OAAiBsC,qBAAa,GAAE;wBAClC,MAAMtC;oBACR;oBAEMoB,WAAUpB,AAAK,YAALA,OAAiB2C,SAAQ3C,MAAMoB,OAAO,GAAGgB,OAAOpC;oBAChES,OAAOT,KAAK,CAAC,oCAAoC;wBAC/CrB,IAAAA;wBACAE,KAAAA;wBACAyC,cAAcvC,SAASwC,MAAM;wBAC7BvB,OAAOoB;oBACT;oBAEA,MAAM,IAAIkB,qBAAa,CAACC,yBAAiB,CAACyB,aAAa,EAAE,AAAC,oCAA2C,OAAR5C,WAAW;wBACtG6C,OAAOjE,AAAK,YAALA,OAAiB2C,SAAQ3C,MAAMiE,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASxF;IACtB,OAAO;QACLmG,MAAM;QACN9D,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-markdown-update.ts"],"sourcesContent":["import { type sheets_v4, 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 { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { buildTextFormatRuns, parseInlineMarkdown } from '../../spreadsheet/markdown-runs.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\n// Input schema for a single markdown-cell request\nconst MarkdownCellRequestSchema = z.object({\n cell: z.string().min(1).describe('Single-cell A1 reference (e.g., \"I2\"). Multi-cell ranges (e.g., \"A1:B2\") are rejected as a per-request failure.'),\n text: z.string().describe('Cell content as inline markdown: [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~. Block syntax and other unsupported markdown is written as literal text.'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(MarkdownCellRequestSchema).min(1).max(50).describe('Array of cell markdown requests. Batch multiple cells for efficiency.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n successCount: z.number().int().nonnegative().describe('Number of cells successfully written'),\n cells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference of the cell that was written'),\n text: z.string().describe('Resolved plain text written to the cell (markdown syntax stripped/literalized)'),\n linkCount: z.number().int().nonnegative().describe('Number of clickable links written into the cell'),\n })\n )\n .describe('Cells successfully written'),\n failedCells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference that failed'),\n error: z.string().describe('Why the cell failed (e.g., not a single-cell reference)'),\n })\n )\n .optional()\n .describe('Only populated if some cells failed'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description:\n 'Replace cell content with text parsed from inline markdown. Supports [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~ — the only way to put MULTIPLE clickable links in one cell. Block syntax (headers, lists, tables) and other unsupported markdown is written as literal text. Writes text cells only — no formula or number coercion. For whole-cell formatting (colors, borders, number formats) use cells-format.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.markdownUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n });\n\n try {\n const sheets = 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: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for markdown update', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).\n const sheetId = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Build one updateCells request per cell\n const batchRequests: sheets_v4.Schema$Request[] = [];\n const cells: Array<{ cell: string; text: string; linkCount: number }> = [];\n const failedCells: Array<{ cell: string; error: string }> = [];\n\n for (const request of requests) {\n try {\n // Parse A1 notation and reject anything that isn't a single cell\n const rangeRef = parseA1Notation(request.cell);\n if (rangeRef.type !== 'cell') {\n throw new Error(`Not a single-cell reference: \"${request.cell}\"`);\n }\n\n const gridRange = rangeReferenceToGridRange(rangeRef, sheetId);\n const parsed = parseInlineMarkdown(request.text);\n const runs = buildTextFormatRuns(parsed);\n\n batchRequests.push({\n updateCells: {\n range: gridRange,\n rows: [\n {\n values: [\n {\n userEnteredValue: { stringValue: parsed.text },\n textFormatRuns: runs,\n },\n ],\n },\n ],\n fields: 'userEnteredValue,textFormatRuns',\n },\n });\n cells.push({ cell: request.cell, text: parsed.text, linkCount: parsed.linkCount });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse cell for markdown update', {\n cell: request.cell,\n error: message,\n });\n failedCells.push({\n cell: request.cell,\n error: `Failed to parse cell: ${message}`,\n });\n }\n }\n\n // Early return if all cells failed\n if (batchRequests.length === 0) {\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: 0,\n cells: [],\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n }\n\n logger.info('sheets.values.markdownUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchRequestsCount: batchRequests.length,\n });\n\n // Execute the batch update\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: batchRequests,\n },\n });\n\n logger.info('sheets.values.markdownUpdate completed successfully', {\n successCount: cells.length,\n failedCount: failedCells.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: cells.length,\n cells,\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n // Re-throw ProtocolError as-is\n if (error instanceof ProtocolError) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Markdown update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error writing markdown to cells: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-markdown-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","MarkdownCellRequestSchema","z","object","cell","string","min","describe","text","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","array","max","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","sheetTitle","sheetUrl","successCount","number","int","nonnegative","cells","linkCount","failedCells","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","sheet","spreadsheetResponse","sheets","sheetId","batchRequests","request","rangeRef","gridRange","parsed","runs","message","info","requestCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","ProtocolError","ProtocolErrorCode","InvalidParams","title","parseA1Notation","Error","rangeReferenceToGridRange","parseInlineMarkdown","buildTextFormatRuns","push","updateCells","range","rows","values","userEnteredValue","stringValue","textFormatRuns","undefined","content","JSON","stringify","structuredContent","batchRequestsCount","batchUpdate","requestBody","failedCount","InternalError","stack","name"],"mappings":";;;;+BAwNA;;;eAAwBA;;;sBAxN4B;2BAE5B;sBAKyB;mBAC/B;4BACS;uBAC8D;8BAChC;iCACE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAR3D,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,kDAAkD;AAClD,IAAME,4BAA4BC,MAAC,CAACC,MAAM,CAAC;IACzCC,MAAMF,MAAC,CAACG,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACjCC,MAAMN,MAAC,CAACG,MAAM,GAAGE,QAAQ,CAAC;AAC5B;AAEA,IAAME,cAAcP,MAAC,CAACC,MAAM,CAAC;IAC3BO,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,UAAUZ,MAAC,CAACa,KAAK,CAACd,2BAA2BK,GAAG,CAAC,GAAGU,GAAG,CAAC,IAAIT,QAAQ,CAAC;AACvE;AAEA,IAAMU,sBAAsBf,MAAC,CAACC,MAAM,CAAC;IACnCe,MAAMhB,MAAC,CAACiB,OAAO,CAAC;IAChBT,IAAIU,4BAAmB;IACvBR,KAAKS,uBAAc;IACnBC,YAAYpB,MAAC,CAACG,MAAM,GAAGE,QAAQ,CAAC;IAChCgB,UAAUrB,MAAC,CAACG,MAAM,GAAGE,QAAQ,CAAC;IAC9BiB,cAActB,MAAC,CAAC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AQ3C,MAAMiE,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASxF;IACtB,OAAO;QACLmG,MAAM;QACN9D,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-replace.ts"],"sourcesContent":["import { type sheets_v4, 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, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\nconst inputSchema = z\n .object({\n id: SpreadsheetIdSchema,\n find: z.string().min(1).describe('Text or regex pattern to find'),\n replacement: z.string().describe('Replacement text. Use $1, $2 for regex capture groups. Empty string deletes matches.'),\n\n // Scope - defaults to all sheets if neither specified\n gid: SheetGidSchema.optional().describe('Limit to specific sheet. If omitted, searches all sheets.'),\n range: A1NotationSchema.optional().describe('Limit to specific A1 range within the sheet (requires gid)'),\n\n // Match options\n matchCase: z.boolean().optional().describe('Case-sensitive matching'),\n matchEntireCell: z.boolean().optional().describe('Only match entire cell content'),\n searchByRegex: z.boolean().optional().describe('Treat find as RE2 regex'),\n includeFormulas: z.boolean().optional().describe('Search within formula text'),\n })\n .refine((data) => !(data.range && !data.gid), { message: 'range requires gid' });\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n spreadsheetUrl: z.string().describe('URL of the spreadsheet'),\n occurrencesChanged: z.number().int().nonnegative().describe('Total replacements made'),\n valuesChanged: z.number().int().nonnegative().describe('Number of non-formula cells changed'),\n formulasChanged: z.number().int().nonnegative().describe('Number of formula cells changed'),\n rowsChanged: z.number().int().nonnegative().describe('Number of rows with replacements'),\n sheetsChanged: z.number().int().nonnegative().describe('Number of sheets with replacements'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Find and replace text across a spreadsheet. Searches all sheets by default, or limit with gid/range. Supports regex with capture groups ($1, $2).',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, find, replacement, gid, range, matchCase, matchEntireCell, searchByRegex, includeFormulas }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-replace called', { id, find, replacement, gid, range });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Build FindReplaceRequest - only include defined options\n const findReplaceRequest: sheets_v4.Schema$FindReplaceRequest = {\n find,\n replacement,\n ...(matchCase !== undefined && { matchCase }),\n ...(matchEntireCell !== undefined && { matchEntireCell }),\n ...(searchByRegex !== undefined && { searchByRegex }),\n ...(includeFormulas !== undefined && { includeFormulas }),\n };\n\n // Set scope based on gid/range\n if (!gid) {\n // No gid = search all sheets\n findReplaceRequest.allSheets = true;\n } else {\n // Need to resolve sheet to get numeric sheetId\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n // Note: sheetId can be 0 which is falsy, so check explicitly for undefined/null\n const sheetId = sheet.properties?.sheetId;\n if (sheetId === undefined || sheetId === null) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, 'Sheet properties not available');\n }\n\n if (!range) {\n // gid but no range = search specific sheet\n findReplaceRequest.sheetId = sheetId;\n } else {\n // gid + range = search specific range\n const rangeRef = parseA1Notation(range);\n findReplaceRequest.range = rangeReferenceToGridRange(rangeRef, sheetId);\n }\n }\n\n // Execute batchUpdate\n const response = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: [{ findReplace: findReplaceRequest }],\n },\n });\n\n const findReplaceResponse = response.data.replies?.[0]?.findReplace;\n const spreadsheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit`;\n\n logger.info('sheets.values-replace completed', {\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n spreadsheetUrl,\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n valuesChanged: findReplaceResponse?.valuesChanged ?? 0,\n formulasChanged: findReplaceResponse?.formulasChanged ?? 0,\n rowsChanged: findReplaceResponse?.rowsChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n if (error instanceof ProtocolError) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Replace operation failed', {\n id,\n find,\n replacement,\n gid,\n range,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error replacing values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-replace',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","SpreadsheetIdSchema","find","string","min","describe","replacement","gid","SheetGidSchema","optional","range","A1NotationSchema","matchCase","boolean","matchEntireCell","searchByRegex","includeFormulas","refine","data","message","successBranchSchema","type","literal","SpreadsheetIdOutput","spreadsheetUrl","occurrencesChanged","number","int","nonnegative","valuesChanged","formulasChanged","rowsChanged","sheetsChanged","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","response","sheets","findReplaceRequest","spreadsheetResponse","sheet","sheetId","rangeRef","findReplaceResponse","error","info","sheetsApi","version","auth","googleAuth","authContext","undefined","allSheets","spreadsheets","get","spreadsheetId","fields","s","String","properties","ProtocolError","ProtocolErrorCode","InvalidParams","InternalError","parseA1Notation","rangeReferenceToGridRange","batchUpdate","requestBody","requests","findReplace","replies","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BA2JA;;;eAAwBA;;;sBA3J4B;2BAE5B;sBAKyB;mBAC/B;4BACS;uBACgE;iCAChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAP3D,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAClBC,MAAM,CAAC;IACNC,IAAIC,4BAAmB;IACvBC,MAAMJ,MAAC,CAACK,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACjCC,aAAaR,MAAC,CAACK,MAAM,GAAGE,QAAQ,CAAC;IAEjC,sDAAsD;IACtDE,KAAKC,uBAAc,CAACC,QAAQ,GAAGJ,QAAQ,CAAC;IACxCK,OAAOC,yBAAgB,CAACF,QAAQ,GAAGJ,QAAQ,CAAC;IAE5C,gBAAgB;IAChBO,WAAWd,MAAC,CAACe,OAAO,GAAGJ,QAAQ,GAAGJ,QAAQ,CAAC;IAC3CS,iBAAiBhB,MAAC,CAACe,OAAO,GAAGJ,QAAQ,GAAGJ,QAAQ,CAAC;IACjDU,eAAejB,MAAC,CAACe,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,WAAEkB,gCAAAA,0CAAAA,oBAAqBlB,eAAe,yCAAI;wBACzDC,WAAW,WAAEiB,gCAAAA,0CAAAA,oBAAqBjB,WAAW,yCAAI;wBACjDC,aAAa,WAAEgB,gCAAAA,0CAAAA,oBAAqBhB,aAAa,yCAAI;oBACvD;oBAEA;;wBAAO;4BACL4C,OAAO;gCAAG;oCAAEvD,MAAM;oCAAiBwD,MAAMC,KAAKC,SAAS,CAAC1C;gCAAQ;;4BAChE2C,mBAAmB;gCAAE3C,QAAAA;4BAAO;wBAC9B;;;oBACOY;oBACP,IAAIA,AAAK,YAALA,OAAiBgB,qBAAa,GAAE;wBAClC,MAAMhB;oBACR;oBACM9B,UAAU8B,AAAK,YAALA,OAAiBgC,SAAQhC,MAAM9B,OAAO,GAAG4C,OAAOd;oBAChET,OAAOS,KAAK,CAAC,4BAA4B;wBACvCjD,IAAAA;wBACAE,MAAAA;wBACAI,aAAAA;wBACAC,KAAAA;wBACAG,OAAAA;wBACAuC,OAAO9B;oBACT;oBAEA,MAAM,IAAI8C,qBAAa,CAACC,yBAAiB,CAACE,aAAa,EAAE,AAAC,2BAAkC,OAARjD,UAAW;wBAC7F+D,OAAOjC,AAAK,YAALA,OAAiBgC,SAAQhC,MAAMiC,KAAK,GAAG1B;oBAChD;;;;;;;IAEJ;;AAEe,SAAS9D;IACtB,OAAO;QACLyF,MAAM;QACNhD,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-replace.ts"],"sourcesContent":["import { type sheets_v4, 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, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\nconst inputSchema = z\n .object({\n id: SpreadsheetIdSchema,\n find: z.string().min(1).describe('Text or regex pattern to find'),\n replacement: z.string().describe('Replacement text. Use $1, $2 for regex capture groups. Empty string deletes matches.'),\n\n // Scope - defaults to all sheets if neither specified\n gid: SheetGidSchema.optional().describe('Limit to specific sheet. If omitted, searches all sheets.'),\n range: A1NotationSchema.optional().describe('Limit to specific A1 range within the sheet (requires gid)'),\n\n // Match options\n matchCase: z.boolean().optional().describe('Case-sensitive matching'),\n matchEntireCell: z.boolean().optional().describe('Only match entire cell content'),\n searchByRegex: z.boolean().optional().describe('Treat find as RE2 regex'),\n includeFormulas: z.boolean().optional().describe('Search within formula text'),\n })\n .refine((data) => !(data.range && !data.gid), { message: 'range requires gid' });\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n spreadsheetUrl: z.string().describe('URL of the spreadsheet'),\n occurrencesChanged: z.number().int().nonnegative().describe('Total replacements made'),\n valuesChanged: z.number().int().nonnegative().describe('Number of non-formula cells changed'),\n formulasChanged: z.number().int().nonnegative().describe('Number of formula cells changed'),\n rowsChanged: z.number().int().nonnegative().describe('Number of rows with replacements'),\n sheetsChanged: z.number().int().nonnegative().describe('Number of sheets with replacements'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Find and replace text across a spreadsheet. Searches all sheets by default, or limit with gid/range. Supports regex with capture groups ($1, $2).',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, find, replacement, gid, range, matchCase, matchEntireCell, searchByRegex, includeFormulas }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-replace called', { id, find, replacement, gid, range });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Build FindReplaceRequest - only include defined options\n const findReplaceRequest: sheets_v4.Schema$FindReplaceRequest = {\n find,\n replacement,\n ...(matchCase !== undefined && { matchCase }),\n ...(matchEntireCell !== undefined && { matchEntireCell }),\n ...(searchByRegex !== undefined && { searchByRegex }),\n ...(includeFormulas !== undefined && { includeFormulas }),\n };\n\n // Set scope based on gid/range\n if (!gid) {\n // No gid = search all sheets\n findReplaceRequest.allSheets = true;\n } else {\n // Need to resolve sheet to get numeric sheetId\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n // Note: sheetId can be 0 which is falsy, so check explicitly for undefined/null\n const sheetId = sheet.properties?.sheetId;\n if (sheetId === undefined || sheetId === null) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, 'Sheet properties not available');\n }\n\n if (!range) {\n // gid but no range = search specific sheet\n findReplaceRequest.sheetId = sheetId;\n } else {\n // gid + range = search specific range\n const rangeRef = parseA1Notation(range);\n findReplaceRequest.range = rangeReferenceToGridRange(rangeRef, sheetId);\n }\n }\n\n // Execute batchUpdate\n const response = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: [{ findReplace: findReplaceRequest }],\n },\n });\n\n const findReplaceResponse = response.data.replies?.[0]?.findReplace;\n const spreadsheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit`;\n\n logger.info('sheets.values-replace completed', {\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n spreadsheetUrl,\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n valuesChanged: findReplaceResponse?.valuesChanged ?? 0,\n formulasChanged: findReplaceResponse?.formulasChanged ?? 0,\n rowsChanged: findReplaceResponse?.rowsChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n if (error instanceof ProtocolError) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Replace operation failed', {\n id,\n find,\n replacement,\n gid,\n range,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error replacing values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-replace',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","SpreadsheetIdSchema","find","string","min","describe","replacement","gid","SheetGidSchema","optional","range","A1NotationSchema","matchCase","boolean","matchEntireCell","searchByRegex","includeFormulas","refine","data","message","successBranchSchema","type","literal","SpreadsheetIdOutput","spreadsheetUrl","occurrencesChanged","number","int","nonnegative","valuesChanged","formulasChanged","rowsChanged","sheetsChanged","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","response","sheets","findReplaceRequest","spreadsheetResponse","sheet","sheetId","rangeRef","findReplaceResponse","error","info","sheetsApi","version","auth","googleAuth","authContext","undefined","allSheets","spreadsheets","get","spreadsheetId","fields","s","String","properties","ProtocolError","ProtocolErrorCode","InvalidParams","InternalError","parseA1Notation","rangeReferenceToGridRange","batchUpdate","requestBody","requests","findReplace","replies","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BA2JA;;;eAAwBA;;;sBA3J4B;2BAE5B;sBAKyB;mBAC/B;4BACS;uBACgE;iCA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OAAOd;oBAChET,OAAOS,KAAK,CAAC,4BAA4B;wBACvCjD,IAAAA;wBACAE,MAAAA;wBACAI,aAAAA;wBACAC,KAAAA;wBACAG,OAAAA;wBACAuC,OAAO9B;oBACT;oBAEA,MAAM,IAAI8C,qBAAa,CAACC,yBAAiB,CAACE,aAAa,EAAE,AAAC,2BAAkC,OAARjD,UAAW;wBAC7F+D,OAAOjC,AAAK,YAALA,OAAiBgC,SAAQhC,MAAMiC,KAAK,GAAG1B;oBAChD;;;;;;;IAEJ;;AAEe,SAAS9D;IACtB,OAAO;QACLyF,MAAM;QACNhD,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Helper to convert column index to letter (0 = A, 1 = B, etc.)\nfunction columnIndexToLetter(index: number): string {\n let letter = '';\n let num = index + 1;\n while (num > 0) {\n const remainder = (num - 1) % 26;\n letter = String.fromCharCode(65 + remainder) + letter;\n num = Math.floor((num - 1) / 26);\n }\n return letter;\n}\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n query: z.coerce.string().trim().optional().describe('Text to search for in sheet cells. If empty, returns all data at specified granularity.'),\n select: z.enum(['cells', 'rows', 'columns']).describe('Granularity: cells (individual matches), rows (full matching rows), columns (columns with matching headers)'),\n values: z.boolean().optional().describe('Include cell values in response'),\n a1s: z.boolean().optional().describe('Include A1 notation references in response'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.'),\n matchCase: z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n count: z.number().int().nonnegative().describe('Number of matches found'),\n a1s: z.array(z.string()).optional().describe('A1 notation references for matches (e.g., \"B5\", \"A5:D5\", \"B:B\")'),\n values: z\n .array(z.union([z.array(SheetCellSchema), SheetCellSchema]))\n .optional()\n .describe('Cell values for matches (arrays for rows/columns, single values for cells)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search spreadsheet and return matches at cell, row, or column granularity. Use a1-notation prompt for range syntax.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, query, select, values = false, a1s = false, render, matchCase = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-search called', { id, gid, query, select, values, a1s, render, matchCase });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details including grid dimensions\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.values-search sheet not found', { id, gid, query });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Use actual sheet dimensions from gridProperties, with sensible defaults\n // Google Sheets default for new sheets is 1000 rows x 26 columns\n const rowCount = sheet.properties?.gridProperties?.rowCount ?? 1000;\n const columnCount = sheet.properties?.gridProperties?.columnCount ?? 26;\n const endColumn = columnIndexToLetter(columnCount - 1);\n const fullRange = `${sheetTitle}!A1:${endColumn}${rowCount}`;\n\n logger.debug?.('sheets.values-search fetching range', { fullRange, rowCount, columnCount });\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n const res = response.data;\n const allRows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n // Prepare query for matching (case-insensitive by default)\n const searchQuery = query ? (matchCase ? query : query.toLowerCase()) : null;\n\n let count = 0;\n const a1Array: string[] = [];\n const valuesArray: (string | number | boolean | null | (string | number | boolean | null)[])[] = [];\n\n // Helper to check if a cell matches the query\n const cellMatches = (cell: string | number | boolean | null): boolean => {\n if (!searchQuery) return true; // If no query, match all\n if (typeof cell !== 'string') return false;\n const cellValue = matchCase ? cell : cell.toLowerCase();\n return cellValue.includes(searchQuery);\n };\n\n if (select === 'cells') {\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n for (let colIdx = 0; colIdx < row.length; colIdx++) {\n const cell = row[colIdx];\n if (cellMatches(cell)) {\n count++;\n if (a1s) {\n const colLetter = columnIndexToLetter(colIdx);\n const rowNum = rowIdx + 1;\n a1Array.push(`${colLetter}${rowNum}`);\n }\n if (values) {\n valuesArray.push(cell ?? null);\n }\n }\n }\n }\n } else if (select === 'rows') {\n const matchingRows: number[] = [];\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n const matches = row.some((cell) => cellMatches(cell));\n if (matches) {\n matchingRows.push(rowIdx);\n }\n }\n\n count = matchingRows.length;\n for (const rowIdx of matchingRows) {\n const row = allRows[rowIdx];\n if (!row) continue; // Skip if row is undefined\n const rowNum = rowIdx + 1;\n\n if (a1s) {\n const colEnd = columnIndexToLetter(Math.max(0, row.length - 1));\n a1Array.push(`A${rowNum}:${colEnd}${rowNum}`);\n }\n if (values) {\n valuesArray.push(row);\n }\n }\n } else if (select === 'columns') {\n const headerRow = allRows[0] || [];\n const matchingCols: number[] = [];\n\n for (let colIdx = 0; colIdx < headerRow.length; colIdx++) {\n const header = headerRow[colIdx];\n if (cellMatches(header)) {\n matchingCols.push(colIdx);\n }\n }\n\n count = matchingCols.length;\n for (const colIdx of matchingCols) {\n const colLetter = columnIndexToLetter(colIdx);\n\n if (a1s) {\n a1Array.push(`${colLetter}:${colLetter}`);\n }\n if (values) {\n const columnValues = allRows.map((row) => (row && row[colIdx] !== undefined ? row[colIdx] : null));\n valuesArray.push(columnValues);\n }\n }\n }\n\n logger.info('sheets.values-search results', { count, select, hasA1s: a1s, hasValues: values });\n\n const result: Output = {\n type: 'success' as const,\n count,\n ...(a1s && a1Array.length > 0 && { a1s: a1Array }),\n ...(values && valuesArray.length > 0 && { values: valuesArray }),\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values-search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching spreadsheet: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","columnIndexToLetter","index","letter","num","remainder","String","fromCharCode","Math","floor","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","query","coerce","string","trim","optional","describe","select","enum","values","boolean","a1s","render","matchCase","successBranchSchema","type","literal","count","number","int","nonnegative","array","union","SheetCellSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetResponse","sheet","sheets","sheetTitle","rowCount","columnCount","endColumn","fullRange","response","res","allRows","searchQuery","a1Array","valuesArray","cellMatches","rowIdx","row","colIdx","cell","colLetter","rowNum","matchingRows","matches","colEnd","headerRow","matchingCols","header","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","gridProperties","debug","range","valueRenderOption","Array","isArray","toLowerCase","cellValue","includes","length","push","some","max","columnValues","map","undefined","hasA1s","hasValues","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","name"],"mappings":";;;;+BA8MA;;;eAAwBA;;;sBA9MY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBAC0C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AANrE,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,gEAAgE;AAChE,SAASE,oBAAoBC,KAAa;IACxC,IAAIC,SAAS;IACb,IAAIC,MAAMF,QAAQ;IAClB,MAAOE,MAAM,EAAG;QACd,IAAMC,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,IAAMO,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,OAAON,MAAC,CAACO,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,QAAQ,GAAGC,QAAQ,CAAC;IACpDC,QAAQZ,MAAC,CAACa,IAAI,CAAC;QAAC;QAAS;QAAQ;KAAU,EAAEF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M;oCAAiBoF,MAAMC,KAAKC,SAAS,CAACzE;gCAAQ;;4BAChE0E,mBAAmB;gCAAE1E,QAAAA;4BAAO;wBAC9B;;;oBACO+B;oBACDC,UAAUD,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAMC,OAAO,GAAGtE,OAAOqE;oBAChE5B,OAAO4B,KAAK,CAAC,8BAA8B;wBAAEA,OAAOC;oBAAQ;oBAE5D,MAAM,IAAIgB,qBAAa,CAACC,yBAAiB,CAAC2B,aAAa,EAAE,AAAC,gCAAuC,OAAR5C,UAAW;wBAClG6C,OAAO9C,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAM8C,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASjH;IACtB,OAAO;QACL4H,MAAM;QACNhF,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Helper to convert column index to letter (0 = A, 1 = B, etc.)\nfunction columnIndexToLetter(index: number): string {\n let letter = '';\n let num = index + 1;\n while (num > 0) {\n const remainder = (num - 1) % 26;\n letter = String.fromCharCode(65 + remainder) + letter;\n num = Math.floor((num - 1) / 26);\n }\n return letter;\n}\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n query: z.coerce.string().trim().optional().describe('Text to search for in sheet cells. If empty, returns all data at specified granularity.'),\n select: z.enum(['cells', 'rows', 'columns']).describe('Granularity: cells (individual matches), rows (full matching rows), columns (columns with matching headers)'),\n values: z.boolean().optional().describe('Include cell values in response'),\n a1s: z.boolean().optional().describe('Include A1 notation references in response'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.'),\n matchCase: z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n count: z.number().int().nonnegative().describe('Number of matches found'),\n a1s: z.array(z.string()).optional().describe('A1 notation references for matches (e.g., \"B5\", \"A5:D5\", \"B:B\")'),\n values: z\n .array(z.union([z.array(SheetCellSchema), SheetCellSchema]))\n .optional()\n .describe('Cell values for matches (arrays for rows/columns, single values for cells)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search spreadsheet and return matches at cell, row, or column granularity. Use a1-notation prompt for range syntax.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, query, select, values = false, a1s = false, render, matchCase = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-search called', { id, gid, query, select, values, a1s, render, matchCase });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details including grid dimensions\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.values-search sheet not found', { id, gid, query });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Use actual sheet dimensions from gridProperties, with sensible defaults\n // Google Sheets default for new sheets is 1000 rows x 26 columns\n const rowCount = sheet.properties?.gridProperties?.rowCount ?? 1000;\n const columnCount = sheet.properties?.gridProperties?.columnCount ?? 26;\n const endColumn = columnIndexToLetter(columnCount - 1);\n const fullRange = `${sheetTitle}!A1:${endColumn}${rowCount}`;\n\n logger.debug?.('sheets.values-search fetching range', { fullRange, rowCount, columnCount });\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n const res = response.data;\n const allRows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n // Prepare query for matching (case-insensitive by default)\n const searchQuery = query ? (matchCase ? query : query.toLowerCase()) : null;\n\n let count = 0;\n const a1Array: string[] = [];\n const valuesArray: (string | number | boolean | null | (string | number | boolean | null)[])[] = [];\n\n // Helper to check if a cell matches the query\n const cellMatches = (cell: string | number | boolean | null): boolean => {\n if (!searchQuery) return true; // If no query, match all\n if (typeof cell !== 'string') return false;\n const cellValue = matchCase ? cell : cell.toLowerCase();\n return cellValue.includes(searchQuery);\n };\n\n if (select === 'cells') {\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n for (let colIdx = 0; colIdx < row.length; colIdx++) {\n const cell = row[colIdx];\n if (cellMatches(cell)) {\n count++;\n if (a1s) {\n const colLetter = columnIndexToLetter(colIdx);\n const rowNum = rowIdx + 1;\n a1Array.push(`${colLetter}${rowNum}`);\n }\n if (values) {\n valuesArray.push(cell ?? null);\n }\n }\n }\n }\n } else if (select === 'rows') {\n const matchingRows: number[] = [];\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n const matches = row.some((cell) => cellMatches(cell));\n if (matches) {\n matchingRows.push(rowIdx);\n }\n }\n\n count = matchingRows.length;\n for (const rowIdx of matchingRows) {\n const row = allRows[rowIdx];\n if (!row) continue; // Skip if row is undefined\n const rowNum = rowIdx + 1;\n\n if (a1s) {\n const colEnd = columnIndexToLetter(Math.max(0, row.length - 1));\n a1Array.push(`A${rowNum}:${colEnd}${rowNum}`);\n }\n if (values) {\n valuesArray.push(row);\n }\n }\n } else if (select === 'columns') {\n const headerRow = allRows[0] || [];\n const matchingCols: number[] = [];\n\n for (let colIdx = 0; colIdx < headerRow.length; colIdx++) {\n const header = headerRow[colIdx];\n if (cellMatches(header)) {\n matchingCols.push(colIdx);\n }\n }\n\n count = matchingCols.length;\n for (const colIdx of matchingCols) {\n const colLetter = columnIndexToLetter(colIdx);\n\n if (a1s) {\n a1Array.push(`${colLetter}:${colLetter}`);\n }\n if (values) {\n const columnValues = allRows.map((row) => (row && row[colIdx] !== undefined ? row[colIdx] : null));\n valuesArray.push(columnValues);\n }\n }\n }\n\n logger.info('sheets.values-search results', { count, select, hasA1s: a1s, hasValues: values });\n\n const result: Output = {\n type: 'success' as const,\n count,\n ...(a1s && a1Array.length > 0 && { a1s: a1Array }),\n ...(values && valuesArray.length > 0 && { values: valuesArray }),\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values-search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching spreadsheet: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","columnIndexToLetter","index","letter","num","remainder","String","fromCharCode","Math","floor","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","query","coerce","string","trim","optional","describe","select","enum","values","boolean","a1s","render","matchCase","successBranchSchema","type","literal","count","number","int","nonnegative","array","union","SheetCellSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetResponse","sheet","sheets","sheetTitle","rowCount","columnCount","endColumn","fullRange","response","res","allRows","searchQuery","a1Array","valuesArray","cellMatches","rowIdx","row","colIdx","cell","colLetter","rowNum","matchingRows","matches","colEnd","headerRow","matchingCols","header","error","message","info","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","gridProperties","debug","range","valueRenderOption","Array","isArray","toLowerCase","cellValue","includes","length","push","some","max","columnValues","map","undefined","hasA1s","hasValues","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","name"],"mappings":";;;;+BA8MA;;;eAAwBA;;;sBA9MY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBAC0C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AANrE,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,gEAAgE;AAChE,SAASE,oBAAoBC,KAAa;IACxC,IAAIC,SAAS;IACb,IAAIC,MAAMF,QAAQ;IAClB,MAAOE,MAAM,EAAG;QACd,IAAMC,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,IAAMO,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,OAAON,MAAC,CAACO,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,Q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C,MAAM,GAAG,KAAK;wBAAEhF,QAAQoC;oBAAY;oBAGhE;;wBAAO;4BACLqD,OAAO;gCAAG;oCAAEnF,MAAM;oCAAiBoF,MAAMC,KAAKC,SAAS,CAACzE;gCAAQ;;4BAChE0E,mBAAmB;gCAAE1E,QAAAA;4BAAO;wBAC9B;;;oBACO+B;oBACDC,UAAUD,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAMC,OAAO,GAAGtE,OAAOqE;oBAChE5B,OAAO4B,KAAK,CAAC,8BAA8B;wBAAEA,OAAOC;oBAAQ;oBAE5D,MAAM,IAAIgB,qBAAa,CAACC,yBAAiB,CAAC2B,aAAa,EAAE,AAAC,gCAAuC,OAAR5C,UAAW;wBAClG6C,OAAO9C,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAM8C,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASjH;IACtB,OAAO;QACL4H,MAAM;QACNhF,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/schemas/index.ts"],"sourcesContent":["import { z } from 'zod';\n\n// Spreadsheet and sheet reference schemas\nexport const SpreadsheetRefSchema = z.string().min(1).describe('Spreadsheet reference: full URL, exact name, or partial name (not ID - use spreadsheet-find to get ID)');\n\nexport const SheetRefSchema = z.string().min(1).describe('Sheet reference: exact title or partial name match (not ID - use sheet-find to get ID)');\n\n// Shared descriptions for consistency\nconst SPREADSHEET_ID_DESC = 'Spreadsheet ID (from URL d/{id})';\nconst SHEET_ID_DESC = 'Sheet ID (from URL gid={gid})';\n\n// Input schemas (with validation)\n// Note: z.coerce.string() converts numbers to strings, handling cases where MCP clients\n// pass gid: 0 (number) instead of gid: \"0\" (string). This is critical for gid=0 which\n// is the default sheet ID in new spreadsheets.\nexport const SpreadsheetIdSchema = z.string().min(1).describe(SPREADSHEET_ID_DESC);\nexport const SheetGidSchema = z.coerce.string().min(1).describe(SHEET_ID_DESC);\n\n// Output schemas (for use in output/response schemas)\nexport const SpreadsheetIdOutput = z.string().describe(SPREADSHEET_ID_DESC);\nexport const SheetGidOutput = z.string().describe(SHEET_ID_DESC);\n\n// Schema for individual sheet cells (can be string, number, boolean, or null)\n// null represents empty cells - JSON cannot represent undefined, and Google API uses null for empty cells\n// Infinity values are allowed as Google Sheets can contain them, but NaN is still rejected\nexport const SheetCellSchema = z.union([z.string(), z.number(), z.literal(Infinity), z.literal(-Infinity), z.boolean(), z.null()]);\n\n// Schema for a row in a sheet search result\nexport const SheetRowSchema = z.object({\n rowIndex: z.number().int().positive().describe('1-based row number in the sheet'),\n values: z.array(SheetCellSchema).optional().describe('Cell values for this row (included when includeData=true)'),\n range: z.string().optional().describe('A1 notation range for this row (e.g., A5:D5)'),\n});\n\n// A1 notation validation - simplified for zod compatibility\nexport const A1NotationSchema = z.string().min(1).describe('A1 notation for cell range (e.g., A1, A1:B2, A:B, 1:2)');\n"],"names":["A1NotationSchema","SheetCellSchema","SheetGidOutput","SheetGidSchema","SheetRefSchema","SheetRowSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","SpreadsheetRefSchema","z","string","min","describe","SPREADSHEET_ID_DESC","SHEET_ID_DESC","coerce","union","number","literal","Infinity","boolean","null","object","rowIndex","int","positive","values","array","optional","range"],"mappings":";;;;;;;;;;;QAmCaA;eAAAA;;QAVAC;eAAAA;;QALAC;eAAAA;;QAJAC;eAAAA;;QAXAC;eAAAA;;QAuBAC;eAAAA;;QATAC;eAAAA;;QAJAC;eAAAA;;QAZAC;eAAAA;;;mBAHK;AAGX,IAAMA,uBAAuBC,MAAC,CAACC,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAExD,IAAMR,iBAAiBK,MAAC,CAACC,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAEzD,sCAAsC;AACtC,IAAMC,sBAAsB;AAC5B,IAAMC,gBAAgB;AAMf,IAAMP,sBAAsBE,MAAC,CAACC,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAACC;AACvD,IAAMV,iBAAiBM,MAAC,CAACM,MAAM,CAACL,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAACE;AAGzD,IAAMR,sBAAsBG,MAAC,CAACC,MAAM,GAAGE,QAAQ,CAACC;AAChD,IAAMX,iBAAiBO,MAAC,CAACC,MAAM,GAAGE,QAAQ,CAACE;AAK3C,IAAMb,kBAAkBQ,MAAC,CAACO,KAAK,CAAC;IAACP,MAAC,CAACC,MAAM;IAAID,MAAC,CAACQ,MAAM;IAAIR,MAAC,CAACS,OAAO,CAACC;IAAWV,MAAC,CAACS,OAAO,CAAC,CAACC;IAAWV,MAAC,CAACW,OAAO;IAAIX,MAAC,CAACY,IAAI;CAAG;AAG1H,IAAMhB,iBAAiBI,MAAC,CAACa,MAAM,CAAC;IACrCC,UAAUd,MAAC,CAACQ,MAAM,GAAGO,GAAG,GAAGC,QAAQ,GAAGb,QAAQ,CAAC;IAC/Cc,QAAQjB,MAAC,CAACkB,KAAK,CAAC1B,iBAAiB2B,QAAQ,GAAGhB,QAAQ,CAAC;IACrDiB,OAAOpB,MAAC,CAACC,MAAM,GAAGkB,QAAQ,GAAGhB,QAAQ,CAAC;AACxC;AAGO,IAAMZ,mBAAmBS,MAAC,CAACC,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/schemas/index.ts"],"sourcesContent":["import { z } from 'zod';\n\n// Spreadsheet and sheet reference schemas\nexport const SpreadsheetRefSchema = z.string().min(1).describe('Spreadsheet reference: full URL, exact name, or partial name (not ID - use spreadsheet-find to get ID)');\n\nexport const SheetRefSchema = z.string().min(1).describe('Sheet reference: exact title or partial name match (not ID - use sheet-find to get ID)');\n\n// Shared descriptions for consistency\nconst SPREADSHEET_ID_DESC = 'Spreadsheet ID (from URL d/{id})';\nconst SHEET_ID_DESC = 'Sheet ID (from URL gid={gid})';\n\n// Input schemas (with validation)\n// Note: z.coerce.string() converts numbers to strings, handling cases where MCP clients\n// pass gid: 0 (number) instead of gid: \"0\" (string). This is critical for gid=0 which\n// is the default sheet ID in new spreadsheets.\nexport const SpreadsheetIdSchema = z.string().min(1).describe(SPREADSHEET_ID_DESC);\nexport const SheetGidSchema = z.coerce.string().min(1).describe(SHEET_ID_DESC);\n\n// Output schemas (for use in output/response schemas)\nexport const SpreadsheetIdOutput = z.string().describe(SPREADSHEET_ID_DESC);\nexport const SheetGidOutput = z.string().describe(SHEET_ID_DESC);\n\n// Schema for individual sheet cells (can be string, number, boolean, or null)\n// null represents empty cells - JSON cannot represent undefined, and Google API uses null for empty cells\n// Infinity values are allowed as Google Sheets can contain them, but NaN is still rejected\nexport const SheetCellSchema = z.union([z.string(), z.number(), z.literal(Infinity), z.literal(-Infinity), z.boolean(), z.null()]);\n\n// Schema for a row in a sheet search result\nexport const SheetRowSchema = z.object({\n rowIndex: z.number().int().positive().describe('1-based row number in the sheet'),\n values: z.array(SheetCellSchema).optional().describe('Cell values for this row (included when includeData=true)'),\n range: z.string().optional().describe('A1 notation range for this row (e.g., A5:D5)'),\n});\n\n// A1 notation validation - simplified for zod compatibility\nexport const A1NotationSchema = z.string().min(1).describe('A1 notation for cell range (e.g., A1, A1:B2, A:B, 1:2)');\n"],"names":["A1NotationSchema","SheetCellSchema","SheetGidOutput","SheetGidSchema","SheetRefSchema","SheetRowSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","SpreadsheetRefSchema","z","string","min","describe","SPREADSHEET_ID_DESC","SHEET_ID_DESC","coerce","union","number","literal","Infinity","boolean","null","object","rowIndex","int","positive","values","array","optional","range"],"mappings":";;;;;;;;;;;QAmCaA;eAAAA;;QAVAC;eAAAA;;QALAC;eAAAA;;QAJAC;eAAAA;;QAXAC;eAAAA;;QAuBAC;eAAAA;;QATAC;eAAAA;;QAJAC;eAAAA;;QAZAC;eAAAA;;;mBAHK;AAGX,IAAMA,uBAAuBC,MAAC,CAACC,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAExD,IAAMR,iBAAiBK,MAAC,CAACC,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAEzD,sCAAsC;AACtC,IAAMC,sBAAsB;AAC5B,IAAMC,gBAAgB;AAMf,IAAMP,sBAAsBE,MAAC,CAACC,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAACC;AACvD,IAAMV,iBAAiBM,MAAC,CAACM,MAAM,CAACL,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAACE;AAGzD,IAAMR,sBAAsBG,MAAC,CAACC,MAAM,GAAGE,QAAQ,CAACC;AAChD,IAAMX,iBAAiBO,MAAC,CAACC,MAAM,GAAGE,QAAQ,CAACE;AAK3C,IAAMb,kBAAkBQ,MAAC,CAACO,KAAK,CAAC;IAACP,MAAC,CAACC,MAAM;IAAID,MAAC,CAACQ,MAAM;IAAIR,MAAC,CAACS,OAAO,CAACC;IAAWV,MAAC,CAACS,OAAO,CAAC,CAACC;IAAWV,MAAC,CAACW,OAAO;IAAIX,MAAC,CAACY,IAAI;CAAG;AAG1H,IAAMhB,iBAAiBI,MAAC,CAACa,MAAM,CAAC;IACrCC,UAAUd,MAAC,CAACQ,MAAM,GAAGO,GAAG,GAAGC,QAAQ,GAAGb,QAAQ,CAAC;IAC/Cc,QAAQjB,MAAC,CAACkB,KAAK,CAAC1B,iBAAiB2B,QAAQ,GAAGhB,QAAQ,CAAC;IACrDiB,OAAOpB,MAAC,CAACC,MAAM,GAAGkB,QAAQ,GAAGhB,QAAQ,CAAC;AACxC;AAGO,IAAMZ,mBAAmBS,MAAC,CAACC,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC"}
@@ -16,6 +16,7 @@ _export(exports, {
16
16
  return parseConfig;
17
17
  }
18
18
  });
19
+ var _nodeurl = require("node:url");
19
20
  var _module = require("module");
20
21
  var _os = require("os");
21
22
  var _path = /*#__PURE__*/ _interop_require_wildcard(require("path"));
@@ -180,12 +181,12 @@ function normalizeResourceStoreUri(resourceStoreUri) {
180
181
  var filePrefix = 'file://';
181
182
  if (resourceStoreUri.startsWith(filePrefix)) {
182
183
  var rawPath = resourceStoreUri.slice(filePrefix.length);
183
- var expandedPath = rawPath.startsWith('~') ? rawPath.replace(/^~/, (0, _os.homedir)()) : rawPath;
184
- return "".concat(filePrefix).concat(_path.resolve(expandedPath));
184
+ var filePath = rawPath.startsWith('~') ? rawPath.replace(/^~/, (0, _os.homedir)()) : rawPath.startsWith('/') ? (0, _nodeurl.fileURLToPath)(resourceStoreUri) : rawPath;
185
+ return (0, _nodeurl.pathToFileURL)(_path.resolve(filePath)).href;
185
186
  }
186
187
  if (resourceStoreUri.includes('://')) return resourceStoreUri;
187
- var expandedPath1 = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, (0, _os.homedir)()) : resourceStoreUri;
188
- return "".concat(filePrefix).concat(_path.resolve(expandedPath1));
188
+ var expandedPath = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, (0, _os.homedir)()) : resourceStoreUri;
189
+ return (0, _nodeurl.pathToFileURL)(_path.resolve(expandedPath)).href;
189
190
  }
190
191
  function createConfig() {
191
192
  return parseConfig(process.argv, process.env);
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/setup/config.ts"],"sourcesContent":["import type * as OAuthGoogle from '@mcp-z/oauth-google';\nimport type * as McpServer from '@mcp-z/server';\nimport { Module } from 'module';\nimport { homedir } from 'os';\nimport * as path from 'path';\nimport { parseArgs } from 'util';\nimport { GOOGLE_SCOPE } from '../constants.ts';\nimport type { ServerConfig } from '../types.ts';\nimport { readPkg } from './version-help.ts';\n\nconst pkg = readPkg();\n\n// @mcp-z/oauth-google and @mcp-z/server are requireable at the >=20 floor; deferred so\n// --version/--help (handled via version-help.ts, never this file) load neither package.\nconst _require = typeof require === 'undefined' ? Module.createRequire(import.meta.url) : require;\n\n/**\n * Parse Sheets server configuration from CLI arguments and environment.\n *\n * CLI Arguments (all optional):\n * - --auth=<mode> Authentication mode (default: loopback-oauth)\n * Modes: loopback-oauth, service-account, dcr\n * - --headless Disable browser auto-open, return auth URL instead\n * - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n * - --dcr-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)\n * - --dcr-verify-url=<url> External verification endpoint (required for external mode)\n * - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)\n * - --port=<port> Enable HTTP transport on specified port\n * - --stdio Enable stdio transport (default if no port)\n * - --log-level=<level> Logging level (default: info)\n * - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: file://~/.mcp-z/mcp-sheets/files)\n * - --base-url=<url> Base URL for HTTP file serving (optional)\n *\n * Environment Variables:\n * - GOOGLE_CLIENT_ID OAuth client ID (REQUIRED)\n * - GOOGLE_CLIENT_SECRET OAuth client secret (optional)\n * - AUTH_MODE Default authentication mode (optional)\n * - HEADLESS Disable browser auto-open (optional)\n * - DCR_MODE DCR mode (optional, same format as --dcr-mode)\n * - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)\n * - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n * - TOKEN_STORE_URI Token storage URI (optional)\n * - PORT Default HTTP port (optional)\n * - LOG_LEVEL Default logging level (optional)\n * - RESOURCE_STORE_URI Resource store URI (optional, file://)\n * - BASE_URL Base URL for HTTP file serving (optional)\n *\n * OAuth Scopes (from constants.ts):\n * openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive\n */\nexport function parseConfig(args: string[], env: Record<string, string | undefined>): ServerConfig {\n const oauthGoogle = _require('@mcp-z/oauth-google') as typeof OAuthGoogle;\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n\n const transportConfig = mcpServer.parseConfig(args, env);\n const oauthConfig = oauthGoogle.parseConfig(args, env);\n\n // Parse DCR configuration if DCR mode is enabled\n const dcrConfig = oauthConfig.auth === 'dcr' ? oauthGoogle.parseDcrConfig(args, env, GOOGLE_SCOPE) : undefined;\n\n // Parse application-level config (LOG_LEVEL, RESOURCE_STORE_URI, BASE_URL)\n const { values } = parseArgs({\n args,\n options: {\n 'log-level': { type: 'string' },\n 'base-url': { type: 'string' },\n 'resource-store-uri': { type: 'string' },\n },\n strict: false, // Allow other arguments\n allowPositionals: true,\n });\n\n const name = pkg.name.replace(/^@[^/]+\\//, '');\n // Parse repository URL from package.json, stripping git+ prefix and .git suffix\n const rawRepoUrl = typeof pkg.repository === 'object' ? pkg.repository.url : pkg.repository;\n const repositoryUrl = rawRepoUrl?.replace(/^git\\+/, '').replace(/\\.git$/, '') ?? `https://github.com/mcp-z/${name}`;\n let rootDir = homedir();\n try {\n const configPath = mcpServer.findConfigPath({ config: '.mcp.json', cwd: process.cwd(), stopDir: homedir() });\n rootDir = path.dirname(configPath);\n } catch {\n rootDir = homedir();\n }\n const baseDir = path.join(rootDir, '.mcp-z');\n const cliLogLevel = typeof values['log-level'] === 'string' ? values['log-level'] : undefined;\n const envLogLevel = env.LOG_LEVEL;\n const logLevel = cliLogLevel ?? envLogLevel ?? 'info';\n\n // Parse storage configuration\n const cliResourceStoreUri = typeof values['resource-store-uri'] === 'string' ? values['resource-store-uri'] : undefined;\n const envResourceStoreUri = env.RESOURCE_STORE_URI;\n const defaultResourceStorePath = path.join(baseDir, name, 'files');\n const resourceStoreUri = normalizeResourceStoreUri(cliResourceStoreUri ?? envResourceStoreUri ?? defaultResourceStorePath);\n\n const cliBaseUrl = typeof values['base-url'] === 'string' ? values['base-url'] : undefined;\n const envBaseUrl = env.BASE_URL;\n const baseUrl = cliBaseUrl ?? envBaseUrl;\n\n // Combine configs\n return {\n ...oauthConfig, // Includes clientId, auth, headless, redirectUri\n transport: transportConfig.transport,\n logLevel,\n baseDir,\n name,\n version: pkg.version,\n repositoryUrl,\n resourceStoreUri,\n ...(baseUrl && { baseUrl }),\n ...(dcrConfig && { dcrConfig }),\n };\n}\n\nfunction normalizeResourceStoreUri(resourceStoreUri: string): string {\n const filePrefix = 'file://';\n if (resourceStoreUri.startsWith(filePrefix)) {\n const rawPath = resourceStoreUri.slice(filePrefix.length);\n const expandedPath = rawPath.startsWith('~') ? rawPath.replace(/^~/, homedir()) : rawPath;\n return `${filePrefix}${path.resolve(expandedPath)}`;\n }\n\n if (resourceStoreUri.includes('://')) return resourceStoreUri;\n\n const expandedPath = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, homedir()) : resourceStoreUri;\n return `${filePrefix}${path.resolve(expandedPath)}`;\n}\n\n/**\n * Build production configuration from process globals.\n * Entry point for production server.\n */\nexport function createConfig(): ServerConfig {\n return parseConfig(process.argv, process.env);\n}\n"],"names":["createConfig","parseConfig","pkg","readPkg","_require","require","Module","createRequire","args","env","cliLogLevel","cliResourceStoreUri","oauthGoogle","mcpServer","transportConfig","oauthConfig","dcrConfig","auth","parseDcrConfig","GOOGLE_SCOPE","undefined","values","parseArgs","options","type","strict","allowPositionals","name","replace","rawRepoUrl","repository","url","repositoryUrl","rootDir","homedir","configPath","findConfigPath","config","cwd","process","stopDir","path","dirname","baseDir","join","envLogLevel","LOG_LEVEL","logLevel","envResourceStoreUri","RESOURCE_STORE_URI","defaultResourceStorePath","resourceStoreUri","normalizeResourceStoreUri","cliBaseUrl","envBaseUrl","BASE_URL","baseUrl","transport","version","filePrefix","startsWith","rawPath","slice","length","expandedPath","resolve","includes","argv"],"mappings":";;;;;;;;;;;QAmIgBA;eAAAA;;QAjFAC;eAAAA;;;sBAhDO;kBACC;4DACF;oBACI;2BACG;6BAEL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,IAAMC,MAAMC,IAAAA,sB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AAwC,OAA3BlB,MAAKwB,OAAO,CAACD;IACtC;IAEA,IAAIb,iBAAiBe,QAAQ,CAAC,QAAQ,OAAOf;IAE7C,IAAMa,gBAAeb,iBAAiBS,UAAU,CAAC,OAAOT,iBAAiBvB,OAAO,CAAC,MAAMM,IAAAA,WAAO,OAAMiB;IACpG,OAAO,AAAC,GAAeV,OAAbkB,YAAwC,OAA3BlB,MAAKwB,OAAO,CAACD;AACtC;AAMO,SAAShE;IACd,OAAOC,YAAYsC,QAAQ4B,IAAI,EAAE5B,QAAQ9B,GAAG;AAC9C"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/setup/config.ts"],"sourcesContent":["import { fileURLToPath, pathToFileURL } from 'node:url';\nimport type * as OAuthGoogle from '@mcp-z/oauth-google';\nimport type * as McpServer from '@mcp-z/server';\nimport { Module } from 'module';\nimport { homedir } from 'os';\nimport * as path from 'path';\nimport { parseArgs } from 'util';\nimport { GOOGLE_SCOPE } from '../constants.ts';\nimport type { ServerConfig } from '../types.ts';\nimport { readPkg } from './version-help.ts';\n\nconst pkg = readPkg();\n\n// @mcp-z/oauth-google and @mcp-z/server are requireable at the >=20 floor; deferred so\n// --version/--help (handled via version-help.ts, never this file) load neither package.\nconst _require = typeof require === 'undefined' ? Module.createRequire(import.meta.url) : require;\n\n/**\n * Parse Sheets server configuration from CLI arguments and environment.\n *\n * CLI Arguments (all optional):\n * - --auth=<mode> Authentication mode (default: loopback-oauth)\n * Modes: loopback-oauth, service-account, dcr\n * - --headless Disable browser auto-open, return auth URL instead\n * - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n * - --dcr-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)\n * - --dcr-verify-url=<url> External verification endpoint (required for external mode)\n * - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)\n * - --port=<port> Enable HTTP transport on specified port\n * - --stdio Enable stdio transport (default if no port)\n * - --log-level=<level> Logging level (default: info)\n * - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: file://~/.mcp-z/mcp-sheets/files)\n * - --base-url=<url> Base URL for HTTP file serving (optional)\n *\n * Environment Variables:\n * - GOOGLE_CLIENT_ID OAuth client ID (REQUIRED)\n * - GOOGLE_CLIENT_SECRET OAuth client secret (optional)\n * - AUTH_MODE Default authentication mode (optional)\n * - HEADLESS Disable browser auto-open (optional)\n * - DCR_MODE DCR mode (optional, same format as --dcr-mode)\n * - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)\n * - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n * - TOKEN_STORE_URI Token storage URI (optional)\n * - PORT Default HTTP port (optional)\n * - LOG_LEVEL Default logging level (optional)\n * - RESOURCE_STORE_URI Resource store URI (optional, file://)\n * - BASE_URL Base URL for HTTP file serving (optional)\n *\n * OAuth Scopes (from constants.ts):\n * openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive\n */\nexport function parseConfig(args: string[], env: Record<string, string | undefined>): ServerConfig {\n const oauthGoogle = _require('@mcp-z/oauth-google') as typeof OAuthGoogle;\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n\n const transportConfig = mcpServer.parseConfig(args, env);\n const oauthConfig = oauthGoogle.parseConfig(args, env);\n\n // Parse DCR configuration if DCR mode is enabled\n const dcrConfig = oauthConfig.auth === 'dcr' ? oauthGoogle.parseDcrConfig(args, env, GOOGLE_SCOPE) : undefined;\n\n // Parse application-level config (LOG_LEVEL, RESOURCE_STORE_URI, BASE_URL)\n const { values } = parseArgs({\n args,\n options: {\n 'log-level': { type: 'string' },\n 'base-url': { type: 'string' },\n 'resource-store-uri': { type: 'string' },\n },\n strict: false, // Allow other arguments\n allowPositionals: true,\n });\n\n const name = pkg.name.replace(/^@[^/]+\\//, '');\n // Parse repository URL from package.json, stripping git+ prefix and .git suffix\n const rawRepoUrl = typeof pkg.repository === 'object' ? pkg.repository.url : pkg.repository;\n const repositoryUrl = rawRepoUrl?.replace(/^git\\+/, '').replace(/\\.git$/, '') ?? `https://github.com/mcp-z/${name}`;\n let rootDir = homedir();\n try {\n const configPath = mcpServer.findConfigPath({ config: '.mcp.json', cwd: process.cwd(), stopDir: homedir() });\n rootDir = path.dirname(configPath);\n } catch {\n rootDir = homedir();\n }\n const baseDir = path.join(rootDir, '.mcp-z');\n const cliLogLevel = typeof values['log-level'] === 'string' ? values['log-level'] : undefined;\n const envLogLevel = env.LOG_LEVEL;\n const logLevel = cliLogLevel ?? envLogLevel ?? 'info';\n\n // Parse storage configuration\n const cliResourceStoreUri = typeof values['resource-store-uri'] === 'string' ? values['resource-store-uri'] : undefined;\n const envResourceStoreUri = env.RESOURCE_STORE_URI;\n const defaultResourceStorePath = path.join(baseDir, name, 'files');\n const resourceStoreUri = normalizeResourceStoreUri(cliResourceStoreUri ?? envResourceStoreUri ?? defaultResourceStorePath);\n\n const cliBaseUrl = typeof values['base-url'] === 'string' ? values['base-url'] : undefined;\n const envBaseUrl = env.BASE_URL;\n const baseUrl = cliBaseUrl ?? envBaseUrl;\n\n // Combine configs\n return {\n ...oauthConfig, // Includes clientId, auth, headless, redirectUri\n transport: transportConfig.transport,\n logLevel,\n baseDir,\n name,\n version: pkg.version,\n repositoryUrl,\n resourceStoreUri,\n ...(baseUrl && { baseUrl }),\n ...(dcrConfig && { dcrConfig }),\n };\n}\n\nfunction normalizeResourceStoreUri(resourceStoreUri: string): string {\n const filePrefix = 'file://';\n if (resourceStoreUri.startsWith(filePrefix)) {\n const rawPath = resourceStoreUri.slice(filePrefix.length);\n const filePath = rawPath.startsWith('~') ? rawPath.replace(/^~/, homedir()) : rawPath.startsWith('/') ? fileURLToPath(resourceStoreUri) : rawPath;\n return pathToFileURL(path.resolve(filePath)).href;\n }\n\n if (resourceStoreUri.includes('://')) return resourceStoreUri;\n\n const expandedPath = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, homedir()) : resourceStoreUri;\n return pathToFileURL(path.resolve(expandedPath)).href;\n}\n\n/**\n * Build production configuration from process globals.\n * Entry point for production server.\n */\nexport function createConfig(): ServerConfig {\n return parseConfig(process.argv, process.env);\n}\n"],"names":["createConfig","parseConfig","pkg","readPkg","_require","require","Module","createRequire","args","env","cliLogLevel","cliResourceStoreUri","oauthGoogle","mcpServer","transportConfig","oauthConfig","dcrConfig","auth","parseDcrConfig","GOOGLE_SCOPE","undefined","values","parseArgs","options","type","strict","allowPositionals","name","replace","rawRepoUrl","repository","url","repositoryUrl","rootDir","homedir","configPath","findConfigPath","config","cwd","process","stopDir","path","dirname","baseDir","join","envLogLevel","LOG_LEVEL","logLevel","envResourceStoreUri","RESOURCE_STORE_URI","defaultResourceStorePath","resourceStoreUri","normalizeResourceStoreUri","cliBaseUrl","envBaseUrl","BASE_URL","baseUrl","transport","version","filePrefix","startsWith","rawPath","slice","length","filePath","fileURLToPath","pathToFileURL","resolve","href","includes","expandedPath","argv"],"mappings":";;;;;;;;;;;QAoIgBA;eAAAA;;QAjFAC;eAAAA;;;uBAnD6B;sBAGtB;kBACC;4DACF;oBACI;2BACG;6BAEL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,IAAMC,MAAMC,IAAAA,sBAAO;AAEnB,uFAAuF;AACvF,wFAAwF;AACxF,IAAMC,WAAW,OAAOC,YAAY,cAAcC,cAAM,CAACC,aAAa,CAAC,uDAAmBF;AAoCnF,SAASJ,YAAYO,IAAc,EAAEC,GAAuC;cAoChEC,OAMkCC;IAzCnD,IAAMC,cAAcR,SAAS;IAC7B,IAAMS,YAAYT,SAAS;IAE3B,IAAMU,kBAAkBD,UAAUZ,WAAW,CAACO,MAAMC;IACpD,IAAMM,cAAcH,YAAYX,WAAW,CAACO,MAAMC;IAElD,iDAAiD;IACjD,IAAMO,YAAYD,YAAYE,IAAI,KAAK,QAAQL,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,QAAQ9B,GAAG;AAC9C"}
@@ -1,6 +1,6 @@
1
1
  import type { RuntimeOverrides, ServerConfig } from '../types.js';
2
2
  export declare function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
3
- httpServer: import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
3
+ httpServer: import("http").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>;
4
4
  logger: import("@mcp-z/server").Logger;
5
5
  close: () => Promise<void>;
6
6
  }>;