@alanse/mcp-server-google-workspace 0.2.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +109 -5
  2. package/dist/auth.js +1 -0
  3. package/dist/index.js +1 -1
  4. package/dist/lib/document-id-resolver.js +76 -0
  5. package/dist/lib/response-formatter.js +82 -0
  6. package/dist/lib/validation.js +112 -0
  7. package/dist/tools/docs/basic/gdocs_create.js +37 -0
  8. package/dist/tools/docs/basic/gdocs_get_metadata.js +45 -0
  9. package/dist/tools/docs/basic/gdocs_list_documents.js +59 -0
  10. package/dist/tools/docs/basic/gdocs_read.js +62 -0
  11. package/dist/tools/docs/content/gdocs_append_text.js +57 -0
  12. package/dist/tools/docs/content/gdocs_apply_style.js +86 -0
  13. package/dist/tools/docs/content/gdocs_create_heading.js +89 -0
  14. package/dist/tools/docs/content/gdocs_create_list.js +86 -0
  15. package/dist/tools/docs/content/gdocs_delete_text.js +64 -0
  16. package/dist/tools/docs/content/gdocs_format_text.js +137 -0
  17. package/dist/tools/docs/content/gdocs_insert_text.js +62 -0
  18. package/dist/tools/docs/content/gdocs_replace_text.js +64 -0
  19. package/dist/tools/docs/content/gdocs_set_alignment.js +76 -0
  20. package/dist/tools/docs/content/gdocs_update_text.js +78 -0
  21. package/dist/tools/docs/elements/gdocs_batch_update.js +108 -0
  22. package/dist/tools/docs/elements/gdocs_create_table.js +73 -0
  23. package/dist/tools/docs/elements/gdocs_export.js +62 -0
  24. package/dist/tools/docs/elements/gdocs_insert_image.js +96 -0
  25. package/dist/tools/docs/elements/gdocs_insert_link.js +77 -0
  26. package/dist/tools/docs/elements/gdocs_insert_page_break.js +55 -0
  27. package/dist/tools/docs/elements/gdocs_insert_toc.js +71 -0
  28. package/dist/tools/docs/elements/gdocs_merge_documents.js +104 -0
  29. package/dist/tools/docs/elements/gdocs_suggest_mode.js +41 -0
  30. package/dist/tools/index.js +119 -0
  31. package/package.json +1 -1
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # MCP Server - Google Workspace
2
2
 
3
- **The most comprehensive MCP server for Google Workspace** - Complete programmatic control over Sheets, Drive, and future Docs, Calendar, Forms integration.
3
+ **The most comprehensive MCP server for Google Workspace** - Complete programmatic control over Sheets, Docs, Drive, and future Calendar, Forms integration.
4
4
 
5
- 🚀 **Current Status**: 59 tools (Drive: 2, Sheets: 57)
6
- 📅 **Roadmap**: Google Docs, Calendar, Forms, Gmail, Slides
5
+ 🚀 **Current Status**: 82 tools (Drive: 2, Sheets: 57, Docs: 23)
6
+ 📅 **Roadmap**: Calendar, Forms, Gmail, Slides
7
7
 
8
8
  Extended implementation by Alanse inc.
9
9
 
@@ -11,15 +11,34 @@ Extended implementation by Alanse inc.
11
11
 
12
12
  ## 🚀 Features
13
13
 
14
- ### 📊 Extended Google Sheets API Implementation
14
+ ### 📊 Extended Google Workspace API Implementation
15
15
 
16
- **59 Total Tools** = 2 GDrive + **57 Google Sheets** operations
16
+ **82 Total Tools** = 2 GDrive + **57 Google Sheets** + **23 Google Docs** operations
17
17
 
18
18
  #### Tool Categories
19
19
 
20
20
  **Google Drive Operations (2 tools)**
21
21
  - Search & File Management
22
22
 
23
+ **Google Docs Operations (23 tools)**
24
+
25
+ **Basic Operations (4 tools)**
26
+ - Create, Read, Get Metadata, List Documents
27
+
28
+ **Content & Formatting (10 tools)**
29
+ - Insert/Update/Delete/Replace/Append Text
30
+ - Format Text (Bold, Italic, Font, Color)
31
+ - Create Headings (H1-H6)
32
+ - Create Lists (Bulleted/Numbered)
33
+ - Set Paragraph Alignment & Apply Styles
34
+
35
+ **Elements & Advanced (9 tools)**
36
+ - Insert Images, Tables, Page Breaks, Links
37
+ - Insert Table of Contents
38
+ - Batch Update Operations
39
+ - Merge Documents, Export to PDF/DOCX/HTML
40
+ - Suggestion Mode
41
+
23
42
  **Sheet Management (13 tools)**
24
43
  - Create, Read, List, Add, Delete, Rename Sheets
25
44
  - Insert/Delete Rows & Columns
@@ -155,6 +174,91 @@ Replace `<YOUR_CLIENT_ID>`, `<YOUR_CLIENT_SECRET>`, and `/path/to/config/directo
155
174
 
156
175
  **Goal**: 100+ tools covering the entire Google Workspace ecosystem
157
176
 
177
+ ## 🛠️ Development
178
+
179
+ ### Prerequisites
180
+
181
+ - Node.js 20 or higher
182
+ - npm or pnpm
183
+ - Google Cloud Platform account with OAuth credentials
184
+
185
+ ### Local Development
186
+
187
+ ```bash
188
+ # Clone the repository
189
+ git clone https://github.com/alanse-inc/mcp-server-google-workspace.git
190
+ cd mcp-server-google-workspace
191
+
192
+ # Install dependencies
193
+ npm install
194
+
195
+ # Build the project
196
+ npm run build
197
+
198
+ # Run tests
199
+ npm test
200
+
201
+ # Watch mode for development
202
+ npm run watch
203
+ ```
204
+
205
+ ### Testing
206
+
207
+ The project uses [Vitest](https://vitest.dev/) for testing:
208
+
209
+ ```bash
210
+ # Run all tests
211
+ npm test
212
+
213
+ # Watch mode
214
+ npm run test:watch
215
+
216
+ # UI mode
217
+ npm run test:ui
218
+
219
+ # Coverage report
220
+ npm run test:coverage
221
+ ```
222
+
223
+ ### Release Process
224
+
225
+ This project uses [release-please](https://github.com/googleapis/release-please) for automated releases.
226
+
227
+ **How it works:**
228
+
229
+ 1. Follow [Conventional Commits](https://www.conventionalcommits.org/) specification for commit messages
230
+ 2. When commits are merged to `main`, release-please creates/updates a release PR
231
+ 3. Merging the release PR triggers:
232
+ - CHANGELOG.md update
233
+ - Version bump in package.json
234
+ - GitHub Release creation
235
+ - npm package publication
236
+
237
+ **Commit message format:**
238
+
239
+ ```text
240
+ feat: add new feature
241
+ fix: fix a bug
242
+ docs: update documentation
243
+ chore: update dependencies
244
+ refactor: code refactoring
245
+ test: add tests
246
+ ```
247
+
248
+ **Example workflow:**
249
+
250
+ ```bash
251
+ # Make changes
252
+ git checkout -b feature/new-tool
253
+ # ... make changes ...
254
+ git commit -m "feat: add gdocs_insert_table tool"
255
+ git push origin feature/new-tool
256
+
257
+ # Create PR and merge to main
258
+ # → release-please creates a release PR automatically
259
+ # → Merge the release PR to publish
260
+ ```
261
+
158
262
  ## 📄 License
159
263
 
160
264
  This project is licensed under the **Elastic License 2.0**.
package/dist/auth.js CHANGED
@@ -5,6 +5,7 @@ import path from "path";
5
5
  export const SCOPES = [
6
6
  "https://www.googleapis.com/auth/drive.readonly",
7
7
  "https://www.googleapis.com/auth/spreadsheets",
8
+ "https://www.googleapis.com/auth/documents",
8
9
  ];
9
10
  // Get credentials directory from environment variable or use default
10
11
  const CREDS_DIR = process.env.GWORKSPACE_CREDS_DIR ||
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { tools } from "./tools/index.js";
9
9
  const drive = google.drive("v3");
10
10
  const server = new Server({
11
11
  name: "@alanse/mcp-server-google-workspace",
12
- version: "0.2.1",
12
+ version: "0.2.2",
13
13
  }, {
14
14
  capabilities: {
15
15
  resources: {
@@ -0,0 +1,76 @@
1
+ /**
2
+ * DocumentIdResolver - Resolves various document ID formats across Google Workspace
3
+ *
4
+ * Supports:
5
+ * - Direct document IDs
6
+ * - Full Google Workspace URLs (Docs, Sheets, Slides, Drive)
7
+ * - Service type detection
8
+ */
9
+ export class DocumentIdResolver {
10
+ static URL_PATTERNS = {
11
+ docs: /docs\.google\.com\/document\/d\/([a-zA-Z0-9-_]+)/,
12
+ sheets: /docs\.google\.com\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/,
13
+ slides: /docs\.google\.com\/presentation\/d\/([a-zA-Z0-9-_]+)/,
14
+ drive: /drive\.google\.com\/file\/d\/([a-zA-Z0-9-_]+)/,
15
+ };
16
+ static ID_PATTERN = /^[a-zA-Z0-9-_]{25,}$/;
17
+ /**
18
+ * Resolve a document reference from ID or URL
19
+ */
20
+ static resolve(input) {
21
+ // Try URL extraction first
22
+ const fromUrl = this.extractFromUrl(input);
23
+ if (fromUrl) {
24
+ return { id: fromUrl.id, type: fromUrl.type, url: input };
25
+ }
26
+ // Validate as direct ID
27
+ if (this.validate(input)) {
28
+ return { id: input, type: "unknown" };
29
+ }
30
+ throw new Error(`Invalid document reference: ${input}. Expected a Google Workspace URL or document ID.`);
31
+ }
32
+ /**
33
+ * Extract document ID from Google Workspace URL
34
+ */
35
+ static extractFromUrl(url) {
36
+ for (const [type, pattern] of Object.entries(this.URL_PATTERNS)) {
37
+ const match = url.match(pattern);
38
+ if (match) {
39
+ return {
40
+ id: match[1],
41
+ type: type,
42
+ };
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+ /**
48
+ * Validate document ID format
49
+ */
50
+ static validate(id, type) {
51
+ if (!this.ID_PATTERN.test(id)) {
52
+ return false;
53
+ }
54
+ // Additional type-specific validation could go here
55
+ return true;
56
+ }
57
+ /**
58
+ * Get service type from URL or ID
59
+ */
60
+ static getServiceType(input) {
61
+ const ref = this.resolve(input);
62
+ return ref.type;
63
+ }
64
+ /**
65
+ * Create a Google Workspace URL from document ID and type
66
+ */
67
+ static createUrl(documentId, type) {
68
+ const urlTemplates = {
69
+ docs: `https://docs.google.com/document/d/${documentId}/edit`,
70
+ sheets: `https://docs.google.com/spreadsheets/d/${documentId}/edit`,
71
+ slides: `https://docs.google.com/presentation/d/${documentId}/edit`,
72
+ drive: `https://drive.google.com/file/d/${documentId}/view`,
73
+ };
74
+ return urlTemplates[type];
75
+ }
76
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * ResponseFormatter - Consistent response formatting across all tools
3
+ */
4
+ export class ResponseFormatter {
5
+ /**
6
+ * Create a success response
7
+ */
8
+ static success(data, message) {
9
+ let text;
10
+ if (message) {
11
+ // If message is provided, combine it with data
12
+ if (typeof data === "object" && data !== null) {
13
+ text = `${message}\n\n${JSON.stringify(data, null, 2)}`;
14
+ }
15
+ else {
16
+ text = message;
17
+ }
18
+ }
19
+ else {
20
+ // Format data only
21
+ text = typeof data === "object" && data !== null
22
+ ? JSON.stringify(data, null, 2)
23
+ : String(data);
24
+ }
25
+ return {
26
+ content: [{ type: "text", text }],
27
+ isError: false,
28
+ };
29
+ }
30
+ /**
31
+ * Create an error response
32
+ */
33
+ static error(error) {
34
+ const message = error instanceof Error ? error.message : error;
35
+ return {
36
+ content: [
37
+ {
38
+ type: "text",
39
+ text: `Error: ${message}`,
40
+ },
41
+ ],
42
+ isError: true,
43
+ };
44
+ }
45
+ /**
46
+ * Format Google Docs document data
47
+ */
48
+ static formatDocumentData(doc) {
49
+ const formatted = {
50
+ documentId: doc.documentId,
51
+ title: doc.title,
52
+ revisionId: doc.revisionId,
53
+ suggestionsViewMode: doc.suggestionsViewMode,
54
+ };
55
+ return JSON.stringify(formatted, null, 2);
56
+ }
57
+ /**
58
+ * Format metadata
59
+ */
60
+ static formatMetadata(metadata) {
61
+ return JSON.stringify(metadata, null, 2);
62
+ }
63
+ /**
64
+ * Format a simple success message
65
+ */
66
+ static simpleSuccess(message) {
67
+ return {
68
+ content: [{ type: "text", text: message }],
69
+ isError: false,
70
+ };
71
+ }
72
+ /**
73
+ * Format operation result with details
74
+ */
75
+ static operationResult(operation, details) {
76
+ const text = `${operation} completed successfully\n\n${JSON.stringify(details, null, 2)}`;
77
+ return {
78
+ content: [{ type: "text", text }],
79
+ isError: false,
80
+ };
81
+ }
82
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Validation - Shared validation logic for tool inputs
3
+ */
4
+ export class Validator {
5
+ /**
6
+ * Validate that required fields exist in an object
7
+ */
8
+ static validateRequired(obj, fields) {
9
+ const missing = fields.filter((field) => obj[field] === undefined);
10
+ if (missing.length > 0) {
11
+ throw new Error(`Missing required fields: ${missing.join(", ")}`);
12
+ }
13
+ }
14
+ /**
15
+ * Validate RGB color values (0-1 range)
16
+ */
17
+ static validateColor(color) {
18
+ const values = [color.red, color.green, color.blue];
19
+ return values.every((v) => typeof v === "number" && v >= 0 && v <= 1);
20
+ }
21
+ /**
22
+ * Validate dimension type
23
+ */
24
+ static validateDimension(dimension) {
25
+ return dimension === "ROWS" || dimension === "COLUMNS";
26
+ }
27
+ /**
28
+ * Validate text style object
29
+ */
30
+ static validateTextStyle(style) {
31
+ // Check for at least one style property
32
+ const validProperties = [
33
+ "bold",
34
+ "italic",
35
+ "underline",
36
+ "fontSize",
37
+ "fontFamily",
38
+ "foregroundColor",
39
+ "backgroundColor",
40
+ ];
41
+ const hasValidProperty = validProperties.some((prop) => style[prop] !== undefined);
42
+ if (!hasValidProperty) {
43
+ return false;
44
+ }
45
+ // Validate color properties if they exist
46
+ if (style.foregroundColor && !this.validateColor(style.foregroundColor)) {
47
+ return false;
48
+ }
49
+ if (style.backgroundColor && !this.validateColor(style.backgroundColor)) {
50
+ return false;
51
+ }
52
+ return true;
53
+ }
54
+ /**
55
+ * Validate index is a positive integer
56
+ */
57
+ static validateIndex(index, allowZero = false) {
58
+ if (!Number.isInteger(index)) {
59
+ return false;
60
+ }
61
+ return allowZero ? index >= 0 : index > 0;
62
+ }
63
+ /**
64
+ * Validate range (startIndex < endIndex)
65
+ */
66
+ static validateRange(startIndex, endIndex) {
67
+ return (this.validateIndex(startIndex) &&
68
+ this.validateIndex(endIndex) &&
69
+ startIndex < endIndex);
70
+ }
71
+ /**
72
+ * Validate alignment value
73
+ */
74
+ static validateAlignment(alignment) {
75
+ return ["START", "CENTER", "END", "JUSTIFIED"].includes(alignment);
76
+ }
77
+ /**
78
+ * Validate named style type
79
+ */
80
+ static validateNamedStyleType(styleType) {
81
+ const validTypes = [
82
+ "NORMAL_TEXT",
83
+ "HEADING_1",
84
+ "HEADING_2",
85
+ "HEADING_3",
86
+ "HEADING_4",
87
+ "HEADING_5",
88
+ "HEADING_6",
89
+ "TITLE",
90
+ "SUBTITLE",
91
+ ];
92
+ return validTypes.includes(styleType);
93
+ }
94
+ /**
95
+ * Validate URL format
96
+ */
97
+ static validateUrl(url) {
98
+ try {
99
+ new URL(url);
100
+ return url.startsWith("http://") || url.startsWith("https://");
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ /**
107
+ * Validate positive number
108
+ */
109
+ static validatePositiveNumber(value) {
110
+ return typeof value === "number" && value > 0 && !isNaN(value);
111
+ }
112
+ }
@@ -0,0 +1,37 @@
1
+ import { google } from "googleapis";
2
+ import { ResponseFormatter } from "../../../lib/response-formatter.js";
3
+ export const schema = {
4
+ name: "gdocs_create",
5
+ description: "Create a new Google Document",
6
+ inputSchema: {
7
+ type: "object",
8
+ properties: {
9
+ title: {
10
+ type: "string",
11
+ description: "The title of the new document",
12
+ },
13
+ },
14
+ required: ["title"],
15
+ },
16
+ };
17
+ export async function createDocument(args) {
18
+ try {
19
+ const docs = google.docs("v1");
20
+ const response = await docs.documents.create({
21
+ requestBody: {
22
+ title: args.title,
23
+ },
24
+ });
25
+ const documentId = response.data.documentId;
26
+ const documentUrl = `https://docs.google.com/document/d/${documentId}/edit`;
27
+ return ResponseFormatter.success({
28
+ documentId,
29
+ documentUrl,
30
+ title: response.data.title,
31
+ revisionId: response.data.revisionId,
32
+ }, "Document created successfully");
33
+ }
34
+ catch (error) {
35
+ return ResponseFormatter.error(error);
36
+ }
37
+ }
@@ -0,0 +1,45 @@
1
+ import { google } from "googleapis";
2
+ import { ResponseFormatter } from "../../../lib/response-formatter.js";
3
+ import { DocumentIdResolver } from "../../../lib/document-id-resolver.js";
4
+ export const schema = {
5
+ name: "gdocs_get_metadata",
6
+ description: "Get metadata for a Google Document including title, revision ID, and document style. Accepts either a document ID or a full Google Docs URL.",
7
+ inputSchema: {
8
+ type: "object",
9
+ properties: {
10
+ documentId: {
11
+ type: "string",
12
+ description: "Document ID or full Google Docs URL (e.g., https://docs.google.com/document/d/DOCUMENT_ID/edit)",
13
+ },
14
+ },
15
+ required: ["documentId"],
16
+ },
17
+ };
18
+ export async function getMetadata(args) {
19
+ try {
20
+ // Resolve document ID from URL if needed
21
+ const docRef = DocumentIdResolver.resolve(args.documentId);
22
+ const documentId = docRef.id;
23
+ const docs = google.docs("v1");
24
+ const response = await docs.documents.get({
25
+ documentId,
26
+ });
27
+ const doc = response.data;
28
+ const metadata = {
29
+ documentId: doc.documentId,
30
+ title: doc.title,
31
+ revisionId: doc.revisionId,
32
+ suggestionsViewMode: doc.suggestionsViewMode,
33
+ documentStyle: doc.documentStyle,
34
+ namedStyles: doc.namedStyles,
35
+ headers: Object.keys(doc.headers || {}).length,
36
+ footers: Object.keys(doc.footers || {}).length,
37
+ inlineObjects: Object.keys(doc.inlineObjects || {}).length,
38
+ lists: Object.keys(doc.lists || {}).length,
39
+ };
40
+ return ResponseFormatter.success(metadata, "Document metadata retrieved successfully");
41
+ }
42
+ catch (error) {
43
+ return ResponseFormatter.error(error);
44
+ }
45
+ }
@@ -0,0 +1,59 @@
1
+ import { google } from "googleapis";
2
+ import { ResponseFormatter } from "../../../lib/response-formatter.js";
3
+ export const schema = {
4
+ name: "gdocs_list_documents",
5
+ description: "List Google Documents from Google Drive. Use query parameter to filter by name, owner, etc.",
6
+ inputSchema: {
7
+ type: "object",
8
+ properties: {
9
+ query: {
10
+ type: "string",
11
+ description: "Search query to filter documents (e.g., 'name contains \"report\"'). Default: list all documents",
12
+ },
13
+ pageToken: {
14
+ type: "string",
15
+ description: "Token for pagination to get the next page of results",
16
+ },
17
+ pageSize: {
18
+ type: "number",
19
+ description: "Maximum number of documents to return (default: 10, max: 100)",
20
+ },
21
+ },
22
+ required: [],
23
+ },
24
+ };
25
+ export async function listDocuments(args) {
26
+ try {
27
+ const drive = google.drive("v3");
28
+ // Build query to find Google Docs files
29
+ let query = "mimeType='application/vnd.google-apps.document'";
30
+ if (args.query) {
31
+ query += ` and ${args.query}`;
32
+ }
33
+ const response = await drive.files.list({
34
+ q: query,
35
+ pageSize: args.pageSize || 10,
36
+ pageToken: args.pageToken,
37
+ fields: "nextPageToken, files(id, name, createdTime, modifiedTime, owners, webViewLink)",
38
+ orderBy: "modifiedTime desc",
39
+ });
40
+ const files = response.data.files || [];
41
+ const documents = files.map((file) => ({
42
+ documentId: file.id,
43
+ name: file.name,
44
+ createdTime: file.createdTime,
45
+ modifiedTime: file.modifiedTime,
46
+ owners: file.owners?.map((owner) => owner.emailAddress),
47
+ webViewLink: file.webViewLink,
48
+ }));
49
+ const result = {
50
+ documents,
51
+ count: documents.length,
52
+ nextPageToken: response.data.nextPageToken,
53
+ };
54
+ return ResponseFormatter.success(result, `Found ${documents.length} document(s)`);
55
+ }
56
+ catch (error) {
57
+ return ResponseFormatter.error(error);
58
+ }
59
+ }
@@ -0,0 +1,62 @@
1
+ import { google } from "googleapis";
2
+ import { ResponseFormatter } from "../../../lib/response-formatter.js";
3
+ import { DocumentIdResolver } from "../../../lib/document-id-resolver.js";
4
+ export const schema = {
5
+ name: "gdocs_read",
6
+ description: "Read content from a Google Document. Accepts either a document ID or a full Google Docs URL.",
7
+ inputSchema: {
8
+ type: "object",
9
+ properties: {
10
+ documentId: {
11
+ type: "string",
12
+ description: "Document ID or full Google Docs URL (e.g., https://docs.google.com/document/d/DOCUMENT_ID/edit)",
13
+ },
14
+ includeFormatting: {
15
+ type: "boolean",
16
+ description: "Whether to include text formatting information (default: false)",
17
+ },
18
+ },
19
+ required: ["documentId"],
20
+ },
21
+ };
22
+ export async function readDocument(args) {
23
+ try {
24
+ // Resolve document ID from URL if needed
25
+ const docRef = DocumentIdResolver.resolve(args.documentId);
26
+ const documentId = docRef.id;
27
+ const docs = google.docs("v1");
28
+ const response = await docs.documents.get({
29
+ documentId,
30
+ });
31
+ const doc = response.data;
32
+ // Extract plain text content
33
+ let textContent = "";
34
+ if (doc.body?.content) {
35
+ for (const element of doc.body.content) {
36
+ if (element.paragraph?.elements) {
37
+ for (const textElement of element.paragraph.elements) {
38
+ if (textElement.textRun?.content) {
39
+ textContent += textElement.textRun.content;
40
+ }
41
+ }
42
+ }
43
+ }
44
+ }
45
+ const result = {
46
+ documentId: doc.documentId,
47
+ title: doc.title,
48
+ revisionId: doc.revisionId,
49
+ textContent,
50
+ };
51
+ // Include formatting if requested
52
+ if (args.includeFormatting) {
53
+ result.body = doc.body;
54
+ result.documentStyle = doc.documentStyle;
55
+ result.namedStyles = doc.namedStyles;
56
+ }
57
+ return ResponseFormatter.success(result, "Document read successfully");
58
+ }
59
+ catch (error) {
60
+ return ResponseFormatter.error(error);
61
+ }
62
+ }
@@ -0,0 +1,57 @@
1
+ import { google } from "googleapis";
2
+ import { ResponseFormatter } from "../../../lib/response-formatter.js";
3
+ import { DocumentIdResolver } from "../../../lib/document-id-resolver.js";
4
+ export const schema = {
5
+ name: "gdocs_append_text",
6
+ description: "Append text to the end of a Google Document.",
7
+ inputSchema: {
8
+ type: "object",
9
+ properties: {
10
+ documentId: {
11
+ type: "string",
12
+ description: "Document ID or full Google Docs URL",
13
+ },
14
+ text: {
15
+ type: "string",
16
+ description: "Text to append to the end of the document",
17
+ },
18
+ },
19
+ required: ["documentId", "text"],
20
+ },
21
+ };
22
+ export async function appendText(args) {
23
+ try {
24
+ // Resolve document ID from URL if needed
25
+ const docRef = DocumentIdResolver.resolve(args.documentId);
26
+ const documentId = docRef.id;
27
+ const docs = google.docs("v1");
28
+ // First get the document to find the end index
29
+ const doc = await docs.documents.get({ documentId });
30
+ const endIndex = doc.data.body?.content?.[doc.data.body.content.length - 1]?.endIndex || 1;
31
+ // Insert text at the end (endIndex - 1 because endIndex is exclusive)
32
+ const response = await docs.documents.batchUpdate({
33
+ documentId,
34
+ requestBody: {
35
+ requests: [
36
+ {
37
+ insertText: {
38
+ text: args.text,
39
+ location: {
40
+ index: endIndex - 1,
41
+ },
42
+ },
43
+ },
44
+ ],
45
+ },
46
+ });
47
+ return ResponseFormatter.success({
48
+ documentId,
49
+ appendedText: args.text,
50
+ appendedAt: endIndex - 1,
51
+ length: args.text.length,
52
+ }, "Text appended successfully");
53
+ }
54
+ catch (error) {
55
+ return ResponseFormatter.error(error);
56
+ }
57
+ }