@mcp-z/mcp-sheets 2.3.1 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -27
- package/dist/cjs/constants.js.map +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/lib/create-store.js.map +1 -1
- package/dist/cjs/lib/google-auth.js.map +1 -1
- package/dist/cjs/mcp/index.js.map +1 -1
- package/dist/cjs/mcp/prompts/a1-notation.js.map +1 -1
- package/dist/cjs/mcp/prompts/index.js.map +1 -1
- package/dist/cjs/mcp/resources/index.js.map +1 -1
- package/dist/cjs/mcp/resources/spreadsheet.js.map +1 -1
- package/dist/cjs/mcp/tools/cells-format.js.map +1 -1
- package/dist/cjs/mcp/tools/cells-metadata-get.d.cts +95 -0
- package/dist/cjs/mcp/tools/cells-metadata-get.d.ts +95 -0
- package/dist/cjs/mcp/tools/cells-metadata-get.js +331 -0
- package/dist/cjs/mcp/tools/cells-metadata-get.js.map +1 -0
- package/dist/cjs/mcp/tools/chart-create.js.map +1 -1
- package/dist/cjs/mcp/tools/columns-get.js.map +1 -1
- package/dist/cjs/mcp/tools/columns-update.js.map +1 -1
- package/dist/cjs/mcp/tools/csv-get-columns.js.map +1 -1
- package/dist/cjs/mcp/tools/dimensions-batch-update.js.map +1 -1
- package/dist/cjs/mcp/tools/dimensions-move.js.map +1 -1
- package/dist/cjs/mcp/tools/index.d.cts +2 -0
- package/dist/cjs/mcp/tools/index.d.ts +2 -0
- package/dist/cjs/mcp/tools/index.js +8 -0
- package/dist/cjs/mcp/tools/index.js.map +1 -1
- package/dist/cjs/mcp/tools/lib/dimension-operations.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-append.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-csv-append.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-get.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-copy-to.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-copy.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-create.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-delete.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-find.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-rename.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-copy.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-create.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-find.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-metadata-get.d.cts +59 -0
- package/dist/cjs/mcp/tools/spreadsheet-metadata-get.d.ts +59 -0
- package/dist/cjs/mcp/tools/spreadsheet-metadata-get.js +259 -0
- package/dist/cjs/mcp/tools/spreadsheet-metadata-get.js.map +1 -0
- package/dist/cjs/mcp/tools/spreadsheet-rename.js.map +1 -1
- package/dist/cjs/mcp/tools/validation-set.js.map +1 -1
- package/dist/cjs/mcp/tools/values-batch-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-clear.js.map +1 -1
- package/dist/cjs/mcp/tools/values-csv-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-markdown-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-replace.js.map +1 -1
- package/dist/cjs/mcp/tools/values-search.js.map +1 -1
- package/dist/cjs/schemas/index.js.map +1 -1
- package/dist/cjs/setup/config.js +5 -4
- package/dist/cjs/setup/config.js.map +1 -1
- package/dist/cjs/setup/http.d.cts +1 -1
- package/dist/cjs/setup/http.d.ts +1 -1
- package/dist/cjs/setup/http.js.map +1 -1
- package/dist/cjs/setup/index.js.map +1 -1
- package/dist/cjs/setup/oauth-google.js.map +1 -1
- package/dist/cjs/setup/runtime.js +3 -2
- package/dist/cjs/setup/runtime.js.map +1 -1
- package/dist/cjs/setup/stdio.js.map +1 -1
- package/dist/cjs/setup/version-help.js.map +1 -1
- package/dist/cjs/spreadsheet/column-utilities.js.map +1 -1
- package/dist/cjs/spreadsheet/csv-streaming.js.map +1 -1
- package/dist/cjs/spreadsheet/data-operations.js.map +1 -1
- package/dist/cjs/spreadsheet/deduplication-utils.js.map +1 -1
- package/dist/cjs/spreadsheet/markdown-runs.js.map +1 -1
- package/dist/cjs/spreadsheet/range-operations.d.cts +2 -1
- package/dist/cjs/spreadsheet/range-operations.d.ts +2 -1
- package/dist/cjs/spreadsheet/range-operations.js +12 -0
- package/dist/cjs/spreadsheet/range-operations.js.map +1 -1
- package/dist/cjs/spreadsheet/sheet-operations.js.map +1 -1
- package/dist/cjs/spreadsheet/spreadsheet-management.js.map +1 -1
- package/dist/esm/constants.js.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/lib/create-store.js.map +1 -1
- package/dist/esm/lib/google-auth.js.map +1 -1
- package/dist/esm/mcp/index.js.map +1 -1
- package/dist/esm/mcp/prompts/a1-notation.js.map +1 -1
- package/dist/esm/mcp/prompts/index.js.map +1 -1
- package/dist/esm/mcp/resources/index.js.map +1 -1
- package/dist/esm/mcp/resources/spreadsheet.js.map +1 -1
- package/dist/esm/mcp/tools/cells-format.js.map +1 -1
- package/dist/esm/mcp/tools/cells-metadata-get.d.ts +95 -0
- package/dist/esm/mcp/tools/cells-metadata-get.js +155 -0
- package/dist/esm/mcp/tools/cells-metadata-get.js.map +1 -0
- package/dist/esm/mcp/tools/chart-create.js.map +1 -1
- package/dist/esm/mcp/tools/columns-get.js.map +1 -1
- package/dist/esm/mcp/tools/columns-update.js.map +1 -1
- package/dist/esm/mcp/tools/csv-get-columns.js.map +1 -1
- package/dist/esm/mcp/tools/dimensions-batch-update.js.map +1 -1
- package/dist/esm/mcp/tools/dimensions-move.js.map +1 -1
- package/dist/esm/mcp/tools/index.d.ts +2 -0
- package/dist/esm/mcp/tools/index.js +2 -0
- package/dist/esm/mcp/tools/index.js.map +1 -1
- package/dist/esm/mcp/tools/lib/dimension-operations.js.map +1 -1
- package/dist/esm/mcp/tools/rows-append.js.map +1 -1
- package/dist/esm/mcp/tools/rows-csv-append.js.map +1 -1
- package/dist/esm/mcp/tools/rows-get.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-copy-to.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-copy.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-create.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-delete.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-find.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-rename.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-copy.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-create.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-find.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-metadata-get.d.ts +59 -0
- package/dist/esm/mcp/tools/spreadsheet-metadata-get.js +89 -0
- package/dist/esm/mcp/tools/spreadsheet-metadata-get.js.map +1 -0
- package/dist/esm/mcp/tools/spreadsheet-rename.js.map +1 -1
- package/dist/esm/mcp/tools/validation-set.js.map +1 -1
- package/dist/esm/mcp/tools/values-batch-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-clear.js.map +1 -1
- package/dist/esm/mcp/tools/values-csv-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-markdown-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-replace.js.map +1 -1
- package/dist/esm/mcp/tools/values-search.js.map +1 -1
- package/dist/esm/schemas/index.js.map +1 -1
- package/dist/esm/setup/config.js +4 -3
- package/dist/esm/setup/config.js.map +1 -1
- package/dist/esm/setup/http.d.ts +1 -1
- package/dist/esm/setup/http.js.map +1 -1
- package/dist/esm/setup/index.js.map +1 -1
- package/dist/esm/setup/oauth-google.js.map +1 -1
- package/dist/esm/setup/runtime.js +3 -2
- package/dist/esm/setup/runtime.js.map +1 -1
- package/dist/esm/setup/stdio.js.map +1 -1
- package/dist/esm/setup/version-help.js.map +1 -1
- package/dist/esm/spreadsheet/column-utilities.js.map +1 -1
- package/dist/esm/spreadsheet/csv-streaming.js.map +1 -1
- package/dist/esm/spreadsheet/data-operations.js.map +1 -1
- package/dist/esm/spreadsheet/deduplication-utils.js.map +1 -1
- package/dist/esm/spreadsheet/markdown-runs.js.map +1 -1
- package/dist/esm/spreadsheet/range-operations.d.ts +2 -1
- package/dist/esm/spreadsheet/range-operations.js +11 -2
- package/dist/esm/spreadsheet/range-operations.js.map +1 -1
- package/dist/esm/spreadsheet/sheet-operations.js.map +1 -1
- package/dist/esm/spreadsheet/spreadsheet-management.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/package.json +11 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/prompts/index.ts"],"sourcesContent":["export { default as a1Notation } from './a1-notation.ts';\n"],"names":["default","a1Notation"],"mappings":"AAAA,SAASA,WAAWC,UAAU,QAAQ,mBAAmB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/resources/index.ts"],"sourcesContent":["export { default as spreadsheet } from './spreadsheet.ts';\n"],"names":["default","spreadsheet"],"mappings":"AAAA,SAASA,WAAWC,WAAW,QAAQ,mBAAmB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/resources/spreadsheet.ts"],"sourcesContent":["import { type sheets_v4, sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ReadResourceResult, ResourceConfig, ResourceModule, ServerContext } from '@mcp-z/server';\nimport { ResourceTemplate } from '@mcp-z/server';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport type { GoogleApiError } from '../../types.ts';\n\nexport default function createResource(): ResourceModule {\n const template = new ResourceTemplate('sheets://spreadsheets/{spreadsheetId}', { list: undefined });\n const config: ResourceConfig = {\n description: 'Sheets spreadsheet resource',\n mimeType: 'application/json',\n };\n\n const handler = async (uri: URL, variables: Record<string, string | string[]>, extra: ServerContext): Promise<ReadResourceResult> => {\n const spreadsheetId = Array.isArray(variables.spreadsheetId) ? variables.spreadsheetId[0] : variables.spreadsheetId;\n\n if (!spreadsheetId) {\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({ error: 'spreadsheetId is required' }),\n },\n ],\n };\n }\n\n try {\n // Safe type guard to access middleware-enriched extra\n const { logger, authContext } = extra as unknown as EnrichedExtra;\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(authContext.auth) });\n const resp = await sheets.spreadsheets.get({\n spreadsheetId,\n fields: 'spreadsheetId,properties.title,sheets.properties',\n });\n const data = resp.data as sheets_v4.Schema$Spreadsheet;\n logger.info('sheets-spreadsheet resource fetch success', {\n spreadsheetId: data.spreadsheetId,\n title: data?.properties?.title,\n sheetCount: (data?.sheets || []).length,\n });\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({\n id: data?.spreadsheetId,\n title: data?.properties?.title,\n sheets: (data?.sheets || []).map((s) => ({\n id: s?.properties?.sheetId,\n title: s?.properties?.title,\n rowCount: s?.properties?.gridProperties?.rowCount,\n columnCount: s?.properties?.gridProperties?.columnCount,\n })),\n }),\n },\n ],\n };\n } catch (error) {\n const { logger } = extra as unknown as EnrichedExtra;\n logger.info('sheets-spreadsheet resource fetch failed', error as Record<string, unknown>);\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({\n error: String((error as GoogleApiError)?.message ?? error),\n }),\n },\n ],\n };\n }\n };\n\n return {\n name: 'spreadsheet',\n template,\n config,\n handler,\n };\n}\n"],"names":["sheets","sheetsApi","ResourceTemplate","googleAuth","createResource","template","list","undefined","config","description","mimeType","handler","uri","variables","extra","spreadsheetId","Array","isArray","contents","href","text","JSON","stringify","error","data","logger","authContext","version","auth","resp","spreadsheets","get","fields","info","title","properties","sheetCount","length","id","map","s","sheetId","rowCount","gridProperties","columnCount","String","message","name"],"mappings":"AAAA,SAAyBA,UAAUC,SAAS,QAAQ,qBAAqB;AAGzE,SAASC,gBAAgB,QAAQ,gBAAgB;AACjD,SAASC,UAAU,QAAQ,2BAA2B;AAGtD,eAAe,SAASC;IACtB,MAAMC,WAAW,IAAIH,iBAAiB,yCAAyC;QAAEI,MAAMC;IAAU;IACjG,MAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,MAAMC,UAAU,OAAOC,KAAUC,WAA8CC;QAC7E,MAAMC,gBAAgBC,MAAMC,OAAO,CAACJ,UAAUE,aAAa,IAAIF,UAAUE,aAAa,CAAC,EAAE,GAAGF,UAAUE,aAAa;QAEnH,IAAI,CAACA,eAAe;YAClB,OAAO;gBACLG,UAAU;oBACR;wBACEN,KAAKA,IAAIO,IAAI;wBACbT,UAAU;wBACVU,MAAMC,KAAKC,SAAS,CAAC;4BAAEC,OAAO;wBAA4B;oBAC5D;iBACD;YACH;QACF;QAEA,IAAI;gBAWOC,kBAUMA;YApBf,sDAAsD;YACtD,MAAM,EAAEC,MAAM,EAAEC,WAAW,EAAE,GAAGZ;YAChC,MAAMd,SAASC,UAAU;gBAAE0B,SAAS;gBAAMC,MAAMzB,WAAWuB,YAAYE,IAAI;YAAE;YAC7E,MAAMC,OAAO,MAAM7B,OAAO8B,YAAY,CAACC,GAAG,CAAC;gBACzChB;gBACAiB,QAAQ;YACV;YACA,MAAMR,OAAOK,KAAKL,IAAI;YACtBC,OAAOQ,IAAI,CAAC,6CAA6C;gBACvDlB,eAAeS,KAAKT,aAAa;gBACjCmB,KAAK,EAAEV,iBAAAA,4BAAAA,mBAAAA,KAAMW,UAAU,cAAhBX,uCAAAA,iBAAkBU,KAAK;gBAC9BE,YAAY,AAACZ,CAAAA,CAA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,OAAO,uCAAIvB;wBACtD;oBACF;iBACD;YACH;QACF;IACF;IAEA,OAAO;QACLwB,MAAM;QACN1C;QACAG;QACAG;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/cells-format.ts"],"sourcesContent":["import { type sheets_v4, sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\n// RGB color schema (0-1 range for Google Sheets API)\nconst ColorSchema = z.object({\n red: z.number().min(0).max(1).describe('Red component (0-1)'),\n green: z.number().min(0).max(1).describe('Green component (0-1)'),\n blue: z.number().min(0).max(1).describe('Blue component (0-1)'),\n});\n\n// Number format schema\nconst NumberFormatSchema = z.object({\n type: z.enum(['TEXT', 'NUMBER', 'PERCENT', 'CURRENCY', 'DATE', 'TIME']).describe('Number format type'),\n pattern: z.string().optional().describe('Custom format pattern (e.g., \"$#,##0.00\" for currency)'),\n});\n\n// Border schema\nconst BorderSchema = z.object({\n style: z.enum(['SOLID', 'DASHED', 'DOTTED']).describe('Border line style'),\n color: ColorSchema.describe('Border color'),\n});\n\n// Input schema for format requests\nconst FormatRequestSchema = z.object({\n range: z.string().min(1).describe('A1 notation range to format (e.g., \"A1:D10\", \"B:B\", \"5:5\")'),\n backgroundColor: ColorSchema.optional().describe('Cell background color'),\n textColor: ColorSchema.optional().describe('Text color'),\n bold: z.boolean().optional().describe('Bold text'),\n fontSize: z.number().int().min(6).max(36).optional().describe('Font size in points'),\n horizontalAlignment: z.enum(['LEFT', 'CENTER', 'RIGHT']).optional().describe('Horizontal text alignment'),\n numberFormat: NumberFormatSchema.optional().describe('Number format pattern'),\n borders: BorderSchema.optional().describe('Cell borders'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(FormatRequestSchema).min(1).max(50).describe('Array of formatting requests. Batch multiple ranges for efficiency.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Title of the formatted sheet'),\n sheetUrl: z.string().describe('URL of the formatted sheet'),\n successCount: z.number().int().nonnegative().describe('Number of format requests successfully applied'),\n failedRanges: z\n .array(\n z.object({\n range: z.string().describe('A1 notation of range that failed'),\n error: z.string().describe('Why formatting failed for this range'),\n })\n )\n .optional()\n .describe('Only populated if some ranges failed to format'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Apply formatting (colors, borders, fonts, alignment, number formats) to cell ranges without modifying data. Supports batch operations for efficiency. Colors use 0-1 RGB format. Best for creating professional, visually organized spreadsheets.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.cells.format called', {\n id,\n gid,\n requestCount: requests.length,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for format cells', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).\n const sheetId = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Build batch update requests\n const batchRequests: sheets_v4.Schema$Request[] = [];\n const failedRanges: Array<{ range: string; error: string }> = [];\n\n for (const request of requests) {\n try {\n // Parse A1 notation to range reference\n const rangeRef = parseA1Notation(request.range);\n\n // Build grid range from range reference using helper function\n const gridRange = rangeReferenceToGridRange(rangeRef, sheetId);\n\n // Build cell format object\n const cellFormat: {\n backgroundColor?: sheets_v4.Schema$Color;\n textFormat?: sheets_v4.Schema$TextFormat;\n horizontalAlignment?: string;\n numberFormat?: sheets_v4.Schema$NumberFormat;\n } = {};\n const fields: string[] = [];\n\n // Background color\n if (request.backgroundColor) {\n cellFormat.backgroundColor = request.backgroundColor;\n fields.push('backgroundColor');\n }\n\n // Text format\n if (request.textColor || request.bold !== undefined || request.fontSize !== undefined) {\n cellFormat.textFormat = {};\n if (request.textColor) {\n cellFormat.textFormat.foregroundColor = request.textColor;\n fields.push('textFormat.foregroundColor');\n }\n if (request.bold !== undefined) {\n cellFormat.textFormat.bold = request.bold;\n fields.push('textFormat.bold');\n }\n if (request.fontSize !== undefined) {\n cellFormat.textFormat.fontSize = request.fontSize;\n fields.push('textFormat.fontSize');\n }\n }\n\n // Horizontal alignment\n if (request.horizontalAlignment) {\n cellFormat.horizontalAlignment = request.horizontalAlignment;\n fields.push('horizontalAlignment');\n }\n\n // Number format\n if (request.numberFormat) {\n const numberFormat: sheets_v4.Schema$NumberFormat = {\n type: request.numberFormat.type,\n };\n if (request.numberFormat.pattern !== undefined) {\n numberFormat.pattern = request.numberFormat.pattern;\n }\n cellFormat.numberFormat = numberFormat;\n fields.push('numberFormat');\n }\n\n // Add repeatCell request for this range\n if (fields.length > 0) {\n batchRequests.push({\n repeatCell: {\n range: gridRange,\n cell: {\n userEnteredFormat: cellFormat,\n },\n fields: `userEnteredFormat(${fields.join(',')})`,\n },\n });\n }\n\n // Add border formatting if specified\n if (request.borders) {\n batchRequests.push({\n updateBorders: {\n range: gridRange,\n top: {\n style: request.borders.style,\n color: request.borders.color,\n },\n bottom: {\n style: request.borders.style,\n color: request.borders.color,\n },\n left: {\n style: request.borders.style,\n color: request.borders.color,\n },\n right: {\n style: request.borders.style,\n color: request.borders.color,\n },\n },\n });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse range for formatting', {\n range: request.range,\n error: message,\n });\n failedRanges.push({\n range: request.range,\n error: `Failed to parse range: ${message}`,\n });\n }\n }\n\n // Early return if all ranges failed\n if (batchRequests.length === 0) {\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: 0,\n failedRanges: failedRanges.length > 0 ? failedRanges : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n }\n\n logger.info('sheets.cells.format executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchRequestsCount: batchRequests.length,\n });\n\n // Execute the batch update\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: batchRequests,\n },\n });\n\n logger.info('sheets.cells.format completed successfully', {\n successCount: requests.length - failedRanges.length,\n failedCount: failedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: requests.length - failedRanges.length,\n failedRanges: failedRanges.length > 0 ? failedRanges : undefined,\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('Format cells operation failed', {\n id,\n gid,\n requestCount: requests.length,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error formatting cells: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'cells-format',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","z","googleAuth","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","parseA1Notation","rangeReferenceToGridRange","ColorSchema","object","red","number","min","max","describe","green","blue","NumberFormatSchema","type","enum","pattern","string","optional","BorderSchema","style","color","FormatRequestSchema","range","backgroundColor","textColor","bold","boolean","fontSize","int","horizontalAlignment","numberFormat","borders","inputSchema","id","gid","requests","array","successBranchSchema","literal","sheetTitle","sheetUrl","successCount","nonnegative","failedRanges","error","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","requestCount","length","sheet","spreadsheetResponse","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","title","batchRequests","request","rangeRef","gridRange","cellFormat","push","undefined","textFormat","foregroundColor","repeatCell","cell","userEnteredFormat","join","updateBorders","top","bottom","left","right","message","Error","content","text","JSON","stringify","structuredContent","batchRequestsCount","batchUpdate","requestBody","failedCount","InternalError","stack","createTool","name"],"mappings":"AAAA,SAAyBA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzE,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB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xB;QAChD;IACF;AACF;AAEA,eAAe,SAASyB;IACtB,OAAO;QACLC,MAAM;QACN1D;QACAG;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/cells-format.ts"],"sourcesContent":["import { type sheets_v4, sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\n// RGB color schema (0-1 range for Google Sheets API)\nconst ColorSchema = z.object({\n red: z.number().min(0).max(1).describe('Red component (0-1)'),\n green: z.number().min(0).max(1).describe('Green component (0-1)'),\n blue: z.number().min(0).max(1).describe('Blue component (0-1)'),\n});\n\n// Number format schema\nconst NumberFormatSchema = z.object({\n type: z.enum(['TEXT', 'NUMBER', 'PERCENT', 'CURRENCY', 'DATE', 'TIME']).describe('Number format type'),\n pattern: z.string().optional().describe('Custom format pattern (e.g., \"$#,##0.00\" for currency)'),\n});\n\n// Border schema\nconst BorderSchema = z.object({\n style: z.enum(['SOLID', 'DASHED', 'DOTTED']).describe('Border line style'),\n color: ColorSchema.describe('Border color'),\n});\n\n// Input schema for format requests\nconst FormatRequestSchema = z.object({\n range: z.string().min(1).describe('A1 notation range to format (e.g., \"A1:D10\", \"B:B\", \"5:5\")'),\n backgroundColor: ColorSchema.optional().describe('Cell background color'),\n textColor: ColorSchema.optional().describe('Text color'),\n bold: z.boolean().optional().describe('Bold text'),\n fontSize: z.number().int().min(6).max(36).optional().describe('Font size in points'),\n horizontalAlignment: z.enum(['LEFT', 'CENTER', 'RIGHT']).optional().describe('Horizontal text alignment'),\n numberFormat: NumberFormatSchema.optional().describe('Number format pattern'),\n borders: BorderSchema.optional().describe('Cell borders'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(FormatRequestSchema).min(1).max(50).describe('Array of formatting requests. Batch multiple ranges for efficiency.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Title of the formatted sheet'),\n sheetUrl: z.string().describe('URL of the formatted sheet'),\n successCount: z.number().int().nonnegative().describe('Number of format requests successfully applied'),\n failedRanges: z\n .array(\n z.object({\n range: z.string().describe('A1 notation of range that failed'),\n error: z.string().describe('Why formatting failed for this range'),\n })\n )\n .optional()\n .describe('Only populated if some ranges failed to format'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Apply formatting (colors, borders, fonts, alignment, number formats) to cell ranges without modifying data. Supports batch operations for efficiency. Colors use 0-1 RGB format. Best for creating professional, visually organized spreadsheets.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.cells.format called', {\n id,\n gid,\n requestCount: requests.length,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for format cells', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).\n const sheetId = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Build batch update requests\n const batchRequests: sheets_v4.Schema$Request[] = [];\n const failedRanges: Array<{ range: string; error: string }> = [];\n\n for (const request of requests) {\n try {\n // Parse A1 notation to range reference\n const rangeRef = parseA1Notation(request.range);\n\n // Build grid range from range reference using helper function\n const gridRange = rangeReferenceToGridRange(rangeRef, sheetId);\n\n // Build cell format object\n const cellFormat: {\n backgroundColor?: sheets_v4.Schema$Color;\n textFormat?: sheets_v4.Schema$TextFormat;\n horizontalAlignment?: string;\n numberFormat?: sheets_v4.Schema$NumberFormat;\n } = {};\n const fields: string[] = [];\n\n // Background color\n if (request.backgroundColor) {\n cellFormat.backgroundColor = request.backgroundColor;\n fields.push('backgroundColor');\n }\n\n // Text format\n if (request.textColor || request.bold !== undefined || request.fontSize !== undefined) {\n cellFormat.textFormat = {};\n if (request.textColor) {\n cellFormat.textFormat.foregroundColor = request.textColor;\n fields.push('textFormat.foregroundColor');\n }\n if (request.bold !== undefined) {\n cellFormat.textFormat.bold = request.bold;\n fields.push('textFormat.bold');\n }\n if (request.fontSize !== undefined) {\n cellFormat.textFormat.fontSize = request.fontSize;\n fields.push('textFormat.fontSize');\n }\n }\n\n // Horizontal alignment\n if (request.horizontalAlignment) {\n cellFormat.horizontalAlignment = request.horizontalAlignment;\n fields.push('horizontalAlignment');\n }\n\n // Number format\n if (request.numberFormat) {\n const numberFormat: sheets_v4.Schema$NumberFormat = {\n type: request.numberFormat.type,\n };\n if (request.numberFormat.pattern !== undefined) {\n numberFormat.pattern = request.numberFormat.pattern;\n }\n cellFormat.numberFormat = numberFormat;\n fields.push('numberFormat');\n }\n\n // Add repeatCell request for this range\n if (fields.length > 0) {\n batchRequests.push({\n repeatCell: {\n range: gridRange,\n cell: {\n userEnteredFormat: cellFormat,\n },\n fields: `userEnteredFormat(${fields.join(',')})`,\n },\n });\n }\n\n // Add border formatting if specified\n if (request.borders) {\n batchRequests.push({\n updateBorders: {\n range: gridRange,\n top: {\n style: request.borders.style,\n color: request.borders.color,\n },\n bottom: {\n style: request.borders.style,\n color: request.borders.color,\n },\n left: {\n style: request.borders.style,\n color: request.borders.color,\n },\n right: {\n style: request.borders.style,\n color: request.borders.color,\n },\n },\n });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse range for formatting', {\n range: request.range,\n error: message,\n });\n failedRanges.push({\n range: request.range,\n error: `Failed to parse range: ${message}`,\n });\n }\n }\n\n // Early return if all ranges failed\n if (batchRequests.length === 0) {\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: 0,\n failedRanges: failedRanges.length > 0 ? failedRanges : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n }\n\n logger.info('sheets.cells.format executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchRequestsCount: batchRequests.length,\n });\n\n // Execute the batch update\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: batchRequests,\n },\n });\n\n logger.info('sheets.cells.format completed successfully', {\n successCount: requests.length - failedRanges.length,\n failedCount: failedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: requests.length - failedRanges.length,\n failedRanges: failedRanges.length > 0 ? failedRanges : undefined,\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('Format cells operation failed', {\n id,\n gid,\n requestCount: requests.length,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error formatting cells: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'cells-format',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","z","googleAuth","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","parseA1Notation","rangeReferenceToGridRange","ColorSchema","object","red","number","min","max","describe","green","blue","NumberFormatSchema","type","enum","pattern","string","optional","BorderSchema","style","color","FormatRequestSchema","range","backgroundColor","textColor","bold","boolean","fontSize","int","horizontalAlignment","numberFormat","borders","inputSchema","id","gid","requests","array","successBranchSchema","literal","sheetTitle","sheetUrl","successCount","nonnegative","failedRanges","error","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","requestCount","length","sheet","spreadsheetResponse","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","title","batchRequests","request","rangeRef","gridRange","cellFormat","push","undefined","textFormat","foregroundColor","repeatCell","cell","userEnteredFormat","join","updateBorders","top","bottom","left","right","message","Error","content","text","JSON","stringify","structuredContent","batchRequestsCount","batchUpdate","requestBody","failedCount","InternalError","stack","createTool","name"],"mappings":"AAAA,SAAyBA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzE,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AAClH,SAASC,eAAe,EAAEC,y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,OAAO;QACLC,MAAM;QACN1D;QACAG;IACF;AACF"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { EnrichedExtra } from '@mcp-z/oauth-google';
|
|
2
|
+
import type { CallToolResult } from '@mcp-z/server';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
declare const inputSchema: z.ZodObject<{
|
|
5
|
+
id: z.ZodString;
|
|
6
|
+
gid: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>, z.ZodTransform<string, string | number>>;
|
|
7
|
+
ranges: z.ZodArray<z.ZodString>;
|
|
8
|
+
}, z.core.$strict>;
|
|
9
|
+
declare const outputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
10
|
+
type: z.ZodLiteral<"success">;
|
|
11
|
+
id: z.ZodString;
|
|
12
|
+
gid: z.ZodString;
|
|
13
|
+
metadata: z.ZodObject<{
|
|
14
|
+
spreadsheetId: z.ZodString;
|
|
15
|
+
sheets: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
16
|
+
properties: z.ZodOptional<z.ZodObject<{
|
|
17
|
+
sheetId: z.ZodOptional<z.ZodNumber>;
|
|
18
|
+
title: z.ZodOptional<z.ZodString>;
|
|
19
|
+
}, z.core.$loose>>;
|
|
20
|
+
data: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
21
|
+
startRow: z.ZodOptional<z.ZodNumber>;
|
|
22
|
+
startColumn: z.ZodOptional<z.ZodNumber>;
|
|
23
|
+
rowData: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
24
|
+
values: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
25
|
+
note: z.ZodOptional<z.ZodString>;
|
|
26
|
+
dataValidation: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
27
|
+
pivotTable: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
28
|
+
dataSourceTable: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
29
|
+
}, z.core.$loose>>>;
|
|
30
|
+
}, z.core.$loose>>>;
|
|
31
|
+
}, z.core.$loose>>>;
|
|
32
|
+
}, z.core.$loose>>>;
|
|
33
|
+
}, z.core.$loose>;
|
|
34
|
+
fieldMask: z.ZodString;
|
|
35
|
+
requestedRanges: z.ZodArray<z.ZodString>;
|
|
36
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
37
|
+
type: z.ZodLiteral<"auth_required">;
|
|
38
|
+
provider: z.ZodString;
|
|
39
|
+
message: z.ZodString;
|
|
40
|
+
url: z.ZodOptional<z.ZodString>;
|
|
41
|
+
}, z.core.$strip>], "type">;
|
|
42
|
+
export type Input = z.infer<typeof inputSchema>;
|
|
43
|
+
export type Output = z.infer<typeof outputSchema>;
|
|
44
|
+
declare function handler(input: Input, extra: EnrichedExtra): Promise<CallToolResult>;
|
|
45
|
+
export default function createTool(): {
|
|
46
|
+
name: string;
|
|
47
|
+
config: {
|
|
48
|
+
readonly description: "Read notes, data validation rules, pivot table and data-source table definitions in required finite ranges on one sheet. Preserves sparse row/column offsets. Excludes cell values, formulas and direct formatting. DATA_SOURCE and OBJECT sheets are unsupported.";
|
|
49
|
+
readonly annotations: {
|
|
50
|
+
readonly readOnlyHint: true;
|
|
51
|
+
};
|
|
52
|
+
readonly inputSchema: z.ZodObject<{
|
|
53
|
+
id: z.ZodString;
|
|
54
|
+
gid: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>, z.ZodTransform<string, string | number>>;
|
|
55
|
+
ranges: z.ZodArray<z.ZodString>;
|
|
56
|
+
}, z.core.$strict>;
|
|
57
|
+
readonly outputSchema: z.ZodObject<{
|
|
58
|
+
result: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
59
|
+
type: z.ZodLiteral<"success">;
|
|
60
|
+
id: z.ZodString;
|
|
61
|
+
gid: z.ZodString;
|
|
62
|
+
metadata: z.ZodObject<{
|
|
63
|
+
spreadsheetId: z.ZodString;
|
|
64
|
+
sheets: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
65
|
+
properties: z.ZodOptional<z.ZodObject<{
|
|
66
|
+
sheetId: z.ZodOptional<z.ZodNumber>;
|
|
67
|
+
title: z.ZodOptional<z.ZodString>;
|
|
68
|
+
}, z.core.$loose>>;
|
|
69
|
+
data: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
70
|
+
startRow: z.ZodOptional<z.ZodNumber>;
|
|
71
|
+
startColumn: z.ZodOptional<z.ZodNumber>;
|
|
72
|
+
rowData: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
73
|
+
values: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
74
|
+
note: z.ZodOptional<z.ZodString>;
|
|
75
|
+
dataValidation: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
76
|
+
pivotTable: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
77
|
+
dataSourceTable: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
78
|
+
}, z.core.$loose>>>;
|
|
79
|
+
}, z.core.$loose>>>;
|
|
80
|
+
}, z.core.$loose>>>;
|
|
81
|
+
}, z.core.$loose>>>;
|
|
82
|
+
}, z.core.$loose>;
|
|
83
|
+
fieldMask: z.ZodString;
|
|
84
|
+
requestedRanges: z.ZodArray<z.ZodString>;
|
|
85
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
86
|
+
type: z.ZodLiteral<"auth_required">;
|
|
87
|
+
provider: z.ZodString;
|
|
88
|
+
message: z.ZodString;
|
|
89
|
+
url: z.ZodOptional<z.ZodString>;
|
|
90
|
+
}, z.core.$strip>], "type">;
|
|
91
|
+
}, z.core.$strip>;
|
|
92
|
+
};
|
|
93
|
+
handler: typeof handler;
|
|
94
|
+
};
|
|
95
|
+
export {};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { sheets as sheetsApi } from '@googleapis/sheets';
|
|
2
|
+
import { schemas } from '@mcp-z/oauth-google';
|
|
3
|
+
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
6
|
+
import { SheetGidOutput, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.js';
|
|
7
|
+
import { calculateFiniteRangeCellCount } from '../../spreadsheet/range-operations.js';
|
|
8
|
+
const { AuthRequiredBranchSchema } = schemas;
|
|
9
|
+
const MAX_RANGES = 50;
|
|
10
|
+
const MAX_CELLS = 250000;
|
|
11
|
+
const FIELD_MASK = 'spreadsheetId,sheets(properties(sheetId,title),data(startRow,startColumn,rowData(values(note,dataValidation,pivotTable,dataSourceTable))))';
|
|
12
|
+
const rangesSchema = z.array(z.string().trim().min(1)).min(1).max(MAX_RANGES).superRefine((ranges, context)=>{
|
|
13
|
+
try {
|
|
14
|
+
const totalCells = ranges.reduce((sum, range)=>sum + calculateFiniteRangeCellCount(range), 0);
|
|
15
|
+
if (totalCells > MAX_CELLS) throw new Error(`Requested ranges exceed the ${MAX_CELLS.toLocaleString('en-US')} aggregate cell limit`);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
context.addIssue({
|
|
18
|
+
code: 'custom',
|
|
19
|
+
message: error instanceof Error ? error.message : String(error)
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
const inputSchema = z.object({
|
|
24
|
+
id: SpreadsheetIdSchema,
|
|
25
|
+
gid: z.union([
|
|
26
|
+
z.string().min(1),
|
|
27
|
+
z.number()
|
|
28
|
+
]).transform(String).describe('Sheet ID (from URL gid={gid})'),
|
|
29
|
+
ranges: rangesSchema.describe(`Required finite sheet-local A1 ranges, such as A1 or B2:D10, for notes, dataValidation, pivotTable and dataSourceTable. Maximum ${MAX_RANGES} ranges and ${MAX_CELLS.toLocaleString('en-US')} aggregate cells, counting overlapping ranges separately.`)
|
|
30
|
+
}).strict();
|
|
31
|
+
const definitionSchema = z.object({}).passthrough();
|
|
32
|
+
const cellSchema = z.object({
|
|
33
|
+
note: z.string().optional(),
|
|
34
|
+
dataValidation: definitionSchema.optional(),
|
|
35
|
+
pivotTable: definitionSchema.optional(),
|
|
36
|
+
dataSourceTable: definitionSchema.optional()
|
|
37
|
+
}).passthrough();
|
|
38
|
+
const metadataSchema = z.object({
|
|
39
|
+
spreadsheetId: z.string(),
|
|
40
|
+
sheets: z.array(z.object({
|
|
41
|
+
properties: z.object({
|
|
42
|
+
sheetId: z.number().int().optional(),
|
|
43
|
+
title: z.string().optional()
|
|
44
|
+
}).passthrough().optional(),
|
|
45
|
+
data: z.array(z.object({
|
|
46
|
+
startRow: z.number().int().nonnegative().optional(),
|
|
47
|
+
startColumn: z.number().int().nonnegative().optional(),
|
|
48
|
+
rowData: z.array(z.object({
|
|
49
|
+
values: z.array(cellSchema).optional()
|
|
50
|
+
}).passthrough()).optional()
|
|
51
|
+
}).passthrough()).optional()
|
|
52
|
+
}).passthrough()).optional()
|
|
53
|
+
}).passthrough();
|
|
54
|
+
const outputSchema = z.discriminatedUnion('type', [
|
|
55
|
+
z.object({
|
|
56
|
+
type: z.literal('success'),
|
|
57
|
+
id: SpreadsheetIdOutput,
|
|
58
|
+
gid: SheetGidOutput,
|
|
59
|
+
metadata: metadataSchema.describe('Selected Google cell metadata with sheet identity and sparse GridData offsets. Omitted startRow/startColumn mean zero; empty rows and cells retain their positions. Values and direct formatting are excluded.'),
|
|
60
|
+
fieldMask: z.string(),
|
|
61
|
+
requestedRanges: z.array(z.string()).describe('Sheet-qualified A1 ranges sent to Google, in request order.')
|
|
62
|
+
}),
|
|
63
|
+
AuthRequiredBranchSchema
|
|
64
|
+
]);
|
|
65
|
+
const config = {
|
|
66
|
+
description: 'Read notes, data validation rules, pivot table and data-source table definitions in required finite ranges on one sheet. Preserves sparse row/column offsets. Excludes cell values, formulas and direct formatting. DATA_SOURCE and OBJECT sheets are unsupported.',
|
|
67
|
+
annotations: {
|
|
68
|
+
readOnlyHint: true
|
|
69
|
+
},
|
|
70
|
+
inputSchema,
|
|
71
|
+
outputSchema: z.object({
|
|
72
|
+
result: outputSchema
|
|
73
|
+
})
|
|
74
|
+
};
|
|
75
|
+
async function handler(input, extra) {
|
|
76
|
+
const parsed = inputSchema.safeParse(input);
|
|
77
|
+
if (!parsed.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, parsed.error.message);
|
|
78
|
+
const { id, gid, ranges } = parsed.data;
|
|
79
|
+
const logger = extra.logger;
|
|
80
|
+
logger.info('sheets.cells.metadata.get called', {
|
|
81
|
+
id,
|
|
82
|
+
gid,
|
|
83
|
+
rangeCount: ranges.length
|
|
84
|
+
});
|
|
85
|
+
try {
|
|
86
|
+
var _preflight_data_sheets_find, _preflight_data_sheets;
|
|
87
|
+
const sheets = sheetsApi({
|
|
88
|
+
version: 'v4',
|
|
89
|
+
auth: googleAuth(extra.authContext.auth)
|
|
90
|
+
});
|
|
91
|
+
// Resolve the title and type without fetching structures. DATA_SOURCE sheets cannot accept specific ranges.
|
|
92
|
+
const preflight = await sheets.spreadsheets.get({
|
|
93
|
+
spreadsheetId: id,
|
|
94
|
+
fields: 'sheets(properties(sheetId,title,sheetType))'
|
|
95
|
+
});
|
|
96
|
+
const properties = (_preflight_data_sheets = preflight.data.sheets) === null || _preflight_data_sheets === void 0 ? void 0 : (_preflight_data_sheets_find = _preflight_data_sheets.find((sheet)=>{
|
|
97
|
+
var _sheet_properties;
|
|
98
|
+
return String((_sheet_properties = sheet.properties) === null || _sheet_properties === void 0 ? void 0 : _sheet_properties.sheetId) === gid;
|
|
99
|
+
})) === null || _preflight_data_sheets_find === void 0 ? void 0 : _preflight_data_sheets_find.properties;
|
|
100
|
+
if (!properties) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);
|
|
101
|
+
if (properties.sheetType === 'DATA_SOURCE' || properties.sheetType === 'OBJECT') {
|
|
102
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Cell metadata ranges are not supported on ${properties.sheetType} sheets: ${gid}`);
|
|
103
|
+
}
|
|
104
|
+
if (properties.title == null) throw new Error(`Sheet title not available for ${gid}`);
|
|
105
|
+
const title = `'${properties.title.replace(/'/g, "''")}'`;
|
|
106
|
+
const requestedRanges = ranges.map((range)=>`${title}!${range}`);
|
|
107
|
+
const response = await sheets.spreadsheets.get({
|
|
108
|
+
spreadsheetId: id,
|
|
109
|
+
fields: FIELD_MASK,
|
|
110
|
+
ranges: requestedRanges
|
|
111
|
+
});
|
|
112
|
+
const result = outputSchema.parse({
|
|
113
|
+
type: 'success',
|
|
114
|
+
id,
|
|
115
|
+
gid,
|
|
116
|
+
metadata: response.data,
|
|
117
|
+
fieldMask: FIELD_MASK,
|
|
118
|
+
requestedRanges
|
|
119
|
+
});
|
|
120
|
+
logger.info('sheets.cells.metadata.get success', {
|
|
121
|
+
id,
|
|
122
|
+
gid,
|
|
123
|
+
rangeCount: ranges.length
|
|
124
|
+
});
|
|
125
|
+
return {
|
|
126
|
+
content: [
|
|
127
|
+
{
|
|
128
|
+
type: 'text',
|
|
129
|
+
text: JSON.stringify(result)
|
|
130
|
+
}
|
|
131
|
+
],
|
|
132
|
+
structuredContent: {
|
|
133
|
+
result
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (error instanceof ProtocolError) throw error;
|
|
138
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
139
|
+
logger.error('sheets.cells.metadata.get error', {
|
|
140
|
+
id,
|
|
141
|
+
gid,
|
|
142
|
+
error: message
|
|
143
|
+
});
|
|
144
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting cell metadata: ${message}`, {
|
|
145
|
+
stack: error instanceof Error ? error.stack : undefined
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
export default function createTool() {
|
|
150
|
+
return {
|
|
151
|
+
name: 'cells-metadata-get',
|
|
152
|
+
config,
|
|
153
|
+
handler
|
|
154
|
+
};
|
|
155
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/cells-metadata-get.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidOutput, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { calculateFiniteRangeCellCount } from '../../spreadsheet/range-operations.ts';\n\nconst { AuthRequiredBranchSchema } = schemas;\nconst MAX_RANGES = 50;\nconst MAX_CELLS = 250_000;\nconst FIELD_MASK = 'spreadsheetId,sheets(properties(sheetId,title),data(startRow,startColumn,rowData(values(note,dataValidation,pivotTable,dataSourceTable))))';\n\nconst rangesSchema = z\n .array(z.string().trim().min(1))\n .min(1)\n .max(MAX_RANGES)\n .superRefine((ranges, context) => {\n try {\n const totalCells = ranges.reduce((sum, range) => sum + calculateFiniteRangeCellCount(range), 0);\n if (totalCells > MAX_CELLS) throw new Error(`Requested ranges exceed the ${MAX_CELLS.toLocaleString('en-US')} aggregate cell limit`);\n } catch (error) {\n context.addIssue({ code: 'custom', message: error instanceof Error ? error.message : String(error) });\n }\n });\nconst inputSchema = z\n .object({\n id: SpreadsheetIdSchema,\n gid: z\n .union([z.string().min(1), z.number()])\n .transform(String)\n .describe('Sheet ID (from URL gid={gid})'),\n ranges: rangesSchema.describe(`Required finite sheet-local A1 ranges, such as A1 or B2:D10, for notes, dataValidation, pivotTable and dataSourceTable. Maximum ${MAX_RANGES} ranges and ${MAX_CELLS.toLocaleString('en-US')} aggregate cells, counting overlapping ranges separately.`),\n })\n .strict();\nconst definitionSchema = z.object({}).passthrough();\nconst cellSchema = z\n .object({\n note: z.string().optional(),\n dataValidation: definitionSchema.optional(),\n pivotTable: definitionSchema.optional(),\n dataSourceTable: definitionSchema.optional(),\n })\n .passthrough();\nconst metadataSchema = z\n .object({\n spreadsheetId: z.string(),\n sheets: z\n .array(\n z\n .object({\n properties: z.object({ sheetId: z.number().int().optional(), title: z.string().optional() }).passthrough().optional(),\n data: z\n .array(\n z\n .object({\n startRow: z.number().int().nonnegative().optional(),\n startColumn: z.number().int().nonnegative().optional(),\n rowData: z.array(z.object({ values: z.array(cellSchema).optional() }).passthrough()).optional(),\n })\n .passthrough()\n )\n .optional(),\n })\n .passthrough()\n )\n .optional(),\n })\n .passthrough();\nconst outputSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n metadata: metadataSchema.describe('Selected Google cell metadata with sheet identity and sparse GridData offsets. Omitted startRow/startColumn mean zero; empty rows and cells retain their positions. Values and direct formatting are excluded.'),\n fieldMask: z.string(),\n requestedRanges: z.array(z.string()).describe('Sheet-qualified A1 ranges sent to Google, in request order.'),\n }),\n AuthRequiredBranchSchema,\n]);\nconst config = {\n description: 'Read notes, data validation rules, pivot table and data-source table definitions in required finite ranges on one sheet. Preserves sparse row/column offsets. Excludes cell values, formulas and direct formatting. DATA_SOURCE and OBJECT sheets are unsupported.',\n annotations: { readOnlyHint: true },\n inputSchema,\n outputSchema: z.object({ result: outputSchema }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler(input: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const parsed = inputSchema.safeParse(input);\n if (!parsed.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, parsed.error.message);\n const { id, gid, ranges } = parsed.data;\n const logger = extra.logger;\n logger.info('sheets.cells.metadata.get called', { id, gid, rangeCount: ranges.length });\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n // Resolve the title and type without fetching structures. DATA_SOURCE sheets cannot accept specific ranges.\n const preflight = await sheets.spreadsheets.get({ spreadsheetId: id, fields: 'sheets(properties(sheetId,title,sheetType))' });\n const properties = preflight.data.sheets?.find((sheet) => String(sheet.properties?.sheetId) === gid)?.properties;\n if (!properties) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n if (properties.sheetType === 'DATA_SOURCE' || properties.sheetType === 'OBJECT') {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Cell metadata ranges are not supported on ${properties.sheetType} sheets: ${gid}`);\n }\n if (properties.title == null) throw new Error(`Sheet title not available for ${gid}`);\n const title = `'${properties.title.replace(/'/g, \"''\")}'`;\n const requestedRanges = ranges.map((range) => `${title}!${range}`);\n const response = await sheets.spreadsheets.get({ spreadsheetId: id, fields: FIELD_MASK, ranges: requestedRanges });\n const result: Output = outputSchema.parse({ type: 'success', id, gid, metadata: response.data, fieldMask: FIELD_MASK, requestedRanges });\n logger.info('sheets.cells.metadata.get success', { id, gid, rangeCount: ranges.length });\n return {\n content: [{ type: 'text', text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n if (error instanceof ProtocolError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.cells.metadata.get error', { id, gid, error: message });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting cell metadata: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return { name: 'cells-metadata-get', config, handler } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","ProtocolError","ProtocolErrorCode","z","googleAuth","SheetGidOutput","SpreadsheetIdOutput","SpreadsheetIdSchema","calculateFiniteRangeCellCount","AuthRequiredBranchSchema","MAX_RANGES","MAX_CELLS","FIELD_MASK","rangesSchema","array","string","trim","min","max","superRefine","ranges","context","totalCells","reduce","sum","range","Error","toLocaleString","error","addIssue","code","message","String","inputSchema","object","id","gid","union","number","transform","describe","strict","definitionSchema","passthrough","cellSchema","note","optional","dataValidation","pivotTable","dataSourceTable","metadataSchema","spreadsheetId","properties","sheetId","int","title","data","startRow","nonnegative","startColumn","rowData","values","outputSchema","discriminatedUnion","type","literal","metadata","fieldMask","requestedRanges","config","description","annotations","readOnlyHint","result","handler","input","extra","parsed","safeParse","success","InvalidParams","logger","info","rangeCount","length","preflight","version","auth","authContext","spreadsheets","get","fields","find","sheet","sheetType","replace","map","response","parse","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool","name"],"mappings":"AAAA,SAASA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzD,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,SAASC,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,cAAc,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,yBAAyB;AAClG,SAASC,6BAA6B,QAAQ,wCAAwC;AAEtF,MAAM,EAAEC,wBAAwB,EAAE,GAAGT;AACrC,MAAMU,aAAa;AACnB,MAAMC,YAAY;AAClB,MAAMC,aAAa;AAEnB,MAAMC,eAAeV,EAClBW,KAAK,CAACX,EAAEY,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,IAC5BA,GAAG,CAAC,GACJC,GAAG,CAACR,YACJS,WAAW,CAAC,CAACC,QAAQC;IACpB,IAAI;QACF,MAAMC,aAAaF,OAAOG,MAAM,CAAC,CAACC,KAAKC,QAAUD,MAAMhB,8BAA8BiB,QAAQ;QAC7F,IAAIH,aAAaX,WAAW,MAAM,IAAIe,MAAM,CAAC,4BAA4B,EAAEf,UAAUgB,cAAc,CAAC,SAAS,qBAAqB,CAAC;IACrI,EAAE,OAAOC,OAAO;QACdP,QAAQQ,QAAQ,CAAC;YAAEC,MAAM;YAAUC,SAASH,iBAAiBF,QAAQE,MAAMG,OAAO,GAAGC,OAAOJ;QAAO;IACrG;AACF;AACF,MAAMK,cAAc9B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O;QACd,IAAIA,iBAAiB3B,eAAe,MAAM2B;QAC1C,MAAMG,UAAUH,iBAAiBF,QAAQE,MAAMG,OAAO,GAAGC,OAAOJ;QAChEqD,OAAOrD,KAAK,CAAC,mCAAmC;YAAEO;YAAIC;YAAKR,OAAOG;QAAQ;QAC1E,MAAM,IAAI9B,cAAcC,kBAAkBsG,aAAa,EAAE,CAAC,6BAA6B,EAAEzE,SAAS,EAAE;YAClG0E,OAAO7E,iBAAiBF,QAAQE,MAAM6E,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QAAEC,MAAM;QAAsBvC;QAAQK;IAAQ;AACvD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/chart-create.ts"],"sourcesContent":["import { type sheets_v4, sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\n// Input schema for chart position\nconst ChartPositionSchema = z.object({\n anchorCell: z.string().min(1).describe('A1 notation cell where chart top-left anchors (e.g., \"F2\")'),\n offsetX: z.number().int().default(0).describe('Horizontal pixel offset from anchor'),\n offsetY: z.number().int().default(0).describe('Vertical pixel offset from anchor'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n chartType: z.enum(['PIE', 'BAR', 'COLUMN', 'LINE']).describe('Type of chart to create'),\n dataRange: z.string().min(1).describe('A1 notation range containing chart data including headers (e.g., \"A1:C10\")'),\n title: z.string().optional().describe('Chart title displayed at top'),\n position: ChartPositionSchema,\n legend: z.enum(['BOTTOM', 'RIGHT', 'TOP', 'LEFT', 'NONE']).default('BOTTOM').describe('Legend position'),\n is3D: z.boolean().default(false).describe('Render as 3D chart (PIE only)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Title of the sheet containing the chart'),\n sheetUrl: z.string().describe('URL of the sheet containing the chart'),\n chartId: z.number().int().describe('Unique chart ID for future updates/deletion'),\n anchorCell: z.string().describe('Where chart was anchored'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Create charts (pie, bar, column, line) from spreadsheet data ranges. Charts anchor to specific cells with optional pixel offsets. Data range should include headers. PIE charts use 2 columns (labels, values). BAR/COLUMN/LINE charts use first row as headers. Best for visualizing spreadsheet data.',\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// Parse A1 notation anchor cell to row/column indices\nfunction parseAnchorCell(anchorCell: string): { rowIndex: number; columnIndex: number } {\n // Simple A1 notation parser for single cells\n const match = anchorCell.match(/^([A-Z]+)(\\d+)$/);\n if (!match || !match[1] || !match[2]) {\n throw new Error(`Invalid anchor cell format: ${anchorCell}`);\n }\n\n const colLetters = match[1];\n const rowNumber = match[2];\n\n // Convert column letters to index (A=0, B=1, ..., Z=25, AA=26, etc.)\n let columnIndex = 0;\n for (let i = 0; i < colLetters.length; i++) {\n columnIndex = columnIndex * 26 + (colLetters.charCodeAt(i) - 65 + 1);\n }\n columnIndex--; // Convert to 0-based\n\n // Convert row number to index (1-based to 0-based)\n const rowIndex = Number.parseInt(rowNumber, 10) - 1;\n\n return { rowIndex, columnIndex };\n}\n\nasync function handler({ id, gid, chartType, dataRange, title, position, legend = 'BOTTOM', is3D = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.chart.create called', {\n id,\n gid,\n chartType,\n dataRange,\n title,\n position,\n legend,\n is3D,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for chart create', { id, gid, chartType });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).\n const sheetId = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Validate 3D only for PIE charts\n // Note: Google Sheets API only supports 3D for PIE charts, not COLUMN/BAR/LINE\n if (is3D && chartType !== 'PIE') {\n logger.info('3D mode not supported for this chart type', {\n chartType,\n is3D,\n });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `3D mode is only supported for PIE charts, not ${chartType}`);\n }\n\n // Parse anchor cell to row/column indices\n let anchorRowIndex: number;\n let anchorColumnIndex: number;\n try {\n const anchorIndices = parseAnchorCell(position.anchorCell);\n anchorRowIndex = anchorIndices.rowIndex;\n anchorColumnIndex = anchorIndices.columnIndex;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse anchor cell', {\n anchorCell: position.anchorCell,\n error: message,\n });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Failed to parse anchor cell: ${message}`);\n }\n\n // Parse data range to grid range\n let dataGridRange: sheets_v4.Schema$GridRange;\n try {\n const rangeRef = parseA1Notation(dataRange);\n dataGridRange = rangeReferenceToGridRange(rangeRef, sheetId);\n\n // Validate that required properties are defined for chart creation\n if (dataGridRange.startColumnIndex === undefined || dataGridRange.startColumnIndex === null) {\n throw new Error('Data range must include column information');\n }\n if (dataGridRange.endColumnIndex === undefined || dataGridRange.endColumnIndex === null) {\n throw new Error('Data range must include column information');\n }\n if (dataGridRange.startRowIndex === undefined || dataGridRange.startRowIndex === null) {\n throw new Error('Data range must include row information');\n }\n if (dataGridRange.endRowIndex === undefined || dataGridRange.endRowIndex === null) {\n throw new Error('Data range must include row information');\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse data range', {\n dataRange,\n error: message,\n });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Failed to parse data range: ${message}`);\n }\n\n // Extract validated properties with defined types\n const dataStartRowIndex = dataGridRange.startRowIndex as number;\n const dataEndRowIndex = dataGridRange.endRowIndex as number;\n const dataStartColumnIndex = dataGridRange.startColumnIndex as number;\n const dataEndColumnIndex = dataGridRange.endColumnIndex as number;\n const dataSheetId = dataGridRange.sheetId ?? sheetId;\n\n // Build chart spec with properly split domain and series ranges\n let chartSpec: sheets_v4.Schema$ChartSpec;\n\n logger.info('Building chart spec', {\n chartType,\n dataGridRange,\n sheetId,\n });\n\n // Map legend position to API format (add _LEGEND suffix)\n const legendPositionMap: Record<string, string> = {\n BOTTOM: 'BOTTOM_LEGEND',\n RIGHT: 'RIGHT_LEGEND',\n TOP: 'TOP_LEGEND',\n LEFT: 'LEFT_LEGEND',\n NONE: 'NO_LEGEND',\n };\n const apiLegendPosition = legendPositionMap[legend] || 'BOTTOM_LEGEND';\n\n if (chartType === 'PIE') {\n // PIE charts use a separate pieChart property, not basicChart\n const baseSheetId = dataSheetId;\n\n const domainRange = {\n sheetId: baseSheetId,\n startRowIndex: dataStartRowIndex,\n endRowIndex: dataEndRowIndex,\n startColumnIndex: dataStartColumnIndex,\n endColumnIndex: dataStartColumnIndex + 1, // First column only (labels)\n };\n\n const seriesRange = {\n sheetId: baseSheetId,\n startRowIndex: dataStartRowIndex,\n endRowIndex: dataEndRowIndex,\n startColumnIndex: dataStartColumnIndex + 1, // Second column (values)\n endColumnIndex: dataStartColumnIndex + 2,\n };\n\n logger.info('PIE chart ranges', {\n dataGridRange,\n domainRange,\n seriesRange,\n apiLegendPosition,\n });\n\n chartSpec = {\n pieChart: {\n // Use pieChart for PIE charts\n legendPosition: legend === 'NONE' ? 'NO_LEGEND' : apiLegendPosition,\n domain: {\n // Note: domain/series are direct objects, not arrays\n sourceRange: {\n sources: [domainRange],\n },\n },\n series: {\n sourceRange: {\n sources: [seriesRange],\n },\n },\n threeDimensional: is3D, // 3D is directly on pieChart\n },\n };\n if (title) {\n chartSpec.title = title;\n }\n } else {\n // For BAR, COLUMN, LINE charts: domain is first column, each subsequent column is a series\n const baseSheetId = dataSheetId;\n\n const domainRange = {\n sheetId: baseSheetId,\n startRowIndex: dataStartRowIndex,\n endRowIndex: dataEndRowIndex,\n startColumnIndex: dataStartColumnIndex,\n endColumnIndex: dataStartColumnIndex + 1, // First column only\n };\n\n // Calculate number of data columns (excluding the first domain column)\n const numDataColumns = dataEndColumnIndex - dataStartColumnIndex - 1;\n const series = [];\n\n // Create a series for each data column\n for (let i = 0; i < numDataColumns; i++) {\n const seriesRange = {\n sheetId: baseSheetId,\n startRowIndex: dataStartRowIndex,\n endRowIndex: dataEndRowIndex,\n startColumnIndex: dataStartColumnIndex + 1 + i,\n endColumnIndex: dataStartColumnIndex + 2 + i,\n };\n\n series.push({\n series: {\n sourceRange: {\n sources: [seriesRange],\n },\n },\n });\n }\n\n // If no data columns were found, default to using the entire range as a fallback\n if (series.length === 0) {\n series.push({\n series: {\n sourceRange: {\n sources: [dataGridRange],\n },\n },\n });\n }\n\n const basicChart: sheets_v4.Schema$BasicChartSpec = {\n chartType, // BAR, COLUMN, LINE are valid for basicChart\n headerCount: 1, // First row is headers\n // Note: Google Sheets API does not support threeDimensional for basicChart (BAR/COLUMN/LINE)\n // threeDimensional is only supported for pieChart\n domains: [\n {\n domain: {\n sourceRange: {\n sources: [domainRange],\n },\n },\n },\n ],\n series,\n };\n if (legend !== 'NONE') {\n basicChart.legendPosition = apiLegendPosition;\n }\n\n chartSpec = { basicChart };\n if (title) {\n chartSpec.title = title;\n }\n }\n\n // Build embedded object position\n const embeddedObjectPosition = {\n overlayPosition: {\n anchorCell: {\n sheetId,\n rowIndex: anchorRowIndex,\n columnIndex: anchorColumnIndex,\n },\n offsetXPixels: position.offsetX,\n offsetYPixels: position.offsetY,\n },\n };\n\n const requestBody = {\n requests: [\n {\n addChart: {\n chart: {\n spec: chartSpec,\n position: embeddedObjectPosition,\n },\n },\n },\n ],\n };\n\n logger.info('sheets.chart.create executing addChart request', {\n spreadsheetId: id,\n sheetTitle,\n chartType,\n dataRange,\n anchorCell: position.anchorCell,\n requestBody: JSON.stringify(requestBody),\n });\n\n // Execute the addChart request\n const response = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody,\n });\n\n // Extract chart ID from response\n const replies = response.data.replies || [];\n if (replies.length === 0 || !replies[0]?.addChart?.chart?.chartId) {\n logger.error('Chart creation failed - no chart ID returned', {\n spreadsheetId: id,\n sheetTitle,\n chartType,\n });\n throw new ProtocolError(ProtocolErrorCode.InternalError, 'Chart creation failed: no chart ID returned from Google Sheets API');\n }\n\n const chartId = replies[0].addChart.chart.chartId;\n\n logger.info('sheets.chart.create completed successfully', {\n chartId,\n chartType,\n anchorCell: position.anchorCell,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n chartId,\n anchorCell: position.anchorCell,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (e) {\n const error = e as Error & { response?: { data?: unknown; status?: number } };\n const message = error.message || String(e);\n logger.error('Chart create operation failed', {\n id,\n gid,\n chartType,\n dataRange,\n error: message,\n response: error.response?.data,\n status: error.response?.status,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error creating chart: ${message}`, {\n stack: e instanceof Error ? e.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'chart-create',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","z","googleAuth","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","parseA1Notation","rangeReferenceToGridRange","ChartPositionSchema","object","anchorCell","string","min","describe","offsetX","number","int","default","offsetY","inputSchema","id","gid","chartType","enum","dataRange","title","optional","position","legend","is3D","boolean","successBranchSchema","type","literal","sheetTitle","sheetUrl","chartId","outputSchema","discriminatedUnion","config","description","result","parseAnchorCell","match","Error","colLetters","rowNumber","columnIndex","i","length","charCodeAt","rowIndex","Number","parseInt","handler","extra","logger","info","sheet","dataGridRange","spreadsheetResponse","replies","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","anchorRowIndex","anchorColumnIndex","anchorIndices","error","message","rangeRef","startColumnIndex","undefined","endColumnIndex","startRowIndex","endRowIndex","dataStartRowIndex","dataEndRowIndex","dataStartColumnIndex","dataEndColumnIndex","dataSheetId","chartSpec","legendPositionMap","BOTTOM","RIGHT","TOP","LEFT","NONE","apiLegendPosition","baseSheetId","domainRange","seriesRange","pieChart","legendPosition","domain","sourceRange","sources","series","threeDimensional","numDataColumns","push","basicChart","headerCount","domains","embeddedObjectPosition","overlayPosition","offsetXPixels","offsetYPixels","requestBody","requests","addChart","chart","spec","JSON","stringify","response","batchUpdate","InternalError","content","text","structuredContent","e","status","stack","createTool","name"],"mappings":"AAAA,SAAyBA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzE,SAASC,O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AG;YASErD,iBACFA;QATV,MAAMA,QAAQqD;QACd,MAAMpD,UAAUD,MAAMC,OAAO,IAAIR,OAAO4D;QACxC5E,OAAOuB,KAAK,CAAC,iCAAiC;YAC5C3D;YACAC;YACAC;YACAE;YACAuD,OAAOC;YACP8C,QAAQ,GAAE/C,kBAAAA,MAAM+C,QAAQ,cAAd/C,sCAAAA,gBAAgBV,IAAI;YAC9BgE,MAAM,GAAEtD,mBAAAA,MAAM+C,QAAQ,cAAd/C,uCAAAA,iBAAgBsD,MAAM;QAChC;QAEA,MAAM,IAAIvI,cAAcC,kBAAkBiI,aAAa,EAAE,CAAC,sBAAsB,EAAEhD,SAAS,EAAE;YAC3FsD,OAAOF,aAAaxF,QAAQwF,EAAEE,KAAK,GAAGnD;QACxC;IACF;AACF;AAEA,eAAe,SAASoD;IACtB,OAAO;QACLC,MAAM;QACNjG;QACAe;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/chart-create.ts"],"sourcesContent":["import { type sheets_v4, sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\n// Input schema for chart position\nconst ChartPositionSchema = z.object({\n anchorCell: z.string().min(1).describe('A1 notation cell where chart top-left anchors (e.g., \"F2\")'),\n offsetX: z.number().int().default(0).describe('Horizontal pixel offset from anchor'),\n offsetY: z.number().int().default(0).describe('Vertical pixel offset from anchor'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n chartType: z.enum(['PIE', 'BAR', 'COLUMN', 'LINE']).describe('Type of chart to create'),\n dataRange: z.string().min(1).describe('A1 notation range containing chart data including headers (e.g., \"A1:C10\")'),\n title: z.string().optional().describe('Chart title displayed at top'),\n position: ChartPositionSchema,\n legend: z.enum(['BOTTOM', 'RIGHT', 'TOP', 'LEFT', 'NONE']).default('BOTTOM').describe('Legend position'),\n is3D: z.boolean().default(false).describe('Render as 3D chart (PIE only)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Title of the sheet containing the chart'),\n sheetUrl: z.string().describe('URL of the sheet containing the chart'),\n chartId: z.number().int().describe('Unique chart ID for future updates/deletion'),\n anchorCell: z.string().describe('Where chart was anchored'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Create charts (pie, bar, column, line) from spreadsheet data ranges. Charts anchor to specific cells with optional pixel offsets. Data range should include headers. PIE charts use 2 columns (labels, values). BAR/COLUMN/LINE charts use first row as headers. Best for visualizing spreadsheet data.',\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// Parse A1 notation anchor cell to row/column indices\nfunction parseAnchorCell(anchorCell: string): { rowIndex: number; columnIndex: number } {\n // Simple A1 notation parser for single cells\n const match = anchorCell.match(/^([A-Z]+)(\\d+)$/);\n if (!match || !match[1] || !match[2]) {\n throw new Error(`Invalid anchor cell format: ${anchorCell}`);\n }\n\n const colLetters = match[1];\n const rowNumber = match[2];\n\n // Convert column letters to index (A=0, B=1, ..., Z=25, AA=26, etc.)\n let columnIndex = 0;\n for (let i = 0; i < colLetters.length; i++) {\n columnIndex = columnIndex * 26 + (colLetters.charCodeAt(i) - 65 + 1);\n }\n columnIndex--; // Convert to 0-based\n\n // Convert row number to index (1-based to 0-based)\n const rowIndex = Number.parseInt(rowNumber, 10) - 1;\n\n return { rowIndex, columnIndex };\n}\n\nasync function handler({ id, gid, chartType, dataRange, title, position, legend = 'BOTTOM', is3D = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.chart.create called', {\n id,\n gid,\n chartType,\n dataRange,\n title,\n position,\n legend,\n is3D,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for chart create', { id, gid, chartType });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).\n const sheetId = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Validate 3D only for PIE charts\n // Note: Google Sheets API only supports 3D for PIE charts, not COLUMN/BAR/LINE\n if (is3D && chartType !== 'PIE') {\n logger.info('3D mode not supported for this chart type', {\n chartType,\n is3D,\n });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `3D mode is only supported for PIE charts, not ${chartType}`);\n }\n\n // Parse anchor cell to row/column indices\n let anchorRowIndex: number;\n let anchorColumnIndex: number;\n try {\n const anchorIndices = parseAnchorCell(position.anchorCell);\n anchorRowIndex = anchorIndices.rowIndex;\n anchorColumnIndex = anchorIndices.columnIndex;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse anchor cell', {\n anchorCell: position.anchorCell,\n error: message,\n });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Failed to parse anchor cell: ${message}`);\n }\n\n // Parse data range to grid range\n let dataGridRange: sheets_v4.Schema$GridRange;\n try {\n const rangeRef = parseA1Notation(dataRange);\n dataGridRange = rangeReferenceToGridRange(rangeRef, sheetId);\n\n // Validate that required properties are defined for chart creation\n if (dataGridRange.startColumnIndex === undefined || dataGridRange.startColumnIndex === null) {\n throw new Error('Data range must include column information');\n }\n if (dataGridRange.endColumnIndex === undefined || dataGridRange.endColumnIndex === null) {\n throw new Error('Data range must include column information');\n }\n if (dataGridRange.startRowIndex === undefined || dataGridRange.startRowIndex === null) {\n throw new Error('Data range must include row information');\n }\n if (dataGridRange.endRowIndex === undefined || dataGridRange.endRowIndex === null) {\n throw new Error('Data range must include row information');\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse data range', {\n dataRange,\n error: message,\n });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Failed to parse data range: ${message}`);\n }\n\n // Extract validated properties with defined types\n const dataStartRowIndex = dataGridRange.startRowIndex as number;\n const dataEndRowIndex = dataGridRange.endRowIndex as number;\n const dataStartColumnIndex = dataGridRange.startColumnIndex as number;\n const dataEndColumnIndex = dataGridRange.endColumnIndex as number;\n const dataSheetId = dataGridRange.sheetId ?? sheetId;\n\n // Build chart spec with properly split domain and series ranges\n let chartSpec: sheets_v4.Schema$ChartSpec;\n\n logger.info('Building chart spec', {\n chartType,\n dataGridRange,\n sheetId,\n });\n\n // Map legend position to API format (add _LEGEND suffix)\n const legendPositionMap: Record<string, string> = {\n BOTTOM: 'BOTTOM_LEGEND',\n RIGHT: 'RIGHT_LEGEND',\n TOP: 'TOP_LEGEND',\n LEFT: 'LEFT_LEGEND',\n NONE: 'NO_LEGEND',\n };\n const apiLegendPosition = legendPositionMap[legend] || 'BOTTOM_LEGEND';\n\n if (chartType === 'PIE') {\n // PIE charts use a separate pieChart property, not basicChart\n const baseSheetId = dataSheetId;\n\n const domainRange = {\n sheetId: baseSheetId,\n startRowIndex: dataStartRowIndex,\n endRowIndex: dataEndRowIndex,\n startColumnIndex: dataStartColumnIndex,\n endColumnIndex: dataStartColumnIndex + 1, // First column only (labels)\n };\n\n const seriesRange = {\n sheetId: baseSheetId,\n startRowIndex: dataStartRowIndex,\n endRowIndex: dataEndRowIndex,\n startColumnIndex: dataStartColumnIndex + 1, // Second column (values)\n endColumnIndex: dataStartColumnIndex + 2,\n };\n\n logger.info('PIE chart ranges', {\n dataGridRange,\n domainRange,\n seriesRange,\n apiLegendPosition,\n });\n\n chartSpec = {\n pieChart: {\n // Use pieChart for PIE charts\n legendPosition: legend === 'NONE' ? 'NO_LEGEND' : apiLegendPosition,\n domain: {\n // Note: domain/series are direct objects, not arrays\n sourceRange: {\n sources: [domainRange],\n },\n },\n series: {\n sourceRange: {\n sources: [seriesRange],\n },\n },\n threeDimensional: is3D, // 3D is directly on pieChart\n },\n };\n if (title) {\n chartSpec.title = title;\n }\n } else {\n // For BAR, COLUMN, LINE charts: domain is first column, each subsequent column is a series\n const baseSheetId = dataSheetId;\n\n const domainRange = {\n sheetId: baseSheetId,\n startRowIndex: dataStartRowIndex,\n endRowIndex: dataEndRowIndex,\n startColumnIndex: dataStartColumnIndex,\n endColumnIndex: dataStartColumnIndex + 1, // First column only\n };\n\n // Calculate number of data columns (excluding the first domain column)\n const numDataColumns = dataEndColumnIndex - dataStartColumnIndex - 1;\n const series = [];\n\n // Create a series for each data column\n for (let i = 0; i < numDataColumns; i++) {\n const seriesRange = {\n sheetId: baseSheetId,\n startRowIndex: dataStartRowIndex,\n endRowIndex: dataEndRowIndex,\n startColumnIndex: dataStartColumnIndex + 1 + i,\n endColumnIndex: dataStartColumnIndex + 2 + i,\n };\n\n series.push({\n series: {\n sourceRange: {\n sources: [seriesRange],\n },\n },\n });\n }\n\n // If no data columns were found, default to using the entire range as a fallback\n if (series.length === 0) {\n series.push({\n series: {\n sourceRange: {\n sources: [dataGridRange],\n },\n },\n });\n }\n\n const basicChart: sheets_v4.Schema$BasicChartSpec = {\n chartType, // BAR, COLUMN, LINE are valid for basicChart\n headerCount: 1, // First row is headers\n // Note: Google Sheets API does not support threeDimensional for basicChart (BAR/COLUMN/LINE)\n // threeDimensional is only supported for pieChart\n domains: [\n {\n domain: {\n sourceRange: {\n sources: [domainRange],\n },\n },\n },\n ],\n series,\n };\n if (legend !== 'NONE') {\n basicChart.legendPosition = apiLegendPosition;\n }\n\n chartSpec = { basicChart };\n if (title) {\n chartSpec.title = title;\n }\n }\n\n // Build embedded object position\n const embeddedObjectPosition = {\n overlayPosition: {\n anchorCell: {\n sheetId,\n rowIndex: anchorRowIndex,\n columnIndex: anchorColumnIndex,\n },\n offsetXPixels: position.offsetX,\n offsetYPixels: position.offsetY,\n },\n };\n\n const requestBody = {\n requests: [\n {\n addChart: {\n chart: {\n spec: chartSpec,\n position: embeddedObjectPosition,\n },\n },\n },\n ],\n };\n\n logger.info('sheets.chart.create executing addChart request', {\n spreadsheetId: id,\n sheetTitle,\n chartType,\n dataRange,\n anchorCell: position.anchorCell,\n requestBody: JSON.stringify(requestBody),\n });\n\n // Execute the addChart request\n const response = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody,\n });\n\n // Extract chart ID from response\n const replies = response.data.replies || [];\n if (replies.length === 0 || !replies[0]?.addChart?.chart?.chartId) {\n logger.error('Chart creation failed - no chart ID returned', {\n spreadsheetId: id,\n sheetTitle,\n chartType,\n });\n throw new ProtocolError(ProtocolErrorCode.InternalError, 'Chart creation failed: no chart ID returned from Google Sheets API');\n }\n\n const chartId = replies[0].addChart.chart.chartId;\n\n logger.info('sheets.chart.create completed successfully', {\n chartId,\n chartType,\n anchorCell: position.anchorCell,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n chartId,\n anchorCell: position.anchorCell,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (e) {\n const error = e as Error & { response?: { data?: unknown; status?: number } };\n const message = error.message || String(e);\n logger.error('Chart create operation failed', {\n id,\n gid,\n chartType,\n dataRange,\n error: message,\n response: error.response?.data,\n status: error.response?.status,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error creating chart: ${message}`, {\n stack: e instanceof Error ? e.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'chart-create',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","z","googleAuth","SheetGidOutput","SheetGidSchema","SpreadsheetIdOutput","SpreadsheetIdSchema","parseA1Notation","rangeReferenceToGridRange","ChartPositionSchema","object","anchorCell","string","min","describe","offsetX","number","int","default","offsetY","inputSchema","id","gid","chartType","enum","dataRange","title","optional","position","legend","is3D","boolean","successBranchSchema","type","literal","sheetTitle","sheetUrl","chartId","outputSchema","discriminatedUnion","config","description","result","parseAnchorCell","match","Error","colLetters","rowNumber","columnIndex","i","length","charCodeAt","rowIndex","Number","parseInt","handler","extra","logger","info","sheet","dataGridRange","spreadsheetResponse","replies","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","anchorRowIndex","anchorColumnIndex","anchorIndices","error","message","rangeRef","startColumnIndex","undefined","endColumnIndex","startRowIndex","endRowIndex","dataStartRowIndex","dataEndRowIndex","dataStartColumnIndex","dataEndColumnIndex","dataSheetId","chartSpec","legendPositionMap","BOTTOM","RIGHT","TOP","LEFT","NONE","apiLegendPosition","baseSheetId","domainRange","seriesRange","pieChart","legendPosition","domain","sourceRange","sources","series","threeDimensional","numDataColumns","push","basicChart","headerCount","domains","embeddedObjectPosition","overlayPosition","offsetXPixels","offsetYPixels","requestBody","requests","addChart","chart","spec","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MAAM;oBAAiBkG,MAAMN,KAAKC,SAAS,CAACpF;gBAAQ;aAAE;YAClE0F,mBAAmB;gBAAE1F;YAAO;QAC9B;IACF,EAAE,OAAO2F,GAAG;YASErD,iBACFA;QATV,MAAMA,QAAQqD;QACd,MAAMpD,UAAUD,MAAMC,OAAO,IAAIR,OAAO4D;QACxC5E,OAAOuB,KAAK,CAAC,iCAAiC;YAC5C3D;YACAC;YACAC;YACAE;YACAuD,OAAOC;YACP8C,QAAQ,GAAE/C,kBAAAA,MAAM+C,QAAQ,cAAd/C,sCAAAA,gBAAgBV,IAAI;YAC9BgE,MAAM,GAAEtD,mBAAAA,MAAM+C,QAAQ,cAAd/C,uCAAAA,iBAAgBsD,MAAM;QAChC;QAEA,MAAM,IAAIvI,cAAcC,kBAAkBiI,aAAa,EAAE,CAAC,sBAAsB,EAAEhD,SAAS,EAAE;YAC3FsD,OAAOF,aAAaxF,QAAQwF,EAAEE,KAAK,GAAGnD;QACxC;IACF;AACF;AAEA,eAAe,SAASoD;IACtB,OAAO;QACLC,MAAM;QACNjG;QACAe;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/columns-get.ts"],"sourcesContent":["/** Get column names from Google Sheet (peek at first row only) */\n\nimport { sheets as sheetsApi } from '@googleapis/sheets';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.'),\n});\n\n// Success branch schema - uses columns: for consistency with standard vocabulary\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n columns: z.array(z.string()).describe('First row values (column names) or empty if no rows'),\n isEmpty: z.boolean().describe('True if sheet has zero rows'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Get first row from Google Sheet. Returns columns array and isEmpty flag.',\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, render }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.debug?.('sheets.columns.get called', { id, gid, render });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(extra.authContext.auth) });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? '';\n\n // Read first row only (A1:ZZZ1 should cover most reasonable sheets)\n const range = `'${sheetTitle}'!A1:ZZZ1`;\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n\n const rows = response.data.values || [];\n const isEmpty = rows.length === 0;\n\n // Extract first row and convert to strings (column names)\n const firstRow = rows[0] || [];\n const columns = firstRow.map((value) => String(value ?? ''));\n\n const result: Output = {\n type: 'success' as const,\n columns,\n isEmpty,\n };\n\n logger.info?.('sheets.columns.get completed', { id, gid, columnCount: columns.length, isEmpty });\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.get error', { error: message });\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting sheet columns: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'columns-get',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["sheets","sheetsApi","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","z","googleAuth","SheetGidSchema","SpreadsheetIdSchema","inputSchema","object","id","gid","render","enum","optional","describe","successBranchSchema","type","literal","columns","array","string","isEmpty","boolean","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","debug","sheet","spreadsheetResponse","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","InvalidParams","sheetTitle","title","range","response","values","valueRenderOption","rows","length","firstRow","map","value","info","columnCount","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","stack","undefined","createTool","name"],"mappings":"AAAA,gEAAgE,GAEhE,SAASA,UAAUC,SAAS,QAAQ,qBAAqB;AAEzD,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AACtD,SAASC,cAAc,EAAEC,mBAAmB,QAAQ,yBAAyB;AAE7E,MAAMC,cAAcJ,EAAEK,MAAM,CAAC;IAC3BC,IAAIH;IACJI,KAAKL;IACLM,QAAQR,EAAES,IAAI,CAAC;QAAC;QAAmB;QAAqB;KAAU,EAAEC,QAAQ,GAAGC,QAAQ,CAAC;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