File size: 10,380 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
import type { FastMCP } from 'fastmcp';
import { UserError } from 'fastmcp';
import { z } from 'zod';
import { docs_v1 } from 'googleapis';
import { getDocsClient } from '../../clients.js';
import { DocumentIdParameter } from '../../types.js';
import * as GDocsHelpers from '../../googleDocsApiHelpers.js';
import { buildInsertTableWithDataRequests } from './insertTableWithData.js';
import { extractDocumentTables, extractTableSnapshot } from './structureHelpers.js';

const CLONE_TABLE_SOURCE_FIELDS =
  'body(content(startIndex,endIndex,table(rows,columns,tableStyle(tableColumnProperties(width,widthType)),tableRows(startIndex,endIndex,tableRowStyle(minRowHeight,preventOverflow,tableHeader),tableCells(startIndex,endIndex,tableCellStyle(backgroundColor,borderTop(color,width,dashStyle),borderBottom(color,width,dashStyle),borderLeft(color,width,dashStyle),borderRight(color,width,dashStyle),contentAlignment,paddingTop,paddingBottom,paddingLeft,paddingRight,rowSpan,columnSpan),content(paragraph(elements(startIndex,endIndex,textRun(content,textStyle(bold))))))))),tabs(tabProperties(tabId,title),documentTab(body(content(startIndex,endIndex,table(rows,columns,tableStyle(tableColumnProperties(width,widthType)),tableRows(startIndex,endIndex,tableRowStyle(minRowHeight,preventOverflow,tableHeader),tableCells(startIndex,endIndex,tableCellStyle(backgroundColor,borderTop(color,width,dashStyle),borderBottom(color,width,dashStyle),borderLeft(color,width,dashStyle),borderRight(color,width,dashStyle),contentAlignment,paddingTop,paddingBottom,paddingLeft,paddingRight,rowSpan,columnSpan),content(paragraph(elements(startIndex,endIndex,textRun(content,textStyle(bold))))))))))))';

const CloneTableParameters = DocumentIdParameter.extend({
  sourceDocumentId: z.string().min(1).describe('Document ID containing the source table template.'),
  sourceTableId: z.string().min(1).describe('Source MCP table ID from listDocumentTables.'),
  index: z
    .number()
    .int()
    .min(1)
    .describe(
      '1-based character index in the target document where the cloned table should be inserted.'
    ),
  sourceTabId: z.string().optional().describe('Optional tab ID for the source document table.'),
  targetTabId: z
    .string()
    .optional()
    .describe('Optional tab ID for the target document insertion point.'),
  copyColumnWidths: z
    .boolean()
    .optional()
    .default(true)
    .describe('Copy fixed column widths from the source table.'),
  copyRowStyles: z
    .boolean()
    .optional()
    .default(true)
    .describe('Copy row min height and overflow settings from the source table.'),
  copyCellStyles: z
    .boolean()
    .optional()
    .default(true)
    .describe('Copy cell-level formatting such as background, padding, alignment, and borders.'),
  copyPinnedHeaderRows: z
    .boolean()
    .optional()
    .default(true)
    .describe('Copy pinned header rows from the source table when present.'),
  copyHeaderBold: z
    .boolean()
    .optional()
    .default(true)
    .describe('Apply bold text to cloned cells whose source cell text was bold.'),
});

export function register(server: FastMCP) {
  server.addTool({
    name: 'cloneTable',
    description:
      'Clones a source Google Docs table into a target document, preserving text, column widths, row styles, cell styles, and pinned header rows where supported.',
    parameters: CloneTableParameters,
    execute: async (args, { log }) => {
      const docs = await getDocsClient();
      log.info(
        `Cloning table ${args.sourceTableId} from ${args.sourceDocumentId} into ${args.documentId} at index ${args.index}`
      );

      try {
        const sourceRes = await docs.documents.get({
          documentId: args.sourceDocumentId,
          includeTabsContent: true,
          fields: CLONE_TABLE_SOURCE_FIELDS,
        });

        const snapshot = extractTableSnapshot(sourceRes.data, args.sourceTableId, args.sourceTabId);
        if (!snapshot) {
          throw new UserError(
            `Source table "${args.sourceTableId}" was not found in source document ${args.sourceDocumentId}.`
          );
        }
        if (snapshot.rowCount === 0 || snapshot.columnCount === 0) {
          throw new UserError(
            `Source table "${args.sourceTableId}" is empty and cannot be cloned.`
          );
        }

        if (args.targetTabId) {
          const targetInfo = await docs.documents.get({
            documentId: args.documentId,
            includeTabsContent: true,
            fields: 'tabs(tabProperties,documentTab(body))',
          });
          const targetTab = GDocsHelpers.findTabById(targetInfo.data, args.targetTabId);
          if (!targetTab)
            throw new UserError(`Target tab "${args.targetTabId}" not found in document.`);
          if (!targetTab.documentTab) {
            throw new UserError(`Target tab "${args.targetTabId}" does not have document content.`);
          }
        }

        const insertRequests = buildInsertTableWithDataRequests(
          snapshot.data,
          args.index,
          false,
          args.targetTabId
        );
        await GDocsHelpers.executeBatchUpdateWithSplitting(
          docs,
          args.documentId,
          insertRequests,
          log
        );

        const targetRes = await docs.documents.get({
          documentId: args.documentId,
          includeTabsContent: true,
          fields:
            'body(content(startIndex,endIndex,table(rows,columns,tableRows(tableCells(startIndex,endIndex,content(paragraph(elements(startIndex,endIndex,textRun(content))))))))),tabs(tabProperties(tabId,title),documentTab(body(content(startIndex,endIndex,table(rows,columns,tableRows(tableCells(startIndex,endIndex,content(paragraph(elements(startIndex,endIndex,textRun(content)))))))))))',
        });

        const targetTable = extractDocumentTables(targetRes.data, args.targetTabId)
          .filter(
            (table) =>
              table.startIndex != null &&
              table.startIndex >= args.index &&
              table.rowCount === snapshot.rowCount &&
              table.columnCount === snapshot.columnCount
          )
          .sort(
            (a, b) =>
              (a.startIndex ?? Number.MAX_SAFE_INTEGER) - (b.startIndex ?? Number.MAX_SAFE_INTEGER)
          )[0];
        if (!targetTable || targetTable.startIndex == null) {
          throw new UserError(
            'Cloned target table was inserted, but could not be re-located safely for style copying.'
          );
        }

        const styleRequests: docs_v1.Schema$Request[] = [];

        if (args.copyColumnWidths) {
          for (const columnStyle of snapshot.columnStyles) {
            if (columnStyle.widthType !== 'FIXED_WIDTH' || !columnStyle.widthPt) continue;
            styleRequests.push(
              GDocsHelpers.buildTableColumnWidthRequest(
                targetTable.startIndex,
                [columnStyle.columnIndex],
                columnStyle.widthPt,
                args.targetTabId
              )
            );
          }
        }

        if (args.copyRowStyles) {
          for (const rowStyle of snapshot.rowStyles) {
            const request = GDocsHelpers.buildTableRowStyleRequest(
              targetTable.startIndex,
              [rowStyle.rowIndex],
              rowStyle.minRowHeightPt,
              rowStyle.preventOverflow,
              args.targetTabId
            );
            if (request) styleRequests.push(request);
          }
        }

        if (args.copyPinnedHeaderRows && snapshot.pinnedHeaderRowsCount > 0) {
          styleRequests.push(
            GDocsHelpers.buildPinTableHeaderRowsRequest(
              targetTable.startIndex,
              snapshot.pinnedHeaderRowsCount,
              args.targetTabId
            )
          );
        }

        if (args.copyCellStyles) {
          for (const cellStyle of snapshot.cellStyles) {
            const requestInfo = GDocsHelpers.buildTableCellStyleRequest(
              targetTable.startIndex,
              cellStyle.rowIndex,
              cellStyle.columnIndex,
              {
                backgroundColor: cellStyle.backgroundColor,
                contentAlignment: cellStyle.contentAlignment ?? undefined,
                paddingTopPt: cellStyle.paddingTopPt,
                paddingBottomPt: cellStyle.paddingBottomPt,
                paddingLeftPt: cellStyle.paddingLeftPt,
                paddingRightPt: cellStyle.paddingRightPt,
                borderTop: cellStyle.borderTop,
                borderBottom: cellStyle.borderBottom,
                borderLeft: cellStyle.borderLeft,
                borderRight: cellStyle.borderRight,
              },
              args.targetTabId
            );
            if (requestInfo) styleRequests.push(requestInfo.request);
          }
        }

        if (args.copyHeaderBold) {
          for (const cellStyle of snapshot.cellStyles) {
            if (!cellStyle.hasBoldText) continue;
            const targetCell = targetTable.cells.find(
              (cell) =>
                cell.rowIndex === cellStyle.rowIndex && cell.columnIndex === cellStyle.columnIndex
            );
            if (!targetCell?.contentStartIndex) continue;

            const targetText = snapshot.data[cellStyle.rowIndex]?.[cellStyle.columnIndex] ?? '';
            if (!targetText) continue;

            const requestInfo = GDocsHelpers.buildUpdateTextStyleRequest(
              targetCell.contentStartIndex,
              targetCell.contentStartIndex + targetText.length,
              { bold: true },
              args.targetTabId
            );
            if (requestInfo) styleRequests.push(requestInfo.request);
          }
        }

        if (styleRequests.length > 0) {
          await GDocsHelpers.executeBatchUpdateWithSplitting(
            docs,
            args.documentId,
            styleRequests,
            log
          );
        }

        return `Successfully cloned ${args.sourceTableId} into ${args.documentId} at index ${args.index}.`;
      } catch (error: any) {
        log.error(
          `Error cloning table ${args.sourceTableId} from ${args.sourceDocumentId}: ${error.message || error}`
        );
        if (error instanceof UserError) throw error;
        throw new UserError(`Failed to clone table: ${error.message || 'Unknown error'}`);
      }
    },
  });
}