-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgooglesheets_server.py
More file actions
1576 lines (1253 loc) · 53.8 KB
/
googlesheets_server.py
File metadata and controls
1576 lines (1253 loc) · 53.8 KB
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Simple Google Sheets MCP Server - Bridge between MCP clients and Google Sheets API
"""
import os
import sys
import logging
import json
from datetime import datetime, timezone
from pathlib import Path
from mcp.server.fastmcp import FastMCP
# Google API imports
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# Configure logging to stderr
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
stream=sys.stderr
)
logger = logging.getLogger("googlesheets-server")
# Initialize MCP server - NO PROMPT PARAMETER!
mcp = FastMCP("googlesheets")
# Configuration
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
GOOGLE_APPLICATION_CREDENTIALS = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", "")
GOOGLE_CREDENTIALS_JSON = os.environ.get("GOOGLE_CREDENTIALS_JSON", "")
SERVICE_ACCOUNT_EMAIL = os.environ.get("SERVICE_ACCOUNT_EMAIL", "")
OAUTH_REDIRECT_URI = os.environ.get("OAUTH_REDIRECT_URI", "")
DRIVE_FOLDER_ID = os.environ.get("DRIVE_FOLDER_ID", "")
# Global service objects
_sheets_service = None
_drive_service = None
# === UTILITY FUNCTIONS ===
def get_credentials():
"""Get Google API credentials from service account or OAuth."""
creds = None
# Debug: Log environment variables (without sensitive data)
logger.info(f"GOOGLE_CREDENTIALS_JSON length: {len(GOOGLE_CREDENTIALS_JSON) if GOOGLE_CREDENTIALS_JSON else 0}")
logger.info(f"GOOGLE_APPLICATION_CREDENTIALS: {GOOGLE_APPLICATION_CREDENTIALS[:50] if GOOGLE_APPLICATION_CREDENTIALS else 'Not set'}...")
logger.info(f"SERVICE_ACCOUNT_EMAIL: {SERVICE_ACCOUNT_EMAIL if SERVICE_ACCOUNT_EMAIL else 'Not set'}")
# Try JSON credentials from environment variable first (for Docker MCP)
if GOOGLE_CREDENTIALS_JSON:
try:
creds_info = json.loads(GOOGLE_CREDENTIALS_JSON)
creds = service_account.Credentials.from_service_account_info(
creds_info, scopes=SCOPES)
logger.info("Using service account credentials from JSON env var")
return creds
except Exception as e:
logger.warning(f"Service account JSON auth failed: {e}")
# Try service account file
if GOOGLE_APPLICATION_CREDENTIALS and os.path.exists(GOOGLE_APPLICATION_CREDENTIALS):
try:
creds = service_account.Credentials.from_service_account_file(
GOOGLE_APPLICATION_CREDENTIALS, scopes=SCOPES)
logger.info("Using service account credentials from file")
return creds
except Exception as e:
logger.warning(f"Service account file auth failed: {e}")
# Try OAuth token
token_path = os.path.join(os.path.expanduser("~"), ".google_sheets_token.json")
if os.path.exists(token_path):
try:
creds = Credentials.from_authorized_user_file(token_path, SCOPES)
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
if creds and creds.valid:
logger.info("Using OAuth credentials")
return creds
except Exception as e:
logger.warning(f"OAuth token load failed: {e}")
logger.error("No valid credentials found")
return None
def get_sheets_service():
"""Get or create Google Sheets service."""
global _sheets_service
if _sheets_service is None:
creds = get_credentials()
if creds:
_sheets_service = build('sheets', 'v4', credentials=creds)
return _sheets_service
def get_drive_service():
"""Get or create Google Drive service."""
global _drive_service
if _drive_service is None:
creds = get_credentials()
if creds:
_drive_service = build('drive', 'v3', credentials=creds)
return _drive_service
def format_error(e):
"""Format error message."""
if isinstance(e, HttpError):
return f"API Error {e.resp.status}: {e.error_details}"
return str(e)
# === MCP TOOLS ===
@mcp.tool()
async def list_spreadsheets(folder_id: str = "") -> str:
"""Lists spreadsheets in the configured Drive folder or accessible by the user."""
logger.info("Executing list_spreadsheets")
try:
drive = get_drive_service()
if not drive:
return "❌ Error: Unable to authenticate with Google API"
folder = folder_id.strip() or DRIVE_FOLDER_ID
query = "mimeType='application/vnd.google-apps.spreadsheet'"
if folder:
query += f" and '{folder}' in parents"
results = drive.files().list(
q=query,
pageSize=100,
fields="files(id, name)"
).execute()
files = results.get('files', [])
if not files:
return "📊 No spreadsheets found"
output = "📊 Spreadsheets:\n"
for f in files:
output += f"- {f['name']} (ID: {f['id']})\n"
return output
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def create_spreadsheet(title: str = "") -> str:
"""Creates a new spreadsheet with the specified title."""
logger.info(f"Executing create_spreadsheet with title={title}")
if not title.strip():
return "❌ Error: Title is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
spreadsheet = {
'properties': {
'title': title
}
}
result = sheets.spreadsheets().create(body=spreadsheet).execute()
return f"✅ Created spreadsheet: {result['properties']['title']}\nID: {result['spreadsheetId']}\nURL: https://docs.google.com/spreadsheets/d/{result['spreadsheetId']}"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def get_sheet_data(spreadsheet_id: str = "", sheet: str = "", range_notation: str = "", include_grid_data: str = "false") -> str:
"""Reads data from a range in a sheet (A1 notation like 'A1:C10' or 'Sheet1!B2:D')."""
logger.info(f"Executing get_sheet_data with spreadsheet_id={spreadsheet_id}, sheet={sheet}, range={range_notation}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet.strip():
return "❌ Error: sheet is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
full_range = f"{sheet}!{range_notation}" if range_notation.strip() else sheet
include_grid = include_grid_data.lower() == "true"
if include_grid:
result = sheets.spreadsheets().get(
spreadsheetId=spreadsheet_id,
ranges=[full_range],
includeGridData=True
).execute()
return f"✅ Grid data:\n{json.dumps(result.get('sheets', []), indent=2)}"
else:
result = sheets.spreadsheets().values().get(
spreadsheetId=spreadsheet_id,
range=full_range
).execute()
values = result.get('values', [])
if not values:
return "📊 No data found in range"
output = f"📊 Data from {full_range}:\n"
for row in values:
output += f"{', '.join(str(cell) for cell in row)}\n"
return output
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def get_sheet_formulas(spreadsheet_id: str = "", sheet: str = "", range_notation: str = "") -> str:
"""Reads formulas from a range in a sheet."""
logger.info(f"Executing get_sheet_formulas with spreadsheet_id={spreadsheet_id}, sheet={sheet}, range={range_notation}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet.strip():
return "❌ Error: sheet is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
full_range = f"{sheet}!{range_notation}" if range_notation.strip() else sheet
result = sheets.spreadsheets().values().get(
spreadsheetId=spreadsheet_id,
range=full_range,
valueRenderOption='FORMULA'
).execute()
values = result.get('values', [])
if not values:
return "📊 No formulas found in range"
output = f"📊 Formulas from {full_range}:\n"
for row in values:
output += f"{', '.join(str(cell) for cell in row)}\n"
return output
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def update_cells(spreadsheet_id: str = "", sheet: str = "", range_notation: str = "", data: str = "") -> str:
"""Writes data to a specific range (overwrites existing data). Data should be JSON 2D array like [[1,2],[3,4]]."""
logger.info(f"Executing update_cells with spreadsheet_id={spreadsheet_id}, sheet={sheet}, range={range_notation}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet.strip():
return "❌ Error: sheet is required"
if not range_notation.strip():
return "❌ Error: range is required"
if not data.strip():
return "❌ Error: data is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
# Parse data as JSON
try:
values = json.loads(data)
except json.JSONDecodeError:
return "❌ Error: data must be valid JSON 2D array"
full_range = f"{sheet}!{range_notation}"
body = {
'values': values
}
result = sheets.spreadsheets().values().update(
spreadsheetId=spreadsheet_id,
range=full_range,
valueInputOption='USER_ENTERED',
body=body
).execute()
return f"✅ Updated {result.get('updatedCells', 0)} cells in {full_range}"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def batch_update_cells(spreadsheet_id: str = "", sheet: str = "", ranges: str = "") -> str:
"""Updates multiple ranges in one call. Ranges should be JSON object mapping range to 2D array like {\"A1:B2\":[[1,2],[3,4]],\"D5\":[[\"Hello\"]]}."""
logger.info(f"Executing batch_update_cells with spreadsheet_id={spreadsheet_id}, sheet={sheet}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet.strip():
return "❌ Error: sheet is required"
if not ranges.strip():
return "❌ Error: ranges is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
# Parse ranges as JSON
try:
ranges_dict = json.loads(ranges)
except json.JSONDecodeError:
return "❌ Error: ranges must be valid JSON object"
data = []
for range_key, values in ranges_dict.items():
data.append({
'range': f"{sheet}!{range_key}",
'values': values
})
body = {
'valueInputOption': 'USER_ENTERED',
'data': data
}
result = sheets.spreadsheets().values().batchUpdate(
spreadsheetId=spreadsheet_id,
body=body
).execute()
return f"✅ Batch updated {result.get('totalUpdatedCells', 0)} cells across {len(data)} ranges"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def add_rows(spreadsheet_id: str = "", sheet: str = "", data: str = "") -> str:
"""Appends rows to the end of a sheet (after the last row with data). Data should be JSON 2D array."""
logger.info(f"Executing add_rows with spreadsheet_id={spreadsheet_id}, sheet={sheet}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet.strip():
return "❌ Error: sheet is required"
if not data.strip():
return "❌ Error: data is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
# Parse data as JSON
try:
values = json.loads(data)
except json.JSONDecodeError:
return "❌ Error: data must be valid JSON 2D array"
body = {
'values': values
}
result = sheets.spreadsheets().values().append(
spreadsheetId=spreadsheet_id,
range=sheet,
valueInputOption='USER_ENTERED',
body=body
).execute()
return f"✅ Appended {result.get('updates', {}).get('updatedRows', 0)} rows to {sheet}"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def list_sheets(spreadsheet_id: str = "") -> str:
"""Lists all sheet names within a spreadsheet."""
logger.info(f"Executing list_sheets with spreadsheet_id={spreadsheet_id}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
result = sheets.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
sheet_list = result.get('sheets', [])
if not sheet_list:
return "📊 No sheets found"
output = "📊 Sheets:\n"
for sheet in sheet_list:
props = sheet.get('properties', {})
output += f"- {props.get('title', 'Untitled')} (ID: {props.get('sheetId', 'N/A')})\n"
return output
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def create_sheet(spreadsheet_id: str = "", title: str = "") -> str:
"""Adds a new sheet (tab) to a spreadsheet."""
logger.info(f"Executing create_sheet with spreadsheet_id={spreadsheet_id}, title={title}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not title.strip():
return "❌ Error: title is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
body = {
'requests': [{
'addSheet': {
'properties': {
'title': title
}
}
}]
}
result = sheets.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id,
body=body
).execute()
new_sheet = result.get('replies', [{}])[0].get('addSheet', {}).get('properties', {})
return f"✅ Created sheet: {new_sheet.get('title', title)}\nSheet ID: {new_sheet.get('sheetId', 'N/A')}"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def get_multiple_sheet_data(queries: str = "") -> str:
"""Fetches data from multiple ranges. Queries should be JSON array like [{\"spreadsheet_id\":\"abc\",\"sheet\":\"Sheet1\",\"range\":\"A1:B2\"}]."""
logger.info("Executing get_multiple_sheet_data")
if not queries.strip():
return "❌ Error: queries is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
# Parse queries as JSON
try:
query_list = json.loads(queries)
except json.JSONDecodeError:
return "❌ Error: queries must be valid JSON array"
results = []
for query in query_list:
sid = query.get('spreadsheet_id', '')
sheet = query.get('sheet', '')
range_notation = query.get('range', '')
if not sid or not sheet:
results.append({
'query': query,
'error': 'Missing spreadsheet_id or sheet'
})
continue
try:
full_range = f"{sheet}!{range_notation}" if range_notation else sheet
result = sheets.spreadsheets().values().get(
spreadsheetId=sid,
range=full_range
).execute()
results.append({
'query': query,
'data': result.get('values', [])
})
except Exception as e:
results.append({
'query': query,
'error': format_error(e)
})
return f"✅ Fetched {len(results)} ranges:\n{json.dumps(results, indent=2)}"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def get_multiple_spreadsheet_summary(spreadsheet_ids: str = "", rows_to_fetch: str = "5") -> str:
"""Gets titles, sheet names, headers, and first few rows for multiple spreadsheets. spreadsheet_ids should be JSON array of IDs."""
logger.info("Executing get_multiple_spreadsheet_summary")
if not spreadsheet_ids.strip():
return "❌ Error: spreadsheet_ids is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
# Parse spreadsheet_ids as JSON
try:
id_list = json.loads(spreadsheet_ids)
except json.JSONDecodeError:
return "❌ Error: spreadsheet_ids must be valid JSON array"
rows = int(rows_to_fetch) if rows_to_fetch.strip() else 5
summaries = []
for sid in id_list:
try:
# Get spreadsheet metadata
result = sheets.spreadsheets().get(spreadsheetId=sid).execute()
title = result.get('properties', {}).get('title', 'Untitled')
sheet_list = result.get('sheets', [])
sheet_summaries = []
for sheet in sheet_list:
sheet_title = sheet.get('properties', {}).get('title', '')
# Get first N rows
data_result = sheets.spreadsheets().values().get(
spreadsheetId=sid,
range=f"{sheet_title}!A1:Z{rows}"
).execute()
values = data_result.get('values', [])
headers = values[0] if values else []
preview_rows = values[1:] if len(values) > 1 else []
sheet_summaries.append({
'sheet_name': sheet_title,
'headers': headers,
'preview_rows': preview_rows
})
summaries.append({
'spreadsheet_id': sid,
'title': title,
'sheets': sheet_summaries
})
except Exception as e:
summaries.append({
'spreadsheet_id': sid,
'error': format_error(e)
})
return f"✅ Summaries:\n{json.dumps(summaries, indent=2)}"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def share_spreadsheet(spreadsheet_id: str = "", recipients: str = "", send_notification: str = "true") -> str:
"""Shares a spreadsheet with users. Recipients should be JSON array like [{\"email_address\":\"user@example.com\",\"role\":\"writer\"}]. Roles: reader, commenter, writer."""
logger.info(f"Executing share_spreadsheet with spreadsheet_id={spreadsheet_id}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not recipients.strip():
return "❌ Error: recipients is required"
try:
drive = get_drive_service()
if not drive:
return "❌ Error: Unable to authenticate with Google API"
# Parse recipients as JSON
try:
recipient_list = json.loads(recipients)
except json.JSONDecodeError:
return "❌ Error: recipients must be valid JSON array"
send_email = send_notification.lower() == "true"
successes = []
failures = []
for recipient in recipient_list:
email = recipient.get('email_address', '')
role = recipient.get('role', 'reader')
if not email:
failures.append({'recipient': recipient, 'error': 'Missing email_address'})
continue
try:
permission = {
'type': 'user',
'role': role,
'emailAddress': email
}
drive.permissions().create(
fileId=spreadsheet_id,
body=permission,
sendNotificationEmail=send_email
).execute()
successes.append(email)
except Exception as e:
failures.append({'email': email, 'error': format_error(e)})
output = f"✅ Shared with {len(successes)} users"
if successes:
output += f"\nSuccesses: {', '.join(successes)}"
if failures:
output += f"\nFailures: {json.dumps(failures, indent=2)}"
return output
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def add_columns(spreadsheet_id: str = "", sheet: str = "", num_columns: str = "1", position: str = "") -> str:
"""Adds columns to a sheet. Position is 1-based index after which to insert (omit to add at end)."""
logger.info(f"Executing add_columns with spreadsheet_id={spreadsheet_id}, sheet={sheet}, num_columns={num_columns}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet.strip():
return "❌ Error: sheet is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
# Get sheet ID
result = sheets.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
sheet_id = None
for s in result.get('sheets', []):
if s.get('properties', {}).get('title') == sheet:
sheet_id = s.get('properties', {}).get('sheetId')
break
if sheet_id is None:
return f"❌ Error: Sheet '{sheet}' not found"
num_cols = int(num_columns) if num_columns.strip() else 1
request = {
'appendDimension' if not position.strip() else 'insertDimension': {
'sheetId': sheet_id,
'dimension': 'COLUMNS',
'length': num_cols
}
}
if position.strip():
pos = int(position)
request['insertDimension']['range'] = {
'sheetId': sheet_id,
'dimension': 'COLUMNS',
'startIndex': pos,
'endIndex': pos + num_cols
}
body = {'requests': [request]}
sheets.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id,
body=body
).execute()
return f"✅ Added {num_cols} column(s) to {sheet}"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def copy_sheet(spreadsheet_id: str = "", sheet_id: str = "", new_title: str = "", destination_spreadsheet_id: str = "") -> str:
"""Duplicates a sheet within a spreadsheet or to another spreadsheet."""
logger.info(f"Executing copy_sheet with spreadsheet_id={spreadsheet_id}, sheet_id={sheet_id}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet_id.strip():
return "❌ Error: sheet_id is required"
if not new_title.strip():
return "❌ Error: new_title is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
sid = int(sheet_id)
dest_id = destination_spreadsheet_id.strip() or spreadsheet_id
body = {
'destinationSpreadsheetId': dest_id
}
result = sheets.spreadsheets().sheets().copyTo(
spreadsheetId=spreadsheet_id,
sheetId=sid,
body=body
).execute()
# Rename the copied sheet
copied_sheet_id = result.get('sheetId')
rename_body = {
'requests': [{
'updateSheetProperties': {
'properties': {
'sheetId': copied_sheet_id,
'title': new_title
},
'fields': 'title'
}
}]
}
sheets.spreadsheets().batchUpdate(
spreadsheetId=dest_id,
body=rename_body
).execute()
return f"✅ Copied sheet to {dest_id} as '{new_title}'"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def rename_sheet(spreadsheet_id: str = "", sheet_id: str = "", new_title: str = "") -> str:
"""Renames an existing sheet."""
logger.info(f"Executing rename_sheet with spreadsheet_id={spreadsheet_id}, sheet_id={sheet_id}, new_title={new_title}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet_id.strip():
return "❌ Error: sheet_id is required"
if not new_title.strip():
return "❌ Error: new_title is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
sid = int(sheet_id)
body = {
'requests': [{
'updateSheetProperties': {
'properties': {
'sheetId': sid,
'title': new_title
},
'fields': 'title'
}
}]
}
sheets.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id,
body=body
).execute()
return f"✅ Renamed sheet to '{new_title}'"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def add_conditional_formatting(spreadsheet_id: str = "", sheet: str = "", range_notation: str = "", rule_config: str = "") -> str:
"""Adds conditional formatting rule to a range. rule_config should be JSON with condition type, values, and format properties."""
logger.info(f"Executing add_conditional_formatting with spreadsheet_id={spreadsheet_id}, sheet={sheet}, range={range_notation}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet.strip():
return "❌ Error: sheet is required"
if not range_notation.strip():
return "❌ Error: range_notation is required"
if not rule_config.strip():
return "❌ Error: rule_config is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
try:
config = json.loads(rule_config)
except json.JSONDecodeError:
return "❌ Error: rule_config must be valid JSON object"
result = sheets.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
sheet_id = None
for s in result.get('sheets', []):
if s.get('properties', {}).get('title') == sheet:
sheet_id = s.get('properties', {}).get('sheetId')
break
if sheet_id is None:
return f"❌ Error: Sheet '{sheet}' not found"
full_range = f"{sheet}!{range_notation}"
range_parts = range_notation.split(':')
start_cell = range_parts[0] if range_parts else 'A1'
end_cell = range_parts[1] if len(range_parts) > 1 else start_cell
def col_to_index(col):
index = 0
for char in col:
if char.isalpha():
index = index * 26 + (ord(char.upper()) - ord('A') + 1)
return index - 1
def parse_cell(cell):
col = ''
row = ''
for char in cell:
if char.isalpha():
col += char
else:
row += char
return col_to_index(col), int(row) - 1 if row else 0
start_col, start_row = parse_cell(start_cell)
end_col, end_row = parse_cell(end_cell)
ranges_obj = [{
'sheetId': sheet_id,
'startRowIndex': start_row,
'endRowIndex': end_row + 1,
'startColumnIndex': start_col,
'endColumnIndex': end_col + 1
}]
rule = {'ranges': ranges_obj}
rule_type = config.get('type', 'boolean')
if rule_type == 'boolean':
boolean_rule = {}
condition = config.get('condition', {})
if condition:
boolean_rule['condition'] = condition
format_spec = config.get('format', {})
if format_spec:
boolean_rule['format'] = format_spec
rule['booleanRule'] = boolean_rule
elif rule_type == 'gradient':
gradient_rule = config.get('gradientRule', {})
if gradient_rule:
rule['gradientRule'] = gradient_rule
body = {
'requests': [{
'addConditionalFormatRule': {
'rule': rule,
'index': 0
}
}]
}
sheets.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id,
body=body
).execute()
return f"✅ Added conditional formatting rule to {full_range}"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
@mcp.tool()
async def update_conditional_formatting(spreadsheet_id: str = "", sheet_id: str = "", rule_index: str = "", rule_config: str = "", new_index: str = "") -> str:
"""Updates or moves an existing conditional formatting rule. Provide either rule_config to replace or new_index to move."""
logger.info(f"Executing update_conditional_formatting with spreadsheet_id={spreadsheet_id}, sheet_id={sheet_id}, rule_index={rule_index}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
if not sheet_id.strip():
return "❌ Error: sheet_id is required"
if not rule_index.strip():
return "❌ Error: rule_index is required"
if not rule_config.strip() and not new_index.strip():
return "❌ Error: Either rule_config or new_index must be provided"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
sid = int(sheet_id)
idx = int(rule_index)
request_obj = {
'updateConditionalFormatRule': {
'sheetId': sid,
'index': idx
}
}
if rule_config.strip():
try:
config = json.loads(rule_config)
except json.JSONDecodeError:
return "❌ Error: rule_config must be valid JSON object"
ranges_obj = config.get('ranges', [])
rule = {'ranges': ranges_obj}
rule_type = config.get('type', 'boolean')
if rule_type == 'boolean':
boolean_rule = {}
condition = config.get('condition', {})
if condition:
boolean_rule['condition'] = condition
format_spec = config.get('format', {})
if format_spec:
boolean_rule['format'] = format_spec
rule['booleanRule'] = boolean_rule
elif rule_type == 'gradient':
gradient_rule = config.get('gradientRule', {})
if gradient_rule:
rule['gradientRule'] = gradient_rule
request_obj['updateConditionalFormatRule']['rule'] = rule
if new_index.strip():
request_obj['updateConditionalFormatRule']['newIndex'] = int(new_index)
body = {'requests': [request_obj]}
sheets.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id,
body=body
).execute()
return f"✅ Updated conditional formatting rule at index {idx}"
except Exception as e:
logger.error(f"Error: {e}")
return f"❌ Error: {format_error(e)}"
# === TABLE-LEVEL OPERATIONS ===
@mcp.tool()
async def list_tables(spreadsheet_id: str = "", sheet: str = "") -> str:
"""Lists all defined tables (named ranges or header-based logical tables) within a sheet or spreadsheet."""
logger.info(f"Executing list_tables with spreadsheet_id={spreadsheet_id}, sheet={sheet}")
if not spreadsheet_id.strip():
return "❌ Error: spreadsheet_id is required"
try:
sheets = get_sheets_service()
if not sheets:
return "❌ Error: Unable to authenticate with Google API"
result = sheets.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
named_ranges = result.get('namedRanges', [])
if not named_ranges:
return "📊 No tables (named ranges) found"
output = "📊 Tables:\n"
for nr in named_ranges: