Skip to main content
Glama

Server Configuration

Describes the environment variables required to run the server.

NameRequiredDescriptionDefault
CREDENTIALS_PATHNoPath to the OAuth client ID JSON file for Google Workspace authentication. Required when using OAuth as the authentication method (the default). Alternative authentication methods (service account, base64 credential injection, Application Default Credentials) may not need this variable.

Instructions

Guidance the server publishes about itself, which clients place ahead of the tool catalog so the model reads it before choosing anything.

This server publishes no instructions, or was last inspected before Glama recorded them.

Capabilities

Features and capabilities supported by this server

Protocol revision2025-11-25

CapabilityDetails
tools
{
  "listChanged": false
}
prompts
{
  "listChanged": false
}
resources
{
  "subscribe": false,
  "listChanged": false
}

Tools

Functions exposed to the LLM to take actions

NameDescription
get_sheet_dataA

Get data from a specific sheet in a Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet range: Optional cell range in A1 notation (e.g., 'A1:C10'). If not provided, gets all data. With include_grid_data=True and no range, the used range is auto-detected (see below) rather than fetching the sheet's full padded grid. include_grid_data: If True, includes cell formatting and other metadata in the response. Note: Setting this to True will significantly increase the response size and token usage when parsing the response, as it includes detailed cell formatting information — densely formatted cells serialize to hundreds of bytes each. If range is omitted, the actual used range is auto-detected first (one extra lightweight values-only request) and formatting is fetched only for that — sheets default to a padded 1000x26 grid regardless of actual content, and fetching per-cell formatting for the full padded grid instead of just your data can produce a response large enough to break the client connection. Default is False (returns values only, more efficient). Raises ValueError if the actual response size exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default — raise it to match a higher MAX_MCP_OUTPUT_TOKENS in your MCP client) and local_path is not set — narrow the range, retry, or pass local_path to bypass the cap entirely. local_path: Optional local filesystem path (file or directory) to write the result to instead of returning it inline. Bypasses the include_grid_data response-size cap. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. Same caveat as download_file/download_folder: this path is resolved on the server's filesystem, not the caller's — over SSE that's only useful if the path is on a volume the caller can also reach; for stdio it's the same machine.

Returns: Grid data structure with either full metadata or just values from Google Sheets API, depending on include_grid_data parameter. If local_path is set, returns {local_path, spreadsheet_id, sheet, range, bytes_written} instead.

get_sheet_formulasA

Get formulas from a specific sheet in a Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet range: Optional cell range in A1 notation (e.g., 'A1:C10'). If not provided, gets all formulas from the sheet.

Returns: A 2D array of the sheet formulas, or {"error": ...} if the range is rejected by the Sheets API (issue #757).

get_multiple_sheet_dataA

Get data from multiple specific ranges in Google Spreadsheets.

Queries fetch concurrently rather than one at a time. If the caller supplied a progressToken, a notifications/progress update is sent as each query finishes (#355).

Args: queries: A list of dictionaries, each specifying a query. Each dictionary must have 'spreadsheet_id' and 'sheet' keys. 'range' is optional; omitting it returns the entire sheet. Example: [{'spreadsheet_id': 'abc', 'sheet': 'Sheet1', 'range': 'A1:B5'}, {'spreadsheet_id': 'xyz', 'sheet': 'Data'}] local_path: Optional local filesystem path (file or directory) to write the result to instead of returning it inline. Bypasses the response-size cap. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. Same caveat as download_file/download_folder: this path is resolved on the server's filesystem, not the caller's.

Returns: A list of dictionaries, each containing the original query parameters and the fetched 'data' or an 'error'. Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default) and local_path is not set — split into fewer queries per call, or pass local_path. If local_path is set, returns {local_path, query_count, bytes_written} instead.

get_multiple_spreadsheet_summaryA

Get a summary of multiple Google Spreadsheets, including sheet names, headers, and the first few rows of data for each sheet.

Spreadsheets summarize concurrently rather than one at a time. If the caller supplied a progressToken, a notifications/progress update is sent as each summary finishes (#355).

Args: spreadsheet_ids: A list of spreadsheet IDs to summarize. rows_to_fetch: The number of rows (including header) to fetch for the summary (default: 5). local_path: Optional local filesystem path (file or directory) to write the result to instead of returning it inline. Bypasses the response-size cap. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. Same caveat as download_file/download_folder: this path is resolved on the server's filesystem, not the caller's.

Returns: A list of dictionaries, each representing a spreadsheet summary. Includes spreadsheet title, sheet summaries (title, headers, first rows), or an error. Results are cached; call refresh_cache(spreadsheet_id=) to invalidate, or refresh_cache() to clear all caches. Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default) and local_path is not set — summarize fewer spreadsheets per call, lower rows_to_fetch, or pass local_path. If local_path is set, returns {local_path, spreadsheet_count, bytes_written} instead.

find_in_spreadsheetA

Find cells containing a specific value in a Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) query: The text to search for in cell values sheet: Optional sheet name to search in. If not provided, searches all sheets. case_sensitive: Whether the search should be case-sensitive (default False) max_results: Maximum number of results to return (default 50) local_path: Optional local filesystem path (file or directory) to write the result to instead of returning it inline. Bypasses the response-size cap. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. Same caveat as download_file/download_folder: this path is resolved on the server's filesystem, not the caller's.

Returns: List of found cells with their location (sheet, cell in A1 notation) and value. max_results bounds match count, not response size — matched cell values can still be large. Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default) and local_path is not set — lower max_results, or pass local_path. If local_path is set, returns {local_path, spreadsheet_id, query, match_count, bytes_written} instead.

clear_valuesA

Clear cell content in a range without touching formatting.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet range: A1 notation range to clear (e.g., 'A1:D10'). If omitted, clears the entire sheet.

Returns: Result of the clear operation

update_cellsA

Update cells in a Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet range: Cell range in A1 notation (e.g., 'A1:C10') data: 2D array of values to update. Each cell is normally a plain scalar (str/int/float/bool), parsed the same way as typing it into the Sheets UI (USER_ENTERED — formulas, dates, etc. are recognized). For a partial (rich-text) hyperlink or mixed-format run within a single cell, pass a list of run dicts instead, e.g. [{"text": "See "}, {"text": "docs", "hyperlink": "https://..."}] — each run's "text" is concatenated into the cell's literal string value (not USER_ENTERED-parsed) and an optional "hyperlink" links just that run.

Returns: Result of the update operation. If data contains only plain cells or only rich-text cells, this is that single API call's raw response. If it mixes both kinds, this is {"values_update": , "rich_text_update": } since the two are separate API calls and neither result should be silently dropped.

batch_update_cellsB

Batch update multiple ranges in a Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet ranges: Dictionary mapping range strings to 2D arrays of values e.g., {'A1:B2': [[1, 2], [3, 4]], 'D1:E2': [['a', 'b'], ['c', 'd']]}

Returns: Result of the batch update operation

batch_updateA

Execute a batch update on a Google Spreadsheet using the full batchUpdate endpoint. This provides access to all batchUpdate operations including adding sheets, updating properties, inserting/deleting dimensions, formatting, and more.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) requests: A list of request objects. Each request object can contain any valid batchUpdate operation. Common operations include: - addSheet: Add a new sheet - updateSheetProperties: Update sheet properties (title, grid properties, etc.) - insertDimension: Insert rows or columns - deleteDimension: Delete rows or columns - updateCells: Update cell values and formatting - updateBorders: Update cell borders - addConditionalFormatRule: Add conditional formatting - deleteConditionalFormatRule: Remove conditional formatting - updateDimensionProperties: Update row/column properties - and many more...

         Example requests:
         [
             {
                 "addSheet": {
                     "properties": {
                         "title": "New Sheet"
                     }
                 }
             },
             {
                 "updateSheetProperties": {
                     "properties": {
                         "sheetId": 0,
                         "title": "Renamed Sheet"
                     },
                     "fields": "title"
                 }
             },
             {
                 "insertDimension": {
                     "range": {
                         "sheetId": 0,
                         "dimension": "ROWS",
                         "startIndex": 1,
                         "endIndex": 3
                     }
                 }
             }
         ]

Returns: Result of the batch update operation, including replies for each request

list_sheetsA

List all sheets in a Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL)

Returns: List of sheet names. Results are cached; call refresh_cache(spreadsheet_id=spreadsheet_id) to invalidate, or refresh_cache() to clear all caches.

copy_sheetB

Copy a sheet from one spreadsheet to another.

Args: src_spreadsheet: Source spreadsheet ID src_sheet: Source sheet name dst_spreadsheet: Destination spreadsheet ID dst_sheet: Destination sheet name

Returns: Result of the operation

duplicate_sheetA

Duplicate a sheet tab within the same spreadsheet.

Distinct from copy_sheet, which copies a sheet across spreadsheets.

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet to duplicate new_name: Optional title for the new sheet. Defaults to Google's auto-generated name (e.g. "Copy of Sheet1") if omitted. insert_index: Optional 0-based tab position for the new sheet. Defaults to immediately after the source sheet if omitted.

Returns: Information about the newly created sheet

rename_sheetC

Rename a sheet in a Google Spreadsheet.

Args: spreadsheet: Spreadsheet ID sheet: Current sheet name new_name: New sheet name

Returns: Result of the operation

create_sheetC

Create a new sheet tab in an existing Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet title: The title for the new sheet

Returns: Information about the newly created sheet

add_rowsA

Add rows to a sheet in a Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet count: Number of rows to add start_row: 0-based row index to start adding. If not provided, adds at the beginning.

Returns: Result of the operation. Returns {"error": ...} without calling the Sheets API if start_row is negative or count isn't positive.

add_columnsA

Add columns to a sheet in a Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet count: Number of columns to add start_column: 0-based column index to start adding. If not provided, adds at the beginning.

Returns: Result of the operation. Returns {"error": ...} without calling the Sheets API if start_column is negative or count isn't positive.

delete_sheetB

Delete a sheet tab from a Google Spreadsheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet to delete

Returns: Result of the operation

delete_rowsA

Delete rows from a sheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet start_row: 0-based index of the first row to delete end_row: 0-based index of the last row to delete (inclusive). If omitted, deletes only start_row.

Returns: Result of the operation. Returns {"error": ...} without calling the Sheets API if start_row is negative or end_row precedes start_row.

delete_columnsA

Delete columns from a sheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet start_column: 0-based index of the first column to delete (0 = column A) end_column: 0-based index of the last column to delete (inclusive). If omitted, deletes only start_column.

Returns: Result of the operation. Returns {"error": ...} without calling the Sheets API if start_column is negative or end_column precedes start_column.

hide_rowsB

Hide rows in a sheet from view.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet start_row: 0-based index of the first row to hide end_row: 0-based index of the last row to hide (inclusive). If omitted, hides only start_row.

Returns: Result of the batchUpdate operation. Returns {"error": ...} without calling the Sheets API if start_row is negative or end_row precedes start_row.

unhide_rowsA

Unhide previously hidden rows in a sheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet start_row: 0-based index of the first row to unhide end_row: 0-based index of the last row to unhide (inclusive). If omitted, unhides only start_row.

Returns: Result of the batchUpdate operation. Returns {"error": ...} without calling the Sheets API if start_row is negative or end_row precedes start_row.

hide_columnsA

Hide columns in a sheet from view.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet start_column: 0-based index of the first column to hide (0 = column A) end_column: 0-based index of the last column to hide (inclusive). If omitted, hides only start_column.

Returns: Result of the batchUpdate operation. Returns {"error": ...} without calling the Sheets API if start_column is negative or end_column precedes start_column.

unhide_columnsA

Unhide previously hidden columns in a sheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet start_column: 0-based index of the first column to unhide (0 = column A) end_column: 0-based index of the last column to unhide (inclusive). If omitted, unhides only start_column.

Returns: Result of the batchUpdate operation. Returns {"error": ...} without calling the Sheets API if start_column is negative or end_column precedes start_column.

resize_rowsA

Set an explicit pixel height for rows, or auto-fit them to content.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet start_row: 0-based index of the first row to resize end_row: 0-based index of the last row to resize (inclusive). If omitted, resizes only start_row. pixel_size: Explicit row height in pixels. Mutually exclusive with auto_resize. auto_resize: If True, auto-fit row height to content instead of setting an explicit pixel_size.

Returns: Result of the batchUpdate operation. Returns {"error": ...} without calling the Sheets API if start_row is negative, end_row precedes start_row, or pixel_size isn't positive.

resize_columnsA

Set an explicit pixel width for columns, or auto-fit them to content.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet start_column: 0-based index of the first column to resize (0 = column A) end_column: 0-based index of the last column to resize (inclusive). If omitted, resizes only start_column. pixel_size: Explicit column width in pixels. Mutually exclusive with auto_resize. auto_resize: If True, auto-fit column width to content instead of setting an explicit pixel_size.

Returns: Result of the batchUpdate operation. Returns {"error": ...} without calling the Sheets API if start_column is negative, end_column precedes start_column, or pixel_size isn't positive.

format_cellsB

Apply formatting to a cell range (background color, font, alignment, number format).

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet range: A1 notation range to format (e.g. "A1:D5") bold: Set bold text italic: Set italic text strikethrough: Set strikethrough font_size: Font size in points font_color: RGB color dict, e.g. {"red": 1.0, "green": 0.0, "blue": 0.0} background_color: RGB color dict for cell background horizontal_alignment: "LEFT", "CENTER", or "RIGHT" vertical_alignment: "TOP", "MIDDLE", or "BOTTOM" number_format_type: "TEXT", "NUMBER", "PERCENT", "CURRENCY", "DATE", "TIME", "DATE_TIME", "SCIENTIFIC" number_format_pattern: Custom number format pattern, e.g. "#,##0.00"

Returns: Result of the batchUpdate operation

update_bordersA

Apply or clear borders on the edges of a cell range.

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet range: A1 notation range to border (e.g. "A1:D5") top: Border spec for the top edge of the range, e.g. {"style": "SOLID", "color": {"red": 0.0, "green": 0.0, "blue": 0.0}}. "style" is required and must be one of "DOTTED", "DASHED", "SOLID", "SOLID_MEDIUM", "SOLID_THICK", "DOUBLE", or "NONE" (clears the border). "color" is an optional RGB dict. "width" is optional and deprecated by the Sheets API in favor of "style", but still accepted. bottom: Border spec for the bottom edge, same shape as top. left: Border spec for the left edge, same shape as top. right: Border spec for the right edge, same shape as top. inner_horizontal: Border spec for the horizontal lines between rows inside the range, same shape as top. inner_vertical: Border spec for the vertical lines between columns inside the range, same shape as top.

Returns: Result of the batchUpdate operation

add_data_validationA

Set a data validation rule on a cell range — dropdown lists, checkboxes, or date/number/text constraints.

    Args:
        spreadsheet_id: The ID of the spreadsheet
        sheet: The name of the sheet
        range: A1 notation range to validate (e.g. "A2:A100")
        condition_type: One of the Sheets API's condition types:
            "ONE_OF_LIST" — dropdown of custom values (values = the list items)
            "ONE_OF_RANGE" — dropdown sourced from another range (values = one item, the
            source range in A1 notation, e.g. ["Sheet2!A:A"] — a leading "=" is added
            automatically if you omit it)
            "BOOLEAN" — checkbox (omit values for a plain TRUE/FALSE checkbox, or give
            two values for custom checked/unchecked labels)
            "NUMBER_GREATER", "NUMBER_GREATER_THAN_EQ", "NUMBER_LESS",
            "NUMBER_LESS_THAN_EQ", "NUMBER_EQ", "NUMBER_NOT_EQ" — one numeric value
            "NUMBER_BETWEEN", "NUMBER_NOT_BETWEEN" — two numeric values
            "DATE_EQ", "DATE_BEFORE", "DATE_AFTER", "DATE_ON_OR_BEFORE",
            "DATE_ON_OR_AFTER" — one date value, e.g. "2025-01-01"
            "DATE_BETWEEN", "DATE_NOT_BETWEEN" — two date values
            "DATE_IS_VALID" — no values; any parseable date passes
            "TEXT_CONTAINS", "TEXT_NOT_CONTAINS", "TEXT_EQ" — one text value
            "TEXT_IS_EMAIL", "TEXT_IS_URL" — no values
            "CUSTOM_FORMULA" — one formula string, e.g. "=A1>0"
        values: Condition values as plain strings — see condition_type above for
                how many each type expects. Numbers and dates are passed as
                strings; the Sheets API parses them per the cell's format.
        input_message: Optional help text shown when a user selects a cell in range.
        strict: If True (default), reject input that fails the rule. If False,
                show a warning but still allow it.
        show_custom_ui: If True (default), show the built-in dropdown/checkbox UI
                for condition types that support one (ONE_OF_LIST, ONE_OF_RANGE,
                BOOLEAN). Ignored by condition types with no UI (e.g. NUMBER_*,
                TEXT_*).

    Returns:
        Result of the batchUpdate operation.
    
get_data_validationA

Read existing data validation rules for a cell range.

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet range: A1 notation range to inspect (e.g. "A1:A100")

Returns: List of {cell, rule} for every cell in the range that has a validation rule; cells without one are omitted. 'rule' matches the Sheets API's DataValidationRule shape: {condition: {type, values}, inputMessage, strict, showCustomUi}. Returns {"error": ...} if the sheet isn't found.

clear_data_validationA

Clear any data validation rule from a cell range.

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet range: A1 notation range to clear (e.g. "A2:A100")

Returns: Result of the batchUpdate operation.

merge_cellsB

Merge a range of cells into one cell.

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet range: A1 notation range to merge (e.g. "A1:C3") merge_type: "MERGE_ALL" (default), "MERGE_COLUMNS" (merge each column independently), or "MERGE_ROWS" (merge each row independently)

Returns: Result of the batchUpdate operation

unmerge_cellsB

Unmerge all merged cells in a range.

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet range: A1 notation range to unmerge (e.g. "A1:C3")

Returns: Result of the batchUpdate operation

freezeA

Freeze rows and/or columns in a sheet.

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet rows: Number of rows to freeze (0 to unfreeze all rows) columns: Number of columns to freeze (0 to unfreeze all columns)

Returns: Result of the batchUpdate operation

update_sheet_propertiesA

Update sheet-level display properties: tab color, gridline visibility, right-to-left layout.

Note: the Sheets API does not expose row/column header visibility as a settable sheet property, so it isn't included here. Frozen row/column counts are handled separately by the freeze tool.

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet tab_color: RGB color dict for the sheet tab, e.g. {"red": 1.0, "green": 0.0, "blue": 0.0}. Pass {} to clear the tab color back to the default. show_gridlines: Whether gridlines are shown in the UI. False hides them. right_to_left: Whether the sheet uses right-to-left layout.

Returns: Result of the batchUpdate operation

sort_rangeB

Sort a range by one or more columns.

Args: spreadsheet_id: The ID of the spreadsheet sheet: The name of the sheet range: A1 notation range to sort (e.g. "A1:D100") sort_order: List of sort specs, each with: - "column_index": 0-based column index within the range - "order": "ASCENDING" (default) or "DESCENDING" If omitted, sorts by the first column ascending.

Returns: Result of the batchUpdate operation

add_chartA

Add a chart to a Google Spreadsheet.

Creates a chart from the specified data range with customizable type, title, and positioning. The chart is added as a floating element on the sheet.

Args: spreadsheet_id: The ID of the spreadsheet (found in the URL) sheet: The name of the sheet containing the data chart_type: Type of chart to create. Supported types: - COLUMN: Vertical bar chart - BAR: Horizontal bar chart - LINE: Line chart - AREA: Area chart - PIE: Pie chart - SCATTER: Scatter plot - COMBO: Combination chart - HISTOGRAM: Histogram data_range: A1 notation range for chart data (e.g., 'A1:C10'). The first row is typically treated as headers. The first column is the domain (x-axis labels) and each remaining column is a series. Must name an end column: a cell-to-row ('B2:5') or row-only ('1:5') range returns an error. PIE needs exactly 2 columns, HISTOGRAM at least 1 (no domain; every column is a series), and every other type at least 2. title: Optional title for the chart x_axis_label: Optional label for the X axis (bottom axis) y_axis_label: Optional label for the Y axis (left axis) position_x: Horizontal position offset in pixels from the top-left corner (default: 0) position_y: Vertical position offset in pixels from the top-left corner (default: 0) width: Width of the chart in pixels (default: 600) height: Height of the chart in pixels (default: 400)

Returns: Result of the chart creation operation

Examples: Create a column chart showing sales data: add_chart( spreadsheet_id="abc123", sheet="Sales", chart_type="COLUMN", data_range="A1:B13", title="Monthly Sales", x_axis_label="Month", y_axis_label="Revenue ($)" )

Create a pie chart for market share:
add_chart(
    spreadsheet_id="abc123",
    sheet="Market",
    chart_type="PIE",
    data_range="A1:B5",
    title="Market Share by Product"
)
create_spreadsheetA

Create a new Google Spreadsheet.

Args: title: The title of the new spreadsheet folder_id: Optional Google Drive folder ID where the spreadsheet should be created. If not provided, uses the configured default folder or creates in root.

Returns: Information about the newly created spreadsheet including its ID

Note: Requires OAuth or ADC auth. Service accounts cannot create files in personal Drive (no storage quota). Works on Shared Drives regardless of auth method. Check server://auth-status for your current auth method.

import_csv_to_sheetA

Create a new Google Spreadsheet populated from a local CSV file. Not available when the server runs with LOCAL_FILE_ACCESS=off.

Reads the CSV, creates the spreadsheet, expands the sheet's grid to fit the data (avoiding the default 1000-row/26-column limit), and writes every row in one or more batched value updates.

Row chunks write concurrently rather than one at a time (#183). If the caller supplied a progressToken, a notifications/progress update is sent as each chunk finishes (#355).

Args: local_path: Absolute path to the local .csv file. title: Title for the new spreadsheet. folder_id: Optional Google Drive folder ID where the spreadsheet should be created. If not provided, uses the configured default folder or creates in root. sheet_name: Name of the sheet the data is written to (default "Sheet1").

Returns: spreadsheetId, title, web_link, and rows_written on full success. Rows are written in row-range chunks that run concurrently; if one or more chunks fail, the spreadsheet (already created) may have some rows missing — not necessarily a clean prefix. In that case returns an 'error' summary plus spreadsheetId, title, web_link, rows_attempted, failed_ranges (start_row, end_row, error per failed chunk), and written_ranges (start_row, end_row per chunk that succeeded), so the missing rows can be retried precisely.

Note: Requires OAuth or ADC auth. Service accounts cannot create files in personal Drive (no storage quota). Works on Shared Drives regardless of auth method. Check server://auth-status for your current auth method.

list_spreadsheetsA

List all spreadsheets in the specified Google Drive folder. If no folder is specified, uses the configured default folder; if that's also unset, searches across 'My Drive' AND every shared drive the authenticated account can access (corpora='allDrives') — not just 'My Drive'.

A strict, less-flexible special case of list_files pre-filtered to the spreadsheet MIME type. For a different result cap or other file types, use list_files(folder_id, mime_type='application/vnd.google-apps.spreadsheet', ...) instead.

Args: folder_id: Optional Google Drive folder ID to search in. If not provided, uses the configured default folder or searches 'My Drive' and every shared drive the account can access. max_results: Maximum number of results to return (default 100, max 1000).

Returns: List of spreadsheets with their ID and title. Trashed files are excluded; to find one to restore, use get_file_metadata or restore_file with its file ID.

list_foldersA

List all folders in the specified Google Drive folder. If no parent is specified, uses the configured default folder (DRIVE_FOLDER_ID); if that is also unset, searches across 'My Drive' AND every shared drive the authenticated account can access (corpora='allDrives') — not just 'My Drive'.

Args: parent_folder_id: Optional Google Drive folder ID to search within. If not provided, uses the configured default folder or searches 'My Drive' and every shared drive the account can access. max_results: Maximum number of results to return (default 100, max 1000).

Returns: List of folders with their ID, name, and parent information

list_drivesA

List shared (Team) Drives accessible to the authenticated account.

Args: query: Optional filter string. Supports Drive query syntax, e.g. 'name contains "Marketing"'. If omitted, all accessible shared drives are returned. max_results: Maximum number of drives to return (default 100, max 200).

Returns: List of shared drives, each with id, name, createdTime, and a capabilities summary (canAddChildren, canManageMembers, etc.).

list_filesA

List files in a Google Drive folder, optionally filtered by MIME type.

For a spreadsheet-only listing, list_spreadsheets(folder_id) is a narrower convenience wrapper around this same call pre-filtered to the spreadsheet MIME type.

Args: folder_id: The Google Drive folder ID to list files from. mime_type: Optional MIME type filter. Common values: 'application/vnd.google-apps.document' (Google Docs) 'application/vnd.google-apps.spreadsheet' (Google Sheets) 'application/vnd.google-apps.folder' (folders) max_results: Maximum number of results to return (default 100, max 1000)

Returns: List of files with their ID, name, MIME type, modified time, web link, starred status, and md5_checksum. md5_checksum is only present for binary files — Google Workspace files (Docs, Sheets, Slides, etc.) have no fixed byte content and the Drive API omits the field for them, so it's None for those. Compare it to a local file's md5 to detect real content drift instead of inferring change from modifiedTime alone; sync_folder(use_checksum=True) does that comparison itself (see its docstring for the cases where modifiedTime misleads). Results are cached; call refresh_cache(folder_id=folder_id) to invalidate, or refresh_cache() to clear all caches.

search_filesA

Search for files in Google Drive by name or content. Without folder_id, searches 'My Drive' AND every shared drive the authenticated account can access (corpora='allDrives').

For a spreadsheet-only search, search_spreadsheets(query, max_results) is a narrower convenience wrapper around this same query pre-filtered to the spreadsheet MIME type.

Args: query: Search string matched against file name and full text. mime_type: Optional MIME type filter, e.g. 'application/vnd.google-apps.document', 'application/vnd.google-apps.spreadsheet', 'application/pdf'. folder_id: Optional folder to restrict the search to. max_results: Maximum results to return (default 20, max 100).

Returns: List of matching files with id, name, mimeType, modified time, owners, parent folder, webViewLink, and starred status. Trashed files are excluded; to find one to restore, use get_file_metadata or restore_file with its file ID.

search_spreadsheetsA

Search for spreadsheets in Google Drive by name or content, across 'My Drive' AND every shared drive the authenticated account can access (corpora='allDrives').

A strict, less-flexible special case of search_files pre-filtered to the spreadsheet MIME type. For folder-scoped search or other file types, use search_files(query, mime_type='application/vnd.google-apps.spreadsheet', ...) instead.

Args: query: Search query string. Searches in file name and content. Examples: "budget 2024", "sales report", "project tracker" max_results: Maximum number of results to return (default 20, max 100)

Returns: List of matching spreadsheets with their ID, name, metadata, and starred status. Trashed files are excluded; to find one to restore, use get_file_metadata or restore_file with its file ID.

get_file_metadataA

Get metadata for any file or folder in Google Drive.

Args: file_id: The Google Drive file or folder ID.

Returns: id, name, mimeType, parents, createdTime, modifiedTime, size, owners, webViewLink, trashed status, starred status, and md5_checksum. md5_checksum (like size) is only present for binary files — Google Workspace files have no fixed byte content and the Drive API omits it for them. Compare it to a local file's md5 to detect real content drift instead of inferring change from modifiedTime alone; sync_folder(use_checksum=True) does that comparison itself (see its docstring for the cases where modifiedTime misleads). starred reflects star_file/unstar_file's own effect (#388) — previously there was no way to read a file's starred state independently of calling one of those two mutating tools.

create_folderB

Create a new folder in Google Drive.

Args: name: The name of the new folder parent_folder_id: Optional parent folder ID. If not provided, creates in the configured default folder or the root of My Drive.

Returns: Information about the newly created folder including its ID

create_shortcutA

Create a Drive shortcut pointing to an existing file.

Args: target_file_id: The ID of the file the shortcut should point to. folder_id: Destination folder ID for the shortcut. If not provided, uses the configured default folder or creates in root. name: Name for the shortcut. Defaults to the target file's own name.

Returns: shortcutId, name, parent, targetId, and targetMimeType of the new shortcut.

copy_fileA

Copy a file in Google Drive.

Args: file_id: The ID of the file to copy. new_name: Name for the copy. Defaults to 'Copy of '. folder_id: Destination folder ID. Defaults to the same folder as the original.

Returns: fileId, name, mimeType, parent, and webViewLink of the new copy.

Note: Requires OAuth or ADC auth. Service accounts cannot copy files into personal Drive (no storage quota). Works on Shared Drives regardless of auth method. Check server://auth-status for your current auth method.

move_fileB

Move a file or folder to a different folder in Google Drive.

Args: file_id: The ID of the file or folder to move destination_folder_id: The ID of the destination folder

Returns: Updated file metadata including new parent folder

rename_fileB

Rename a file or folder in Google Drive.

Args: file_id: The ID of the file or folder to rename. new_name: The new name.

Returns: Updated fileId, name, and parent folder ID.

star_fileA

Mark a file or folder as starred in Google Drive, for easy retrieval later.

Args: file_id: The ID of the file or folder to star.

Returns: fileId, name, and the resulting starred state.

unstar_fileA

Remove a file or folder's starred marker in Google Drive.

Args: file_id: The ID of the file or folder to unstar.

Returns: fileId, name, and the resulting starred state.

list_shared_with_meA

List files explicitly shared with the authenticated user, including shared drive files shared with them directly.

Args: mime_type: Optional MIME type filter, e.g. 'application/vnd.google-apps.spreadsheet'. max_results: Maximum number of files to return (default 50, max 200).

Returns: List of shared files with id, name, mime_type, modified_time, owners, and web_link, ordered by modification time descending. Note: With service account auth, returns files shared with the service account email, not files shared with a personal user.

list_recent_filesA

List recently modified files in Drive, newest first, across 'My Drive' AND every shared drive the authenticated account can access (corpora='allDrives').

Args: max_results: Maximum number of files to return (default 20, max 100). days: If provided, only return files modified within the last N days. mime_type: Optional MIME type filter.

Returns: List of files with id, name, mime_type, modified_time, owners, and web_link, ordered by modification time descending.

get_storage_quotaA

Get Drive storage usage and limits for the authenticated account.

Returns: Storage quota with limit_bytes, usage_bytes, usage_in_drive_bytes, usage_in_trash_bytes, email, and display_name. All byte values are integers. limit_bytes is None if the key is absent, or 0 if the API returns "0" (typical for service accounts with no personal quota).

delete_fileA

Move a file to the trash or permanently delete it.

Args: file_id: The ID of the file or folder to remove. permanent: If False (default), moves to trash (recoverable). If True, permanently deletes — this cannot be undone. Raises ValueError, without deleting anything, if the caller can't permanently delete the file (e.g. a Content manager on a Shared Drive, who can only trash).

Returns: Confirmation with fileId and action taken ('trashed' or 'deleted').

restore_fileA

Restore a trashed file or folder back to its original location — undoes delete_file when it was called without permanent=True. Raises an API error (does not silently no-op) if the file was permanently deleted or otherwise no longer exists — permanent deletion can't be recovered from.

Args: file_id: The ID of the trashed file or folder to restore.

Returns: Confirmation with fileId and action taken ('restored').

empty_trashA

Permanently delete every trashed file in a single trash. This cannot be undone — unlike delete_file's default (recoverable) trash behavior, there is no restoring a file after this.

Args: drive_id: If omitted (default), empties the caller's own My Drive trash only. If set to a Shared Drive's ID (see list_drives), empties that Shared Drive's trash instead. A single call only ever targets one trash — to empty several Shared Drives' trash, call this once per drive_id.

Returns: Confirmation that the trash was emptied, echoing which drive (drive_id, or None for My Drive) was targeted.

share_spreadsheetB

Share a Google Spreadsheet with multiple users via email, assigning specific roles.

Recipients share concurrently rather than one at a time. If the caller supplied a progressToken, a notifications/progress update is sent as each share finishes (#355).

Args: spreadsheet_id: The ID of the spreadsheet to share. recipients: A list of dictionaries, each containing 'email_address' and 'role'. The role should be one of: 'reader', 'commenter', 'writer'. Example: [ {'email_address': 'user1@example.com', 'role': 'writer'}, {'email_address': 'user2@example.com', 'role': 'reader'} ] send_notification: Whether to send a notification email to the users. Defaults to True.

Returns: A dictionary containing lists of 'successes' and 'failures'. Each item in the lists includes the email address and the outcome.

list_permissionsA

List all permissions on a file or folder in Google Drive.

Args: file_id: The Google Drive file or folder ID.

Returns: List of permissions, each with id, type, role, email_address (for user/group), domain (for domain permissions), display_name, expiration_time, and deleted flag.

update_permissionA

Change the role on an existing permission for a file or folder.

Args: file_id: The Google Drive file or folder ID. permission_id: The permission ID to update (from list_permissions). role: New role. One of: 'reader', 'commenter', 'writer'.

Returns: Updated permissionId and role.

remove_permissionA

Revoke a permission on a file or folder.

Args: file_id: The Google Drive file or folder ID. permission_id: The permission ID to remove (from list_permissions).

Returns: Confirmation with fileId, permissionId, and action taken.

transfer_ownershipA

Transfer ownership of a file or folder to another user.

Args: file_id: The Google Drive file or folder ID. new_owner_email: Email address of the new owner. send_notification: Whether to send a notification email to the new owner. Defaults to True, and must stay True: Drive refuses any ownership transfer whose notification is disabled.

Returns: Confirmation with fileId, new_owner, and permissionId. {"error": ...} if send_notification is False, before any API call.

Note: Requires OAuth auth — service accounts have no personal Drive identity to transfer ownership to/from, so Drive's API rejects the transfer. Check server://auth-status for your current auth method.

share_fileA

Share any file or folder with one or more principals.

Permission entries share concurrently rather than one at a time. If the caller supplied a progressToken, a notifications/progress update is sent as each share finishes (#355).

Args: file_id: The Google Drive file or folder ID. permissions: List of permission entries. Each must have 'type' and 'role'. Additional fields depend on type: type='user' or 'group' — requires 'email_address' type='domain' — requires 'domain' type='anyone' — no extra fields

             type values: 'user', 'group', 'domain', 'anyone'
             role values: 'reader', 'commenter', 'writer'

             Example:
             [
                 {'type': 'user', 'email_address': 'alice@example.com', 'role': 'writer'},
                 {'type': 'domain', 'domain': 'example.com', 'role': 'reader'},
                 {'type': 'anyone', 'role': 'reader'},
             ]
send_notification: Send notification email to user/group recipients (default True).

Returns: Dictionary with 'successes' and 'failures' lists.

export_fileA

Export or download a file from Google Drive.

Prefer download_file when saving to disk — this tool returns raw base64-encoded bytes for binary formats (xlsx, pdf, docx, etc.) that require manual decoding. Use export_file only when you need the file content in-memory.

For Google Workspace files (Docs, Sheets, Slides) the file is converted to the requested format. For non-Google files the raw content is downloaded.

Supported export_format values: All Google types: 'pdf', 'html' Google Docs: 'txt', 'docx', 'odt', 'rtf', 'epub' Google Sheets: 'csv', 'xlsx', 'ods' Google Slides: 'pptx' Non-Google files: 'raw'

Args: file_id: The Google Drive file ID. export_format: One of the format strings above.

Returns: fileId, name, mime_type, format, encoding ('utf-8' or 'base64'), content. Text formats (txt, html, csv, rtf) are returned as plain strings; all others are base64-encoded bytes. Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default) — base64 encoding inflates raw file size by ~33%, so binary exports hit this cap at a much smaller file size than text ones. Call download_file instead for anything but small files; it writes raw bytes straight to disk with no base64/JSON overhead.

list_revisionsA

List available revisions for a Google Drive file (Sheets, Docs, or any file).

Returns every revision in chronological order with its ID, timestamp, and the user who made the change. Use the revision ID with export_revision to read a historical version of a spreadsheet (cell data) or a Google Doc (Markdown).

Retention differs by file type:

  • Binary (uploaded) files: Drive purges a revision 30 days after newer content replaces it, unless keepForever is set (at most 200 per file).

  • Google Docs, Sheets, and Slides: not subject to that purge, and keepForever doesn't apply to them (always false). Drive may still merge older edits into fewer revisions, so not every edit has its own.

Args: file_id: The Google Drive file ID.

Returns: List of revisions, each with revisionId, modifiedTime, modifiedBy, keepForever.

export_revisionA

Export a historical revision of a Google Sheets file (cell data) or a Google Doc (Markdown). Use list_revisions to find the revision_id.

Google Sheets: downloads the revision as XLSX and returns the values for the requested sheet and range. Typical recovery workflow:

  1. list_revisions → find the revision ID from the timestamp before data was lost

  2. export_revision → read the affected range from that revision

  3. batch_update_cells → write the recovered values back to the current sheet Each call downloads the full file, so a large spreadsheet may be slow.

Google Docs: returns the revision as Markdown, converted the same way as get_doc_as_markdown. The Docs API can only read a document's current state, so the revision is exported as DOCX, imported into a temporary Google Doc, converted, and the temporary Doc is deleted (trashed if this identity can't delete it), so this call writes to Drive even though it changes nothing of yours. Expect several seconds per call. Two revisions' exports diff cleanly, with these differences from get_doc_as_markdown's output:

  • A link to a heading in the document renders as "#slug" (GitHub style), not a docs.google.com URL. A link to a bookmark, or to a heading that doesn't render as one (e.g. a heading in a table cell), is dropped, leaving its text.

  • An image renders as "image:sha256-", so an unchanged image doesn't show up in a diff. No viewable URL is returned: the temporary Doc's image URLs stop working once it's deleted.

  • Comments aren't included: they aren't part of a revision.

Args: file_id: The Google Drive file ID of the spreadsheet or document. revision_id: The revision ID from list_revisions. range: Sheets only. A1 notation range to return, e.g. "A1:D20". Omit for all data. sheet: Sheets only. Sheet (tab) name. Defaults to the first sheet. local_path: Docs only. Local path to write the Markdown to instead of returning it inline (the raw Markdown text, UTF-8). A directory path writes <file_id>-r<revision_id>.md inside it; a path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError before the export; an existing file at a plain file path is replaced. Bypasses the response-size cap.

Returns: Sheets: revisionId, modifiedTime, sheet name, range, and values as a list of rows. Docs: revisionId, modifiedTime, and markdown, plus warning if the temporary Doc couldn't be removed (it names the Doc's ID). With local_path, local_path and bytes_written replace markdown. Raises ValueError for a file that is neither a Sheet nor a Doc, for an argument that doesn't apply to the file's type, for a revision ID that no longer exists, for a local_path with a non-directory component (checked before the export), or if a Docs response exceeds the size cap without local_path.

Note: For a Doc, a user identity (OAuth, or ADC with user credentials) creates the temporary Doc in My Drive root, not shared with anyone. That needs room in My Drive and permission to create files there, even when the default folder is a Shared Drive. A service account has no My Drive storage, so it uses the default folder, which must be a Shared Drive: that drive's members can open the copy while the export runs.

upload_fileA

Upload a text file to Google Drive, optionally converting it to a Google Doc.

Args: name: File name (include extension, e.g. 'notes.md', 'report.html'). content: Text content to upload. source_format: How to interpret the content. One of: 'markdown' — Markdown text. Uploaded as an HTML file, or with convert_to_doc=True written into a new Doc (see convert_to_doc). 'html' — Raw HTML. 'text' — Plain text (default). folder_id: Destination folder ID. Defaults to the configured folder or Drive root. convert_to_doc: If True, create a Google Doc instead of a raw file. A 'markdown' source is written with the same converter as create_doc(content_format='markdown'), so it renders the same way, images included (a local path, drive:<file_id> or public http(s) URL, embedded as create_doc does; bare URLs are linked). An 'html' source keeps its heading, list, and link formatting via Drive's HTML import. 'text' uploads as plain text and Drive converts it (no formatting preserved). auto_downscale: For a 'markdown' source with convert_to_doc=True, resize a local-path/drive: image over Google Docs' inline-image limit instead of failing it (default False), as create_doc's auto_downscale does: a drive: source gets a new " (resized)" copy beside the original, a local-path source uploads the resized bytes. No effect otherwise.

Returns: fileId, name, parent folder ID, and webViewLink of the created file. A Markdown Doc also gets create_doc's "images" (per-image outcomes) and "dropped_links" (links written as plain text) when there are any. If writing a Markdown Doc's content fails after the Doc was created, returns {"error", "fileId"} plus those fields instead.

Note: Requires OAuth or ADC auth. Service accounts cannot upload files to personal Drive (no storage quota). Works on Shared Drives regardless of auth method. Check server://auth-status for your current auth method.

upload_local_fileA

Upload a file from the local filesystem to a Google Drive folder. Handles binary and text files (images, PDFs, DOCX, XLSX, scripts, etc.). Not available when the server runs with LOCAL_FILE_ACCESS=off.

Args: local_path: Absolute path to the local file to upload. parent_folder_id: ID of the destination Drive folder. name: Name to give the file in Drive. Defaults to the local filename. skip_if_exists: If True (default), skip the upload and return the existing file's metadata if a file with the same name already exists in the destination folder. With convert=True, only an existing file already in the target format counts, and one named after the extension-stripped stem (Drive strips the extension on some conversions, e.g. 'report.csv' -> 'report') counts too — see Returns for how an unverified stem match is reported. convert: If True, request Drive's native import conversion instead of uploading as-is: .csv/.xlsx -> Google Sheets, .docx/.md/.html/.htm -> Google Docs, .pptx -> Google Slides. Any other extension returns an error. Default False (upload preserving original format). A .md conversion is recognized by sync_folder's convert_markdown matching too (same underlying mechanism, #211) — a later sync_folder call on the same folder won't create a duplicate. A .md file is rendered by Drive's Markdown importer, not this server's converter, so it looks different from create_doc's output: '-' bullets at every level, fenced code in a gray monospace box with a language label ('None' when it has no recognized language), at the page margin even inside a list item, quotes without a border, nested numbering '1.' rather than 'a.'. Full list: docs/known-limitations.md. To render a .md the way the Docs tools do, use create_doc_from_file instead. Leading YAML front matter is left out of the Doc, as in the Docs tools.

Returns: fileId, name, webViewLink, and 'skipped' (True if skip_if_exists fired) on success, plus web_content_link (a direct download link) for a new non-converted upload. A skip on a stem match whose existing file carries no marker proving this tool converted it from this file (an earlier conversion predating the marker, or an unrelated file sharing the name) also sets 'skipped_unverified': True plus a 'reason'; pass skip_if_exists=False to upload anyway. On failure, 'error' — plus a 'fileId' alongside it in the narrow case where convert=True and the file was actually created in Drive but a follow-up metadata call then failed (#420): that fileId names a real, already-created Drive file, not something to retry creating again.

Note: Requires OAuth or ADC auth. Service accounts cannot upload files to personal Drive (no storage quota). Works on Shared Drives regardless of auth method. Check server://auth-status for your current auth method.

upload_local_folderA

Upload all files in a local directory (non-recursive) to a Google Drive folder. Not available when the server runs with LOCAL_FILE_ACCESS=off.

Args: local_path: Absolute path to the local directory. parent_folder_id: ID of the destination Drive folder. skip_if_exists: Skip files that already exist in the destination (default True). skip_system_files: Skip OS metadata files like .DS_Store (default True). convert: If True, request Drive's native import conversion for every file — same mapping as upload_local_file's convert param: .csv/.xlsx -> Google Sheets, .docx/.md/.html/.htm -> Google Docs, .pptx -> Google Slides. A file whose extension isn't in that mapping is reported in 'failed' rather than uploaded as-is, matching upload_local_file's own convert=True behavior for an unsupported extension. Default False (upload every file preserving its original format). A .md file is rendered by Drive's Markdown importer, not this server's converter: '-' bullets at every level, fenced code in a gray monospace box with a language label ('None' when it has no recognized language), at the page margin even inside a list item, quotes without a border, nested numbering '1.' rather than 'a.'. Full list: docs/known-limitations.md. Leading YAML front matter is left out of the Doc.

Returns: Summary with lists of 'uploaded', 'skipped', 'skipped_unverified', and 'failed'. 'uploaded'/'skipped' are filenames. 'skipped' also lists any '.gee-sweet-partial-*' temp file an interrupted download left in the folder; those are never uploaded. 'skipped_unverified' (only ever populated under convert=True) holds {name, matched_name, reason} entries for files skipped because an existing file in the target format is named after the local file's extension-stripped stem (Drive strips the extension on some conversions, e.g. 'report.csv' -> 'report') but carries no marker proving this tool created it from that file — it may be an earlier conversion predating the marker, or an unrelated file sharing the name. Nothing was uploaded for these; pass skip_if_exists=False to upload one anyway (upload_local_file applies the same check). Each 'failed' entry is {name, error} plus a 'fileId' in the narrow convert=True case where the file was actually created in Drive but a follow-up metadata call then failed (#420) — see upload_local_file's own Returns docs.

Note: Requires OAuth or ADC auth. Service accounts cannot upload files to personal Drive (no storage quota). Works on Shared Drives regardless of auth method. Check server://auth-status for your current auth method.

download_fileA

Download a file from Google Drive to the local filesystem. Not available when the server runs with LOCAL_FILE_ACCESS=off.

For non-Google files the raw content is downloaded. For Google Workspace files (Docs, Sheets, Slides) an export_format is required to convert the file before download.

If local_path is a directory, the file is saved inside it using the Drive filename (with an extension appended for exported Workspace files). A local_path ending in a path separator (or in '/.' or '/..') is always treated as a directory target, and is created (mkdir -p) if it doesn't exist yet. Directories are created only once the content is ready to write, so a refused call or a failed export leaves nothing new on disk; a non-Workspace download that fails partway keeps the directory it created. A local_path that can't be written (a parent is a file, or the destination is a symlink to a missing target) raises ValueError before anything is downloaded. A Drive name that isn't a single ordinary filename (it contains '/' or '', is '.' or '..', etc.) is refused for a directory target with a ValueError, before anything is written; pass a full file path as local_path instead.

Args: file_id: The Google Drive file ID. local_path: Destination file path or directory on the local filesystem. export_format: Required for Google Workspace files. One of: Docs → 'pdf', 'docx', 'html', 'txt', 'odt', 'rtf', 'epub' Sheets → 'pdf', 'xlsx', 'csv', 'ods' Slides → 'pdf', 'pptx' For non-Google files omit this (raw download).

Returns: local_path where the file was written, file name, and byte size.

download_folderA

Download all files in a Google Drive folder (non-recursive) to a local directory. Not available when the server runs with LOCAL_FILE_ACCESS=off.

For non-Google files the raw content is downloaded. Google Workspace files are skipped unless export_format is provided, in which case they are exported to that format. Subfolders are always skipped, regardless of export_format — this tool never descends into them. A file whose Drive name isn't a single ordinary filename (it contains '/' or '', is '.' or '..', etc.) is listed under 'failed' and not downloaded.

Files transfer concurrently rather than one at a time. If the caller supplied a progressToken, a notifications/progress update is sent as each file finishes (e.g. "12/217: report.pdf: ok"). The message text always adds bytes transferred so far as supplementary context (#352), e.g. "12/217, 4823001/98234112 bytes: report.pdf: ok" when every candidate's size is known upfront, or "12/217, 4823001 bytes so far: report.pdf: ok" when one or more candidates (a Workspace export) has an unknown size.

The structured progress/total fields default to file-count (progress_unit='files'), for consistency with every other progress-reporting tool in this file. Pass progress_unit='bytes' to report bytes transferred instead, for a client that renders a progress bar from the structured fields alone rather than parsing the message text (#741) — this only takes effect when every candidate's size is known upfront (see _DownloadCandidate's docstring); otherwise it silently falls back to file-count, since there's no reliable byte total to report against.

Args: folder_id: The Google Drive folder ID. local_path: Local directory to download files into. Created only when there's at least one file to download, so a folder whose every entry is skipped or refused leaves nothing on disk. export_format: If provided, Google Workspace files are exported to this format (e.g. 'pdf', 'docx'). See download_file for full list. Without this, Workspace files are skipped. mime_type_filter: Only download files matching this MIME type. skip_if_exists: Skip files that already exist at the destination (default True). progress_unit: 'files' (default) or 'bytes' — which metric feeds the structured progress/total fields reported via notifications/progress. Falls back to 'files' when not every candidate's size is known upfront.

Returns: Summary with lists of 'downloaded', 'skipped', and 'failed' filenames, plus total 'size_bytes' downloaded.

sync_folderA

Sync files between a Google Drive folder and a local directory. Not available when the server runs with LOCAL_FILE_ACCESS=off.

Sync logic

Files are matched by name. For Google Workspace files (Docs, Sheets, Slides), the export extension is appended to form the local name — e.g. a Doc called 'Notes' with export_format='docx' matches the local file 'Notes.docx'. Workspace files with no export_format are skipped entirely — except a Doc produced by convert_markdown, which keeps its '.md' name and matches its local .md file directly regardless of export_format (see convert_markdown below).

For each matched name the action is decided as follows:

Drive only + direction includes download → download Drive only + direction is 'upload' → skip Local only + direction includes upload → upload Local only + direction is 'download' → skip Both sides, mtimes within 5 s tolerance → skip (already in sync) Both sides, mtimes match but byte sizes differ → conflict (content diverged; recency unknown — any direction) Both sides, mtimes and sizes match but md5 differs → conflict (use_checksum=True only; recency unknown — any direction) Both sides, local newer by > 5 s → upload (if direction includes upload) Both sides, Drive newer by > 5 s → download (if direction includes download) Both sides, conflict (direction mismatch) → skip, listed under 'conflicts'

A name that isn't a single ordinary filename (it contains '/' or '', is '.' or '..', etc.), for a file or a subfolder on either side, is never synced: it's listed under 'failed' (action 'unsafe_name' in a dry_run), unless it exists only on the side this direction wouldn't act on, where it's skipped as usual.

Modified times are compared in UTC. When a file is uploaded, its Drive modifiedTime is set to the local file's mtime so future syncs stay accurate. A convert_markdown Doc is the exception: its changes are tracked through properties and revision history instead (see convert_markdown below).

The "mtimes match but byte sizes differ" row (#659) exists because equal mtimes don't guarantee equal content: a rename-in-place (mv keeps the mtime) leaves a name pointing at different bytes with an unchanged timestamp, which the plain equal-mtime skip would hide permanently. Drive's size is already in the folder listing, so this check is nearly free (one stat) and runs during dry_run too. It is always a 'conflict', never an auto-transfer: the mtimes agree, so which side is newer is unknown, and a directional sync already reports 'conflict' rather than overwrite a target it can tell is newer. It only applies to non-Workspace files (Workspace and convert_markdown files report no size). A same-size content edit that also preserves mtime is still reported as "in sync" unless use_checksum=True (below) — hashing every within-tolerance pair by default would make every sync read every file.

When use_checksum=True, every name present on both sides is checked for a content match (local md5 vs. Drive's md5Checksum) before the direction decision above runs — a match is always treated as in sync regardless of how far apart the modifiedTimes are. This includes a pair whose mtimes are within tolerance and whose sizes match: a checksum mismatch there means a same-size, mtime-preserving content change, reported as a 'conflict' for every direction (recency unknown, same as the byte-size row above). A within-tolerance pair whose sizes already differ is reported by the byte-size row without being read. Every such file is read, so this costs a full read of the folder's matched content on every sync (run concurrently, a few files at a time). Skipped during dry_run, so this never turns a cheap preview into a full read of every file — an affected step's reason then ends in "(checksum not verified in dry_run)", since the real run may decide differently. This catches the cases mtime alone gets wrong. A local overwrite that preserves mtime hides a real change. A local regeneration that rewrites the same bytes reads as "local newer." A file created by upload_file (inline content, no local mtime to stamp) carries its upload time as modifiedTime, so a same-content local copy reads as changed. A local read failure for one file (deleted, permission-denied, etc.) reports that name under 'failed' rather than aborting the whole call. Only applies to files with a real md5Checksum — Google Workspace files (Docs, Sheets, Slides) and convert_markdown Docs have none and always fall back to the mtime comparison. A checksum mismatch doesn't change anything by itself when the mtimes disagree; it just falls through to the same mtime-based direction decision used when use_checksum=False.

direction values

'bidirectional' (default) — newer side wins; Drive-only files are downloaded, local-only files are uploaded. 'upload' — only push local changes to Drive; Drive-only files and Drive-newer files are left alone. 'download' — only pull Drive changes locally; local-only files and local-newer files are left alone.

recursive

By default (recursive=False) only files directly inside folder_id / local_path are considered — subfolders are ignored entirely, on either side.

When recursive=True, subfolders matched by name (same rules as files) are walked to any depth. A subfolder present on only one side is only descended into — and created on the missing side — when direction would actually create it there:

  • a Drive-only subfolder is downloaded (local dir created) when direction includes download; left alone under 'upload' direction.

  • a local-only subfolder is uploaded (Drive folder created) when direction includes upload; left alone under 'download' direction. Subfolders left alone this way are listed under 'folders_skipped' (relative path, trailing '/') instead of being silently ignored.

dry_run

When dry_run=True no files or folders are created/transferred, local_path included: a local_path that doesn't exist yet is planned as empty. 'uploaded', 'downloaded', 'skipped', 'conflicts', and 'failed' are always empty in this mode (nothing was materialized to report there) — the response instead includes an 'actions' list with {name, action, reason} for every file considered at every level visited; this is the complete, non-redundant picture of what a real run would do and why, without duplicating each name into a second, action-labelless list alongside it (#512).

Progress

File transfers within each level run concurrently rather than one at a time. If the caller supplied a progressToken, a notifications/progress update is sent as each individual upload/download completes (skips and conflicts don't emit updates — they're free, not transfers). No update is sent during dry_run, since nothing is transferred. progress stays a running file-transfer count with no total (recursive descent means the overall file count isn't known upfront) — the message text adds a running total of bytes transferred so far as supplementary context (#352), e.g. "notes.txt: upload_ok, 40231 bytes so far".

Args: folder_id: Google Drive folder ID to sync against. local_path: Local directory path to sync against. A missing one plans as empty, and is created only at the first local write (a download, or a Drive-only subfolder), so a dry_run or an upload-only sync never creates it. direction: 'bidirectional', 'upload', or 'download'. export_format: Required to include Workspace files in the sync. They are exported/compared using this format (e.g. 'pdf', 'docx', 'csv'). convert_markdown: If True, local .md files are uploaded via Drive's native import conversion, landing as Google Docs (still named '.md') instead of raw text files — same mechanism as upload_local_file's convert param (#188), and a Doc created either way is recognized by this matching. Drive's importer renders the Markdown, not this server's converter: '-' bullets at every level, fenced code in a gray monospace box with a language label ('None' when it has no recognized language), at the page margin even inside a list item, quotes without a border, nested numbering '1.' rather than 'a.' (full list: docs/known-limitations.md). Leading YAML front matter is left out of the Doc. The converted Doc is matched back to its local .md file directly on later syncs (independent of export_format, and independent of whether a later sync passes convert_markdown=True again), so edits round-trip normally instead of re-uploading a duplicate every run. Matching is scoped to Docs carrying an internal Drive property this tool sets on conversion — a pre-existing Doc a human happened to name '.md' is never mistaken for one and never has its content overwritten. There is no reverse conversion: if the Doc is edited in Drive, or has no local counterpart at all, that entry is reported under 'conflicts' instead of downloaded. A converted Doc's changes aren't judged from modifiedTime, which Drive updates minutes behind a Docs edit: the local .md is compared with the mtime recorded at its last upload, and a Drive edit is detected from the Doc's revision history (one extra metadata call per converted Doc per sync). A Doc edited in Drive is a conflict even when the local .md changed too, rather than being overwritten by the upload; clear it with resolve (below). A local change made within seconds of the previous upload waits for a later sync. A Doc converted by an older version of this tool keeps the modifiedTime comparison until it's next re-uploaded. A .md previously synced with convert_markdown=False can't be promoted to a Doc in place — that entry is reported under 'failed' with an explanatory message; delete it in Drive and re-sync to convert it. use_checksum: If True, treat a name present on both sides as in sync whenever its local md5 hash matches Drive's md5Checksum, regardless of modifiedTime drift, and report a within-tolerance pair whose hashes differ as a conflict (see above). Reads every both-sides file with a Drive md5Checksum. Default False (mtime + size comparison). skip_system_files: Skip .DS_Store and similar OS metadata files (default True). dry_run: If True, plan the sync but transfer nothing. recursive: If True, also sync matching subfolders at any depth (see above). Defaults to False — a single call only covers the top-level folder. result_local_path: If set, write the result to this file/directory path instead of returning it inline, unconditionally bypassing the response-size safety cap below — useful for a large recursive sync (dry_run or real) whose result would otherwise exceed it. Returns a manifest ({local_path, bytes_written, folder_id, dry_run}) instead of the sync result itself. Must not be local_path or a path inside it — local_path is scanned as sync input on every call, so a result manifest written there would show up as a new local-only file on the next sync (and get uploaded to Drive on a real run); raises ValueError if it resolves inside local_path. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. Both checks run before any transfer or local write. resolve: Clears convert_markdown conflicts one Doc at a time, keeping its file ID (and so its sharing, comments, and links). Maps a name exactly as 'conflicts' reports it ('sub/notes.md' under recursive) to one of: 'keep_drive' — accept the Doc's current Drive version as the new baseline. Nothing in Drive changes, and the local .md is recorded as matching it, so use this only once the local file holds exactly the Doc's content (carry the Drive edits in first). If the local file has edits of its own, merge and use 'keep_local' instead, or those edits never reach Drive. From then on, a local change uploads as usual. Also moves a Doc converted by an older version of this tool onto the revision-history check. 'keep_local' — re-upload the local .md over the Drive version, in place. The Drive edits are overwritten (they stay in the Doc's version history). Not allowed with direction='download'. Every name must be a convert_markdown Doc with a matching local .md that this sync would report under 'conflicts'; otherwise the call returns an error listing each bad name and changes nothing (there's no folder-wide form). With dry_run=True, 'actions' previews each one as a 'keep_drive' or 'keep_local' action. If the Doc is edited in Drive again between the plan and the write, it stays under 'conflicts' instead. Checking the names costs one read-only planning pass before a real run.

Returns: uploaded, downloaded, skipped, conflicts, failed lists (relative paths — just the filename at the top level, 'subdir/name' for nested matches when recursive descends; always empty when dry_run=True, see the dry_run section above), 'folders_skipped' (relative subfolder paths not entered — always empty when recursive=False), 'resolved' (names resolve was applied to; a 'keep_local' name is also under 'uploaded'), size_bytes transferred (uploaded plus downloaded), dry_run flag, and — when dry_run=True — an 'actions' list with {name, action, reason} for every file considered at every level visited. A '.gee-sweet-partial-*' temp file an interrupted download left locally is never synced; it's listed under 'skipped' (a 'skip' action under dry_run). Each 'failed' entry is {name, error} plus a 'fileId' in the narrow convert_markdown case where create() actually succeeded in Drive but a follow-up metadata call then failed (#420) — that fileId names a real, already-created Drive file, not something the next sync will retry creating from scratch. Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default, or pass result_local_path to bypass it and write to disk instead) — a recursive sync/preview over many files is the most likely way to hit this.

list_file_activityA

Return the activity timeline for a Google Drive file.

Uses the Drive Activity API (driveactivity/v2) to fetch a chronological list of edits, permission changes, comments, and other events for the given file.

Each activity entry reports:

  • timestamp: ISO 8601 UTC time of the activity

  • action: type of action (edit, create, move, rename, delete, restore, permission_change, comment, settings_change, system_event, …)

  • actors: list of who performed the action; each actor has a type field ("user", "system", "administrator", "anonymous") plus a person_name for known users (a People API resource name, not an email address)

Args: file_id: Google Drive file ID to query. page_size: Maximum number of activities to return (1-100, default 50). page_token: Continuation token from a previous response for pagination.

Returns: Dictionary with: - file_id: echoed back for reference - activities: list of activity entries (timestamp, action, actors) - next_page_token: present when more results are available Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default) — lower page_size and paginate via next_page_token instead of raising the cap; a single activity's actors list can be large on files with many collaborators.

Note: The Drive Activity API requires the drive.activity.readonly OAuth scope. Service accounts must be granted file access to see its activity. person_name values (e.g. "people/123456") are opaque identifiers; the People API is required to resolve them to display names or email addresses.

create_docA

Create a new Google Doc, optionally with initial content.

Content is interpreted as HTML by default. Pass content_format='markdown' to supply Markdown instead (headings, bold, italic, lists, links, tables, fenced code blocks, task list items, and images are all supported). Each table is inserted where it appears in the content. A table nested inside a table cell needs HTML content; Markdown has no syntax for one. In HTML, a line break inside a tag's text is a space, as a browser shows it: use or (or Markdown) for line structure. Plain text with no tags at all keeps each line as its own paragraph.

Images: a markdown "alt" (or an HTML ) is embedded inline. src may be a local filesystem path (uploaded to Drive automatically), a "drive:<file_id>" reference to an already-uploaded file, or a public http(s) URL (used directly). A local-path or drive: image is temporarily shared anyone-with- link/reader — required, since the Docs backend fetches inline images as an anonymous HTTP request — then, by default, that share is revoked again once the image is actually embedded (revoke_sharing=False leaves it shared instead; see insert_local_images for the same tradeoff). Images inside table cells, nested tables included, are embedded the same way. A local-path image is uploaded to folder_id, else the server's default folder, else the new doc's own folder. Per-image outcomes (including any resolution or sharing failure) are returned under "images" when the content had any.

An image that can't be embedded (Docs can't fetch it, e.g. an SVG badge or an unreachable URL, or its source couldn't be resolved) is written as its alt text instead, keeping its link, or as its file name when the alt is empty. Its "images" entry then has an "error" and a "fallback_text" with that text. In a heading it's left out instead, so the heading's text, and a "#slug" link to it, stay as written; its entry has only the "error". A data: URI image can't be embedded (Docs takes an image only by URL).

A local-path or drive: image over Google Docs' ~25-megapixel or ~50MB inline-image limit fails with a clear error naming the limit it exceeds and its actual dimensions or file size, before any upload/share happens — set auto_downscale=True to resize it instead (see that arg's own docs). A public http(s) image can't be pre-validated this way; an oversized one instead fails at the embed step with a rewritten error explaining the likely cause.

Args: title: The title of the new document content: Optional content for the document body folder_id: Optional Google Drive folder ID where the document should be created. If not provided, creates in the root of My Drive. content_format: 'html' (default) or 'markdown' autolink_urls: When content_format='markdown', whether a bare http(s):// URL, www. address or email address (not already wrapped in a Markdown link or angle brackets) becomes a real hyperlink, as in GitHub Markdown (default True). Set False to leave them as plain text; to suppress just one instead of the whole call, wrap it in backticks. revoke_sharing: Whether a local-path/drive: image's temporary anyone:reader share is revoked again after it's embedded (default True). An image file that was already link-shared before the call keeps its link and is reported with already_shared: true. auto_downscale: Resize an oversized local-path/drive: image instead of failing it (default False). A drive: source gets a new " (resized)" copy created alongside the original (left untouched); a local-path source uploads the resized bytes directly instead of the original file. No effect on a public http(s) image source (see above).

Returns: Information about the newly created document including its ID and web link. Includes "images" (per-image outcomes) when content contained any images. Includes "dropped_links" when a link was written as plain text instead: a list of {"url", "reason"}, where reason is "no_scheme" for a target Docs can't store as a link (a relative path such as ./guide.md or /guide.md), or "no_matching_heading" for a "#slug" anchor that no heading matches. A scheme-less target that names a host is linked over https instead: //host/x as https://host/x, www.host as https://www.host. If the content can't be converted, returns {"error"} and creates no doc. If writing the content fails after the doc was created, returns {"error", "docId", "images", "dropped_links"} instead, with any temporary image share already revoked.

Note: Requires OAuth or ADC auth. Service accounts cannot create files in personal Drive (no storage quota). Works on Shared Drives regardless of auth method. Workaround for service accounts: create the file manually in Drive, then use write_doc_content to populate it. Check server://auth-status for your current auth method.

create_doc_from_fileA

Create a Google Doc from a local .md or .html file. Not available when the server runs with LOCAL_FILE_ACCESS=off.

The file format is inferred from the extension: .md files are parsed as Markdown, .html / .htm files as HTML. The document title defaults to the filename without extension if not supplied.

Images referenced from the file (markdown "alt" or HTML ) are embedded inline the same way create_doc's own content_format='markdown' path handles them — see that tool's docstring for the src conventions, the revoke_sharing tradeoff, the auto_downscale size-limit behavior, and the alt-text fallback. A relative local image path is relative to the file's own folder, as in a README.

For .md files specifically, upload_local_file(convert=True) is a Drive-native alternative: one API call using Drive's own import converter, versus this tool's local parse-and-rebuild pipeline. This tool supports more Markdown features (tables, nested lists, task items, fenced code blocks, inline images) at the cost of more Docs API calls; Drive's importer is a single call but its fidelity is whatever Drive's own converter does.

Args: local_path: Absolute or relative path to the local file. title: Document title. Defaults to the filename stem. folder_id: Optional Google Drive folder ID for the doc and its local images. Defaults to the server's default folder, else the root of My Drive. autolink_urls: For .md files, whether a bare http(s):// URL, www. address or email address becomes a real hyperlink (default True). Set False to leave them as plain text; to suppress just one, wrap it in backticks instead. No effect on .html files. revoke_sharing: Whether a local-path/drive: image's temporary anyone:reader share is revoked again after it's embedded (default True). An image file that was already link-shared before the call keeps its link and is reported with already_shared: true. auto_downscale: Resize an oversized local-path/drive: image instead of failing it (default False) — see create_doc's own docstring.

Returns: Information about the newly created document including its ID and web link. Includes "images" (per-image outcomes) when the file contained any images. Includes "dropped_links" when a link was written as plain text instead (see create_doc). If the content can't be converted, returns {"error"} and creates no doc. If writing the content fails after the doc was created, returns {"error", "docId", "images", "dropped_links"} instead, with any temporary image share already revoked.

Note: Requires OAuth or ADC auth. Service accounts cannot create files in personal Drive (no storage quota). Check server://auth-status for your current auth method.

get_doc_contentA

Get the plain text content of a Google Doc.

Args: file_id: The Google Drive file ID of the document. local_path: Optional local filesystem path (file or directory) to write the result to instead of returning it inline. Bypasses the response-size cap. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. Same caveat as download_file/download_folder: this path is resolved on the server's filesystem, not the caller's.

Returns: Dictionary with the document's text content and metadata. Results are cached; call refresh_cache(doc_id=file_id) to invalidate, or refresh_cache() to clear all caches. Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default) and local_path is not set. If local_path is set, returns {local_path, id, bytes_written} instead.

write_doc_contentA

Replace the full content of an existing Google Doc.

Content is interpreted as HTML by default. Pass content_format='markdown' to supply Markdown instead. Headings, paragraphs, lists, links, tables, fenced code blocks, task list items, and images are all supported. Each table is inserted where it appears in the content. In HTML, a line break inside a tag's text is a space, as a browser shows it: use or (or Markdown) for line structure. Plain text with no tags at all keeps each line as its own paragraph. Use this to populate a doc created manually in Drive (bypassing service account storage quota limits).

Images are embedded inline the same way create_doc's own content_format='markdown' path handles them — see that tool's docstring for the src conventions, the revoke_sharing tradeoff, the auto_downscale size-limit behavior, and the alt-text fallback. A local-path image is uploaded to folder_id, else the server's default folder, else the doc's own folder. If the content has a local-path image this server can read and none of those is known (or the doc's folder can't be looked up), the call returns an error and leaves the doc unchanged. A local-path image it can't read (a missing file, or one LOCAL_FILE_ACCESS refuses) doesn't stop the call: it's written as its alt text, like any image that can't be embedded. A relative path that doesn't exist as written is also tried percent-decoded ("my%20pic.png").

Args: doc_id: The Google Doc file ID. content: Content to write into the document body. content_format: 'html' (default) or 'markdown' autolink_urls: When content_format='markdown', whether a bare http(s):// URL, www. address or email address becomes a real hyperlink (default True). Set False to leave them as plain text; to suppress just one, wrap it in backticks instead. revoke_sharing: Whether a local-path/drive: image's temporary anyone:reader share is revoked again after it's embedded (default True). An image file that was already link-shared before the call keeps its link and is reported with already_shared: true. auto_downscale: Resize an oversized local-path/drive: image instead of failing it (default False) — see create_doc's own docstring. allow_no_backup: Replace the content even when Drive refuses the backup copy (below) because the doc's sharing settings don't allow this account to copy it, or the account is at its item-creation limit (default False: the call refuses and leaves the doc unchanged). It has no effect when the account can't edit the doc. folder_id: Optional Google Drive folder ID to upload local-path images into. Defaults to the server's default folder, else the doc's own folder.

Returns: Confirmation with the document ID and web link. Includes "images" (per-image outcomes) when content contained any images. Includes "dropped_links" when a link was written as plain text instead (see create_doc). Includes "warning" if the backup copy (below) couldn't be removed, or if the content was replaced without one. Before clearing a doc that has content, a full copy of it is made in Drive, next to the doc, and deleted again once the new content is in. If the copy fails, nothing is changed and an error is returned, except when Drive refuses it for storage quota, because the account can't add a file to the doc's folder, or because the folder or Shared Drive is at its item limit: the replace then goes ahead without a backup. When sharing settings don't allow copying or the account is at its item-creation limit, it goes ahead without a backup only with allow_no_backup=True. If writing the new content fails, returns {"error", "docId", "backupId", "images", "dropped_links"} instead, with any temporary image share already revoked: the doc may be empty or partly written, and backupId is the kept copy of its previous content. When the replace went ahead without a backup there's no backupId, and the error says the previous content couldn't be backed up: it can't be recovered. The content is converted before any of this, so if it can't be converted, the doc is left unchanged and {"error", "docId"} is returned.

update_doc_from_fileA

Replace an existing Google Doc's content in place from a local .md or .html file. Not available when the server runs with LOCAL_FILE_ACCESS=off.

Reads local_path server-side the same way create_doc_from_file does (file format inferred from extension, or pass content_format to override), then replaces the doc's content the same way write_doc_content does — preserving the doc's ID, URL, permissions, and Drive location. Unlike calling create_doc_from_file again, this never mints a duplicate Doc, and unlike write_doc_content, the caller never has to read the file into its own context — the server reads it directly.

Images referenced from the file (markdown "alt" or HTML ) are embedded inline the same way create_doc's own content_format='markdown' path handles them — see that tool's docstring for the src conventions, the revoke_sharing tradeoff, the auto_downscale size-limit behavior, and the alt-text fallback. A relative local image path is relative to the file's own folder, as in a README. A local-path image is uploaded to folder_id, else the server's default folder, else the doc's own folder. If the file has a local-path image this server can read and none of those is known (or the doc's folder can't be looked up), the call returns an error and leaves the doc unchanged. A local-path image it can't read (a missing file, or one LOCAL_FILE_ACCESS refuses) doesn't stop the call: it's written as its alt text, like any image that can't be embedded. A relative path that doesn't exist as written is also tried percent-decoded ("my%20pic.png").

Args: doc_id: The Google Doc file ID to update in place. local_path: Absolute or relative path to the local file. content_format: 'markdown' or 'html'. Defaults to inferring from local_path's extension (.md -> markdown, .html/.htm -> html); pass explicitly to override the extension-based guess. autolink_urls: For markdown content, whether a bare http(s):// URL, www. address or email address becomes a real hyperlink (default True). Set False to leave them as plain text; to suppress just one, wrap it in backticks instead. No effect on HTML content. revoke_sharing: Whether a local-path/drive: image's temporary anyone:reader share is revoked again after it's embedded (default True). An image file that was already link-shared before the call keeps its link and is reported with already_shared: true. auto_downscale: Resize an oversized local-path/drive: image instead of failing it (default False) — see create_doc's own docstring. allow_no_backup: Replace the content even when Drive refuses the backup copy (below) because the doc's sharing settings don't allow this account to copy it, or the account is at its item-creation limit (default False: the call refuses and leaves the doc unchanged). It has no effect when the account can't edit the doc. folder_id: Optional Google Drive folder ID to upload local-path images into. Defaults to the server's default folder, else the doc's own folder.

Returns: Confirmation with the document ID and web link. Includes "images" (per-image outcomes) when the file contained any images. Includes "dropped_links" when a link was written as plain text instead (see create_doc). Includes "warning" if the backup copy (below) couldn't be removed, or if the content was replaced without one. Before clearing a doc that has content, a full copy of it is made in Drive, next to the doc, and deleted again once the new content is in. If the copy fails, nothing is changed and an error is returned, except when Drive refuses it for storage quota, because the account can't add a file to the doc's folder, or because the folder or Shared Drive is at its item limit: the replace then goes ahead without a backup. When sharing settings don't allow copying or the account is at its item-creation limit, it goes ahead without a backup only with allow_no_backup=True. If writing the new content fails, returns {"error", "docId", "backupId", "images", "dropped_links"} instead, with any temporary image share already revoked: the doc may be empty or partly written, and backupId is the kept copy of its previous content. When the replace went ahead without a backup there's no backupId, and the error says the previous content couldn't be backed up: it can't be recovered. The content is converted before any of this, so if it can't be converted, the doc is left unchanged and {"error", "docId"} is returned.

get_doc_structureA

Return the full structural map of a Google Doc body with element indices.

Every batchUpdate operation (insert, delete, style, table) requires knowing the startIndex and endIndex of the target element. This tool exposes those indices alongside paragraph styles, text run formatting, and table cell positions.

Args: doc_id: The Google Doc file ID.

Returns: Dictionary with docId, title, and an elements list. Each element has: - type: "paragraph" | "table" | "sectionBreak" | "tableOfContents" - startIndex, endIndex Paragraphs also include namedStyleType, text, headingId (Google's internal ID for this heading, present only when namedStyleType is HEADING_1..6 — e.g. "h.abc123"; null otherwise), a runs list (each run has text, bold, italic, underline, strikethrough, font_size, link_url; an inline image is a run with type "inlineObject", its inlineObjectId, and its own startIndex/endIndex, and empty text), and bullet (null for a non-list paragraph; otherwise {listId, nestingLevel} — nestingLevel is 0 for a top-level list item, absent from the raw API response in that case, normalized to 0 here so every list paragraph reports a level). Use this to detect a markdown-to-Doc conversion that flattened an intended nested list — sibling paragraphs that should differ in depth but share the same nestingLevel — then fix it with create_paragraph_bullets. Tables include rows, columns, and a cells list (each cell has row, col, startIndex, endIndex, paragraphStartIndex, text).

Note: headingId is the piece needed to build a working in-doc jump link: set link_url via style_doc_range to f"https://docs.google.com/document/d/{doc_id}/edit?tab=t.0#heading={heading_id}" — an ordinary URL, no special Link-object field required. Confirmed live 2026-07-24 (issue #409).

find_in_docA

Search a Google Doc's text and return match locations as document character offsets.

Matches feed directly into style_doc_range's ranges — e.g. to link up bare URLs already sitting in a doc: find_in_doc(doc_id, query=r'https?://[^\s<>"]+(?<![.,;:!?)])', regex=True), then style_doc_range with link_url per match. The trailing negative lookbehind keeps a URL followed by sentence punctuation (or an unmatched closing paren) from swallowing it into the link.

Args: doc_id: The Google Doc file ID. query: Text to search for. Interpreted literally by default; pass regex=True to treat it as a Python regular expression. regex: Whether query is a regular expression (default False). case_sensitive: Whether the search is case-sensitive (default False). max_results: Maximum number of matches to return (default 50). local_path: Optional local filesystem path (file or directory) to write the result to instead of returning it inline. Bypasses the response-size cap. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. Same caveat as download_file/download_folder: this path is resolved on the server's filesystem, not the caller's.

Returns: List of matches, each with start_index/end_index (document offsets usable directly as a style_doc_range range), matched_text, and context (the containing paragraph's full text). Searches paragraph text in the document body, including table cells; headers, footers, and footnotes are not searched. A zero-length regex match (e.g. "x*" with no "x" present) is skipped. Returns {"error": ...} if query is an invalid regex, or if the Docs API call itself fails (e.g. doc_id doesn't exist). max_results bounds match count, not response size — matched context can still be large. Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default) and local_path is not set — lower max_results, or pass local_path. If local_path is set, returns {local_path, doc_id, query, match_count, bytes_written} instead.

insert_doc_textA

Insert text at one or more positions in a Google Doc.

All indices are interpreted as positions in the document before any of the insertions in this call. Insertions are applied high-index-first so earlier indices are not shifted by later ones.

Use get_doc_structure to obtain the correct target indices.

Args: doc_id: The Google Doc file ID. insertions: List of insertion dicts. Required keys: index (int): document position to insert at. text (str): text to insert. "\n" creates a new paragraph. Optional keys: segment_id (str): segmentId of the header or footer to insert into (the headerId / footerId returned by create_header / create_footer). Omit to insert into the document body.

Returns: Confirmation with docId and count of insertions applied.

delete_doc_rangeA

Delete one or more content ranges from a Google Doc.

All indices are interpreted as positions in the document before any of the deletions in this call. Deletions are applied high-index-first so earlier indices are not shifted by later ones.

Use get_doc_structure to obtain the correct start/end indices.

Args: doc_id: The Google Doc file ID. deletions: List of {"start_index": int, "end_index": int}. The range [start_index, end_index) is deleted (end_index is exclusive). Do not include the document's final newline (last endIndex - 1).

Returns: Confirmation with docId and count of deletions applied.

Note: Including a paragraph's trailing paragraph mark in the deleted range merges that paragraph into the next one, and the merged result inherits the next paragraph's style (e.g. deleting through a NORMAL_TEXT paragraph's newline when the following paragraph is HEADING_1 leaves the surviving content styled as HEADING_1). Text inserted afterward at that position silently picks up the same inherited style. Follow a paragraph-mark-inclusive delete with an explicit updateParagraphStyle (style_doc_range's named_style_type, or insert_softbreak_paragraph's named_style_type) rather than assuming the original style survived.

insert_page_breakA

Insert an explicit page break at a specific index in a Google Doc.

Use get_doc_structure to find a suitable insertion index.

Args: doc_id: The Google Doc file ID. index: Document body index where the page break should be inserted.

Returns: Confirmation with docId and the insertion index.

insert_softbreak_paragraphA

Insert a single paragraph built from multiple lines joined by soft line breaks (Shift+Enter in the Docs UI), with the paragraph's style set explicitly rather than inherited from whatever is at index.

Use this for metadata/header-style blocks that must render as one tight paragraph with no blank line between rows — e.g. a document header block: Document ID: KH-OPS-001 (bold) Category: AWS / Database Source: ... insert_doc_text with "\n" between lines creates separate paragraphs with a blank line between them instead. This also sidesteps delete_doc_range's paragraph-merge style-inheritance gotcha (see its docstring) by setting namedStyleType explicitly on the whole paragraph the block lands in, rather than leaving it to whichever neighboring paragraph it happened to merge into.

To replace existing content with a soft-break block: delete it first with delete_doc_range, then call this tool at the same index.

Args: doc_id: The Google Doc file ID. index: Document position to insert at. Use get_doc_structure to find it. lines: List of line dicts, each with: text (str): the line's text (required, non-empty). Optional per-line text style, applied only to that line's own span (same vocabulary as style_doc_range's text-style fields): bold, italic, underline, strikethrough (bool) font_size (float): size in points foreground_color (dict): {"red": 0-1, "green": 0-1, "blue": 0-1} link_url (str | null): set a hyperlink (null to clear) named_style_type: Paragraph style applied to the whole paragraph the inserted block ends up in (per Docs API updateParagraphStyle semantics, this covers the entire paragraph touched by the insert, not just the newly-inserted span). NORMAL_TEXT (default), HEADING_1 … HEADING_6, TITLE, SUBTITLE.

Returns: Confirmation with docId, start_index, end_index (the inserted block's span), and line_ranges — a parallel list of {start_index, end_index} per line, usable directly with style_doc_range for any styling beyond what this call already applied.

insert_inline_imageA

Insert an inline image at a specific index in a Google Doc.

Provide either uri (a publicly accessible HTTPS image URL) or drive_file_id (a Drive file ID for an image stored in Drive). The image is inserted at the given document index.

Use get_doc_structure to find a suitable insertion index.

Args: doc_id: The Google Doc file ID. index: Document body index where the image should be inserted. uri: A publicly accessible image URI (HTTPS). Mutually exclusive with drive_file_id. drive_file_id: A Google Drive file ID for an image stored in Drive. The Docs backend fetches the image over HTTP as an anonymous request, so the file must be shared as anyone-with-link (e.g. via share_file with {"type": "anyone", "role": "reader"}) — being accessible to the authenticated user alone is not sufficient and fails with "There was a problem retrieving the image" (confirmed live 2026-07-18). Mutually exclusive with uri. width: Optional image width in points. height: Optional image height in points. auto_downscale: Google Docs rejects any inline image over ~25 megapixels or ~50MB. When drive_file_id is provided and Drive's own reported dimensions or file size exceed either limit, the default (False) fails fast with a clear error naming the limit and the image's actual size — before ever calling the Docs API. Set True to instead resize it and embed the resized copy: the original Drive file is left untouched, a new file named " (resized)" is created alongside it and shared anyone:reader, and its own fileId is returned as resized_file_id. Ignored when uri is used instead of drive_file_id — there's no local copy of a bare uri to resize; an oversized uri source instead fails with a rewritten error explaining the likely cause, since pre-validating or re-hosting arbitrary external content is out of scope here (see docs/decisions/decision- pillow-image-dependency.md).

Returns: Confirmation with docId and the insertion index. Also includes resized_file_id if drive_file_id was resized under auto_downscale, on an error result too, since the resized copy exists either way.

insert_local_imagesA

Upload local image files to Drive and swap each into a Google Doc at a plain-text marker, in one call. Not available when the server runs with LOCAL_FILE_ACCESS=off.

Typical flow: write doc content with a unique plain-text placeholder per image (e.g. "IMGMARKERONE") via create_doc/write_doc_content/insert_doc_text, then call this tool once with the marker → local file mapping. Collapses the N manual upload/find/insert/delete round trips a multi-image doc would otherwise need into a single call.

For each image: uploads the local file to Drive, shares it as anyone-with-link/reader (required — the Docs backend fetches inline images as an anonymous HTTP request, so a private file fails with "There was a problem retrieving the image"; confirmed live 2026-07-18), locates its marker's current position, inserts the image immediately before the marker text, then deletes the marker text. Once the image is actually embedded, that temporary share is revoked again by default (revoke_sharing=True) — revoking any earlier would break the embed, since Docs fetches the image at insertion time, not upload time. The revoke also runs if the document edit fails or the call is cancelled; a cancelled call returns nothing, so the uploaded file IDs are logged as a warning instead.

All markers are located in a single pass over the document's current text before any edits are applied — markers are matched longest-first at each position, so one marker that's a substring of another (e.g. "IMG1" vs "IMG10") can't produce a false match or a false "occurs twice" collision. Uploads and shares run in parallel; the document edit is one batchUpdate applied highest-index-first so replacing one marker never invalidates another marker's already-computed position — same convention as insert_doc_text/delete_doc_range. Uploading and sharing happen before any document edit, so a failed upload never leaves the doc partially edited.

Args: doc_id: The Google Doc file ID. images: List of image dicts, each with: marker (str): exact literal text already present in the doc body, marking where this image goes. Matched as a whole token — not immediately preceded or followed by another letter, digit, or underscore — so a marker like "IMG1" can't falsely match inside unrelated text like "IMG10". Must occur exactly once in the document (searched case-sensitively) — an ambiguous or missing marker fails just that image, not the whole call. local_path: absolute path to the local image file. width, height (float, optional): image size in points. folder_id: Drive folder to upload images into. Defaults to the server's configured default folder. revoke_sharing: Whether each image's temporary anyone:reader share is revoked again after it's embedded (default True). Set False to leave images shared instead — matches this tool's original behavior. A file that was already link-shared before the call (e.g. inherited from its folder) keeps its link and is reported with already_shared: true. auto_downscale: Google Docs rejects any inline image over ~25 megapixels or ~50MB. Each image's local file is checked against both limits before it's ever uploaded. The default (False) fails just that image with a clear error naming the limit and its actual size — other images in the same call are unaffected. Set True to instead resize an oversized image and upload the resized copy (the local file on disk is never modified); that outcome's entry gets downscaled: true.

Returns: Dictionary with docId and results — a list of per-image outcomes in the same order as the images argument, each echoing marker and local_path plus either fileId + index + shared (+ revoke_error if a revoke attempt failed, + downscaled: true if auto_downscale resized it, + already_shared: true if the file was link-shared before this call) on success, or error on failure (marker not found, marker not unique, local file missing, oversized with auto_downscale off, upload failure, sharing failure, or — rare, since uploads happen first — a failed document edit; that last case keeps fileId and shared, with no index, since the upload and share happened even though the image was never placed). A sharing failure after the underlying Drive file was already created also carries fileId (#649) — the upload itself succeeded even though the share didn't.

insert_doc_tableA

Insert an empty table at a specific position in a Google Doc.

The table is inserted at the given index. The document is re-fetched immediately to return the actual cell indices. Use those indices with insert_doc_text (targeting each cell's paragraphStartIndex) to fill cells, or with style_doc_table_cells to apply formatting.

Also useful for form-style column alignment (labels/values lined up without a visible table) — a zero-padding table gives exact column positions where tabStops would otherwise be needed (tabStops itself is read-only, #404). See docs/design/borderless-table-columns.md for the full recipe.

Args: doc_id: The Google Doc file ID. index: Document body index where the table should be inserted. Use get_doc_structure to find a suitable position (e.g. the endIndex of the paragraph before the intended location). rows: Number of table rows. columns: Number of table columns.

Returns: precedingParagraphIndex (= index), tableStartIndex (= index + 1), tableEndIndex, rows, columns, and a cells list (each cell has row, col, startIndex, endIndex, paragraphStartIndex). To fully delete the table later, delete the range [precedingParagraphIndex, tableEndIndex] in one call.

insert_table_rowA

Insert a row into an existing table in a Google Doc.

Use get_doc_structure to find the table's startIndex and the row_index to insert relative to.

Args: doc_id: The Google Doc file ID. table_start_index: The startIndex of the table (from get_doc_structure). row_index: The row to insert relative to. insert_below: If True (default), insert below the specified row. If False, insert above it.

Returns: Confirmation with docId, table_start_index, and the row_index used.

delete_table_rowA

Delete a row from an existing table in a Google Doc.

Use get_doc_structure to find the table's startIndex and the row_index to delete.

Args: doc_id: The Google Doc file ID. table_start_index: The startIndex of the table (from get_doc_structure). row_index: Zero-based index of the row to delete.

Returns: Confirmation with docId, table_start_index, and deleted row_index.

insert_table_columnA

Insert a column into an existing table in a Google Doc.

Use get_doc_structure to find the table's startIndex and the column_index to insert relative to.

Args: doc_id: The Google Doc file ID. table_start_index: The startIndex of the table (from get_doc_structure). column_index: The column to insert relative to. insert_right: If True (default), insert to the right of the specified column. If False, insert to the left.

Returns: Confirmation with docId, table_start_index, and the column_index used.

merge_table_cellsA

Merge a rectangular range of cells in an existing table into one cell.

Use get_doc_structure to find the table's startIndex and the row/column of the merge range's top-left (anchor) cell. Merging doesn't delete content or shift character indices: cells covered by the merge remain physical entries in the doc, they're just no longer independently addressable in the rendered table.

Args: doc_id: The Google Doc file ID. table_start_index: The startIndex of the table (from get_doc_structure). row_index: Zero-based row of the merge range's top-left cell. column_index: Zero-based column of the merge range's top-left cell. row_span: Number of rows the merged cell should span (default 1). column_span: Number of columns the merged cell should span (default 1).

Returns: Confirmation with docId, table_start_index, row_index, column_index, row_span, and column_span.

delete_table_columnA

Delete a column from an existing table in a Google Doc.

Use get_doc_structure to find the table's startIndex and the column_index to delete.

Args: doc_id: The Google Doc file ID. table_start_index: The startIndex of the table (from get_doc_structure). column_index: Zero-based index of the column to delete.

Returns: Confirmation with docId, table_start_index, and deleted column_index.

style_doc_rangeA

Apply paragraph and/or text styles to one or more index ranges in a Google Doc.

Use get_doc_structure to obtain the startIndex and endIndex for each target range. Multiple ranges can be styled in a single call; all batchUpdate requests are sent together.

Args: doc_id: The Google Doc file ID. ranges: List of range dicts. Each dict must include start_index and end_index, plus any combination of the style fields below:

    Paragraph style:
      named_style_type (str): NORMAL_TEXT, HEADING_1 … HEADING_6,
          TITLE, SUBTITLE

    Text style:
      bold (bool), italic (bool), underline (bool), strikethrough (bool)
      font_size (float): size in points
      font_family (str): font family name (e.g. "Courier New", "Consolas")
      foreground_color (dict): {"red": 0-1, "green": 0-1, "blue": 0-1}
      link_url (str | null): set a hyperlink (null to clear)

Returns: Confirmation with docId and count of batchUpdate requests sent.

style_doc_table_cellsA

Apply border, padding, and background styles to table cells in a Google Doc.

Args: doc_id: The Google Doc file ID. table_start_index: The startIndex of the table (from get_doc_structure or insert_doc_table). cells: List of cell style dicts. Each dict must include row_index and column_index, plus any combination of:

    background_color (dict): {"red": 0-1, "green": 0-1, "blue": 0-1}
    padding_top, padding_right, padding_bottom, padding_left (float): points
    border_color (dict): {"red": 0-1, "green": 0-1, "blue": 0-1}
        Applies the same color to all four borders (any edge not given its
        own border_top/right/bottom/left below).
    border_width (float): border line width in points
    border_dash_style (str): "SOLID", "DOT", "DASH", "DASH_DOT",
        "LONG_DASH", "LONG_DASH_DOT" (default SOLID)
    border_top, border_right, border_bottom, border_left (dict): optional
        per-edge override, each {"color": {...}, "width": float,
        "dash_style": str}. Any field omitted from a per-edge dict falls
        back to the uniform border_color/border_width/border_dash_style
        above, if given (the Docs API rejects a border with non-zero width
        and no color as "transparent", so a width-only override needs a
        color from somewhere). An edge with no border_<side> key falls back
        entirely to the uniform border_color/border_width/border_dash_style,
        if given; with neither, that edge's border is left untouched.
    row_span (int): default 1
    column_span (int): default 1

Returns: Confirmation with docId and count of batchUpdate requests sent.

Example — standard data-room table style (grey header, thin border, 3.6pt padding): table_start_index: cells: [ {"row_index": 0, "column_index": 0, "column_span": <num_cols>, "background_color": {"red": 0.953, "green": 0.953, "blue": 0.953}, "padding_top": 3.6, "padding_right": 3.6, "padding_bottom": 3.6, "padding_left": 3.6, "border_color": {"red": 0, "green": 0, "blue": 0}, "border_width": 0.5, "border_dash_style": "SOLID"} ]

Example — signature line (bottom border only): cells: [ {"row_index": 0, "column_index": 0, "border_bottom": {"color": {"red": 0, "green": 0, "blue": 0}, "width": 1.0}} ]

For form-style column alignment (labels/values lined up without a visible table, since tabStops is read-only — #404), zero padding on every cell is the confirmed part of the recipe; whether border_width: 0 also suppresses a table's default visible border is not yet confirmed live. See docs/design/borderless-table-columns.md.

create_paragraph_bulletsA

Turn one or more paragraph ranges into a bulleted or numbered list, with explicit nesting depth.

Wraps the Docs API's createParagraphBullets/deleteParagraphBullets requests, working around two confirmed-live API quirks:

  • createParagraphBullets is a no-op on a paragraph that's already part of a list — it neither changes the existing nesting level nor consumes any leading tab characters meant to signal a new one (they're left behind as literal text). Every paragraph this tool touches is deleteParagraphBullets'd first (harmless even if it wasn't previously a list item) so createParagraphBullets always applies to a clean, non-list paragraph. deleteParagraphBullets keeps a removed item's indent, which createParagraphBullets would read as extra depth, so the tool also zeroes each paragraph's indentation before bulleting it. nesting_level is therefore absolute: repeating the same call changes nothing.

  • createParagraphBullets has no nestingLevel field of its own — the API infers each paragraph's depth from its own leading tab characters, but only relative to whatever ELSE is included in that same call. A paragraph immediately adjacent to an existing list item that call doesn't also cover gets pulled back to that neighbor's level regardless of its own tabs (the same class of bug PR #432 fixed in this project's own markdown-to-Doc converter). To keep every requested paragraph's relative depth correct, this tool fetches the document, resolves each requested range to the paragraph(s) it covers, and — for any that are already part of a list — expands the affected span to include their full contiguous run of same-list neighbors (preserving each neighbor's own current nesting level unchanged). Contiguous spans sharing one bullet preset are then submitted as a single createParagraphBullets call each, applied in descending document-position order so no not-yet-processed span's indices are invalidated by an earlier span's tab insertions. A span in which every paragraph sits at nesting_level > 0 (no level-0 member to anchor the API's relative depth inference) is wrapped with a throwaway 0-tab anchor paragraph that is bulleted alongside the real items and then deleted, so the items land at their true nesting level instead of collapsing to 0 (issue #713; the same fix emitter.py carries for #439).

Use get_doc_structure to obtain start_index/end_index for each target range — typically one paragraph's own startIndex/endIndex, or a contiguous span covering several (all promoted to the same nesting_level/bullet_preset). For independent depths per paragraph, pass one range per paragraph.

Args: doc_id: The Google Doc file ID. ranges: List of range dicts, each with: start_index (int), end_index (int): from get_doc_structure — must overlap at least one existing paragraph. bullet_preset (str, optional): "BULLET_DISC_CIRCLE_SQUARE" (unordered) or "NUMBERED_DECIMAL_ALPHA_ROMAN" (ordered) — the only two presets this codebase has confirmed live (see emitter.py). The Docs API defines additional glyph/numbering presets not exercised here; pass the literal API enum string to use one anyway. If omitted, an already-listed target paragraph keeps its existing list's own style (read from the document's own lists map) rather than silently being converted to a different one; a paragraph with no existing list falls back to "BULLET_DISC_CIRCLE_SQUARE". nesting_level (int, optional): 0 = top-level (default), 1 = one level indented, etc. Must be >= 0.

Returns: Confirmation with docId and count of batchUpdate requests sent. {"error": ...} if ranges is empty, a nesting_level is negative, a range doesn't overlap any paragraph, two explicitly-requested contiguous paragraphs specify conflicting presets, or the Docs API call fails.

delete_paragraph_bulletsA

Remove list membership (bullets/numbering) from one or more paragraph ranges, leaving each paragraph's text and other styling untouched. The API keeps a nested item's indent as paragraph indentation (36pt per nesting level for the standard presets), so a nested item stays indented after its bullet is gone; a top-level item doesn't.

Args: doc_id: The Google Doc file ID. ranges: List of range dicts, each with start_index and end_index (from get_doc_structure).

Returns: Confirmation with docId and count of batchUpdate requests sent.

get_doc_themeA

Derive a theme dict from a Google Doc's actual paragraph styles.

Scans the document body and reads the style of the first paragraph found for each named style type (NORMAL_TEXT, HEADING_1 through HEADING_6, TITLE, SUBTITLE). Text-level fields (font_family, font_size, bold, italic, color) are the ones every non-empty text run in that paragraph shares, so a bold lead-in isn't reported; paragraph-level fields (line_spacing, space_above, space_below) come from the paragraph's paragraphStyle. A named style type that doesn't appear in the body, or whose first paragraph has no explicit style, is left out.

NORMAL_TEXT's first paragraph is the first of body text: a quote, a rule, a code block or an empty line is skipped, unless the doc has no body text, and then the first of them with text is used. Its space_above and space_below leave out 8pt and 10pt, the spacing a Markdown or HTML write puts around blocks and between paragraphs.

Subsequent paragraphs of the same named style type that differ in style are ignored — they are treated as intentional individual overrides outside the theme.

Use this tool when styles were applied directly to paragraphs (the common case). Use get_doc_named_styles instead when the human explicitly set named style defaults via Format > Paragraph styles > Update X to match in the Google Docs UI. Calling both and comparing results lets you detect whether explicit named styles are in use.

The returned dict is suitable for passing directly to apply_theme.

Args: doc_id: The Google Doc file ID.

Returns: Theme dict keyed by named style type. Empty dict if no explicit paragraph styles are found (e.g. the doc uses purely inherited named style defaults).

get_doc_named_stylesA

Read a Google Doc's named style defaults and return them as a theme dict.

Named styles are set via Format > Paragraph styles > Update X to match in the Google Docs UI. They define the default appearance for each style type and are inherited by paragraphs that have no explicit overrides.

Most docs leave named styles at Google's defaults even when paragraphs look custom — because humans usually format text directly without updating named styles. In that case this tool returns Google's defaults (Arial/Roboto etc.), which may not reflect the doc's actual appearance. Use get_doc_theme to read what the doc actually looks like based on applied paragraph styles.

Calling both tools and comparing results is useful: if they agree, named styles are in sync with actual content; if they differ, styles were applied directly to paragraphs without updating named style definitions.

Args: doc_id: The Google Doc file ID.

Returns: Theme dict keyed by named style type. Only entries with at least one non-default field are included. Returns an empty dict if named styles are at Google's defaults.

apply_themeA

Apply a theme dict to a Google Doc by updating its named style definitions.

By default (overwrite=False), theme entries are applied as document-level named style defaults via updateNamedStyle. Paragraphs that have explicit individual style overrides are unaffected — their styles take precedence over the named style defaults. This preserves intentional per-paragraph variations (e.g. a section deliberately styled in a different colour). One exception: a NORMAL_TEXT entry with space_above or space_below replaces the 10pt space below a paragraph that a Markdown or HTML write leaves between paragraphs, so the theme's spacing shows.

For AI-generated docs where all content uses explicit paragraph/run styles, the default mode updates the named style definitions but does not visually change existing content. New paragraphs added without explicit styles will inherit the updated named style defaults.

Set overwrite=True to also apply the theme directly to all existing paragraphs, overwriting their current styles including any individual overrides.

Theme entry keys (NORMAL_TEXT, HEADING_1-6, TITLE, SUBTITLE). Each entry can include (all optional): font_family (str), font_size (float, points), bold (bool), italic (bool), color (dict {"red": 0-1, "green": 0-1, "blue": 0-1}), line_spacing (float, 100=single, 115=1.15x, 150=1.5x), space_above (float, points), space_below (float, points)

An optional "table" key applies styling to every table currently in the document: border_color (dict), border_width (float, points), border_dash_style (str, default "SOLID"), border_top, border_right, border_bottom, border_left (dict): optional per-edge override, each {"color": {...}, "width": float, "dash_style": str}. Any field omitted from a per-edge dict falls back to the uniform border_color/border_width/border_dash_style above, if given (the Docs API rejects a border with non-zero width and no color as "transparent", so a width-only override needs a color from somewhere). An edge with no border_ key falls back entirely to the uniform border_color/ border_width/border_dash_style, if given. cell_padding (float, points — all four sides), header_background (dict) — first row only

Args: doc_id: The Google Doc file ID. theme: Theme dict. See above for schema. overwrite: If True, also apply styles directly to existing paragraphs, overwriting individual per-paragraph style overrides.

Returns: Confirmation with docId and count of batchUpdate requests sent.

create_headerA

Add a page header to a Google Doc.

Creates a header section and optionally inserts plain text content into it. For rich formatting, use insert_doc_text with the returned headerId as segmentId after calling this tool.

Args: doc_id: The Google Doc file ID. header_type: "DEFAULT" (all pages, default) or "FIRST_PAGE_HEADER" (applies only to the first page — requires useFirstPageHeaderFooter to be set on the document section, which the Docs UI handles automatically). content: Optional plain text content to insert into the header.

Returns: Confirmation with docId and headerId. Use headerId as the segmentId in subsequent insert_doc_text calls to add formatted content.

create_footerA

Add a page footer to a Google Doc.

Creates a footer section and optionally inserts plain text content into it. For rich formatting, use insert_doc_text with the returned footerId as segmentId after calling this tool.

Args: doc_id: The Google Doc file ID. footer_type: "DEFAULT" (all pages, default) or "FIRST_PAGE_FOOTER" (applies only to the first page — requires useFirstPageHeaderFooter to be set on the document section, which the Docs UI handles automatically). content: Optional plain text content to insert into the footer.

Returns: Confirmation with docId and footerId. Use footerId as the segmentId in subsequent insert_doc_text calls to add formatted content.

list_doc_commentsA

List comments (and their replies) on a Google Doc via the Drive comments resource.

Args: doc_id: The Google Doc file ID. page_size: Maximum number of comments to return per page (default 20). page_token: Continuation token from a previous response for pagination. include_deleted: Whether to include deleted comments (default False).

Returns: Dictionary with: - doc_id: echoed back for reference - comments: list of comments, each with id, content, author (display_name, email_address), created_time, modified_time, resolved, deleted, quoted_text (the anchored text, if any), and replies. Each reply has id, content, author, created_time, modified_time, deleted, and action ("resolve" or "reopen", or None for an ordinary reply) — replies have no resolved or quoted_text field of their own; a comment's resolved status is derived from its most recent reply's action. - next_page_token: present when more results are available Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default) — lower page_size and paginate via next_page_token instead of raising the cap.

add_doc_commentA

Add a comment to a Google Doc via the Drive comments resource.

Args: doc_id: The Google Doc file ID. content: The comment text. quoted_text: Optional text from the document to anchor the comment to, shown as the quoted range the comment refers to.

Returns: Dictionary with id, content, author (display_name, email_address), created_time, and quoted_text (echoing the anchor, if one was set).

resolve_doc_commentA

Mark a comment on a Google Doc as resolved, by posting a reply with a "resolve" action via the Drive comments resource.

Args: doc_id: The Google Doc file ID. comment_id: The ID of the comment to resolve (from list_doc_comments). reply_content: Optional text to attach to the resolving reply.

Returns: Dictionary with doc_id, comment_id, reply id, and action ("resolve").

create_named_rangeA

Create a named range over a span of content in a Google Doc.

A named range lets you reference a section of the document by name later (e.g. with ReplaceNamedRangeContentRequest via batch_update) without tracking raw indices yourself — the Docs API automatically shifts the range's bounds as content is inserted or deleted elsewhere in the doc.

Use get_doc_structure to find start/end indices for the target span.

Args: doc_id: The Google Doc file ID. name: Name for the range. Not required to be unique; 1-256 UTF-16 code units. start_index: Start of the range (inclusive). end_index: End of the range (exclusive).

Returns: Confirmation with docId, namedRangeId, name, startIndex, endIndex.

Note: Named ranges are not visible in the Docs UI and cannot be used as internal hyperlink targets (the Link object only supports UI-created bookmarks and headings, not named ranges) — they exist purely for programmatic reference via the API.

create_bookmarkA

Create a lightweight, named anchor point at a single position in a Google Doc.

The Docs API has no dedicated bookmark-creation endpoint (Docs UI bookmarks can only be inserted by hand). This is a convenience wrapper around create_named_range that spans the single character at index, giving you a named position you can look up later without hardcoding raw indices — the range's bounds shift automatically as the API tracks surrounding edits.

Use get_doc_structure to find a suitable index.

Args: doc_id: The Google Doc file ID. name: Name for the bookmark. Not required to be unique; 1-256 UTF-16 code units. index: Document position to anchor at (the character at this index is included in the underlying named range).

Returns: Confirmation with docId, namedRangeId, name, index.

Note: This is not a Docs UI bookmark: it won't appear in Insert > Bookmark and cannot be used as an internal hyperlink target (the Link object only supports UI-created bookmarks and headings, not named ranges). Use create_named_range directly for an anchor spanning more than one character.

get_doc_as_markdownA

Export a Google Doc's content as GitHub-flavored Markdown.

The inverse of create_doc/write_doc_content's content_format='markdown' path — walks the Docs API structure into this project's own AST and serializes it to Markdown, rather than converting Docs' own HTML export. Supports headings, bold/italic/strikethrough/links, nested bullet and numbered lists, task-list checkboxes, blockquotes, inline code and code blocks, images, and tables (including nested tables, best-effort — see Known limitations below).

Args: doc_id: The Google Doc file ID. include_comments: When True, appends a "## Comments" section listing every open (non-resolved) comment's author, quoted anchor text, content, and replies, via the same Drive comments resource list_doc_comments uses. Default False. local_path: Optional local filesystem path to write the Markdown to instead of returning it inline. The file holds the raw Markdown text (UTF-8), byte-identical to the inline markdown field, including the comments section when include_comments is True. A directory path writes <doc_id>.md inside it; a path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. Bypasses the response-size cap.

Returns: Dictionary with doc_id, title, and markdown (the full Markdown text) — or {local_path, doc_id, title, bytes_written} if local_path is set. Raises ValueError if the response exceeds a safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md) and local_path is not set.

Known limitations: - A table nested inside another table's cell has no Markdown table syntax to express it — that cell renders a placeholder note instead (the write side has the identical gap in reverse; see docs/design/markdown-support.md's "What this does NOT do"). - Inline images resolve to Drive's temporary contentUri, which expires (roughly 30 minutes) — re-export if the Markdown is consumed well after generation. - Only the document's default tab is read (matches get_doc_structure's existing scope) — multi-tab documents are out of scope. - namedStyleType TITLE/SUBTITLE map to H1/H2; Markdown has no equivalent to Docs' distinct Title/Subtitle paragraph styles. - Merged table cells (colspan/rowspan) render best-effort: GFM pipe tables have no merge concept, so a spanned cell's text lands in its first column and the rest render blank.

get_cache_ttlA

Read the cache TTL currently in effect for this running process.

Returns: {"ttl_seconds": }. All five cache namespaces are always kept in sync by set_cache_ttl, so a single value represents all of them.

set_cache_ttlA

Change the cache time-to-live at runtime, without restarting the server.

The change takes effect in the running server process, without a restart. Use get_cache_ttl first if you need to restore the previous value afterward.

Args: ttl_seconds: New TTL in seconds, applied to all five cache namespaces (sheet structure, sheet data, Drive folders, docs, calendars). Must be >= 0; 0 effectively disables TTL-based caching (every entry is immediately eligible for expiry).

Returns: Confirmation with the new TTL. Applies only to this running process — set CACHE_TTL in the environment/.env for the startup default.

refresh_cacheA

Invalidate caches, forcing a fresh fetch on next use.

Args: spreadsheet_id: Invalidate sheet structure and data cache for this spreadsheet. doc_id: Invalidate doc content cache for this Google Doc file ID. folder_id: Invalidate Drive folder listing cache for this folder ID. calendar_id: Invalidate calendar metadata cache for this calendar ID. If none are provided, invalidates all caches (sheets, data, folders, docs, calendars, and the Gmail mailbox's own send-as addresses).

Returns: Confirmation of what was invalidated

list_calendarsA

List all calendars accessible to the authenticated user.

Returns: List of calendars with id, summary, time_zone, access_role, and primary flag. Results are cached; call refresh_cache(calendar_id=...) to invalidate.

get_calendarB

Fetch metadata for a single calendar.

Args: calendar_id: The calendar ID, or 'primary' for the user's primary calendar.

Returns: Calendar metadata: id, summary, description, time_zone, access_role, primary.

create_calendarB

Create a new secondary calendar owned by the authenticated user.

Args: summary: Calendar title. description: Optional calendar description. timezone: IANA timezone name (e.g. 'America/Los_Angeles'). Defaults to the account's timezone if omitted.

Returns: Created calendar: id, summary, description, time_zone.

update_calendarA

Update fields on an existing calendar using patch semantics. Only the fields you provide are changed; omitted fields are left as-is.

Note: color_id is set via the authenticated user's calendar list entry (calendarList().patch()), not the calendar resource itself — it is a per-user setting, not a property of the calendar shared with others.

Args: calendar_id: The calendar ID, or 'primary'. summary: New calendar title. description: New calendar description. timezone: New IANA timezone name (e.g. 'America/Los_Angeles'). color_id: New color ID from the palette returned by the Calendar API's colors().get() endpoint (predefined IDs, typically '1'-'24').

Returns: Updated calendar: id, summary, description, time_zone, color_id.

delete_calendarA

Permanently delete a calendar. For calendars you own, this deletes the calendar entirely for all users it is shared with — use with caution. To only stop seeing a calendar in your own list, use remove_calendar_from_list instead.

Args: calendar_id: The calendar ID to delete.

Returns: Confirmation with calendar_id and action 'deleted'.

add_calendar_to_listA

Subscribe the authenticated user (or service account) to a calendar, adding it to their calendar list so it appears in list_calendars.

This does not create or share a calendar — it only adds an existing, already-accessible calendar to your own list. For service accounts, this is the required step before a calendar shared with the service account's email will show up in list_calendars.

Args: calendar_id: The calendar ID to subscribe to (e.g. the owner's email for a personal calendar, or a ...@group.calendar.google.com ID). color_id: Optional color ID from the palette returned by the Calendar API's colors().get() endpoint (predefined IDs, typically '1'-'24').

Returns: The new calendar list entry: id, summary, time_zone, access_role, primary, color_id.

remove_calendar_from_listA

Unsubscribe from a calendar, removing it from the authenticated user's calendar list. The calendar itself is not deleted and is unaffected for any other user it's shared with — use delete_calendar to permanently delete a calendar you own.

Args: calendar_id: The calendar ID to remove from the list.

Returns: Confirmation with calendar_id and action 'removed_from_list'.

list_calendar_aclA

List the access control rules (sharing entries) on a calendar. Every page is fetched (250 rules each), up to a 100-page safety bound.

Args: calendar_id: The calendar ID, or 'primary'.

Returns: List of ACL rules, each with id, role, scope_type, and scope_value. If the first page fails, returns [{"error": ...}]. If a later page fails (or the page bound is hit), returns the rules already fetched followed by one final {"error": ..., "partial": True} entry, so a truncated list is never mistaken for a complete one. Raises ValueError if the response exceeds the safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default).

add_calendar_aclA

Grant access to a calendar by adding an access control rule.

Args: calendar_id: The calendar ID, or 'primary'. role: Access role to grant. One of: 'reader', 'writer', 'owner', 'freeBusyReader'. scope_type: Who the rule applies to. One of: 'user', 'group', 'domain', 'default' ('default' grants public access to all users and must not have a scope_value). scope_value: Email address (for 'user'/'group') or domain name (for 'domain'). Required unless scope_type is 'default', in which case it must be omitted. send_notifications: Whether to send a notification email to the grantee. Defaults to True.

Returns: Created ACL rule: id, role, scope_type, scope_value. Google rejects any change to the calendar's primary-owner rule or to the authenticated account's own rule; that returns an {"error": ...} naming which one.

remove_calendar_aclA

Revoke an access control rule from a calendar.

Args: calendar_id: The calendar ID, or 'primary'. rule_id: The ACL rule ID to remove (from list_calendar_acl).

Returns: Confirmation with calendar_id, rule_id, and action 'removed'. The calendar's primary-owner rule and the authenticated account's own rule can't be removed; that returns an {"error": ...} naming which one.

list_eventsA

List events in a calendar.

Args: calendar_id: The calendar ID, or 'primary'. time_min: Lower bound (inclusive) for event start times, RFC 3339 format, e.g. '2026-01-01T00:00:00Z'. Defaults to the current UTC time. time_max: Upper bound (exclusive) for event end times, RFC 3339 format. query: Free-text search terms to find events matching summary, description, location, attendee names/emails. max_results: Maximum number of events to return (default 50, max 2500). expand_recurring: When True (default), recurring events are expanded into individual instances. When False, each recurring series is returned as a single master event — useful for retrieving the master event ID needed to update all instances at once.

Returns: List of events with id, summary, start, end, location, description, organizer, attendees, recurrence, html_link, and status.

get_eventC

Fetch a single event by calendar ID and event ID.

Args: calendar_id: The calendar ID, or 'primary'. event_id: The event ID.

Returns: Full event details: id, summary, start, end, location, description, organizer, attendees, recurrence, html_link, status, created, updated.

create_eventA

Create a new event in a calendar.

Args: calendar_id: The calendar ID, or 'primary'. summary: Event title. start: Start datetime in RFC 3339 format, e.g. '2026-06-01T10:00:00-07:00'. Use 'YYYY-MM-DD' for all-day events. end: End datetime in RFC 3339 format. Use 'YYYY-MM-DD' for all-day events. description: Optional event description. location: Optional location string. attendees: Optional list of attendee email addresses. timezone: IANA timezone name (e.g. 'America/Los_Angeles'). Required when start/end are date-only (all-day events) or when recurrence is set with datetime start/end. recurrence: RFC 5545 recurrence rules, e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR"] for Mon/Wed/Fri weekly, ["RRULE:FREQ=DAILY;COUNT=5"] for 5 occurrences, ["RRULE:FREQ=MONTHLY;UNTIL=20261231T000000Z"] until a date. EXDATE and RDATE lines are also accepted in the array.

Returns: Created event: id, summary, start, end, recurrence, html_link, status.

update_eventA

Update fields on an existing event using a partial update (patch semantics). Only the fields you provide are changed; omitted fields are left as-is.

Recurring event scope — the Calendar API controls which instances are updated based on which event ID you pass:

  • This event only: pass the instance event ID (e.g. "base_id_20260601T100000Z"). The API creates an exception override for that occurrence.

  • All events in the series: pass the master (recurring) event ID. Use list_events(expand_recurring=False) to retrieve master event IDs.

  • This and following: not directly supported by the API. As a workaround, update the master event's RRULE to add an UNTIL date before the target instance, then create a new event starting from that date.

Args: calendar_id: The calendar ID, or 'primary'. event_id: The event ID to update (instance ID for single-occurrence changes, master ID for all-occurrence changes). summary: New event title. start: New start datetime (RFC 3339) or date ('YYYY-MM-DD'). end: New end datetime (RFC 3339) or date ('YYYY-MM-DD'). description: New description. location: New location. attendees: Replacement attendee list (full replacement, not append). timezone: IANA timezone for start/end when they are date-only. recurrence: RFC 5545 recurrence rules to replace the event's RRULE, e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR"]. Pass an empty list ([]) to remove recurrence and make the event a one-time occurrence.

Returns: Updated event: id, summary, start, end, recurrence, html_link, status.

delete_eventB

Delete or cancel an event.

Args: calendar_id: The calendar ID, or 'primary'. event_id: The event ID to delete.

Returns: Confirmation with calendar_id, event_id, and action 'deleted'.

find_free_slotsA

Query busy times for a list of calendars and return free slots within the window.

Args: calendar_ids: List of calendar IDs to check (use 'primary' for the user's primary calendar). time_min: Start of the window to check, RFC 3339 format, e.g. '2026-06-01T09:00:00Z'. time_max: End of the window to check, RFC 3339 format. timezone: IANA timezone name for the query (default 'UTC').

Returns: busy: dict mapping each calendar_id to its list of busy periods ({start, end} each in RFC 3339). A calendar the freebusy API couldn't read (bad id, no access, etc.) maps instead to a single-element list holding {calendar_id, calendar_summary, error} — the same per-calendar error shape list_all_events uses, rather than aborting the whole query. calendar_summary falls back to the id when the calendar isn't in the user's list. free_slots: list of free periods ({start, end}) across all calendars, computed as the complement of the union of all busy times.

list_all_eventsA

List events across multiple calendars in one call, fanning out to each calendar in parallel instead of requiring one list_events call per calendar. At most LIST_ALL_EVENTS_MAX_CONCURRENCY (default 20) calendars are queried at once, shared across every concurrent list_all_events call on this server.

Args: time_min: Lower bound (inclusive) for event start times, RFC 3339 format, e.g. '2026-01-01T00:00:00Z'. Defaults to the current UTC time. time_max: Upper bound (exclusive) for event end times, RFC 3339 format. query: Free-text search terms to find events matching summary, description, location, attendee names/emails. calendar_ids: Calendar IDs to query. Defaults to every calendar in the authenticated user's calendar list (list_calendars). max_results_per_calendar: Maximum number of events to return per calendar (default 50, max 2500). expand_recurring: When True (default), recurring events are expanded into individual instances. When False, each recurring series is returned as a single master event. group_by_calendar: When False (default), returns a flat list of events sorted by calendar. When True, returns a dict keyed by calendar summary instead (disambiguated with " (calendar_id)" suffix when two calendars share the same summary).

Returns: A flat list of events (each including calendar_id and calendar_summary), or if group_by_calendar=True, a dict mapping calendar summary to that calendar's event list. A calendar that fails to query is included inline as {calendar_id, calendar_summary, error} rather than aborting the batch. If the calendar list itself fails to load and calendar_ids wasn't given (so there's no way to know what to query), returns a single top-level {"error": ...} instead of raising. Raises ValueError if the response exceeds the safety cap (see MAX_TOOL_RESPONSE_CHARS in docs/configuration.md for the configured default) — narrow the time window, pass calendar_ids, or lower max_results_per_calendar.

list_messagesA

List messages in the authenticated user's mailbox.

Args: query: Gmail search syntax filter, e.g. 'from:alice@example.com is:unread'. label_ids: Only return messages that have all of these label IDs (e.g. ['INBOX', 'UNREAD']). max_results: Maximum number of messages to return (default 50, max 500). page_token: Continuation token from a previous response for pagination. include_spam_trash: When True, include messages from SPAM and TRASH.

Returns: Dictionary with messages (id, thread_id), optional next_page_token, and result_size_estimate. Use get_message for headers/body. On API failure, returns {"error": "..."}.

get_messageA

Fetch a single message by ID, including headers, body, and attachment metadata.

Args: message_id: The Gmail message ID (from list_messages or get_thread). local_path: Optional local filesystem path (file or directory) to write the message JSON to instead of returning it inline. Bypasses the response-size cap, for messages with very large bodies. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. include_body: When False, fetch only metadata (Gmail's format='metadata'): no body is downloaded, and body_plain, body_html, and attachments are left out of the result.

Returns: Message with id, thread_id, snippet, label_ids, headers (from/to/cc/bcc/ subject/date/message_id), body_plain, body_html, and attachments metadata (filename, mime_type, size, attachment_id). A large body that Gmail delivers separately is fetched and returned in body_plain/body_html like any other. A text part whose data can't be decoded leaves its body null and is listed in body_decode_errors; a separately delivered body that can't be fetched leaves its body null and is listed in body_fetch_errors (both: part_id, mime_type, error, plus attachment_id for a separately delivered part; present only when non-empty). Raises an error naming the size if the message is over the response-size cap and local_path is not set; a separately delivered body already over the cap raises before being downloaded. If local_path is set, returns {local_path, message_id, bytes_written} instead, plus body_fetch_errors / body_decode_errors (each entry with message_id) when present. With include_body=False, only id, thread_id, snippet, label_ids, internal_date, size_estimate, and headers. On API failure, {"error": "..."}.

list_threadsA

List conversation threads in the authenticated user's mailbox.

Args: query: Gmail search syntax filter, e.g. 'subject:invoice newer_than:7d'. label_ids: Only return threads that have all of these label IDs. max_results: Maximum number of threads to return (default 50, max 500). page_token: Continuation token from a previous response for pagination. include_spam_trash: When True, include threads from SPAM and TRASH.

Returns: Dictionary with threads (id, snippet, history_id), optional next_page_token, and result_size_estimate. Use get_thread for full messages. On API failure, returns {"error": "..."}.

get_threadA

Fetch all messages in a conversation thread.

Args: thread_id: The Gmail thread ID (from list_threads or a message's thread_id). local_path: Optional local filesystem path (file or directory) to write the thread JSON to instead of returning it inline. Bypasses the response-size cap, for threads with very large bodies. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. include_body: When False, fetch only each message's metadata (Gmail's format='metadata'): no body is downloaded, and body_plain, body_html, and attachments are left out. Use it to list a thread too large to read whole, then get_message each ID.

Returns: Thread with id, snippet, history_id, and messages (same shape as get_message, including its include_body=False shape). Raises an error naming the size if the thread is over the response-size cap and local_path is not set. If local_path is set, returns {local_path, thread_id, message_count, bytes_written} instead, plus body_fetch_errors / body_decode_errors (each entry with message_id) when present. On API failure, {"error": "..."}.

list_labelsA

List all labels in the authenticated user's mailbox (system and user-defined).

Returns: List of labels with id, name, type, message_list_visibility, and label_list_visibility. On API failure, {"error": "..."}.

send_messageA

Send a new email message, after the user confirms it (by default).

By default (GMAIL_SEND=confirm) the message is saved as a Gmail draft and sent only when the user confirms it in a form the MCP client shows, which lists the sender, every recipient, the subject, attachment names, the start of the body, and any recipient flags. Declining, cancelling, no answer, or a client that can't show the form leaves it as an unsent draft. Confirmation needs a client on the 2025-11-25 handshake; on 2026-07-28 connections mail stays a draft. Claude Code currently connects on 2026-07-28, so from it every send is held as a draft. A client hook that auto-accepts confirmations with a yes makes this the same as GMAIL_SEND=direct, which sends at once.

Args: to: Recipient email address, or a list of addresses. subject: Email subject line. body: Plain-text body. cc: Optional CC address or list of addresses. bcc: Optional BCC address or list of addresses. body_html: Optional HTML body (sent alongside the plain-text body). attachments: Optional list of attachment dicts. Each needs either local_path or content_base64, plus optional filename and mime_type (guessed from the filename's extension when omitted, else application/octet-stream).

Returns: Once sent: sent true, the sent message id, thread_id, and label_ids, plus (under confirm) draft_id and recipient_flags. If not sent: sent false, reason (no_elicitation, declined, cancelled, timeout, error, or changed), draft_id, message {id, thread_id, label_ids}, recipient_flags (each {flag, message, ...}: outside_organization, many_recipients, hidden_recipients, or outside_organization_unchecked), and a note saying the email is waiting in Gmail's Drafts folder. On failure, {"error": "..."}.

create_draftA

Create a draft email without sending it.

Args: to: Recipient email address, or a list of addresses. subject: Email subject line. body: Plain-text body. cc: Optional CC address or list of addresses. bcc: Optional BCC address or list of addresses. body_html: Optional HTML body (sent alongside the plain-text body). attachments: Optional list of attachment dicts. Each needs either local_path or content_base64, plus optional filename and mime_type (guessed from the filename's extension when omitted, else application/octet-stream).

Returns: Draft id and nested message id/thread_id. On failure, {"error": "..."}.

send_draftA

Send an existing draft by ID, after the user confirms it (by default).

By default (GMAIL_SEND=confirm) the user confirms the draft in a form the MCP client shows, built from the draft as Gmail stores it, and only an explicit yes sends it. If the client can't show the form, or the user doesn't confirm, nothing is sent and the draft stays in Gmail's Drafts folder. A draft changed after the confirmation (e.g. by update_draft) is refused, not sent. Confirmation needs a client on the 2025-11-25 handshake; on 2026-07-28 connections (Claude Code, currently) this tool refuses. A client hook that auto-accepts confirmations with a yes makes this the same as GMAIL_SEND=direct, which sends at once.

Args: draft_id: The draft ID returned by create_draft.

Returns: Once sent: sent true, the sent message id, thread_id, and label_ids, plus (under confirm) draft_id and recipient_flags. If refused: sent false with the same reason, draft_id, message, recipient_flags, and note fields as send_message. On failure, {"error": "..."}.

list_draftsA

List drafts in the authenticated user's mailbox.

Args: query: Gmail search syntax filter, e.g. 'to:alice@example.com subject:invoice'. max_results: Maximum number of drafts to return (default 50, max 500). page_token: Continuation token from a previous response for pagination. include_spam_trash: When True, include drafts from SPAM and TRASH.

Returns: Dictionary with drafts, optional next_page_token, and result_size_estimate. Each draft is {"id": draft ID (for get_draft, update_draft, delete_draft and send_draft), "message": ...}, where message is get_message's include_body=False shape: id, thread_id, snippet, label_ids, internal_date, size_estimate, and headers (to, cc, bcc, subject, date, ...). A draft that can't be read (e.g. sent or updated since it was listed) has message {id, thread_id} and an error. On API failure, returns {"error": "..."}.

get_draftA

Fetch a single draft by ID, including headers, body, and attachment metadata.

Args: draft_id: The draft ID (from list_drafts or create_draft). local_path: Optional local filesystem path (file or directory) to write the draft JSON to instead of returning it inline. Bypasses the response-size cap, for drafts with very large bodies. A path ending in '/' is a directory, created if missing. A file in place of a parent directory, or at a path ending in '/', raises ValueError; an existing file at a plain file path is replaced. include_body: When False, fetch only metadata: no body is downloaded, and body_plain, body_html, and attachments are left out.

Returns: {"id": draft ID, "message": ...}, where message has the same shape as get_message's result (including its include_body=False shape and its body_decode_errors / body_fetch_errors). Raises an error naming the size if the draft is over the response-size cap and local_path is not set. If local_path is set, returns {local_path, draft_id, bytes_written} instead, plus body_fetch_errors / body_decode_errors (each entry with message_id) when present. On API failure, {"error": "..."}.

update_draftA

Replace a draft's content without sending it. The draft keeps its ID.

The call's arguments replace the draft's old content: omitted cc, bcc, body_html, and attachments are removed, not kept. A reply draft stays in its thread, keeping its In-Reply-To and References headers, as long as the subject still matches the thread's (Gmail's threading rule). The draft's From (e.g. a send-as alias chosen in Gmail) is also kept.

Args: draft_id: The draft ID (from list_drafts or create_draft). to: Recipient email address, or a list of addresses. subject: Email subject line. body: Plain-text body. cc: Optional CC address or list of addresses. bcc: Optional BCC address or list of addresses. body_html: Optional HTML body (sent alongside the plain-text body). attachments: Optional list of attachment dicts to add. Each needs either local_path or content_base64, plus optional filename and mime_type (guessed from the filename's extension when omitted, else application/octet-stream). keep_attachments: When True, keep every part of the draft except its plain and HTML bodies (so every attachment get_draft lists), ahead of any in attachments. Inline images (parts with a Content-ID) stay inline with the new body_html, so its cid: references still resolve; without body_html they become ordinary attachments.

Returns: Draft id and nested message id/thread_id/label_ids. The message id changes on every update; the draft id doesn't. On failure, {"error": "..."}.

delete_draftA

Permanently delete a draft. Unlike trash_message, it can't be recovered.

Args: draft_id: The draft ID (from list_drafts or create_draft).

Returns: {"id": draft_id, "action": "deleted"}. On failure, {"error": "..."}.

reply_to_messageA

Send a reply in an existing thread, after the user confirms it (by default).

Fetches the original message for Subject / Message-ID / References headers and sets the reply's threadId so Gmail groups it correctly.

By default (GMAIL_SEND=confirm) the reply is saved as a draft in the original thread and sent only when the user confirms it, exactly as send_message describes; otherwise it waits in Gmail's Drafts folder. GMAIL_SEND=direct sends at once.

Args: message_id: ID of the message being replied to. body: Plain-text reply body. body_html: Optional HTML reply body. reply_all: When True, also include the original To and Cc recipients in addition to the reply target.

Recipients follow standard mail-client rules: the reply goes to the original's Reply-To if it has one, otherwise its From. Replying to a message you sent yourself goes to that message's original To (or its Cc, if nobody else was in To) instead. Your own addresses, including send-as aliases, are left off the recipients unless nobody else is on the message.

Returns: The same shapes as send_message: sent true with the sent message id, thread_id, and label_ids, or sent false with the held draft. A reply_all, or a reply to your own sent message, also has a warning when your own addresses couldn't be fully looked up (so you may be among the recipients). On failure, {"error": "..."}.

modify_labelsA

Add or remove labels on a message or an entire thread.

Common label IDs: INBOX (archive = remove INBOX), UNREAD (mark read = remove UNREAD; mark unread = add UNREAD), STARRED, IMPORTANT, TRASH, SPAM. User labels use their id from list_labels.

Args: add_label_ids: Label IDs to add. remove_label_ids: Label IDs to remove. message_id: Target a single message. Provide message_id or thread_id, not both. thread_id: Target every message in a thread. Provide message_id or thread_id, not both.

Returns: For a message: id, thread_id, label_ids. For a thread: id and messages (id + label_ids each). On failure, {"error": "..."}.

trash_messageA

Move a message to trash (recoverable).

Permanent delete is intentionally not exposed — it requires the full https://mail.google.com/ scope, which this server does not request.

Args: message_id: The Gmail message ID to trash.

Returns: Message id, thread_id, label_ids, and action 'trashed'. On failure, {"error": "..."}.

Prompts

Interactive templates invoked by user choice

NameDescription

No prompts

Resources

Contextual data attached and managed by the client

NameDescription
get_auth_status Current authentication method and its Drive capability limitations. Returns a JSON summary of the active auth method and which tools are restricted. Useful for deciding which tools to attempt before calling them. `local_file_access` gives the LOCAL_FILE_ACCESS policy: its mode, whether it was set explicitly, the allowed directories in roots mode, and the local-only tools off mode left unregistered.

TDQS

A3.5/5.0

Scored across 143 tools

Disambiguation4/5

Most tools are clearly separated by resource and action, and descriptions explicitly call out differences where overlap exists (e.g. list_files vs list_spreadsheets, export_file vs download_file, batch_update vs the narrower sheet tools). A handful of pairs remain easy to confuse at a glance, but the docstrings generally resolve the choice.

Naming Consistency4/5

The set uses snake_case almost throughout with predictable verb_noun names (get_sheet_data, create_doc, delete_event, list_messages). Minor deviations like freeze, sort_range, find_free_slots, and list_all_events are readable and not indicative of mixed conventions.

Tool Count1/5

143 tools is an extreme surface for an agent to navigate, even across five Google services; many granular operations (table row/column manipulation, numerous formatting wrappers, single-purpose Drive helpers) could be consolidated. The count is far beyond the well-scoped 3-15 range and creates real selection and context overhead.

Completeness4/5

Coverage is broad across Sheets, Docs, Drive, Calendar, and Gmail, including CRUD, formatting, sharing, revisions, comments, and event management. Gaps remain, such as Google Slides creation/editing, Gmail attachment download, and some comment lifecycle operations, but core workflows are well covered.

Maintenance

ActivityActive
ResponsivenessUsually handled