File size: 9,121 Bytes
7dc28be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import type { FastMCP } from 'fastmcp';
import { UserError } from 'fastmcp';
import { z } from 'zod';
import { getSheetsClient } from '../../clients.js';
import * as SheetsHelpers from '../../googleSheetsApiHelpers.js';

export function register(server: FastMCP) {
  server.addTool({
    name: 'insertChart',
    description:
      'Inserts a chart into a Google Sheet. Supports bar, column, line, area, scatter, pie, donut, and treemap (hierarchical) chart types. ' +
      'For treemap charts, the data must have a label column and a parent label column (use empty string for root nodes) plus a numeric size column. ' +
      'Chart is placed as an overlay at the specified anchor cell.',
    parameters: z.strictObject({
      spreadsheetId: z
        .string()
        .describe(
          'The spreadsheet ID — the long string between /d/ and /edit in a Google Sheets URL.'
        ),
      sheetName: z
        .string()
        .optional()
        .describe('Name of the sheet/tab containing the data. Defaults to the first sheet.'),
      chartType: z
        .enum(['BAR', 'COLUMN', 'LINE', 'AREA', 'SCATTER', 'PIE', 'DONUT', 'TREEMAP'])
        .describe('Chart type to create.'),
      stackedType: z
        .enum(['NOT_STACKED', 'STACKED', 'PERCENT_STACKED'])
        .default('NOT_STACKED')
        .describe(
          'For bar/column/area charts: whether to stack series. NOT_STACKED = grouped, STACKED = absolute stacked, PERCENT_STACKED = 100% stacked.'
        ),
      title: z.string().optional().describe('Chart title.'),
      dataRange: z
        .string()
        .describe(
          'A1 notation range of the data (e.g., "A1:E50"). Include the header row if present.'
        ),
      headerRow: z
        .boolean()
        .default(true)
        .describe('Whether the first row of the data range is a header row.'),
      // Column indices for flexible data mapping
      labelColumnIndex: z
        .number()
        .int()
        .min(1)
        .optional()
        .describe(
          'For pie/donut/treemap: 1-based column index for node labels (default: 1). For treemap this is the leaf/child label.'
        ),
      parentColumnIndex: z
        .number()
        .int()
        .min(1)
        .optional()
        .describe(
          'For treemap: 1-based column index for parent node labels. Root nodes should have an empty string in this column.'
        ),
      valueColumnIndex: z
        .number()
        .int()
        .min(1)
        .optional()
        .describe(
          'For pie/donut/treemap: 1-based column index for the numeric size/value (default: 2).'
        ),
      // Chart position and size
      anchorRow: z
        .number()
        .int()
        .min(0)
        .default(0)
        .describe('Row index (0-based) of the anchor cell for chart placement.'),
      anchorColumn: z
        .number()
        .int()
        .min(0)
        .default(6)
        .describe('Column index (0-based) of the anchor cell for chart placement.'),
      offsetXPixels: z
        .number()
        .int()
        .default(0)
        .describe('Horizontal offset in pixels from the anchor cell.'),
      offsetYPixels: z
        .number()
        .int()
        .default(0)
        .describe('Vertical offset in pixels from the anchor cell.'),
      widthPixels: z.number().int().default(600).describe('Chart width in pixels.'),
      heightPixels: z.number().int().default(400).describe('Chart height in pixels.'),
    }),
    execute: async (args, { log }) => {
      const sheets = await getSheetsClient();
      log.info(`Inserting ${args.chartType} chart into spreadsheet ${args.spreadsheetId}`);

      try {
        const sheetId = await SheetsHelpers.resolveSheetId(
          sheets,
          args.spreadsheetId,
          args.sheetName
        );

        const { a1Range } = SheetsHelpers.parseRange(args.dataRange);
        const gridRange = SheetsHelpers.parseA1ToGridRange(a1Range, sheetId);

        const startRow = gridRange.startRowIndex ?? 0;
        const endRow = gridRange.endRowIndex ?? startRow + 1;
        const startCol = gridRange.startColumnIndex ?? 0;
        const endCol = gridRange.endColumnIndex ?? startCol + 1;
        const dataStartRow = args.headerRow ? startRow + 1 : startRow;

        const labelCol = startCol + (args.labelColumnIndex ? args.labelColumnIndex - 1 : 0);
        const valueCol = startCol + (args.valueColumnIndex ? args.valueColumnIndex - 1 : 1);
        const parentCol = startCol + (args.parentColumnIndex ? args.parentColumnIndex - 1 : 0);

        const makeSourceRange = (colStart: number, colEnd: number, rowStart = dataStartRow) => ({
          sources: [
            {
              sheetId,
              startRowIndex: rowStart,
              endRowIndex: endRow,
              startColumnIndex: colStart,
              endColumnIndex: colEnd,
            },
          ],
        });

        let chartSpec: Record<string, unknown> = {};

        if (args.chartType === 'PIE' || args.chartType === 'DONUT') {
          chartSpec.pieChart = {
            legendPosition: 'LABELED_LEGEND',
            pieHole: args.chartType === 'DONUT' ? 0.5 : 0,
            domain: {
              data: { sourceRange: makeSourceRange(labelCol, labelCol + 1) },
            },
            series: {
              data: { sourceRange: makeSourceRange(valueCol, valueCol + 1) },
            },
          };
        } else if (args.chartType === 'TREEMAP') {
          chartSpec.treemapChart = {
            labels: {
              sourceRange: makeSourceRange(labelCol, labelCol + 1),
            },
            parentLabels: {
              sourceRange: makeSourceRange(parentCol, parentCol + 1),
            },
            sizeData: {
              sourceRange: makeSourceRange(valueCol, valueCol + 1),
            },
            colorData: {
              sourceRange: makeSourceRange(valueCol, valueCol + 1),
            },
          };
        } else {
          // Basic chart types: BAR, COLUMN, LINE, AREA, SCATTER
          // Each series must be a separate entry with a single-column source range.
          const seriesCount = endCol - startCol - 1;
          const series = Array.from({ length: seriesCount }, (_, i) => ({
            series: {
              sourceRange: {
                sources: [
                  {
                    sheetId,
                    startRowIndex: startRow, // include header so Sheets names the series automatically
                    endRowIndex: endRow,
                    startColumnIndex: startCol + 1 + i,
                    endColumnIndex: startCol + 2 + i,
                  },
                ],
              },
            },
            targetAxis: 'LEFT_AXIS',
          }));

          chartSpec.basicChart = {
            chartType: args.chartType,
            stackedType: args.stackedType,
            legendPosition: 'BOTTOM_LEGEND',
            axis: [
              { position: 'BOTTOM_AXIS', title: '' },
              { position: 'LEFT_AXIS', title: '' },
            ],
            domains: [
              {
                domain: {
                  sourceRange: {
                    sources: [
                      {
                        sheetId,
                        startRowIndex: startRow,
                        endRowIndex: endRow,
                        startColumnIndex: startCol,
                        endColumnIndex: startCol + 1,
                      },
                    ],
                  },
                },
                reversed: false,
              },
            ],
            series,
            headerCount: args.headerRow ? 1 : 0,
          };
        }

        if (args.title) {
          chartSpec.title = args.title;
        }

        const response = await sheets.spreadsheets.batchUpdate({
          spreadsheetId: args.spreadsheetId,
          requestBody: {
            requests: [
              {
                addChart: {
                  chart: {
                    spec: chartSpec,
                    position: {
                      overlayPosition: {
                        anchorCell: {
                          sheetId,
                          rowIndex: args.anchorRow,
                          columnIndex: args.anchorColumn,
                        },
                        offsetXPixels: args.offsetXPixels,
                        offsetYPixels: args.offsetYPixels,
                        widthPixels: args.widthPixels,
                        heightPixels: args.heightPixels,
                      },
                    },
                  },
                },
              },
            ],
          },
        });

        const chartId = response.data.replies?.[0]?.addChart?.chart?.chartId;
        return `Chart created successfully${chartId ? ` (Chart ID: ${chartId})` : ''}.`;
      } catch (error: any) {
        log.error(`Error inserting chart: ${error.message || error}`);
        if (error instanceof UserError) throw error;
        throw new UserError(`Failed to insert chart: ${error.message || 'Unknown error'}`);
      }
    },
  });
}