@mcp-z/mcp-sheets 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/lib/google-auth.d.cts +9 -0
- package/dist/cjs/lib/google-auth.d.ts +9 -0
- package/dist/cjs/lib/google-auth.js +16 -0
- package/dist/cjs/lib/google-auth.js.map +1 -0
- package/dist/cjs/mcp/resources/spreadsheet.js +2 -1
- package/dist/cjs/mcp/resources/spreadsheet.js.map +1 -1
- package/dist/cjs/mcp/tools/cells-format.js +2 -1
- package/dist/cjs/mcp/tools/cells-format.js.map +1 -1
- package/dist/cjs/mcp/tools/chart-create.js +2 -1
- package/dist/cjs/mcp/tools/chart-create.js.map +1 -1
- package/dist/cjs/mcp/tools/columns-get.js +2 -1
- package/dist/cjs/mcp/tools/columns-get.js.map +1 -1
- package/dist/cjs/mcp/tools/columns-update.js +2 -1
- package/dist/cjs/mcp/tools/columns-update.js.map +1 -1
- package/dist/cjs/mcp/tools/dimensions-batch-update.js +2 -1
- package/dist/cjs/mcp/tools/dimensions-batch-update.js.map +1 -1
- package/dist/cjs/mcp/tools/dimensions-move.js +2 -1
- package/dist/cjs/mcp/tools/dimensions-move.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-append.js +2 -1
- package/dist/cjs/mcp/tools/rows-append.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-csv-append.js +2 -1
- package/dist/cjs/mcp/tools/rows-csv-append.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-get.js +2 -1
- package/dist/cjs/mcp/tools/rows-get.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-copy-to.js +2 -1
- package/dist/cjs/mcp/tools/sheet-copy-to.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-copy.js +2 -1
- package/dist/cjs/mcp/tools/sheet-copy.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-create.js +2 -1
- package/dist/cjs/mcp/tools/sheet-create.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-delete.js +2 -1
- package/dist/cjs/mcp/tools/sheet-delete.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-find.js +2 -1
- package/dist/cjs/mcp/tools/sheet-find.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-rename.js +2 -1
- package/dist/cjs/mcp/tools/sheet-rename.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-copy.js +3 -2
- package/dist/cjs/mcp/tools/spreadsheet-copy.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-create.js +2 -1
- package/dist/cjs/mcp/tools/spreadsheet-create.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-find.js +3 -2
- package/dist/cjs/mcp/tools/spreadsheet-find.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-rename.js +2 -1
- package/dist/cjs/mcp/tools/spreadsheet-rename.js.map +1 -1
- package/dist/cjs/mcp/tools/validation-set.js +2 -1
- package/dist/cjs/mcp/tools/validation-set.js.map +1 -1
- package/dist/cjs/mcp/tools/values-batch-update.js +2 -1
- package/dist/cjs/mcp/tools/values-batch-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-clear.js +2 -1
- package/dist/cjs/mcp/tools/values-clear.js.map +1 -1
- package/dist/cjs/mcp/tools/values-csv-update.js +2 -1
- package/dist/cjs/mcp/tools/values-csv-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-markdown-update.js +2 -1
- package/dist/cjs/mcp/tools/values-markdown-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-replace.js +2 -1
- package/dist/cjs/mcp/tools/values-replace.js.map +1 -1
- package/dist/cjs/mcp/tools/values-search.js +2 -1
- package/dist/cjs/mcp/tools/values-search.js.map +1 -1
- package/dist/esm/lib/google-auth.d.ts +9 -0
- package/dist/esm/lib/google-auth.js +11 -0
- package/dist/esm/lib/google-auth.js.map +1 -0
- package/dist/esm/mcp/resources/spreadsheet.js +2 -1
- package/dist/esm/mcp/resources/spreadsheet.js.map +1 -1
- package/dist/esm/mcp/tools/cells-format.js +2 -1
- package/dist/esm/mcp/tools/cells-format.js.map +1 -1
- package/dist/esm/mcp/tools/chart-create.js +2 -1
- package/dist/esm/mcp/tools/chart-create.js.map +1 -1
- package/dist/esm/mcp/tools/columns-get.js +2 -1
- package/dist/esm/mcp/tools/columns-get.js.map +1 -1
- package/dist/esm/mcp/tools/columns-update.js +2 -1
- package/dist/esm/mcp/tools/columns-update.js.map +1 -1
- package/dist/esm/mcp/tools/dimensions-batch-update.js +2 -1
- package/dist/esm/mcp/tools/dimensions-batch-update.js.map +1 -1
- package/dist/esm/mcp/tools/dimensions-move.js +2 -1
- package/dist/esm/mcp/tools/dimensions-move.js.map +1 -1
- package/dist/esm/mcp/tools/rows-append.js +2 -1
- package/dist/esm/mcp/tools/rows-append.js.map +1 -1
- package/dist/esm/mcp/tools/rows-csv-append.js +2 -1
- package/dist/esm/mcp/tools/rows-csv-append.js.map +1 -1
- package/dist/esm/mcp/tools/rows-get.js +2 -1
- package/dist/esm/mcp/tools/rows-get.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-copy-to.js +2 -1
- package/dist/esm/mcp/tools/sheet-copy-to.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-copy.js +2 -1
- package/dist/esm/mcp/tools/sheet-copy.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-create.js +2 -1
- package/dist/esm/mcp/tools/sheet-create.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-delete.js +2 -1
- package/dist/esm/mcp/tools/sheet-delete.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-find.js +2 -1
- package/dist/esm/mcp/tools/sheet-find.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-rename.js +2 -1
- package/dist/esm/mcp/tools/sheet-rename.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-copy.js +3 -2
- package/dist/esm/mcp/tools/spreadsheet-copy.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-create.js +2 -1
- package/dist/esm/mcp/tools/spreadsheet-create.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-find.js +3 -2
- package/dist/esm/mcp/tools/spreadsheet-find.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-rename.js +2 -1
- package/dist/esm/mcp/tools/spreadsheet-rename.js.map +1 -1
- package/dist/esm/mcp/tools/validation-set.js +2 -1
- package/dist/esm/mcp/tools/validation-set.js.map +1 -1
- package/dist/esm/mcp/tools/values-batch-update.js +2 -1
- package/dist/esm/mcp/tools/values-batch-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-clear.js +2 -1
- package/dist/esm/mcp/tools/values-clear.js.map +1 -1
- package/dist/esm/mcp/tools/values-csv-update.js +2 -1
- package/dist/esm/mcp/tools/values-csv-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-markdown-update.js +2 -1
- package/dist/esm/mcp/tools/values-markdown-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-replace.js +2 -1
- package/dist/esm/mcp/tools/values-replace.js.map +1 -1
- package/dist/esm/mcp/tools/values-search.js +2 -1
- package/dist/esm/mcp/tools/values-search.js.map +1 -1
- package/package.json +3 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/columns-update.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { generateRowKey, type KeyGenerationStrategy, type Row, snapshotHeaderKeysAndPositions, type UpsertOptions, upsertByKey } from '../../spreadsheet/data-operations.ts';\n\n// Input schema for columns update requests with enhanced validation\nconst inputSchema = z\n .object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n rows: z.array(z.array(SheetCellSchema)).min(1).max(1000).describe('Array of rows to upsert (max 1000 rows per request). Each row is an array of cell values matching the headers array'),\n headers: z.array(z.string().min(1).max(100)).min(1).max(50).describe('Array of column names/headers (max 50 columns). Must match the length of each row in the rows array'),\n updateBy: z.array(z.string().min(1).max(100)).min(1).max(10).describe('Array of column names to use as unique keys for matching existing rows (max 10 key columns). These columns must exist in the headers array'),\n behavior: z\n .enum(['add-or-update', 'update-only', 'add-only'])\n .default('add-or-update')\n .describe('Update behavior: add-or-update (default) adds new rows and updates existing, update-only skips new rows, add-only skips existing rows. BEST FOR: Bulk upsert operations with key matching in structured database or table contexts.'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input with formulas, dates, etc.)'),\n })\n .refine(\n (data) => {\n // Validate that all updateBy columns exist in headers\n const missingColumns = data.updateBy.filter((col) => !data.headers.includes(col));\n return missingColumns.length === 0;\n },\n {\n message: 'All updateBy columns must exist in the headers array',\n path: ['updateBy'],\n }\n )\n .refine(\n (data) => {\n // Validate that all rows have the same length as headers\n const invalidRows = data.rows.findIndex((row) => row.length !== data.headers.length);\n return invalidRows === -1;\n },\n {\n message: 'All rows must have the same length as the headers array',\n path: ['rows'],\n }\n )\n .refine(\n (data) => {\n // Validate that updateBy columns are unique\n const uniqueColumns = new Set(data.updateBy);\n return uniqueColumns.size === data.updateBy.length;\n },\n {\n message: 'updateBy columns must be unique',\n path: ['updateBy'],\n }\n );\n\n// Success branch schema\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 updatedRows: z.number().int().nonnegative().describe('Number of rows that were successfully updated or inserted'),\n insertedKeys: z.array(z.string()).describe('Keys of rows that were successfully inserted (new rows)'),\n rowsSkipped: z.number().int().nonnegative().describe('Number of rows that were skipped based on the update behavior and existing data'),\n headersAdded: z.array(z.string()).describe('Column headers that were added to the sheet (if any were missing)'),\n errors: z.array(z.string()).optional().describe('Any non-fatal errors encountered during the operation'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Update spreadsheet data by column headers with intelligent upsert logic. Supports adding missing columns, flexible update behaviors, and robust error handling. Uses column names as keys for matching existing rows, enabling context-aware data synchronization workflows.',\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\n// Helper function to ensure consistent key generation\nfunction generateConsistentRowKey(row: Row, headers: string[], strategy: KeyGenerationStrategy): string {\n return generateRowKey(row, headers, strategy);\n}\n\nasync function handler({ id, gid, rows, headers, updateBy, behavior = 'add-or-update', valueInputOption = 'USER_ENTERED' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.debug?.('sheets.columns.update called', {\n id,\n gid,\n rowCount: rows.length,\n headerCount: headers.length,\n updateByColumns: updateBy,\n behavior,\n valueInputOption,\n });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Note: Basic input validation is now handled by the enhanced Zod schema\n\n // EARLY VALIDATION: Validate that updateBy columns have non-empty values for all rows\n // This validation happens before finding spreadsheet/sheet to fail fast\n const emptyKeyErrors: string[] = [];\n rows.forEach((row, rowIndex) => {\n const keyValues = updateBy.map((keyCol) => {\n const colIndex = headers.indexOf(keyCol);\n return colIndex >= 0 ? String(row[colIndex] ?? '').trim() : '';\n });\n\n if (keyValues.some((val) => val === '')) {\n emptyKeyErrors.push(`Row ${rowIndex + 1} has empty key values for columns: ${updateBy.join(', ')}`);\n }\n });\n\n if (emptyKeyErrors.length > 0) {\n const message = `Silent data loss prevented - empty key columns detected:\\n${emptyKeyErrors.join('\\n')}`;\n logger.error?.('sheets.columns.update error', { error: message });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, message);\n }\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.warn?.('Sheet not found for columns update', { id, gid, rowCount: rows.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 // Configure upsert options based on behavior\n const upsertOptions: UpsertOptions = {\n keyStrategy: {\n keyColumns: updateBy,\n useProviderIdLogic: false, // Use standard key generation for column-based updates\n separator: '\\\\',\n },\n allowUpdates: behavior === 'add-or-update' || behavior === 'update-only',\n batchSize: 50,\n valueInputOption: valueInputOption,\n };\n\n // Get existing keys to implement behavior filtering\n const { keySet: existingKeys } = await snapshotHeaderKeysAndPositions(sheets, id, sheetTitle, updateBy, upsertOptions.keyStrategy);\n\n // Filter rows based on behavior using consistent key generation\n let processedRows = rows;\n if (behavior === 'add-only') {\n // Only include rows that don't exist yet\n processedRows = rows.filter((row) => {\n // Use the same key generation strategy as the upsert function\n const key = generateConsistentRowKey(row, headers, upsertOptions.keyStrategy);\n return key !== '' && !existingKeys.has(key);\n });\n logger.debug?.('Filtered rows for add-only behavior', {\n originalCount: rows.length,\n filteredCount: processedRows.length,\n });\n } else if (behavior === 'update-only') {\n // Only include rows that already exist\n processedRows = rows.filter((row) => {\n // Use the same key generation strategy as the upsert function\n const key = generateConsistentRowKey(row, headers, upsertOptions.keyStrategy);\n return key !== '' && existingKeys.has(key);\n });\n logger.debug?.('Filtered rows for update-only behavior', {\n originalCount: rows.length,\n filteredCount: processedRows.length,\n });\n }\n\n // Early return if no rows to process after behavior filtering\n if (processedRows.length === 0) {\n logger.info?.('No rows to process after behavior filtering', { behavior, originalCount: rows.length });\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 updatedRows: 0,\n insertedKeys: [],\n rowsSkipped: rows.length,\n headersAdded: [],\n errors: [`No rows matched behavior '${behavior}' - all ${rows.length} rows were skipped`],\n };\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n }\n\n logger.debug?.('sheets.columns.update executing upsert operation', {\n spreadsheetId: id,\n sheetTitle,\n canonicalHeaders: headers,\n keyColumns: updateBy,\n behavior,\n processedRowsCount: processedRows.length,\n });\n\n // Execute the upsert operation using the shared function\n const upsertResult = await upsertByKey(sheets, {\n spreadsheetId: id,\n sheetTitle,\n rows: processedRows,\n canonicalHeaders: headers,\n options: upsertOptions,\n logger,\n });\n\n // Track headers that were added (if any)\n // This would require additional logic in upsertByKey to return added headers\n const headersAdded: string[] = [];\n\n // Calculate total rows skipped: behavior filter + upsert duplicates\n const rowsFilteredByBehavior = rows.length - processedRows.length;\n const totalRowsSkipped = upsertResult.rowsSkipped + rowsFilteredByBehavior;\n\n logger.debug?.('sheets.columns.update completed successfully', {\n updatedRows: upsertResult.updatedRows,\n insertedCount: upsertResult.inserted.length,\n rowsSkipped: totalRowsSkipped,\n rowsFilteredByBehavior,\n rowsSkippedByUpsert: upsertResult.rowsSkipped,\n errorsCount: upsertResult.errors?.length || 0,\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 updatedRows: upsertResult.updatedRows,\n insertedKeys: upsertResult.inserted,\n rowsSkipped: totalRowsSkipped,\n headersAdded,\n errors: upsertResult.errors,\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.columns.update error', { error: message });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error updating columns: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'columns-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","SheetCellSchema","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","generateRowKey","snapshotHeaderKeysAndPositions","upsertByKey","inputSchema","object","id","gid","rows","array","min","max","describe","headers","string","updateBy","behavior","enum","default","valueInputOption","refine","data","missingColumns","filter","col","includes","length","message","path","invalidRows","findIndex","row","uniqueColumns","Set","size","successBranchSchema","type","literal","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRows","number","int","nonnegative","insertedKeys","rowsSkipped","headersAdded","errors","optional","outputSchema","discriminatedUnion","config","description","result","generateConsistentRowKey","strategy","handler","extra","logger","debug","rowCount","headerCount","updateByColumns","spreadsheetData","sheet","upsertResult","sheets","version","auth","authContext","emptyKeyErrors","forEach","rowIndex","keyValues","map","keyCol","colIndex","indexOf","String","trim","some","val","push","join","error","InvalidParams","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","properties","title","find","s","sheetId","warn","sheetGid","upsertOptions","keyStrategy","keyColumns","useProviderIdLogic","separator","allowUpdates","batchSize","keySet","existingKeys","processedRows","key","has","originalCount","filteredCount","info","content","text","JSON","stringify","structuredContent","canonicalHeaders","processedRowsCount","options","rowsFilteredByBehavior","totalRowsSkipped","insertedCount","inserted","rowsSkippedByUpsert","errorsCount","Error","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,eAAe,EAAEC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AACnI,SAASC,cAAc,EAAwCC,8BAA8B,EAAsBC,WAAW,QAAQ,uCAAuC;AAE7K,oEAAoE;AACpE,MAAMC,cAAcT,EACjBU,MAAM,CAAC;IACNC,IAAIN;IACJO,KAAKT;IACLU,MAAMb,EAAEc,KAAK,CAACd,EAAEc,KAAK,CAACb,kBAAkBc,GAAG,CAAC,GAAGC,GAAG,CAAC,MAAMC,QAAQ,CAAC;IAClEC,SAASlB,EAAEc,KAAK,CAACd,EAAEmB,MAAM,GAAGJ,GAAG,CAAC,GAAGC,GAAG,CAAC,MAAMD,GAAG,CAAC,GAAGC,GAAG,CAAC,IAAIC,QAAQ,CAAC;IACrEG,UAAUpB,EAAEc,KAAK,CAACd,EAAEmB,MAAM,GAAGJ,GAAG,CAAC,GAAGC,GAAG,CAAC,MAAMD,GAAG,CAAC,GAAGC,GAAG,CAAC,IAAIC,QAAQ,CAAC;IACtEI,UAAUrB,EACPsB,IAAI,CAAC;QAAC;QAAiB;QAAe;KAAW,EACjDC,OAAO,CAAC,iBACRN,QAAQ,CAAC;IACZO,kBAAkBxB,EAAEsB,IAAI,CAAC;QAAC;QAAO;KAAe,EAAEC,OAAO,CAAC,gBAAgBN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GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNjF;QACAK;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/columns-update.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { generateRowKey, type KeyGenerationStrategy, type Row, snapshotHeaderKeysAndPositions, type UpsertOptions, upsertByKey } from '../../spreadsheet/data-operations.ts';\n\n// Input schema for columns update requests with enhanced validation\nconst inputSchema = z\n .object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n rows: z.array(z.array(SheetCellSchema)).min(1).max(1000).describe('Array of rows to upsert (max 1000 rows per request). Each row is an array of cell values matching the headers array'),\n headers: z.array(z.string().min(1).max(100)).min(1).max(50).describe('Array of column names/headers (max 50 columns). Must match the length of each row in the rows array'),\n updateBy: z.array(z.string().min(1).max(100)).min(1).max(10).describe('Array of column names to use as unique keys for matching existing rows (max 10 key columns). These columns must exist in the headers array'),\n behavior: z\n .enum(['add-or-update', 'update-only', 'add-only'])\n .default('add-or-update')\n .describe('Update behavior: add-or-update (default) adds new rows and updates existing, update-only skips new rows, add-only skips existing rows. BEST FOR: Bulk upsert operations with key matching in structured database or table contexts.'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input with formulas, dates, etc.)'),\n })\n .refine(\n (data) => {\n // Validate that all updateBy columns exist in headers\n const missingColumns = data.updateBy.filter((col) => !data.headers.includes(col));\n return missingColumns.length === 0;\n },\n {\n message: 'All updateBy columns must exist in the headers array',\n path: ['updateBy'],\n }\n )\n .refine(\n (data) => {\n // Validate that all rows have the same length as headers\n const invalidRows = data.rows.findIndex((row) => row.length !== data.headers.length);\n return invalidRows === -1;\n },\n {\n message: 'All rows must have the same length as the headers array',\n path: ['rows'],\n }\n )\n .refine(\n (data) => {\n // Validate that updateBy columns are unique\n const uniqueColumns = new Set(data.updateBy);\n return uniqueColumns.size === data.updateBy.length;\n },\n {\n message: 'updateBy columns must be unique',\n path: ['updateBy'],\n }\n );\n\n// Success branch schema\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 updatedRows: z.number().int().nonnegative().describe('Number of rows that were successfully updated or inserted'),\n insertedKeys: z.array(z.string()).describe('Keys of rows that were successfully inserted (new rows)'),\n rowsSkipped: z.number().int().nonnegative().describe('Number of rows that were skipped based on the update behavior and existing data'),\n headersAdded: z.array(z.string()).describe('Column headers that were added to the sheet (if any were missing)'),\n errors: z.array(z.string()).optional().describe('Any non-fatal errors encountered during the operation'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Update spreadsheet data by column headers with intelligent upsert logic. Supports adding missing columns, flexible update behaviors, and robust error handling. Uses column names as keys for matching existing rows, enabling context-aware data synchronization workflows.',\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\n// Helper function to ensure consistent key generation\nfunction generateConsistentRowKey(row: Row, headers: string[], strategy: KeyGenerationStrategy): string {\n return generateRowKey(row, headers, strategy);\n}\n\nasync function handler({ id, gid, rows, headers, updateBy, behavior = 'add-or-update', valueInputOption = 'USER_ENTERED' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.debug?.('sheets.columns.update called', {\n id,\n gid,\n rowCount: rows.length,\n headerCount: headers.length,\n updateByColumns: updateBy,\n behavior,\n valueInputOption,\n });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Note: Basic input validation is now handled by the enhanced Zod schema\n\n // EARLY VALIDATION: Validate that updateBy columns have non-empty values for all rows\n // This validation happens before finding spreadsheet/sheet to fail fast\n const emptyKeyErrors: string[] = [];\n rows.forEach((row, rowIndex) => {\n const keyValues = updateBy.map((keyCol) => {\n const colIndex = headers.indexOf(keyCol);\n return colIndex >= 0 ? String(row[colIndex] ?? '').trim() : '';\n });\n\n if (keyValues.some((val) => val === '')) {\n emptyKeyErrors.push(`Row ${rowIndex + 1} has empty key values for columns: ${updateBy.join(', ')}`);\n }\n });\n\n if (emptyKeyErrors.length > 0) {\n const message = `Silent data loss prevented - empty key columns detected:\\n${emptyKeyErrors.join('\\n')}`;\n logger.error?.('sheets.columns.update error', { error: message });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, message);\n }\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.warn?.('Sheet not found for columns update', { id, gid, rowCount: rows.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 // Configure upsert options based on behavior\n const upsertOptions: UpsertOptions = {\n keyStrategy: {\n keyColumns: updateBy,\n useProviderIdLogic: false, // Use standard key generation for column-based updates\n separator: '\\\\',\n },\n allowUpdates: behavior === 'add-or-update' || behavior === 'update-only',\n batchSize: 50,\n valueInputOption: valueInputOption,\n };\n\n // Get existing keys to implement behavior filtering\n const { keySet: existingKeys } = await snapshotHeaderKeysAndPositions(sheets, id, sheetTitle, updateBy, upsertOptions.keyStrategy);\n\n // Filter rows based on behavior using consistent key generation\n let processedRows = rows;\n if (behavior === 'add-only') {\n // Only include rows that don't exist yet\n processedRows = rows.filter((row) => {\n // Use the same key generation strategy as the upsert function\n const key = generateConsistentRowKey(row, headers, upsertOptions.keyStrategy);\n return key !== '' && !existingKeys.has(key);\n });\n logger.debug?.('Filtered rows for add-only behavior', {\n originalCount: rows.length,\n filteredCount: processedRows.length,\n });\n } else if (behavior === 'update-only') {\n // Only include rows that already exist\n processedRows = rows.filter((row) => {\n // Use the same key generation strategy as the upsert function\n const key = generateConsistentRowKey(row, headers, upsertOptions.keyStrategy);\n return key !== '' && existingKeys.has(key);\n });\n logger.debug?.('Filtered rows for update-only behavior', {\n originalCount: rows.length,\n filteredCount: processedRows.length,\n });\n }\n\n // Early return if no rows to process after behavior filtering\n if (processedRows.length === 0) {\n logger.info?.('No rows to process after behavior filtering', { behavior, originalCount: rows.length });\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 updatedRows: 0,\n insertedKeys: [],\n rowsSkipped: rows.length,\n headersAdded: [],\n errors: [`No rows matched behavior '${behavior}' - all ${rows.length} rows were skipped`],\n };\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n }\n\n logger.debug?.('sheets.columns.update executing upsert operation', {\n spreadsheetId: id,\n sheetTitle,\n canonicalHeaders: headers,\n keyColumns: updateBy,\n behavior,\n processedRowsCount: processedRows.length,\n });\n\n // Execute the upsert operation using the shared function\n const upsertResult = await upsertByKey(sheets, {\n spreadsheetId: id,\n sheetTitle,\n rows: processedRows,\n canonicalHeaders: headers,\n options: upsertOptions,\n logger,\n });\n\n // Track headers that were added (if any)\n // This would require additional logic in upsertByKey to return added headers\n const headersAdded: string[] = [];\n\n // Calculate total rows skipped: behavior filter + upsert duplicates\n const rowsFilteredByBehavior = rows.length - processedRows.length;\n const totalRowsSkipped = upsertResult.rowsSkipped + rowsFilteredByBehavior;\n\n logger.debug?.('sheets.columns.update completed successfully', {\n updatedRows: upsertResult.updatedRows,\n insertedCount: upsertResult.inserted.length,\n rowsSkipped: totalRowsSkipped,\n rowsFilteredByBehavior,\n rowsSkippedByUpsert: upsertResult.rowsSkipped,\n errorsCount: upsertResult.errors?.length || 0,\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 updatedRows: upsertResult.updatedRows,\n insertedKeys: upsertResult.inserted,\n rowsSkipped: totalRowsSkipped,\n headersAdded,\n errors: upsertResult.errors,\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.columns.update error', { error: message });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error updating columns: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'columns-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","googleAuth","SheetCellSchema","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","generateRowKey","snapshotHeaderKeysAndPositions","upsertByKey","inputSchema","object","id","gid","rows","array","min","max","describe","headers","string","updateBy","behavior","enum","default","valueInputOption","refine","data","missingColumns","filter","col","includes","length","message","path","invalidRows","findIndex","row","uniqueColumns","Set","size","successBranchSchema","type","literal","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRows","number","int","nonnegative","insertedKeys","rowsSkipped","headersAdded","errors","optional","outputSchema","discriminatedUnion","config","description","result","generateConsistentRowKey","strategy","handler","extra","logger","debug","rowCount","headerCount","updateByColumns","spreadsheetData","sheet","upsertResult","sheets","version","auth","authContext","emptyKeyErrors","forEach","rowIndex","keyValues","map","keyCol","colIndex","indexOf","String","trim","some","val","push","join","error","InvalidParams","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","properties","title","find","s","sheetId","warn","sheetGid","upsertOptions","keyStrategy","keyColumns","useProviderIdLogic","separator","allowUpdates","batchSize","keySet","existingKeys","processedRows","key","has","originalCount","filteredCount","info","content","text","JSON","stringify","structuredContent","canonicalHeaders","processedRowsCount","options","rowsFilteredByBehavior","totalRowsSkipped","insertedCount","inserted","rowsSkippedByUpsert","errorsCount","Error","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,eAAe,EAAEC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AACnI,SAASC,cAAc,EAAwCC,8BAA8B,EAAsBC,WAAW,QAAQ,uCAAuC;AAE7K,oEAA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B;YACZ7D,kBAAkBA,oBAAoB;YACtCC,gBAAgBA,kBAAkB;YAClCC;YACAC;YACAC,aAAayB,aAAazB,WAAW;YACrCI,cAAcqB,aAAa2D,QAAQ;YACnC/E,aAAa6E;YACb5E;YACAC,QAAQkB,aAAalB,MAAM;QAC7B;QAEA,OAAO;YACLkE,SAAS;gBAAC;oBAAE/E,MAAM;oBAAiBgF,MAAMC,KAAKC,SAAS,CAAC/D;gBAAQ;aAAE;YAClEgE,mBAAmB;gBAAEhE;YAAO;QAC9B;IACF,EAAE,OAAO+B,OAAO;YAEd1B;QADA,MAAMjC,UAAU2D,iBAAiB2C,QAAQ3C,MAAM3D,OAAO,GAAGqD,OAAOM;SAChE1B,iBAAAA,OAAO0B,KAAK,cAAZ1B,qCAAAA,oBAAAA,QAAe,+BAA+B;YAAE0B,OAAO3D;QAAQ;QAC/D,MAAM,IAAIpC,cAAcC,kBAAkB0I,aAAa,EAAE,CAAC,wBAAwB,EAAEvG,SAAS,EAAE;YAC7FwG,OAAO7C,iBAAiB2C,QAAQ3C,MAAM6C,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNjF;QACAK;IACF;AACF"}
|
|
@@ -3,6 +3,7 @@ const { AuthRequiredBranchSchema } = schemas;
|
|
|
3
3
|
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
4
4
|
import { google } from 'googleapis';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
6
7
|
import { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.js';
|
|
7
8
|
import { buildDimensionRequest, calculateAffectedCount, DEFAULT_COLUMN_COUNT, DEFAULT_ROW_COUNT, MAX_COLUMN_COUNT, MAX_ROW_COUNT, sortOperations } from './lib/dimension-operations.js';
|
|
8
9
|
// Input schema for dimension batch update requests
|
|
@@ -84,7 +85,7 @@ async function handler({ id, gid, requests }, extra) {
|
|
|
84
85
|
var _spreadsheetData_properties, _spreadsheetData_sheets, _sheet_properties_gridProperties, _sheet_properties_gridProperties1, _logger_debug1, _logger_debug2;
|
|
85
86
|
const sheets = google.sheets({
|
|
86
87
|
version: 'v4',
|
|
87
|
-
auth: extra.authContext.auth
|
|
88
|
+
auth: googleAuth(extra.authContext.auth)
|
|
88
89
|
});
|
|
89
90
|
// Get spreadsheet and sheet info in single API call
|
|
90
91
|
const spreadsheetResponse = await sheets.spreadsheets.get({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/dimensions-batch-update.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { buildDimensionRequest, calculateAffectedCount, DEFAULT_COLUMN_COUNT, DEFAULT_ROW_COUNT, type DimensionRequest, MAX_COLUMN_COUNT, MAX_ROW_COUNT, sortOperations } from './lib/dimension-operations.ts';\n\n// Input schema for dimension batch update requests\nconst DimensionRequestSchema = z.object({\n operation: z.enum(['insertDimension', 'deleteDimension', 'appendDimension']).describe('Type of dimension operation to perform'),\n dimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether to operate on rows or columns'),\n startIndex: z.number().int().nonnegative().describe('Starting index for the operation (0-based)'),\n endIndex: z.number().int().nonnegative().optional().describe('Ending index for the operation (0-based, exclusive). Optional - if omitted, the range is unbounded (extends to the end of the sheet)'),\n inheritFromBefore: z.boolean().optional().describe('For insertDimension: whether new rows/columns inherit properties from the row/column before the insertion point'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(DimensionRequestSchema).min(1).describe('Array of dimension update requests'),\n});\n\n// Success branch schema\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 totalOperations: z.number().int().nonnegative().describe('Total number of dimension operations performed'),\n operationResults: z\n .array(\n z.object({\n operation: z.enum(['insertDimension', 'deleteDimension', 'appendDimension']).describe('Type of operation that was performed'),\n dimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension that was operated on'),\n startIndex: z.number().int().nonnegative().describe('Starting index of the operation'),\n endIndex: z.number().int().nonnegative().optional().describe('Ending index of the operation (for insert/delete)'),\n affectedCount: z.number().int().nonnegative().describe('Number of rows/columns affected by this operation'),\n })\n )\n .describe('Detailed results for each dimension operation'),\n updatedDimensions: z\n .object({\n rows: z.number().int().nonnegative().describe('Total number of rows in the sheet after all operations'),\n columns: z.number().int().nonnegative().describe('Total number of columns in the sheet after all operations'),\n })\n .describe('Final dimensions of the sheet after all operations'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Batch update sheet dimensions by inserting, deleting, or appending rows/columns. Operations are atomic (all succeed or all fail) and execute in optimal order automatically.',\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.debug?.('sheets.dimensions.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n operations: requests.map((r) => ({ operation: r.operation, dimension: r.dimension, startIndex: r.startIndex, endIndex: r.endIndex })),\n });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\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.warn?.('Sheet not found for dimensions 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 sheetId = sheet.properties.sheetId;\n\n if (sheetId === undefined || sheetId === null) {\n logger.error?.('Sheet ID not available for dimensions batch update', { id, gid, sheetTitle });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Sheet ID not available for ${gid}. Cannot perform dimension operations without valid sheet ID.`);\n }\n\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Get current sheet dimensions for response calculation\n // Note: Google Sheets API may not always provide gridProperties for older sheets\n // Fall back to Google's documented defaults for new sheets\n const currentRowCount = sheet.properties.gridProperties?.rowCount ?? DEFAULT_ROW_COUNT;\n const currentColumnCount = sheet.properties.gridProperties?.columnCount ?? DEFAULT_COLUMN_COUNT;\n\n // Sort operations for optimal execution order to prevent index conflicts\n // Delete operations are processed first (high to low index) to avoid shifting issues\n // Insert/append operations are processed after (low to high index)\n const sortedRequests = sortOperations(requests as DimensionRequest[]);\n\n // Build Google Sheets API batch update requests\n const batchRequests = sortedRequests.map((operation) => buildDimensionRequest(operation, sheetId));\n\n logger.debug?.('sheets.dimensions.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n sheetId,\n totalOperations: batchRequests.length,\n operationTypes: sortedRequests.map((r) => r.operation),\n operationDetails: sortedRequests.map((r, i) => ({\n index: i,\n operation: r.operation,\n dimension: r.dimension,\n startIndex: r.startIndex,\n endIndex: r.endIndex,\n affectedCount: calculateAffectedCount(r),\n })),\n currentDimensions: { rows: currentRowCount, columns: currentColumnCount },\n });\n\n // Execute the atomic batch update\n const batchUpdateResponse = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: batchRequests,\n includeSpreadsheetInResponse: false, // We don't need the full spreadsheet data back\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Comprehensive validation of batch update results\n if (!updateResult) {\n logger.error?.('Dimensions batch update failed - no response data', {\n spreadsheetId: id,\n sheetTitle,\n requestCount: requests.length,\n });\n throw new ProtocolError(ProtocolErrorCode.InternalError, 'Batch update failed: no response data received from Google Sheets API');\n }\n\n const replies = updateResult.replies || [];\n const expectedCount = requests.length;\n const actualCount = replies.length;\n\n // Validate operation count matches expectations\n if (actualCount !== expectedCount) {\n logger.error?.('Dimensions batch update failed - operation count mismatch', {\n expectedOperations: expectedCount,\n actualReplies: actualCount,\n spreadsheetId: id,\n sheetTitle,\n receivedReplies: replies.map((reply, index) => ({\n index,\n replyType: Object.keys(reply || {})[0] || 'empty',\n })),\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation failed: expected ${expectedCount} operations, received ${actualCount} replies. This may indicate a partial failure or Google API issue.`);\n }\n\n // Validate each reply exists - Google Sheets API may return empty objects for successful operations\n for (let i = 0; i < replies.length; i++) {\n const reply = replies[i];\n const request = sortedRequests[i];\n\n if (!request) {\n logger.error?.('Dimensions batch update failed - missing request', {\n replyIndex: i,\n hasReply: !!reply,\n hasRequest: !!request,\n spreadsheetId: id,\n sheetTitle,\n });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Operation ${i} failed: missing request data`);\n }\n\n // Note: Google Sheets API often returns empty objects {} for successful dimension operations\n // This is normal behavior and indicates success, not failure\n // We validate that the reply exists (even if empty) rather than checking specific keys\n if (reply === null || reply === undefined) {\n logger.error?.('Dimensions batch update failed - null reply', {\n operationIndex: i,\n expectedOperation: request.operation,\n spreadsheetId: id,\n sheetTitle,\n });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Operation ${i} (${request.operation}) failed: null reply from Google Sheets API`);\n }\n }\n\n // Calculate final dimensions and operation results\n // Note: We calculate based on the operations we performed, but actual dimensions\n // may vary slightly due to Google Sheets internal behavior (e.g., minimum dimensions)\n let finalRowCount = currentRowCount;\n let finalColumnCount = currentColumnCount;\n\n const operationResults = sortedRequests.map((operation, _index) => {\n const affectedCount = calculateAffectedCount(operation);\n\n // Update dimension counts based on operation\n // Operations are applied in sorted order, so this should match actual result\n if (operation.dimension === 'ROWS') {\n if (operation.operation === 'insertDimension') {\n finalRowCount += affectedCount;\n } else if (operation.operation === 'appendDimension') {\n finalRowCount += affectedCount;\n } else if (operation.operation === 'deleteDimension') {\n finalRowCount = Math.max(1, finalRowCount - affectedCount); // Google Sheets minimum 1 row\n }\n } else if (operation.dimension === 'COLUMNS') {\n if (operation.operation === 'insertDimension') {\n finalColumnCount += affectedCount;\n } else if (operation.operation === 'appendDimension') {\n finalColumnCount += affectedCount;\n } else if (operation.operation === 'deleteDimension') {\n finalColumnCount = Math.max(1, finalColumnCount - affectedCount); // Google Sheets minimum 1 column\n }\n }\n\n return {\n operation: operation.operation,\n dimension: operation.dimension,\n startIndex: operation.startIndex,\n endIndex: operation.endIndex,\n affectedCount,\n };\n });\n\n // Validate final dimensions are within Google Sheets limits\n if (finalRowCount > MAX_ROW_COUNT) {\n logger.warn?.('Final row count exceeds Google Sheets maximum', {\n finalRowCount,\n maxRowCount: MAX_ROW_COUNT,\n spreadsheetId: id,\n sheetTitle,\n });\n }\n if (finalColumnCount > MAX_COLUMN_COUNT) {\n logger.warn?.('Final column count exceeds Google Sheets maximum', {\n finalColumnCount,\n maxColumnCount: MAX_COLUMN_COUNT,\n spreadsheetId: id,\n sheetTitle,\n });\n }\n\n logger.debug?.('sheets.dimensions.batchUpdate completed successfully', {\n totalOperations: requests.length,\n finalRowCount,\n finalColumnCount,\n operationResults: operationResults.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalOperations: requests.length,\n operationResults,\n updatedDimensions: {\n rows: finalRowCount,\n columns: finalColumnCount,\n },\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.dimensions.batchUpdate error', { error: message });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating dimensions: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'dimensions-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","buildDimensionRequest","calculateAffectedCount","DEFAULT_COLUMN_COUNT","DEFAULT_ROW_COUNT","MAX_COLUMN_COUNT","MAX_ROW_COUNT","sortOperations","DimensionRequestSchema","object","operation","enum","describe","dimension","startIndex","number","int","nonnegative","endIndex","optional","inheritFromBefore","boolean","inputSchema","id","gid","requests","array","min","successBranchSchema","type","literal","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalOperations","operationResults","affectedCount","updatedDimensions","rows","columns","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","debug","requestCount","length","operations","map","r","spreadsheetData","sheet","sheets","version","auth","authContext","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","warn","InvalidParams","undefined","error","InternalError","currentRowCount","gridProperties","rowCount","currentColumnCount","columnCount","sortedRequests","batchRequests","operationTypes","operationDetails","i","index","currentDimensions","batchUpdateResponse","batchUpdate","requestBody","includeSpreadsheetInResponse","updateResult","replies","expectedCount","actualCount","expectedOperations","actualReplies","receivedReplies","reply","replyType","Object","keys","request","replyIndex","hasReply","hasRequest","operationIndex","expectedOperation","finalRowCount","finalColumnCount","_index","Math","max","maxRowCount","maxColumnCount","content","text","JSON","stringify","structuredContent","message","Error","stack","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AAClH,SAASC,qBAAqB,EAAEC,sBAAsB,EAAEC,oBAAoB,EAAEC,iBAAiB,EAAyBC,gBAAgB,EAAEC,aAAa,EAAEC,cAAc,QAAQ,gCAAgC;AAE/M,mDAAmD;AACnD,MAAMC,yBAAyBZ,EAAEa,MAAM,CAAC;IACtCC,WAAWd,EAAEe,IAAI,CAAC;QAAC;QAAmB;QAAmB;KAAkB,EAAEC,QAAQ,CAAC;IACtFC,WAAWjB,EAAEe,IAAI,CAAC;QAAC;QAAQ;KAAU,EAAEC,QAAQ,CAAC;IAChDE,YAAYlB,EAAEmB,MAAM,GAAGC,GAAG,GAAGC,WAAW,GAAGL,QAAQ,CAAC;IACpDM,UAAUtB,EAAEmB,MAAM,GAAGC,GAAG,GAAGC,WAAW,GAAGE,QAAQ,GAAGP,QAAQ,CAAC;IAC7DQ,mBAAmBxB,EAAEyB,OAAO,GAAGF,QAAQ,GAAGP,QAAQ,CAAC;AACrD;AAEA,MAAMU,cAAc1B,EAAEa,MAAM,CAA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AAAA,mBAAAA,QAAc,oDAAoD;gBAChEgE;gBACAK,gBAAgBjH;gBAChB4D,eAAe1C;gBACfW;YACF;QACF;SAEAe,iBAAAA,OAAOC,KAAK,cAAZD,qCAAAA,oBAAAA,QAAe,wDAAwD;YACrEb,iBAAiBX,SAAS2B,MAAM;YAChC4D;YACAC;YACA5E,kBAAkBA,iBAAiBe,MAAM;QAC3C;QAEA,MAAMN,SAAiB;YACrBjB,MAAM;YACNN;YACAC,KAAKgD,OAAOC;YACZ1C,kBAAkBA,oBAAoB;YACtCE,gBAAgBA,kBAAkB;YAClCC;YACAC;YACAC,iBAAiBX,SAAS2B,MAAM;YAChCf;YACAE,mBAAmB;gBACjBC,MAAMwE;gBACNvE,SAASwE;YACX;QACF;QAEA,OAAO;YACLM,SAAS;gBAAC;oBAAE1F,MAAM;oBAAiB2F,MAAMC,KAAKC,SAAS,CAAC5E;gBAAQ;aAAE;YAClE6E,mBAAmB;gBAAE7E;YAAO;QAC9B;IACF,EAAE,OAAO+B,OAAO;YAEd5B;QADA,MAAM2E,UAAU/C,iBAAiBgD,QAAQhD,MAAM+C,OAAO,GAAGpD,OAAOK;SAChE5B,iBAAAA,OAAO4B,KAAK,cAAZ5B,qCAAAA,oBAAAA,QAAe,uCAAuC;YAAE4B,OAAO+C;QAAQ;QACvE,MAAM,IAAInI,cAAcC,kBAAkBoF,aAAa,EAAE,CAAC,iCAAiC,EAAE8C,SAAS,EAAE;YACtGE,OAAOjD,iBAAiBgD,QAAQhD,MAAMiD,KAAK,GAAGlD;QAChD;IACF;AACF;AAEA,eAAe,SAASmD;IACtB,OAAO;QACLC,MAAM;QACNpF;QACAG;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/dimensions-batch-update.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { buildDimensionRequest, calculateAffectedCount, DEFAULT_COLUMN_COUNT, DEFAULT_ROW_COUNT, type DimensionRequest, MAX_COLUMN_COUNT, MAX_ROW_COUNT, sortOperations } from './lib/dimension-operations.ts';\n\n// Input schema for dimension batch update requests\nconst DimensionRequestSchema = z.object({\n operation: z.enum(['insertDimension', 'deleteDimension', 'appendDimension']).describe('Type of dimension operation to perform'),\n dimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether to operate on rows or columns'),\n startIndex: z.number().int().nonnegative().describe('Starting index for the operation (0-based)'),\n endIndex: z.number().int().nonnegative().optional().describe('Ending index for the operation (0-based, exclusive). Optional - if omitted, the range is unbounded (extends to the end of the sheet)'),\n inheritFromBefore: z.boolean().optional().describe('For insertDimension: whether new rows/columns inherit properties from the row/column before the insertion point'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(DimensionRequestSchema).min(1).describe('Array of dimension update requests'),\n});\n\n// Success branch schema\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 totalOperations: z.number().int().nonnegative().describe('Total number of dimension operations performed'),\n operationResults: z\n .array(\n z.object({\n operation: z.enum(['insertDimension', 'deleteDimension', 'appendDimension']).describe('Type of operation that was performed'),\n dimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension that was operated on'),\n startIndex: z.number().int().nonnegative().describe('Starting index of the operation'),\n endIndex: z.number().int().nonnegative().optional().describe('Ending index of the operation (for insert/delete)'),\n affectedCount: z.number().int().nonnegative().describe('Number of rows/columns affected by this operation'),\n })\n )\n .describe('Detailed results for each dimension operation'),\n updatedDimensions: z\n .object({\n rows: z.number().int().nonnegative().describe('Total number of rows in the sheet after all operations'),\n columns: z.number().int().nonnegative().describe('Total number of columns in the sheet after all operations'),\n })\n .describe('Final dimensions of the sheet after all operations'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Batch update sheet dimensions by inserting, deleting, or appending rows/columns. Operations are atomic (all succeed or all fail) and execute in optimal order automatically.',\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.debug?.('sheets.dimensions.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n operations: requests.map((r) => ({ operation: r.operation, dimension: r.dimension, startIndex: r.startIndex, endIndex: r.endIndex })),\n });\n\n try {\n const sheets = google.sheets({ 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,sheets.properties.gridProperties',\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.warn?.('Sheet not found for dimensions 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 sheetId = sheet.properties.sheetId;\n\n if (sheetId === undefined || sheetId === null) {\n logger.error?.('Sheet ID not available for dimensions batch update', { id, gid, sheetTitle });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Sheet ID not available for ${gid}. Cannot perform dimension operations without valid sheet ID.`);\n }\n\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Get current sheet dimensions for response calculation\n // Note: Google Sheets API may not always provide gridProperties for older sheets\n // Fall back to Google's documented defaults for new sheets\n const currentRowCount = sheet.properties.gridProperties?.rowCount ?? DEFAULT_ROW_COUNT;\n const currentColumnCount = sheet.properties.gridProperties?.columnCount ?? DEFAULT_COLUMN_COUNT;\n\n // Sort operations for optimal execution order to prevent index conflicts\n // Delete operations are processed first (high to low index) to avoid shifting issues\n // Insert/append operations are processed after (low to high index)\n const sortedRequests = sortOperations(requests as DimensionRequest[]);\n\n // Build Google Sheets API batch update requests\n const batchRequests = sortedRequests.map((operation) => buildDimensionRequest(operation, sheetId));\n\n logger.debug?.('sheets.dimensions.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n sheetId,\n totalOperations: batchRequests.length,\n operationTypes: sortedRequests.map((r) => r.operation),\n operationDetails: sortedRequests.map((r, i) => ({\n index: i,\n operation: r.operation,\n dimension: r.dimension,\n startIndex: r.startIndex,\n endIndex: r.endIndex,\n affectedCount: calculateAffectedCount(r),\n })),\n currentDimensions: { rows: currentRowCount, columns: currentColumnCount },\n });\n\n // Execute the atomic batch update\n const batchUpdateResponse = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: batchRequests,\n includeSpreadsheetInResponse: false, // We don't need the full spreadsheet data back\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Comprehensive validation of batch update results\n if (!updateResult) {\n logger.error?.('Dimensions batch update failed - no response data', {\n spreadsheetId: id,\n sheetTitle,\n requestCount: requests.length,\n });\n throw new ProtocolError(ProtocolErrorCode.InternalError, 'Batch update failed: no response data received from Google Sheets API');\n }\n\n const replies = updateResult.replies || [];\n const expectedCount = requests.length;\n const actualCount = replies.length;\n\n // Validate operation count matches expectations\n if (actualCount !== expectedCount) {\n logger.error?.('Dimensions batch update failed - operation count mismatch', {\n expectedOperations: expectedCount,\n actualReplies: actualCount,\n spreadsheetId: id,\n sheetTitle,\n receivedReplies: replies.map((reply, index) => ({\n index,\n replyType: Object.keys(reply || {})[0] || 'empty',\n })),\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation failed: expected ${expectedCount} operations, received ${actualCount} replies. This may indicate a partial failure or Google API issue.`);\n }\n\n // Validate each reply exists - Google Sheets API may return empty objects for successful operations\n for (let i = 0; i < replies.length; i++) {\n const reply = replies[i];\n const request = sortedRequests[i];\n\n if (!request) {\n logger.error?.('Dimensions batch update failed - missing request', {\n replyIndex: i,\n hasReply: !!reply,\n hasRequest: !!request,\n spreadsheetId: id,\n sheetTitle,\n });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Operation ${i} failed: missing request data`);\n }\n\n // Note: Google Sheets API often returns empty objects {} for successful dimension operations\n // This is normal behavior and indicates success, not failure\n // We validate that the reply exists (even if empty) rather than checking specific keys\n if (reply === null || reply === undefined) {\n logger.error?.('Dimensions batch update failed - null reply', {\n operationIndex: i,\n expectedOperation: request.operation,\n spreadsheetId: id,\n sheetTitle,\n });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Operation ${i} (${request.operation}) failed: null reply from Google Sheets API`);\n }\n }\n\n // Calculate final dimensions and operation results\n // Note: We calculate based on the operations we performed, but actual dimensions\n // may vary slightly due to Google Sheets internal behavior (e.g., minimum dimensions)\n let finalRowCount = currentRowCount;\n let finalColumnCount = currentColumnCount;\n\n const operationResults = sortedRequests.map((operation, _index) => {\n const affectedCount = calculateAffectedCount(operation);\n\n // Update dimension counts based on operation\n // Operations are applied in sorted order, so this should match actual result\n if (operation.dimension === 'ROWS') {\n if (operation.operation === 'insertDimension') {\n finalRowCount += affectedCount;\n } else if (operation.operation === 'appendDimension') {\n finalRowCount += affectedCount;\n } else if (operation.operation === 'deleteDimension') {\n finalRowCount = Math.max(1, finalRowCount - affectedCount); // Google Sheets minimum 1 row\n }\n } else if (operation.dimension === 'COLUMNS') {\n if (operation.operation === 'insertDimension') {\n finalColumnCount += affectedCount;\n } else if (operation.operation === 'appendDimension') {\n finalColumnCount += affectedCount;\n } else if (operation.operation === 'deleteDimension') {\n finalColumnCount = Math.max(1, finalColumnCount - affectedCount); // Google Sheets minimum 1 column\n }\n }\n\n return {\n operation: operation.operation,\n dimension: operation.dimension,\n startIndex: operation.startIndex,\n endIndex: operation.endIndex,\n affectedCount,\n };\n });\n\n // Validate final dimensions are within Google Sheets limits\n if (finalRowCount > MAX_ROW_COUNT) {\n logger.warn?.('Final row count exceeds Google Sheets maximum', {\n finalRowCount,\n maxRowCount: MAX_ROW_COUNT,\n spreadsheetId: id,\n sheetTitle,\n });\n }\n if (finalColumnCount > MAX_COLUMN_COUNT) {\n logger.warn?.('Final column count exceeds Google Sheets maximum', {\n finalColumnCount,\n maxColumnCount: MAX_COLUMN_COUNT,\n spreadsheetId: id,\n sheetTitle,\n });\n }\n\n logger.debug?.('sheets.dimensions.batchUpdate completed successfully', {\n totalOperations: requests.length,\n finalRowCount,\n finalColumnCount,\n operationResults: operationResults.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalOperations: requests.length,\n operationResults,\n updatedDimensions: {\n rows: finalRowCount,\n columns: finalColumnCount,\n },\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.dimensions.batchUpdate error', { error: message });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating dimensions: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'dimensions-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","googleAuth","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","buildDimensionRequest","calculateAffectedCount","DEFAULT_COLUMN_COUNT","DEFAULT_ROW_COUNT","MAX_COLUMN_COUNT","MAX_ROW_COUNT","sortOperations","DimensionRequestSchema","object","operation","enum","describe","dimension","startIndex","number","int","nonnegative","endIndex","optional","inheritFromBefore","boolean","inputSchema","id","gid","requests","array","min","successBranchSchema","type","literal","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalOperations","operationResults","affectedCount","updatedDimensions","rows","columns","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","debug","requestCount","length","operations","map","r","spreadsheetData","sheet","sheets","version","auth","authContext","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","warn","InvalidParams","undefined","error","InternalError","currentRowCount","gridProperties","rowCount","currentColumnCount","columnCount","sortedRequests","batchRequests","operationTypes","operationDetails","i","index","currentDimensions","batchUpdateResponse","batchUpdate","requestBody","includeSpreadsheetInResponse","updateResult","replies","expectedCount","actualCount","expectedOperations","actualReplies","receivedReplies","reply","replyType","Object","keys","request","replyIndex","hasReply","hasRequest","operationIndex","expectedOperation","finalRowCount","finalColumnCount","_index","Math","max","maxRowCount","maxColumnCount","content","text","JSON","stringify","structuredContent","message","Error","stack","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AAC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YACX;QACF;QAEA,OAAO;YACLM,SAAS;gBAAC;oBAAE1F,MAAM;oBAAiB2F,MAAMC,KAAKC,SAAS,CAAC5E;gBAAQ;aAAE;YAClE6E,mBAAmB;gBAAE7E;YAAO;QAC9B;IACF,EAAE,OAAO+B,OAAO;YAEd5B;QADA,MAAM2E,UAAU/C,iBAAiBgD,QAAQhD,MAAM+C,OAAO,GAAGpD,OAAOK;SAChE5B,iBAAAA,OAAO4B,KAAK,cAAZ5B,qCAAAA,oBAAAA,QAAe,uCAAuC;YAAE4B,OAAO+C;QAAQ;QACvE,MAAM,IAAIpI,cAAcC,kBAAkBqF,aAAa,EAAE,CAAC,iCAAiC,EAAE8C,SAAS,EAAE;YACtGE,OAAOjD,iBAAiBgD,QAAQhD,MAAMiD,KAAK,GAAGlD;QAChD;IACF;AACF;AAEA,eAAe,SAASmD;IACtB,OAAO;QACLC,MAAM;QACNpF;QACAG;IACF;AACF"}
|
|
@@ -3,6 +3,7 @@ const { AuthRequiredBranchSchema } = schemas;
|
|
|
3
3
|
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
4
4
|
import { google } from 'googleapis';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
6
7
|
import { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.js';
|
|
7
8
|
const inputSchema = z.object({
|
|
8
9
|
id: SpreadsheetIdSchema,
|
|
@@ -68,7 +69,7 @@ async function handler({ id, gid, dimension, startIndex, endIndex, destinationIn
|
|
|
68
69
|
var _spreadsheetData_properties, _spreadsheetData_sheets;
|
|
69
70
|
const sheets = google.sheets({
|
|
70
71
|
version: 'v4',
|
|
71
|
-
auth: extra.authContext.auth
|
|
72
|
+
auth: googleAuth(extra.authContext.auth)
|
|
72
73
|
});
|
|
73
74
|
// Get spreadsheet and sheet info in single API call
|
|
74
75
|
const spreadsheetResponse = await sheets.spreadsheets.get({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/dimensions-move.ts"],"sourcesContent":["import 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 { google } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n dimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether to move rows or columns'),\n startIndex: z.number().int().nonnegative().describe('Starting index of the range to move (0-based)'),\n endIndex: z.number().int().positive().describe('Ending index of the range to move (0-based, exclusive)'),\n destinationIndex: z.number().int().nonnegative().describe('Index where the rows/columns will be moved to (0-based)'),\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 dimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension that was moved'),\n sourceRange: z.object({\n startIndex: z.number().describe('Starting index of the moved range'),\n endIndex: z.number().describe('Ending index of the moved range'),\n }),\n destinationIndex: z.number().describe('Index where the range was moved to'),\n movedCount: z.number().describe('Number of rows/columns moved'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Move rows or columns within a sheet to a new position. Use 0-based indices. The destinationIndex is where the rows/columns will be moved TO.',\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, dimension, startIndex, endIndex, destinationIndex }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.dimensions.move called', { id, gid, dimension, startIndex, endIndex, destinationIndex });\n\n // Validate indices\n if (startIndex >= endIndex) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `startIndex (${startIndex}) must be less than endIndex (${endIndex})`);\n }\n\n // Check if destination is within source range (invalid move)\n if (destinationIndex > startIndex && destinationIndex < endIndex) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `destinationIndex (${destinationIndex}) cannot be within the source range (${startIndex}-${endIndex})`);\n }\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: '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 move', { id, gid, dimension });\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 logger.info('sheets.dimensions.move executing', { spreadsheetId: id, sheetTitle, dimension, startIndex, endIndex, destinationIndex });\n\n // Execute the move dimension request\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: [\n {\n moveDimension: {\n source: {\n sheetId: sheetGid,\n dimension,\n startIndex,\n endIndex,\n },\n destinationIndex,\n },\n },\n ],\n },\n });\n\n const movedCount = endIndex - startIndex;\n\n logger.info('sheets.dimensions.move completed successfully', {\n spreadsheetId: id,\n sheetTitle,\n dimension,\n movedCount,\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 dimension,\n sourceRange: {\n startIndex,\n endIndex,\n },\n destinationIndex,\n movedCount,\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('Move operation failed', { id, gid, dimension, startIndex, endIndex, destinationIndex, error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving ${dimension.toLowerCase()}: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'dimensions-move',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","inputSchema","object","id","gid","dimension","enum","describe","startIndex","number","int","nonnegative","endIndex","positive","destinationIndex","successBranchSchema","type","literal","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","sourceRange","movedCount","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","InvalidParams","spreadsheetData","sheet","sheets","version","auth","authContext","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","sheetGid","batchUpdate","requestBody","requests","moveDimension","source","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","toLowerCase","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,M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aAAa;gBACXf;gBACAI;YACF;YACAE;YACAU;QACF;QAEA,OAAO;YACLmC,SAAS;gBAAC;oBAAE3C,MAAM;oBAAiB4C,MAAMC,KAAKC,SAAS,CAACjC;gBAAQ;aAAE;YAClEkC,mBAAmB;gBAAElC;YAAO;QAC9B;IACF,EAAE,OAAOmC,OAAO;QACd,IAAIA,iBAAiBvE,eAAe;YAClC,MAAMuE;QACR;QACA,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGd,OAAOa;QAChEhC,OAAOgC,KAAK,CAAC,yBAAyB;YAAE7D;YAAIC;YAAKC;YAAWG;YAAYI;YAAUE;YAAkBkD,OAAOC;QAAQ;QAEnH,MAAM,IAAIxE,cAAcC,kBAAkByE,aAAa,EAAE,CAAC,aAAa,EAAE9D,UAAU+D,WAAW,GAAG,EAAE,EAAEH,SAAS,EAAE;YAC9GI,OAAOL,iBAAiBE,QAAQF,MAAMK,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACN7C;QACAG;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/dimensions-move.ts"],"sourcesContent":["import 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 { google } from 'googleapis';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n dimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether to move rows or columns'),\n startIndex: z.number().int().nonnegative().describe('Starting index of the range to move (0-based)'),\n endIndex: z.number().int().positive().describe('Ending index of the range to move (0-based, exclusive)'),\n destinationIndex: z.number().int().nonnegative().describe('Index where the rows/columns will be moved to (0-based)'),\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 dimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension that was moved'),\n sourceRange: z.object({\n startIndex: z.number().describe('Starting index of the moved range'),\n endIndex: z.number().describe('Ending index of the moved range'),\n }),\n destinationIndex: z.number().describe('Index where the range was moved to'),\n movedCount: z.number().describe('Number of rows/columns moved'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Move rows or columns within a sheet to a new position. Use 0-based indices. The destinationIndex is where the rows/columns will be moved TO.',\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, dimension, startIndex, endIndex, destinationIndex }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.dimensions.move called', { id, gid, dimension, startIndex, endIndex, destinationIndex });\n\n // Validate indices\n if (startIndex >= endIndex) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `startIndex (${startIndex}) must be less than endIndex (${endIndex})`);\n }\n\n // Check if destination is within source range (invalid move)\n if (destinationIndex > startIndex && destinationIndex < endIndex) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `destinationIndex (${destinationIndex}) cannot be within the source range (${startIndex}-${endIndex})`);\n }\n\n try {\n const sheets = google.sheets({ 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 move', { id, gid, dimension });\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 logger.info('sheets.dimensions.move executing', { spreadsheetId: id, sheetTitle, dimension, startIndex, endIndex, destinationIndex });\n\n // Execute the move dimension request\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: [\n {\n moveDimension: {\n source: {\n sheetId: sheetGid,\n dimension,\n startIndex,\n endIndex,\n },\n destinationIndex,\n },\n },\n ],\n },\n });\n\n const movedCount = endIndex - startIndex;\n\n logger.info('sheets.dimensions.move completed successfully', {\n spreadsheetId: id,\n sheetTitle,\n dimension,\n movedCount,\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 dimension,\n sourceRange: {\n startIndex,\n endIndex,\n },\n destinationIndex,\n movedCount,\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('Move operation failed', { id, gid, dimension, startIndex, endIndex, destinationIndex, error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving ${dimension.toLowerCase()}: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'dimensions-move',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","googleAuth","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","inputSchema","object","id","gid","dimension","enum","describe","startIndex","number","int","nonnegative","endIndex","positive","destinationIndex","successBranchSchema","type","literal","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","sourceRange","movedCount","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","InvalidParams","spreadsheetData","sheet","sheets","version","auth","authContext","spreadsheetResponse","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","sheetGid","batchUpdate","requestBody","requests","moveDimension","source","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","toLowerCase","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AAElH,MAAMC,cAAcN,EAAEO,MAAM,CAAC;IAC3BC,IAAIH;IACJI,KAAKN;IACLO,WAAWV,EAAEW,IAAI,CAAC;QAAC;QAAQ;KAAU,EAAEC,QAAQ,CAAC;IAChDC,YAAYb,EAAEc,MAAM,GAAGC,GAAG,GAAGC,WAAW,GAAGJ,QAAQ,CAAC;IACpDK,UAAUjB,EAAEc,MAAM,GAAGC,GAAG,GAAGG,Q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,EAAE9D,UAAU+D,WAAW,GAAG,EAAE,EAAEH,SAAS,EAAE;YAC9GI,OAAOL,iBAAiBE,QAAQF,MAAMK,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACN7C;QACAG;IACF;AACF"}
|
|
@@ -3,6 +3,7 @@ const { AuthRequiredBranchSchema } = schemas;
|
|
|
3
3
|
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
4
4
|
import { google } from 'googleapis';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
6
7
|
import { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.js';
|
|
7
8
|
import { appendRows, mapRowsToHeader } from '../../spreadsheet/data-operations.js';
|
|
8
9
|
import { ensureTabAndHeaders } from '../../spreadsheet/sheet-operations.js';
|
|
@@ -52,7 +53,7 @@ async function handler({ id, gid, rows, headers, deduplicateBy }, extra) {
|
|
|
52
53
|
var _spreadsheetResponse_data_sheets, _sheet_properties;
|
|
53
54
|
const sheets = google.sheets({
|
|
54
55
|
version: 'v4',
|
|
55
|
-
auth: extra.authContext.auth
|
|
56
|
+
auth: googleAuth(extra.authContext.auth)
|
|
56
57
|
});
|
|
57
58
|
// Get sheet details using the gid
|
|
58
59
|
const spreadsheetResponse = await sheets.spreadsheets.get({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/rows-append.ts"],"sourcesContent":["import 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 { google } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { appendRows, mapRowsToHeader } from '../../spreadsheet/data-operations.ts';\nimport { ensureTabAndHeaders } from '../../spreadsheet/sheet-operations.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n rows: z\n .array(z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).min(1))\n .min(1)\n .describe('Array of rows, where each row is an array of cell values. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n headers: z.array(z.string()).optional().describe('Column order/names - used for blank sheets or column mapping'),\n deduplicateBy: z.array(z.string()).optional().describe('Column names to use as composite key for deduplication'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Sheet tab name'),\n updatedRows: z.number().describe('Number of rows appended'),\n rowsSkipped: z.number().optional().describe('Number of duplicate rows skipped'),\n sheetUrl: z.string().optional().describe('URL to view the sheet'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Add new rows to the bottom of an existing sheet with smart header handling and optional deduplication. BEST FOR: Structured database operations where spreadsheet has headers defining schema and rows represent records.',\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, rows, headers, deduplicateBy }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.rows.append called', { id, gid, rowCount: rows.length, headers, deduplicateBy });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get sheet details using the gid\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet?.properties?.title ?? '';\n\n // Smart header handling and data processing\n let processedRows = rows;\n let currentHeaders: string[] = [];\n let rowsSkipped = 0;\n let existingKeySet: Set<string> = new Set();\n\n if (headers && headers.length > 0) {\n // Use ensureTabAndHeaders to handle header logic\n const headerResult = await ensureTabAndHeaders(sheets, {\n spreadsheetId: id,\n sheetTitle,\n requiredHeader: headers,\n keyColumns: deduplicateBy || [],\n logger,\n });\n\n currentHeaders = headerResult.header;\n existingKeySet = headerResult.keySet;\n\n // Map data rows to match current header order\n processedRows = mapRowsToHeader({ rows, header: currentHeaders, canonical: headers }) as (string | number | boolean | null)[][];\n }\n\n // Append rows with optional deduplication\n // If headers are empty but deduplication is requested, skip deduplication for empty spreadsheets\n const effectiveKeyColumns = currentHeaders.length === 0 && deduplicateBy && deduplicateBy.length > 0 ? [] : deduplicateBy || [];\n\n const appendResult = await appendRows(sheets, {\n spreadsheetId: id,\n sheetTitle,\n rows: processedRows,\n keySet: existingKeySet,\n keyColumns: effectiveKeyColumns,\n header: currentHeaders,\n logger,\n });\n\n rowsSkipped = appendResult.rowsSkipped || 0;\n // Only count data rows, not headers - headers are metadata, not items\n const updatedRows = appendResult.updatedRows || 0;\n\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${gid}`;\n\n logger.info('sheets.rows.append completed', { id, gid, updatedRows, rowsSkipped });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid,\n sheetTitle,\n updatedRows,\n rowsSkipped, // Always include rowsSkipped, even when 0\n sheetUrl,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.rows.append error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error appending rows: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'rows-append',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","appendRows","mapRowsToHeader","ensureTabAndHeaders","inputSchema","object","id","gid","rows","array","union","string","number","boolean","null","min","describe","headers","optional","deduplicateBy","successBranchSchema","type","literal","sheetTitle","updatedRows","rowsSkipped","sheetUrl","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","rowCount","length","spreadsheetResponse","sheet","sheets","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","title","processedRows","currentHeaders","existingKeySet","Set","headerResult","requiredHeader","keyColumns","header","keySet","canonical","effectiveKeyColumns","appendResult","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AAClH,SAASC,UAAU,EAAEC,eAAe,QAAQ,uCAAuC;AACnF,SAASC,mBAAmB,QAAQ,wCAAwC;AAE5E,MAAMC,cAAcR,EAAES,MAAM,CAAC;IAC3BC,IAAIN;IACJO,KAAKT;IACLU,MAAMZ,EACHa,KAAK,CAACb,EAAEa,KAAK,CAACb,EAAEc,KAAK,CAAC;QAACd,EAAEe,MAAM;QAAIf,EAAEgB,MAAM;QAAIhB,EAAEiB,OAAO;QAAIjB,EAAEkB,IAAI;KAAG,GAAGC,GAAG,CAAC,IAC5EA,GAAG,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,EAAEpB,GAAG,UAAU,EAAEC,KAAK;QAE/E2B,OAAOC,IAAI,CAAC,gCAAgC;YAAE7B;YAAIC;YAAKiB;YAAaC;QAAY;QAEhF,MAAMM,SAAiB;YACrBV,MAAM;YACNf;YACAC;YACAgB;YACAC;YACAC;YACAC;QACF;QAEA,OAAO;YACL0C,SAAS;gBAAC;oBAAE/C,MAAM;oBAAiBgD,MAAMC,KAAKC,SAAS,CAACxC;gBAAQ;aAAE;YAClEyC,mBAAmB;gBAAEzC;YAAO;QAC9B;IACF,EAAE,OAAO0C,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGvB,OAAOsB;QAChEvC,OAAOuC,KAAK,CAAC,4BAA4B;YAAEA,OAAOC;QAAQ;QAE1D,MAAM,IAAIjF,cAAcC,kBAAkBkF,aAAa,EAAE,CAAC,sBAAsB,EAAEF,SAAS,EAAE;YAC3FG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNnD;QACAG;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/rows-append.ts"],"sourcesContent":["import 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 { google } from 'googleapis';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { appendRows, mapRowsToHeader } from '../../spreadsheet/data-operations.ts';\nimport { ensureTabAndHeaders } from '../../spreadsheet/sheet-operations.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n rows: z\n .array(z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).min(1))\n .min(1)\n .describe('Array of rows, where each row is an array of cell values. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n headers: z.array(z.string()).optional().describe('Column order/names - used for blank sheets or column mapping'),\n deduplicateBy: z.array(z.string()).optional().describe('Column names to use as composite key for deduplication'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Sheet tab name'),\n updatedRows: z.number().describe('Number of rows appended'),\n rowsSkipped: z.number().optional().describe('Number of duplicate rows skipped'),\n sheetUrl: z.string().optional().describe('URL to view the sheet'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Add new rows to the bottom of an existing sheet with smart header handling and optional deduplication. BEST FOR: Structured database operations where spreadsheet has headers defining schema and rows represent records.',\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, rows, headers, deduplicateBy }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.rows.append called', { id, gid, rowCount: rows.length, headers, deduplicateBy });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details using the gid\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet?.properties?.title ?? '';\n\n // Smart header handling and data processing\n let processedRows = rows;\n let currentHeaders: string[] = [];\n let rowsSkipped = 0;\n let existingKeySet: Set<string> = new Set();\n\n if (headers && headers.length > 0) {\n // Use ensureTabAndHeaders to handle header logic\n const headerResult = await ensureTabAndHeaders(sheets, {\n spreadsheetId: id,\n sheetTitle,\n requiredHeader: headers,\n keyColumns: deduplicateBy || [],\n logger,\n });\n\n currentHeaders = headerResult.header;\n existingKeySet = headerResult.keySet;\n\n // Map data rows to match current header order\n processedRows = mapRowsToHeader({ rows, header: currentHeaders, canonical: headers }) as (string | number | boolean | null)[][];\n }\n\n // Append rows with optional deduplication\n // If headers are empty but deduplication is requested, skip deduplication for empty spreadsheets\n const effectiveKeyColumns = currentHeaders.length === 0 && deduplicateBy && deduplicateBy.length > 0 ? [] : deduplicateBy || [];\n\n const appendResult = await appendRows(sheets, {\n spreadsheetId: id,\n sheetTitle,\n rows: processedRows,\n keySet: existingKeySet,\n keyColumns: effectiveKeyColumns,\n header: currentHeaders,\n logger,\n });\n\n rowsSkipped = appendResult.rowsSkipped || 0;\n // Only count data rows, not headers - headers are metadata, not items\n const updatedRows = appendResult.updatedRows || 0;\n\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${gid}`;\n\n logger.info('sheets.rows.append completed', { id, gid, updatedRows, rowsSkipped });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid,\n sheetTitle,\n updatedRows,\n rowsSkipped, // Always include rowsSkipped, even when 0\n sheetUrl,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.rows.append error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error appending rows: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'rows-append',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","googleAuth","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","appendRows","mapRowsToHeader","ensureTabAndHeaders","inputSchema","object","id","gid","rows","array","union","string","number","boolean","null","min","describe","headers","optional","deduplicateBy","successBranchSchema","type","literal","sheetTitle","updatedRows","rowsSkipped","sheetUrl","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","rowCount","length","spreadsheetResponse","sheet","sheets","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","title","processedRows","currentHeaders","existingKeySet","Set","headerResult","requiredHeader","keyColumns","header","keySet","canonical","effectiveKeyColumns","appendResult","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AAClH,SAASC,UAAU,EAAEC,eAAe,QAAQ,uCAAuC;AACnF,SAASC,mBAAmB,QAAQ,wCAAwC;AAE5E,MAAMC,cAAcT,EAAEU,MAAM,CAAC;IAC3BC,IAAIN;IACJO,KAAKT;IACLU,MAAMb,EACHc,KAAK,CAACd,EAAEc,KAAK,CAACd,EAAEe,KAAK,CAAC;QAACf,EAAEgB,MAAM;QAAIhB,EAAEiB,MAAM;QAAIjB,EAAEkB,OAAO;QAAIlB,EAAEmB,IAAI;KAAG,GAAGC,GAAG,CAAC,IAC5EA,GAAG,CAAC,GACJC,QAAQ,CAAC;IACZC,SAAStB,EAAEc,KAAK,CAACd,EAAEgB,MAAM,IAAIO,QAAQ,GAAGF,QAAQ,CAAC;IACjDG,eAAexB,E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;QAEhF,MAAMM,SAAiB;YACrBV,MAAM;YACNf;YACAC;YACAgB;YACAC;YACAC;YACAC;QACF;QAEA,OAAO;YACL0C,SAAS;gBAAC;oBAAE/C,MAAM;oBAAiBgD,MAAMC,KAAKC,SAAS,CAACxC;gBAAQ;aAAE;YAClEyC,mBAAmB;gBAAEzC;YAAO;QAC9B;IACF,EAAE,OAAO0C,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGvB,OAAOsB;QAChEvC,OAAOuC,KAAK,CAAC,4BAA4B;YAAEA,OAAOC;QAAQ;QAE1D,MAAM,IAAIlF,cAAcC,kBAAkBmF,aAAa,EAAE,CAAC,sBAAsB,EAAEF,SAAS,EAAE;YAC3FG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNnD;QACAG;IACF;AACF"}
|
|
@@ -4,6 +4,7 @@ import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
|
4
4
|
import { parse } from 'csv-parse';
|
|
5
5
|
import { google } from 'googleapis';
|
|
6
6
|
import { z } from 'zod';
|
|
7
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
7
8
|
import { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.js';
|
|
8
9
|
import { getCsvReadStream } from '../../spreadsheet/csv-streaming.js';
|
|
9
10
|
import { buildDeduplicationKey } from '../../spreadsheet/deduplication-utils.js';
|
|
@@ -111,7 +112,7 @@ async function handler({ id, gid, sourceUri, sourceHasHeaders, headerMap, dedupl
|
|
|
111
112
|
}
|
|
112
113
|
const sheets = google.sheets({
|
|
113
114
|
version: 'v4',
|
|
114
|
-
auth: extra.authContext.auth
|
|
115
|
+
auth: googleAuth(extra.authContext.auth)
|
|
115
116
|
});
|
|
116
117
|
// Get sheet details using the gid
|
|
117
118
|
const spreadsheetResponse = await sheets.spreadsheets.get({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/rows-csv-append.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with database-style row append and deduplication */\n\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 { google } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\nimport { buildDeduplicationKey } from '../../spreadsheet/deduplication-utils.ts';\nimport { ensureTabAndHeaders } from '../../spreadsheet/sheet-operations.ts';\n\n// Header mapping schema: source/target can be string (name) or number (0-based index)\nconst HeaderMapItemSchema = z.object({\n source: z.union([z.string(), z.number().int().min(0)]).describe('CSV column: header name (string) or 0-based index (number)'),\n target: z.union([z.string(), z.number().int().min(0)]).describe('Sheet column: header name (string) or 0-based index (number)'),\n});\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 sourceHasHeaders: z.boolean().default(true).describe('Source has header row for column name mapping. Set to false for data-only sources (numeric indices required).'),\n headerMap: z.array(HeaderMapItemSchema).describe('Column mappings from CSV to sheet'),\n deduplicateBy: z\n .array(z.union([z.string(), z.number().int().min(0)]))\n .optional()\n .describe('Sheet columns for deduplication (names or indices)'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Sheet tab name'),\n updatedRows: z.number().describe('Number of rows appended'),\n rowsSkipped: z.number().optional().describe('Number of duplicate rows skipped'),\n sheetUrl: z.string().optional().describe('URL to view the sheet'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Import CSV to Google Sheets with column mapping and optional deduplication. Streams data for large files.',\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\n/** Batch size for Sheets API calls (1000 rows × 12 cols = 12K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\n/**\n * Resolve column reference to numeric index\n * @param ref Column reference (string name or number index)\n * @param headers Header row (null when sourceHasHeaders=false)\n * @param sourceHasHeaders Whether headers are present\n * @returns 0-based column index\n */\nfunction resolveColumnReference(ref: string | number, headers: string[] | null, sourceHasHeaders: boolean, context: string): number {\n // If number, use directly as 0-based index\n if (typeof ref === 'number') {\n if (ref < 0) {\n throw new Error(`${context}: Column index must be >= 0, got ${ref}`);\n }\n return ref;\n }\n\n // If string, must be header name\n if (!sourceHasHeaders || !headers) {\n throw new Error(`${context}: String column reference \"${ref}\" requires sourceHasHeaders=true. Use numeric index when sourceHasHeaders=false.`);\n }\n\n const index = headers.indexOf(ref);\n if (index === -1) {\n throw new Error(`${context}: Header \"${ref}\" not found in [${headers.join(', ')}]`);\n }\n\n return index;\n}\n\nasync function handler({ id, gid, sourceUri, sourceHasHeaders, headerMap, deduplicateBy }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.rows.csv-append called', { id, gid, sourceUri, sourceHasHeaders, headerMap, deduplicateBy });\n\n try {\n if (headerMap.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'headerMap cannot be empty');\n }\n\n // Validate: if sourceHasHeaders=false, all references must be numeric\n if (!sourceHasHeaders) {\n for (const { source, target } of headerMap) {\n if (typeof source === 'string') {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `sourceHasHeaders=false requires numeric indices. Got string source: \"${source}\"`);\n }\n if (typeof target === 'string') {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `sourceHasHeaders=false requires numeric indices. Got string target: \"${target}\"`);\n }\n }\n if (deduplicateBy) {\n for (const colRef of deduplicateBy) {\n if (typeof colRef === 'string') {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `sourceHasHeaders=false requires numeric indices in deduplicateBy. Got string: \"${colRef}\"`);\n }\n }\n }\n }\n\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get sheet details using the gid\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet?.properties?.title ?? '';\n\n // Determine target headers (for sourceHasHeaders=true) or column count (for sourceHasHeaders=false)\n let sheetHeaders: string[] | null = null;\n let existingKeySet: Set<string> = new Set();\n const keyColumns: (string | number)[] = deduplicateBy || [];\n\n if (sourceHasHeaders) {\n // Extract target header names from headerMap\n const targetHeaderNames = headerMap.map(({ target }) => target).filter((t) => typeof t === 'string') as string[];\n\n // Use ensureTabAndHeaders to setup headers and fetch existing keys\n const headerResult = await ensureTabAndHeaders(sheets, {\n spreadsheetId: id,\n sheetTitle,\n requiredHeader: targetHeaderNames.length > 0 ? targetHeaderNames : null,\n keyColumns: keyColumns.filter((k) => typeof k === 'string') as string[],\n logger,\n });\n\n sheetHeaders = headerResult.header;\n existingKeySet = headerResult.keySet;\n } else {\n // sourceHasHeaders=false: Read existing data for deduplication (if needed)\n if (deduplicateBy && deduplicateBy.length > 0) {\n // Read data in chunks for memory efficiency with large sheets\n const CHUNK_SIZE = 1000;\n let startRow = 1;\n let hasMore = true;\n\n while (hasMore) {\n const endRow = startRow + CHUNK_SIZE - 1;\n const chunkRange = `${sheetTitle}!A${startRow}:ZZZ${endRow}`;\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: chunkRange,\n });\n\n const rows = response.data.values || [];\n\n for (const row of rows) {\n const key = buildDeduplicationKey(row, keyColumns, null, false);\n if (key.replace(/::/g, '') !== '') {\n existingKeySet.add(key);\n }\n }\n\n // Check if there are more rows to read\n if (rows.length < CHUNK_SIZE) {\n hasMore = false;\n } else {\n startRow += CHUNK_SIZE;\n }\n }\n\n logger.info('sheets.rows.csv-append existing keys loaded', { keyCount: existingKeySet.size });\n }\n }\n\n // Streaming CSV processing state\n let sourceHeaders: string[] | null = null;\n let batch: (string | number | boolean | null)[][] = [];\n let totalRows = 0;\n let rowsSkipped = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser\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 // Helper to append batch to Sheets\n const appendBatch = async (rows: (string | number | boolean | null)[][]): Promise<void> => {\n if (rows.length === 0) return;\n\n await sheets.spreadsheets.values.append({\n spreadsheetId: id,\n range: `${sheetTitle}!A:A`,\n valueInputOption: 'USER_ENTERED',\n requestBody: { values: rows, majorDimension: 'ROWS' },\n });\n\n logger.info('sheets.rows.csv-append batch appended', { batchSize: rows.length, totalRows });\n };\n\n // Resolve headerMap to numeric indices (do this after extracting CSV headers)\n let resolvedMap: Array<{ sourceIdx: number; targetIdx: number }> = [];\n\n // Stream and process records\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders === null) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n logger.info('sheets.rows.csv-append source headers', { sourceHeaders });\n\n // Resolve headerMap now that we have both source and sheet headers\n resolvedMap = headerMap.map(({ source, target }) => ({\n sourceIdx: resolveColumnReference(source, sourceHeaders, sourceHasHeaders, 'headerMap.source'),\n targetIdx: resolveColumnReference(target, sheetHeaders, sourceHasHeaders, 'headerMap.target'),\n }));\n }\n\n // Map source record to sheet row\n const sourceRow = sourceHeaders?.map((h) => (record as Record<string, unknown>)[h] ?? null);\n const maxTargetIdx = Math.max(...resolvedMap.map((m) => m.targetIdx));\n const sheetRow = new Array(maxTargetIdx + 1).fill(null);\n\n for (const { sourceIdx, targetIdx } of resolvedMap) {\n if (sourceRow) {\n sheetRow[targetIdx] = sourceRow[sourceIdx] ?? null;\n }\n }\n\n // Check deduplication\n if (deduplicateBy && deduplicateBy.length > 0) {\n const key = buildDeduplicationKey(sheetRow, keyColumns, sheetHeaders, sourceHasHeaders);\n if (existingKeySet.has(key)) {\n rowsSkipped++;\n continue; // Skip duplicate\n }\n existingKeySet.add(key); // Add to set for future deduplication\n }\n\n // Add to batch\n batch.push(sheetRow);\n totalRows++;\n } else {\n // sourceHasHeaders=false: record is an array (not an object)\n // Resolve map on first row\n if (resolvedMap.length === 0) {\n resolvedMap = headerMap.map(({ source, target }) => ({\n sourceIdx: resolveColumnReference(source, null, sourceHasHeaders, 'headerMap.source'),\n targetIdx: resolveColumnReference(target, null, sourceHasHeaders, 'headerMap.target'),\n }));\n }\n\n const sourceRow = record as unknown[];\n const maxTargetIdx = Math.max(...resolvedMap.map((m) => m.targetIdx));\n const sheetRow = new Array(maxTargetIdx + 1).fill(null);\n\n for (const { sourceIdx, targetIdx } of resolvedMap) {\n if (sourceIdx < sourceRow.length) {\n sheetRow[targetIdx] = sourceRow[sourceIdx] ?? null;\n }\n }\n\n // Check deduplication\n if (deduplicateBy && deduplicateBy.length > 0) {\n const key = buildDeduplicationKey(sheetRow, keyColumns, null, sourceHasHeaders);\n if (existingKeySet.has(key)) {\n rowsSkipped++;\n continue; // Skip duplicate\n }\n existingKeySet.add(key);\n }\n\n // Add to batch\n batch.push(sheetRow);\n totalRows++;\n }\n\n // Append batch when full\n if (batch.length >= BATCH_SIZE) {\n await appendBatch(batch);\n batch = []; // Clear batch\n }\n }\n\n // Flush remaining rows\n if (batch.length > 0) {\n await appendBatch(batch);\n }\n\n logger.info('sheets.rows.csv-append streaming complete', { totalRows, rowsSkipped });\n\n const updatedRows = totalRows;\n\n logger.info('sheets.rows.csv-append completed', { id, gid, updatedRows, rowsSkipped, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid,\n sheetTitle,\n updatedRows,\n rowsSkipped,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${gid}`,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.rows.csv-append error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error appending CSV rows: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'rows-csv-append',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","parse","google","z","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","getCsvReadStream","buildDeduplicationKey","ensureTabAndHeaders","HeaderMapItemSchema","object","source","union","string","number","int","min","describe","target","inputSchema","id","gid","sourceUri","trim","sourceHasHeaders","boolean","default","headerMap","array","deduplicateBy","optional","successBranchSchema","type","literal","sheetTitle","updatedRows","rowsSkipped","sheetUrl","outputSchema","discriminatedUnion","config","description","result","BATCH_SIZE","resolveColumnReference","ref","headers","context","Error","index","indexOf","join","handler","extra","logger","info","spreadsheetResponse","sheet","length","InvalidParams","colRef","sheets","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","title","sheetHeaders","existingKeySet","Set","keyColumns","targetHeaderNames","map","filter","t","headerResult","requiredHeader","k","header","keySet","CHUNK_SIZE","startRow","hasMore","endRow","chunkRange","response","values","range","rows","row","key","replace","add","keyCount","size","sourceHeaders","batch","totalRows","readStream","parser","pipe","columns","skip_empty_lines","cast","relax_column_count","appendBatch","append","valueInputOption","requestBody","majorDimension","batchSize","resolvedMap","record","Object","keys","sourceIdx","targetIdx","sourceRow","h","maxTargetIdx","Math","max","m","sheetRow","Array","fill","has","push","content","text","JSON","stringify","structuredContent","error","message","InternalError","stack","undefined","createTool","name"],"mappings":"AAAA,sFAAsF,GAGtF,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,KAAK,QAAQ,YAAY;AAClC,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AAClH,SAASC,gBAAgB,QAAQ,qCAAqC;AACtE,SAASC,qBAAqB,QAAQ,2CAA2C;AACjF,SAASC,mBAAmB,QAAQ,wCAAwC;AAE5E,sFAAsF;AACtF,MAAMC,sBAAsBR,EAAES,MAAM,CAAC;IACnCC,QAAQV,EAAEW,KAAK,CAAC;QAACX,EAAEY,MAAM;QAAIZ,EAAEa,MAAM,GAAGC,GAAG,GAAGC,GAAG,CAAC;KAAG,EAAEC,QAAQ,CAAC;IAChEC,QAAQjB,EAAEW,KAAK,CAAC;QAACX,EAAEY,MAAM;QAAIZ,EAAEa,MAAM,GAAGC,GAAG,GAAGC,GAAG,CAAC;KAAG,EAAEC,QAAQ,CAAC;AAClE;AAEA,MAAME,cAAclB,EAAES,MAAM,CAAC;IAC3BU,IAAIf;IACJgB,KAAKlB;IACLmB,WAAWrB,EAAEY,MAAM,GAAGU,IAAI,GAAGP,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CO,kBAAkBvB,EAAEw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f,YAAY;gBAC9B,MAAMuE,YAAYT;gBAClBA,QAAQ,EAAE,EAAE,cAAc;YAC5B;QACF;QAEA,uBAAuB;QACvB,IAAIA,MAAM/C,MAAM,GAAG,GAAG;YACpB,MAAMwD,YAAYT;QACpB;QAEAnD,OAAOC,IAAI,CAAC,6CAA6C;YAAEmD;YAAWtE;QAAY;QAElF,MAAMD,cAAcuE;QAEpBpD,OAAOC,IAAI,CAAC,oCAAoC;YAAEnC;YAAIC;YAAKc;YAAaC;YAAad;QAAU;QAE/F,MAAMoB,SAAiB;YACrBV,MAAM;YACNZ;YACAC;YACAa;YACAC;YACAC;YACAC,UAAU,CAAC,uCAAuC,EAAEjB,GAAG,UAAU,EAAEC,KAAK;QAC1E;QAEA,OAAO;YACLoH,SAAS;gBAAC;oBAAEzG,MAAM;oBAAiB0G,MAAMC,KAAKC,SAAS,CAAClG;gBAAQ;aAAE;YAClEmG,mBAAmB;gBAAEnG;YAAO;QAC9B;IACF,EAAE,OAAOoG,OAAO;QACd,MAAMC,UAAUD,iBAAiB9F,QAAQ8F,MAAMC,OAAO,GAAGvE,OAAOsE;QAChExF,OAAOwF,KAAK,CAAC,gCAAgC;YAAEA,OAAOC;QAAQ;QAE9D,MAAM,IAAIlJ,cAAcC,kBAAkBkJ,aAAa,EAAE,CAAC,0BAA0B,EAAED,SAAS,EAAE;YAC/FE,OAAOH,iBAAiB9F,QAAQ8F,MAAMG,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACN5G;QACAY;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/rows-csv-append.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with database-style row append and deduplication */\n\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 { google } from 'googleapis';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\nimport { buildDeduplicationKey } from '../../spreadsheet/deduplication-utils.ts';\nimport { ensureTabAndHeaders } from '../../spreadsheet/sheet-operations.ts';\n\n// Header mapping schema: source/target can be string (name) or number (0-based index)\nconst HeaderMapItemSchema = z.object({\n source: z.union([z.string(), z.number().int().min(0)]).describe('CSV column: header name (string) or 0-based index (number)'),\n target: z.union([z.string(), z.number().int().min(0)]).describe('Sheet column: header name (string) or 0-based index (number)'),\n});\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 sourceHasHeaders: z.boolean().default(true).describe('Source has header row for column name mapping. Set to false for data-only sources (numeric indices required).'),\n headerMap: z.array(HeaderMapItemSchema).describe('Column mappings from CSV to sheet'),\n deduplicateBy: z\n .array(z.union([z.string(), z.number().int().min(0)]))\n .optional()\n .describe('Sheet columns for deduplication (names or indices)'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Sheet tab name'),\n updatedRows: z.number().describe('Number of rows appended'),\n rowsSkipped: z.number().optional().describe('Number of duplicate rows skipped'),\n sheetUrl: z.string().optional().describe('URL to view the sheet'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Import CSV to Google Sheets with column mapping and optional deduplication. Streams data for large files.',\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\n/** Batch size for Sheets API calls (1000 rows × 12 cols = 12K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\n/**\n * Resolve column reference to numeric index\n * @param ref Column reference (string name or number index)\n * @param headers Header row (null when sourceHasHeaders=false)\n * @param sourceHasHeaders Whether headers are present\n * @returns 0-based column index\n */\nfunction resolveColumnReference(ref: string | number, headers: string[] | null, sourceHasHeaders: boolean, context: string): number {\n // If number, use directly as 0-based index\n if (typeof ref === 'number') {\n if (ref < 0) {\n throw new Error(`${context}: Column index must be >= 0, got ${ref}`);\n }\n return ref;\n }\n\n // If string, must be header name\n if (!sourceHasHeaders || !headers) {\n throw new Error(`${context}: String column reference \"${ref}\" requires sourceHasHeaders=true. Use numeric index when sourceHasHeaders=false.`);\n }\n\n const index = headers.indexOf(ref);\n if (index === -1) {\n throw new Error(`${context}: Header \"${ref}\" not found in [${headers.join(', ')}]`);\n }\n\n return index;\n}\n\nasync function handler({ id, gid, sourceUri, sourceHasHeaders, headerMap, deduplicateBy }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.rows.csv-append called', { id, gid, sourceUri, sourceHasHeaders, headerMap, deduplicateBy });\n\n try {\n if (headerMap.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'headerMap cannot be empty');\n }\n\n // Validate: if sourceHasHeaders=false, all references must be numeric\n if (!sourceHasHeaders) {\n for (const { source, target } of headerMap) {\n if (typeof source === 'string') {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `sourceHasHeaders=false requires numeric indices. Got string source: \"${source}\"`);\n }\n if (typeof target === 'string') {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `sourceHasHeaders=false requires numeric indices. Got string target: \"${target}\"`);\n }\n }\n if (deduplicateBy) {\n for (const colRef of deduplicateBy) {\n if (typeof colRef === 'string') {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `sourceHasHeaders=false requires numeric indices in deduplicateBy. Got string: \"${colRef}\"`);\n }\n }\n }\n }\n\n const sheets = google.sheets({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get sheet details using the gid\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet?.properties?.title ?? '';\n\n // Determine target headers (for sourceHasHeaders=true) or column count (for sourceHasHeaders=false)\n let sheetHeaders: string[] | null = null;\n let existingKeySet: Set<string> = new Set();\n const keyColumns: (string | number)[] = deduplicateBy || [];\n\n if (sourceHasHeaders) {\n // Extract target header names from headerMap\n const targetHeaderNames = headerMap.map(({ target }) => target).filter((t) => typeof t === 'string') as string[];\n\n // Use ensureTabAndHeaders to setup headers and fetch existing keys\n const headerResult = await ensureTabAndHeaders(sheets, {\n spreadsheetId: id,\n sheetTitle,\n requiredHeader: targetHeaderNames.length > 0 ? targetHeaderNames : null,\n keyColumns: keyColumns.filter((k) => typeof k === 'string') as string[],\n logger,\n });\n\n sheetHeaders = headerResult.header;\n existingKeySet = headerResult.keySet;\n } else {\n // sourceHasHeaders=false: Read existing data for deduplication (if needed)\n if (deduplicateBy && deduplicateBy.length > 0) {\n // Read data in chunks for memory efficiency with large sheets\n const CHUNK_SIZE = 1000;\n let startRow = 1;\n let hasMore = true;\n\n while (hasMore) {\n const endRow = startRow + CHUNK_SIZE - 1;\n const chunkRange = `${sheetTitle}!A${startRow}:ZZZ${endRow}`;\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: chunkRange,\n });\n\n const rows = response.data.values || [];\n\n for (const row of rows) {\n const key = buildDeduplicationKey(row, keyColumns, null, false);\n if (key.replace(/::/g, '') !== '') {\n existingKeySet.add(key);\n }\n }\n\n // Check if there are more rows to read\n if (rows.length < CHUNK_SIZE) {\n hasMore = false;\n } else {\n startRow += CHUNK_SIZE;\n }\n }\n\n logger.info('sheets.rows.csv-append existing keys loaded', { keyCount: existingKeySet.size });\n }\n }\n\n // Streaming CSV processing state\n let sourceHeaders: string[] | null = null;\n let batch: (string | number | boolean | null)[][] = [];\n let totalRows = 0;\n let rowsSkipped = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser\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 // Helper to append batch to Sheets\n const appendBatch = async (rows: (string | number | boolean | null)[][]): Promise<void> => {\n if (rows.length === 0) return;\n\n await sheets.spreadsheets.values.append({\n spreadsheetId: id,\n range: `${sheetTitle}!A:A`,\n valueInputOption: 'USER_ENTERED',\n requestBody: { values: rows, majorDimension: 'ROWS' },\n });\n\n logger.info('sheets.rows.csv-append batch appended', { batchSize: rows.length, totalRows });\n };\n\n // Resolve headerMap to numeric indices (do this after extracting CSV headers)\n let resolvedMap: Array<{ sourceIdx: number; targetIdx: number }> = [];\n\n // Stream and process records\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders === null) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n logger.info('sheets.rows.csv-append source headers', { sourceHeaders });\n\n // Resolve headerMap now that we have both source and sheet headers\n resolvedMap = headerMap.map(({ source, target }) => ({\n sourceIdx: resolveColumnReference(source, sourceHeaders, sourceHasHeaders, 'headerMap.source'),\n targetIdx: resolveColumnReference(target, sheetHeaders, sourceHasHeaders, 'headerMap.target'),\n }));\n }\n\n // Map source record to sheet row\n const sourceRow = sourceHeaders?.map((h) => (record as Record<string, unknown>)[h] ?? null);\n const maxTargetIdx = Math.max(...resolvedMap.map((m) => m.targetIdx));\n const sheetRow = new Array(maxTargetIdx + 1).fill(null);\n\n for (const { sourceIdx, targetIdx } of resolvedMap) {\n if (sourceRow) {\n sheetRow[targetIdx] = sourceRow[sourceIdx] ?? null;\n }\n }\n\n // Check deduplication\n if (deduplicateBy && deduplicateBy.length > 0) {\n const key = buildDeduplicationKey(sheetRow, keyColumns, sheetHeaders, sourceHasHeaders);\n if (existingKeySet.has(key)) {\n rowsSkipped++;\n continue; // Skip duplicate\n }\n existingKeySet.add(key); // Add to set for future deduplication\n }\n\n // Add to batch\n batch.push(sheetRow);\n totalRows++;\n } else {\n // sourceHasHeaders=false: record is an array (not an object)\n // Resolve map on first row\n if (resolvedMap.length === 0) {\n resolvedMap = headerMap.map(({ source, target }) => ({\n sourceIdx: resolveColumnReference(source, null, sourceHasHeaders, 'headerMap.source'),\n targetIdx: resolveColumnReference(target, null, sourceHasHeaders, 'headerMap.target'),\n }));\n }\n\n const sourceRow = record as unknown[];\n const maxTargetIdx = Math.max(...resolvedMap.map((m) => m.targetIdx));\n const sheetRow = new Array(maxTargetIdx + 1).fill(null);\n\n for (const { sourceIdx, targetIdx } of resolvedMap) {\n if (sourceIdx < sourceRow.length) {\n sheetRow[targetIdx] = sourceRow[sourceIdx] ?? null;\n }\n }\n\n // Check deduplication\n if (deduplicateBy && deduplicateBy.length > 0) {\n const key = buildDeduplicationKey(sheetRow, keyColumns, null, sourceHasHeaders);\n if (existingKeySet.has(key)) {\n rowsSkipped++;\n continue; // Skip duplicate\n }\n existingKeySet.add(key);\n }\n\n // Add to batch\n batch.push(sheetRow);\n totalRows++;\n }\n\n // Append batch when full\n if (batch.length >= BATCH_SIZE) {\n await appendBatch(batch);\n batch = []; // Clear batch\n }\n }\n\n // Flush remaining rows\n if (batch.length > 0) {\n await appendBatch(batch);\n }\n\n logger.info('sheets.rows.csv-append streaming complete', { totalRows, rowsSkipped });\n\n const updatedRows = totalRows;\n\n logger.info('sheets.rows.csv-append completed', { id, gid, updatedRows, rowsSkipped, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid,\n sheetTitle,\n updatedRows,\n rowsSkipped,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${gid}`,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.rows.csv-append error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error appending CSV rows: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'rows-csv-append',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","parse","google","z","googleAuth","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","getCsvReadStream","buildDeduplicationKey","ensureTabAndHeaders","HeaderMapItemSchema","object","source","union","string","number","int","min","describe","target","inputSchema","id","gid","sourceUri","trim","sourceHasHeaders","boolean","default","headerMap","array","deduplicateBy","optional","successBranchSchema","type","literal","sheetTitle","updatedRows","rowsSkipped","sheetUrl","outputSchema","discriminatedUnion","config","description","result","BATCH_SIZE","resolveColumnReference","ref","headers","context","Error","index","indexOf","join","handler","extra","logger","info","spreadsheetResponse","sheet","length","InvalidParams","colRef","sheets","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","title","sheetHeaders","existingKeySet","Set","keyColumns","targetHeaderNames","map","filter","t","headerResult","requiredHeader","k","header","keySet","CHUNK_SIZE","startRow","hasMore","endRow","chunkRange","response","values","range","rows","row","key","replace","add","keyCount","size","sourceHeaders","batch","totalRows","readStream","parser","pipe","columns","skip_empty_lines","cast","relax_column_count","appendBatch","append","valueInputOption","requestBody","majorDimension","batchSize","resolvedMap","record","Object","keys","sourceIdx","targetIdx","sourceRow","h","maxTargetIdx","Math","max","m","sheetRow","Array","fill","has","push","content","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;YAAWtE;QAAY;QAElF,MAAMD,cAAcuE;QAEpBpD,OAAOC,IAAI,CAAC,oCAAoC;YAAEnC;YAAIC;YAAKc;YAAaC;YAAad;QAAU;QAE/F,MAAMoB,SAAiB;YACrBV,MAAM;YACNZ;YACAC;YACAa;YACAC;YACAC;YACAC,UAAU,CAAC,uCAAuC,EAAEjB,GAAG,UAAU,EAAEC,KAAK;QAC1E;QAEA,OAAO;YACLoH,SAAS;gBAAC;oBAAEzG,MAAM;oBAAiB0G,MAAMC,KAAKC,SAAS,CAAClG;gBAAQ;aAAE;YAClEmG,mBAAmB;gBAAEnG;YAAO;QAC9B;IACF,EAAE,OAAOoG,OAAO;QACd,MAAMC,UAAUD,iBAAiB9F,QAAQ8F,MAAMC,OAAO,GAAGvE,OAAOsE;QAChExF,OAAOwF,KAAK,CAAC,gCAAgC;YAAEA,OAAOC;QAAQ;QAE9D,MAAM,IAAInJ,cAAcC,kBAAkBmJ,aAAa,EAAE,CAAC,0BAA0B,EAAED,SAAS,EAAE;YAC/FE,OAAOH,iBAAiB9F,QAAQ8F,MAAMG,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACN5G;QACAY;IACF;AACF"}
|
|
@@ -3,6 +3,7 @@ const { AuthRequiredBranchSchema } = schemas;
|
|
|
3
3
|
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
4
4
|
import { google } from 'googleapis';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
6
7
|
import { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.js';
|
|
7
8
|
const inputSchema = z.object({
|
|
8
9
|
id: SpreadsheetIdSchema,
|
|
@@ -45,7 +46,7 @@ async function handler({ id, gid, range, render }, extra) {
|
|
|
45
46
|
var _spreadsheetResponse_data_sheets, _sheet_properties;
|
|
46
47
|
const sheets = google.sheets({
|
|
47
48
|
version: 'v4',
|
|
48
|
-
auth: extra.authContext.auth
|
|
49
|
+
auth: googleAuth(extra.authContext.auth)
|
|
49
50
|
});
|
|
50
51
|
// Get sheet details using the gid to get sheet title
|
|
51
52
|
const spreadsheetResponse = await sheets.spreadsheets.get({
|