All connectors

Google Docs

OfficialProductivity

Google Docs

Let agents read your documents, summarize them and keep them up to date.

  • Read a document's text, tab by tab, including its tables.
  • See its structure and formatting, its comments and the suggestions in progress.
  • With Write access: create documents, add and replace text, insert tables, images and page breaks, apply headings and styles, add tabs, comment and reply, suggest edits for you to review, and accept or reject suggestions.

Agents work with a document when you share its link. To let them search your Drive for documents, also connect Google Drive. Read access cannot change your documents.

Setup instructions

Connect your Google account

  1. Choose the level for Access:
    • Read to let agents read documents without changing anything.
    • Write to also let agents create documents and edit their text, formatting, tabs, comments and suggestions.
  2. Select Continue with Google, choose your account, and approve the permissions Google lists. If Google shows a checkbox per permission, tick them all: Houston refuses a partial grant.

The connection can open every document your Google account can open, but nothing else in your Drive; connecting Google Docs does not grant access to your other Google services.

Advanced: changing access and troubleshooting
  • To change the access level, edit the connection and connect with Google again. Google then asks for the new set of permissions.
  • To revoke access, remove the connection in Houston, or remove Houston from your Google Account's third-party connections.
  • Google Workspace administrators can block third-party apps. If Google refuses the connection, ask your administrator to allow Houston.
  • An agent that cannot open a document may be using a link from Publish to the web (it contains /document/d/e/). Share the document's normal link instead, from the address bar while it is open.
  • Word files stored in Drive open in Docs but cannot be read by agents. Convert one with File > Save as Google Docs and share the new link.

Files

  • connector.luau
    -- Google Docs API v1. Arguments and results keep Google's native field names.
    local API = "https://docs.googleapis.com/v1"
    
    -- Request layer shared verbatim by the Google connectors (tools/validate checks they match).
    type Options = {[string]: any}
    type Endpoint = {method: string, path: string, access: string?, query: {string}?, body: boolean?, defaults: Options?, list: string?, required: {[string]: string}?, help: string}
    
    local function text(value: any, field: string): string
    	assert(type(value) == "string" and value ~= "", field .. " must be a nonempty string")
    	return value
    end
    
    local function options(value: any): Options
    	if value == nil then return {} end
    	assert(type(value) == "table", "opts must be an object")
    	for key in value do assert(type(key) == "string", "opts must have named fields") end
    	return table.clone(value)
    end
    
    -- Moves the named fields from args into a query string; arrays repeat the key.
    local function query(args: Options, names: {string}): string
    	local parts: {string} = {}
    	for _, name in names do
    		local value = args[name]
    		args[name] = nil
    		for key, item in (if type(value) == "table" then value else {value}) do
    			assert(type(key) == "number" and (type(item) == "string" or type(item) == "number" or type(item) == "boolean"), name .. " must be a string, number, boolean or an array of them")
    			table.insert(parts, url.encode(name) .. "=" .. url.encode(item))
    		end
    	end
    	return if #parts > 0 then "?" .. table.concat(parts, "&") else ""
    end
    
    -- Older APIs name the reason in errors[], newer ones in an ErrorInfo detail.
    local function reasonOf(problem: any): string?
    	for _, list in {problem.errors, problem.details} :: {any} do
    		if type(list) == "table" then
    			for _, item in list do
    				if type(item) == "table" and type(item.reason) == "string" then return item.reason end
    			end
    		end
    	end
    	return nil
    end
    
    local function fail(operation: string, response: HttpResponse): never
    	local ok, decoded = pcall(json.decode, await(response.body:readPrefix(4096)))
    	local problem = if ok and type(decoded) == "table" and type(decoded.error) == "table" then decoded.error else {}
    	local reason = reasonOf(problem)
    	local message = "Google HTTP " .. tostring(response.statusCode)
    	if type(problem.status) == "string" then message ..= " (" .. problem.status .. ")" end
    	if type(problem.message) == "string" then message ..= ": " .. string.sub(problem.message, 1, 600) end
    	if reason then message ..= " [" .. reason .. "]" end
    	local retry = response.headers["retry-after"]
    	if retry and retry[1] then message ..= "; Retry-After: " .. retry[1] end
    	local limited = reason ~= nil and string.find(string.lower(reason), "ratelimitexceeded", 1, true) ~= nil
    	return houston.fail({operation = operation, layer = "upstream", upstream_status = response.statusCode,
    		retryable = response.statusCode == 429 or response.statusCode >= 500 or limited, message = message})
    end
    
    local function decode(operation: string, response: HttpResponse): any
    	if response.statusCode < 200 or response.statusCode >= 300 then fail(operation, response) end
    	local raw = await(response.body:readAll())
    	if raw == "" then return {success = true} end
    	local ok, value = pcall(json.decode, raw)
    	if not ok or type(value) ~= "table" or not string.match(raw, "^%s*{") then
    		houston.fail({operation = operation, layer = "upstream", upstream_status = response.statusCode,
    			retryable = false, message = "Google returned an invalid JSON object"})
    	end
    	return value
    end
    
    local function call(operation: string, method: string, href: string, body: any?): any
    	return decode(operation, await(http.request({method = method, url = href,
    		headers = if body ~= nil then {["Content-Type"] = {"application/json"}} else nil,
    		body = if body ~= nil then json.encode(body) else nil})))
    end
    
    -- Accepts a docs.google.com editor URL in place of its file ID; published and responder links (/d/e/...) carry no ID.
    local function docsId(value: any, product: string, field: string): any
    	if type(value) ~= "string" then return value end
    	local rest = string.match(value, "^https://docs%.google%.com/" .. product .. "/d/(.*)$")
    		or string.match(value, "^https://docs%.google%.com/" .. product .. "/u/%d+/d/(.*)$")
    		or string.match(value, "^https://docs%.google%.com/a/[^/]+/" .. product .. "/d/(.*)$")
    	local id: string = if rest then string.match(rest, "^[^/?#]*") or "" else value
    	assert(string.match(id, "^[%w_%-]+$") and id ~= "e", field .. " must be an ID or its https://docs.google.com/" .. product .. "/d/<id> URL")
    	return id
    end
    
    -- Moves {placeholders} and declared query fields from args into the URL; remaining fields form the JSON body.
    local function target(name: string, endpoint: Endpoint, args: Options): string
    	local defaults: Options = endpoint.defaults or {}
    	for key, value in defaults do
    		if args[key] == nil then args[key] = value end
    	end
    	local required: {[string]: string} = endpoint.required or {}
    	for field, kind in required do
    		local value = args[field]
    		assert(if kind == "array" then type(value) == "table" and value[1] ~= nil elseif kind == "string" then type(value) == "string" and value ~= "" elseif kind == "object" then type(value) == "table" and next(value) ~= nil and value[1] == nil else false,
    			name .. " requires " .. field .. " as a nonempty " .. kind)
    	end
    	local path = string.gsub(endpoint.path, "{(%w+)}", function(field: string)
    		local value = url.segment(text(args[field], field), field)
    		args[field] = nil
    		return value
    	end)
    	path ..= query(args, endpoint.query or {})
    	if not endpoint.body then assert(next(args) == nil, name .. " received an unknown option") end
    	return API .. path
    end
    
    local function invoke(name: string, endpoint: Endpoint, input: any): any
    	local args = options(input)
    	local result = call(name, endpoint.method, target(name, endpoint, args), if endpoint.body then args else nil)
    	if endpoint.list and result[endpoint.list] == nil then result[endpoint.list] = json.decode("[]") end
    	return result
    end
    
    local exports: {[string]: any} = {}
    local help: {[string]: string} = {}
    
    -- Exposes an operation when the connection allows the access it needs, if any.
    local function export(name: string, access: string?, fn: (any) -> any, doc: string)
    	if access == nil or houston.allows(access) then
    		exports[name], help[name] = fn, doc
    	end
    end
    
    local function exportEndpoints(endpoints: {[string]: Endpoint})
    	for name, endpoint in endpoints do
    		export(name, endpoint.access, function(args: Options?): any return invoke(name, endpoint, args) end, endpoint.help)
    	end
    end
    
    -- help() introduces the API, then documents exactly the configured operations.
    local function helpWith(overview: {string}): () -> string
    	return function(): string
    		local names: {string} = {}
    		for name in help do table.insert(names, name) end
    		table.sort(names)
    		local lines = table.clone(overview)
    		for _, name in names do table.insert(lines, help[name]) end
    		return table.concat(lines, "\n")
    	end
    end
    -- End of the shared request layer.
    
    local endpoints: {[string]: Endpoint} = {
    	getDocument = {method = "GET", path = "/documents/{documentId}", defaults = {includeTabsContent = true},
    		query = {"includeTabsContent", "suggestionsViewMode", "commentsViewMode", "fields"},
    		help = "getDocument({documentId, includeTabsContent?, suggestionsViewMode?, commentsViewMode?, fields?}) -> {documentId, title, revisionId?, tabs=[{tabProperties={tabId, title, index?, parentTabId?, nestingLevel?}, documentTab={body={content}, headers?, footers?, footnotes?, lists?, inlineObjects?, namedStyles, documentStyle, commentAnchors?}, childTabs?}]}. tabs are in display order and nest up to three levels; a link's ?tab=t.<id> names the open tab, tabId 't.<id>'. content is a list of {startIndex?, endIndex, paragraph?={elements=[{startIndex, endIndex, textRun?={content, textStyle}, person?, richLink?, dateElement?, dropdown?, footnoteReference?, inlineObjectElement?}], paragraphStyle={namedStyleType='NORMAL_TEXT'|'TITLE'|'HEADING_1'...}, bullet?}, table?={rows, columns, tableRows=[{tableCells=[{content}]}]}, sectionBreak?, tableOfContents?}. Fields equal to 0 are omitted, such as the first element's startIndex, the first tab's index and a top-level tab's nestingLevel. revisionId is present only for editors and valid for 24 hours. Responses carry every style and fail over 8 MiB; fields='title,tabs(tabProperties,childTabs(tabProperties,childTabs(tabProperties)))' lists the tabs only. includeTabsContent=false returns the first tab in the legacy body field and no tabs. suggestionsViewMode is SUGGESTIONS_INLINE (the default for anyone who can comment or edit, marking suggested text with suggestedInsertionIds and suggestedDeletionIds), PREVIEW_SUGGESTIONS_ACCEPTED or PREVIEW_WITHOUT_SUGGESTIONS (the default for viewers, who get HTTP 403 for the other two). Take indexes for batchUpdate from a SUGGESTIONS_INLINE read: suggested text shifts them. commentsViewMode='COMMENTS_VIEW_MODE_INCLUDED' with suggestionsViewMode='SUGGESTIONS_INLINE' adds comments=[{commentId, anchorId, headPost={postId, author, content, createTime}, replies, status, plainTextQuote}] and suggestions=[{suggestionId, status, summaryText, headPost, replies}]; each tab's documentTab.commentAnchors[anchorId].ranges locates them."},
    	createDocument = {method = "POST", path = "/documents", access = "data:write", body = true,
    		help = "createDocument({title?}) -> the new document, with documentId and revisionId. Creates an empty document in the root of My Drive; Google ignores any other field, so add content with batchUpdate."},
    	batchUpdate = {method = "POST", path = "/documents/{documentId}:batchUpdate", access = "data:write", body = true, required = {requests = "array"},
    		help = "batchUpdate({documentId, requests, writeControl?}) -> {documentId, replies, writeControl, suggestionResponses?, commentUpdateState?}. Applies requests in order, all or nothing; replies and suggestionResponses (createdSuggestionIds, ...) match requests one to one. Indexes count UTF-16 code units, not the UTF-8 bytes # counts: é is 1 unit and an emoji 2. Take them from getDocument's startIndex and endIndex, never from offsets in getDocumentText. A body's text starts at index 1. Locations and ranges take tabId (omitted: the first tab), and segmentId for a header, footer or footnote. Each request sees the indexes shifted by earlier ones: edit from the end backwards, or use replaceAllText and endOfSegmentLocation, which need no index. Kinds include insertText={text, location={index, tabId?} or endOfSegmentLocation={tabId?}}, deleteContentRange={range={startIndex, endIndex, tabId?}}, replaceAllText={containsText={text, matchCase?, searchByRegex?}, replaceText, tabsCriteria?={tabIds}} (every tab unless tabsCriteria is given), updateTextStyle={range, textStyle={bold?, italic?, link?={url}, ...}, fields='bold,link'}, updateParagraphStyle={range, paragraphStyle={namedStyleType='HEADING_1'}, fields='namedStyleType'}, createParagraphBullets={range, bulletPreset='BULLET_DISC_CIRCLE_SQUARE'|'NUMBERED_DECIMAL_ALPHA_ROMAN'}, insertTable={rows, columns, location or endOfSegmentLocation}, insertTableRow={tableCellLocation={tableStartLocation={index}, rowIndex, columnIndex}, insertBelow}, insertInlineImage={uri, location or endOfSegmentLocation} (a public PNG, JPEG or GIF under 50 MB), insertPageBreak, insertPerson={personProperties={email}, location}, insertDate, insertRichLink, addDocumentTab={tabProperties={title, parentTabId?}}, updateDocumentTabProperties, deleteTab, createHeader={type='DEFAULT'}, createFooter, createFootnote, insertComment={content, range, assigneeEmailAddress?}, addCommentReply={commentId or suggestionId, post={content?, commentAction?='RESOLVE'|'REOPEN'}}, updateCommentPost, deleteComment, deleteCommentReply, acceptSuggestion={suggestionId}, rejectSuggestion and deleteSuggestion. Text edits can be saved while their comments or suggestions fail: when a batch writes comments or suggestions, check that commentUpdateState is ALL_SAVED, not ALL_FAILED_UNKNOWN_REASON; other batches report NO_UPDATES_REQUESTED or omit it. The final newline of a body, header, footer, footnote or table cell cannot be deleted: end ranges before it. A newline in inserted text starts a new paragraph. writeControl={writeMode='SUGGEST'} records the edits as suggestions for an editor to accept, and refuses addDocumentTab, deleteTab, updateDocumentTabProperties, createNamedRange, deleteNamedRange, deleteHeader, deleteFooter and updateTableColumnProperties. writeControl={requiredRevisionId=doc.revisionId} fails with HTTP 400 if the document changed since that read; targetRevisionId instead merges the edits with changes made since. Example: requests={{replaceAllText={containsText={text='{{client}}', matchCase=true}, replaceText='Acme'}}, {insertText={endOfSegmentLocation={}, text='\\nNext steps'}}}."},
    }
    
    local function withDocument(name: string, endpoint: Endpoint, args: Options): any
    	if string.find(endpoint.path, "{documentId}", 1, true) then
    		args.documentId = docsId(args.documentId, "document", "documentId")
    	else
    		assert(args.documentId == nil, name .. " assigns the documentId")
    	end
    	return invoke(name, endpoint, args)
    end
    for name, endpoint in endpoints do
    	export(name, endpoint.access, function(input: any): any return withDocument(name, endpoint, options(input)) end, endpoint.help)
    end
    
    local NONE: {any} = table.freeze({})
    local function inline(element: any): string
    	local person = element.person and element.person.personProperties
    	local link = element.richLink and element.richLink.richLinkProperties
    	local date = element.dateElement and element.dateElement.dateElementProperties
    	local dropdown = element.dropdown and element.dropdown.dropdownProperties
    	return if element.textRun then element.textRun.content or ""
    		elseif person then person.name or person.email or ""
    		elseif link then link.title or link.uri or ""
    		elseif date then date.displayText or ""
    		elseif dropdown then dropdown.displayValue or ""
    		else ""
    end
    
    -- Appends the text of structural elements: paragraphs as written, table rows as lines of tab-separated cells.
    local function collect(content: any, out: {string})
    	for _, element in content or NONE do
    		if element.paragraph then
    			for _, item in element.paragraph.elements or NONE do table.insert(out, inline(item)) end
    		elseif element.table then
    			for _, row in element.table.tableRows or NONE do
    				local cells: {string} = {}
    				for _, cell in row.tableCells or NONE do
    					local parts: {string} = {}
    					collect(cell.content, parts)
    					local cellText = string.gsub(table.concat(parts), "\n+$", "")
    					table.insert(cells, (string.gsub(cellText, "[\t\n\v]", " ")))
    				end
    				table.insert(out, table.concat(cells, "\t") .. "\n")
    			end
    		end
    	end
    end
    
    -- Flattens tabs in display order, each child tab after its parent. Google marks embedded objects in
    -- text runs with U+E907 and soft line breaks with U+000B.
    local function tabTexts(tabs: any, wanted: string?, out: {Options})
    	for _, tab in tabs or NONE do
    		local properties = tab.tabProperties or {}
    		if wanted == nil or properties.tabId == wanted then
    			local parts: {string} = {}
    			collect(tab.documentTab and tab.documentTab.body and tab.documentTab.body.content, parts)
    			local tabText = string.gsub(table.concat(parts), "\u{E907}", "")
    			table.insert(out, {tabId = properties.tabId, title = properties.title, parentTabId = properties.parentTabId,
    				nestingLevel = properties.nestingLevel or 0, text = (string.gsub(tabText, "\v", "\n"))})
    		end
    		tabTexts(tab.childTabs, wanted, out)
    	end
    end
    
    -- Only the text-bearing fields of each tab, three levels deep like the Docs editor.
    local INLINE = "paragraph.elements(textRun.content,person.personProperties,richLink.richLinkProperties,dateElement.dateElementProperties.displayText,dropdown.dropdownProperties.displayValue)"
    local TAB_TEXT = "tabProperties,documentTab.body.content(" .. INLINE .. ",table.tableRows.tableCells.content(" .. INLINE .. ",table))"
    local TEXT_FIELDS = "documentId,title,revisionId,tabs(" .. TAB_TEXT .. ",childTabs(" .. TAB_TEXT .. ",childTabs(" .. TAB_TEXT .. ")))"
    local PREVIEWS = table.freeze({PREVIEW_WITHOUT_SUGGESTIONS = true, PREVIEW_SUGGESTIONS_ACCEPTED = true})
    export("getDocumentText", nil, function(input: any): Options
    	local args = options(input)
    	local tabId = if args.tabId == nil then nil else text(args.tabId, "tabId")
    	assert(args.includeTabsContent == nil and args.fields == nil and args.commentsViewMode == nil, "getDocumentText received an unknown option")
    	args.suggestionsViewMode = args.suggestionsViewMode or "PREVIEW_WITHOUT_SUGGESTIONS"
    	assert(PREVIEWS[args.suggestionsViewMode], "suggestionsViewMode must be PREVIEW_WITHOUT_SUGGESTIONS or PREVIEW_SUGGESTIONS_ACCEPTED")
    	args.tabId, args.fields = nil, TEXT_FIELDS
    	local document = withDocument("getDocumentText", endpoints.getDocument, args)
    	local tabs: {Options} = json.decode("[]")
    	tabTexts(document.tabs, tabId, tabs)
    	assert(tabId == nil or #tabs > 0, "tabId " .. tostring(tabId) .. " is not a tab of this document")
    	return {documentId = document.documentId, title = document.title, revisionId = document.revisionId, tabs = tabs}
    end, "getDocumentText({documentId, tabId?, suggestionsViewMode?}) -> {documentId, title, revisionId?, tabs=[{tabId, title, parentTabId?, nestingLevel, text}]}. The plain text of every tab's body in display order, child tabs after their parent, or of tabId alone (the whole document is still read). Paragraphs end with '\\n', table rows are lines of tab-separated cells, and people, dates, dropdowns and rich links appear as their names. Headers, footers, footnotes, tables of contents, images, equations and comments are left out: read them with getDocument. Suggested changes are hidden; suggestionsViewMode='PREVIEW_SUGGESTIONS_ACCEPTED' reads the text as if they were accepted, which needs comment or edit access. Offsets in text are not batchUpdate indexes.")
    
    local overview = {
    	"Google Docs API v1. Operations take one named options object with Google's camelCase fields and return Google's JSON unchanged, except getDocumentText. Calls return completed values: use instance.getDocumentText(...) directly, without await.",
    	"documentId is the ID or the document's https://docs.google.com/document/d/<id>/edit URL. Links from Publish to the web (/document/d/e/...) carry no ID. This connector cannot search for files: ask for the URL, or find the ID with the Google Drive connector (listFiles with q=\"mimeType = 'application/vnd.google-apps.document' and trashed = false\"). Word files opened in Docs are refused with HTTP 400 until saved as Google Docs (File > Save as Google Docs).",
    	"A document has one or more tabs, which may have child tabs. Read its words with getDocumentText, and its structure, styles, comments and indexes with getDocument.",
    	"No hidden paging or retries. Errors report the HTTP status and Google's message. Google allows about 300 reads and 60 writes per minute per user, and 3000 and 600 per minute across all Houston users; HTTP 429 errors are retryable after a pause.",
    }
    if houston.allows("data:write") then
    	table.insert(overview, "Writes change a document's text, styles, tabs, comments and suggestions. An empty Luau table encodes as a JSON object: write an empty array as json.decode('[]'). Documents cannot be deleted, renamed, moved or shared here: use the Google Drive connector. A failed or timed-out write may already have succeeded: check with getDocument before repeating it (getDocumentText hides suggestions; add suggestionsViewMode='SUGGESTIONS_INLINE' and commentsViewMode='COMMENTS_VIEW_MODE_INCLUDED' after comment writes), or pass writeControl={requiredRevisionId=doc.revisionId}, with doc read by getDocument, so a repeat fails with HTTP 400 instead of applying twice.")
    end
    exports.help = helpWith(overview)
    return exports
    
  • houston.json
    {
      "schema_version": 2,
      "name": "Google Docs",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "access": [
        {
          "name": "data",
          "label": "Access",
          "levels": [
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "write",
              "label": "Write"
            }
          ],
          "default": "read"
        }
      ],
      "auth": {
        "oauth": {
          "type": "oauth2",
          "label": "Connect with Google",
          "brand": "google",
          "authorize_url": "https://accounts.google.com/o/oauth2/v2/auth",
          "token_url": "https://oauth2.googleapis.com/token",
          "client_id": "{{publisher.client_id}}",
          "client_secret": "{{publisher.client_secret}}",
          "client_auth": "body",
          "pkce": "S256",
          "require_refresh": true,
          "authorize_params": {
            "access_type": "offline",
            "include_granted_scopes": "false",
            "prompt": "consent"
          },
          "scopes": [
            {
              "values": [
                "https://www.googleapis.com/auth/userinfo.email"
              ]
            },
            {
              "if": "{{ is access.data \"read\" }}",
              "values": [
                "https://www.googleapis.com/auth/documents.readonly"
              ]
            },
            {
              "if": "{{ is access.data \"write\" }}",
              "values": [
                "https://www.googleapis.com/auth/documents"
              ]
            }
          ],
          "account": {
            "method": "GET",
            "url": "https://www.googleapis.com/oauth2/v2/userinfo",
            "headers": {
              "Authorization": {
                "value": "Bearer {{auth.oauth.access_token}}"
              }
            },
            "label": "/email"
          }
        }
      },
      "publisher": {
        "client_id": {
          "type": "string",
          "label": "Google OAuth client ID",
          "required": true,
          "order": 1
        },
        "client_secret": {
          "type": "secret",
          "label": "Google OAuth client secret",
          "required": true,
          "order": 2
        }
      },
      "proxy": [
        {
          "match": {
            "protocol": "http",
            "host": [
              "docs.googleapis.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/v1/documents/{documentId}"
            ]
          },
          "action": {
            "headers": {
              "set": {
                "Authorization": "Bearer {{auth.oauth.access_token}}"
              }
            }
          }
        },
        {
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "protocol": "http",
            "host": [
              "docs.googleapis.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/v1/documents",
              "/v1/documents/{documentId}:batchUpdate"
            ]
          },
          "action": {
            "headers": {
              "set": {
                "Authorization": "Bearer {{auth.oauth.access_token}}"
              }
            }
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Read and write Google Docs documents.
    ---
    # Google Docs
    
    Let agents read your documents, summarize them and keep them up to date.
    
    - Read a document's text, tab by tab, including its tables.
    - See its structure and formatting, its comments and the suggestions in
      progress.
    - With **Write** access: create documents, add and replace text,
      insert tables, images and page breaks, apply headings and styles, add tabs,
      comment and reply, suggest edits for you to review, and accept or reject
      suggestions.
    
    Agents work with a document when you share its link. To let them search your
    Drive for documents, also connect Google Drive. Read access cannot change
    your documents.
    
  • SETUP.md
    # Connect your Google account
    
    1. Choose the level for **Access**:
       - **Read** to let agents read documents without changing anything.
       - **Write** to also let agents create documents and edit their
         text, formatting, tabs, comments and suggestions.
    2. Select **Continue with Google**, choose your account, and approve the
       permissions Google lists. If Google shows a checkbox per permission, tick
       them all: Houston refuses a partial grant.
    
    The connection can open every document your Google account can open, but
    nothing else in your Drive; connecting Google Docs does not grant access to
    your other Google services.
    
    ## Advanced: changing access and troubleshooting
    
    - To change the access level, edit the connection and connect with Google again.
      Google then asks for the new set of permissions.
    - To revoke access, remove the connection in Houston, or remove Houston from
      [your Google Account's third-party connections](https://myaccount.google.com/connections).
    - Google Workspace administrators can block third-party apps. If Google refuses
      the connection, ask your administrator to allow Houston.
    - An agent that cannot open a document may be using a link from **Publish to
      the web** (it contains `/document/d/e/`). Share the document's normal link
      instead, from the address bar while it is open.
    - Word files stored in Drive open in Docs but cannot be read by agents.
      Convert one with **File > Save as Google Docs** and share the new link.
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = {},
      				config = {},
      				endpoint = { "GET", "https://docs.googleapis.com/v1/documents/d1" },
      				expected = "Bearer synthetic-oauth-token",
      				header = "Authorization",
      				method = "oauth",
      				oauth = true,
      				publisher = {
      					client_id = "synthetic-public-client",
      					client_secret = "synthetic-client-secret",
      				},
      				scopes = true,
      			},
      		})
      	end,
      }
      
    • endpoints.luau
      return {
      	contract = function(m)
      		m.endpointRules()
      	end,
      }
      
    • errors.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {data = "write"},
      	configure = function()
      		calls, status, payload, responseHeaders = 0, 200, "{}", {}
      		http = {request = function(req)
      			calls += 1
      			return fixture.operation({statusCode = status, headers = responseHeaders, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(c)
      		local function upstream(code, body, headers, expected)
      			status, payload, responseHeaders = code, body, headers
      			local before = calls
      			local ok, err = pcall(c.batchUpdate, {documentId = "d1", requests = {{deleteContentRange = {range = {startIndex = 1, endIndex = 5}}}}})
      			for _, text in expected do
      				assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err))
      			end
      			assert(calls == before + 1, "failed write was retried")
      		end
      		upstream(403, '{"error":{"code":403,"message":"The caller does not have permission","status":"PERMISSION_DENIED"}}', {},
      			{"HTTP 403 (PERMISSION_DENIED): The caller does not have permission", '"retryable":false'})
      		upstream(400, '{"error":{"code":400,"message":"Invalid requests[0].deleteContentRange: The range cannot include the newline character at the end of the segment.","status":"INVALID_ARGUMENT"}}', {},
      			{"HTTP 400 (INVALID_ARGUMENT)", "newline character at the end of the segment", '"retryable":false'})
      		upstream(429, '{"error":{"code":429,"message":"Quota exceeded for quota metric \'Write requests\' and limit \'Write requests per minute per user\'","status":"RESOURCE_EXHAUSTED"}}', {["retry-after"] = {"30"}},
      			{"HTTP 429 (RESOURCE_EXHAUSTED)", "Retry-After: 30", '"retryable":true'})
      		upstream(403, '{"error":{"code":403,"message":"Request had insufficient authentication scopes.","status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.Help"},{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"ACCESS_TOKEN_SCOPE_INSUFFICIENT","domain":"googleapis.com"}]}}', {},
      			{"insufficient authentication scopes. [ACCESS_TOKEN_SCOPE_INSUFFICIENT]", '"retryable":false'})
      		upstream(403, '{"error":{"code":403,"message":"Quota exceeded for quota metric \'Write requests per day\'.","status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"RATE_LIMIT_EXCEEDED"}]}}', {},
      			{"[RATE_LIMIT_EXCEEDED]", '"retryable":false'})
      		upstream(400, "<html><title>Error 400 (Bad Request)</title></html>", {}, {"Google HTTP 400", '"retryable":false'})
      		upstream(503, '{"error":{"code":503,"message":"The service is currently unavailable.","status":"UNAVAILABLE"}}', {}, {"HTTP 503", '"retryable":true'})
      		upstream(200, "<html>Maintenance</html>", {}, {"invalid JSON object"})
      		upstream(200, "[]", {}, {"invalid JSON object"})
      		status, payload = 404, '{"error":{"code":404,"message":"Requested entity was not found.","status":"NOT_FOUND"}}'
      		local before = calls
      		local ok, err = pcall(c.getDocument, {documentId = "missing"})
      		assert(not ok and string.find(tostring(err), "NOT_FOUND", 1, true) and string.find(tostring(err), '"operation":"getDocument"', 1, true), tostring(err))
      		assert(string.find(tostring(err), '"retryable":false', 1, true) and calls == before + 1, tostring(err))
      	end,
      }
      
    • manifest.luau
      return {
      	contract = function(m)
      		local function google(access, scopes)
      			local r, err = m.resolve(
      				{ client_id = "publisher-client", client_secret = "publisher-secret" },
      				{},
      				nil,
      				"oauth",
      				{ data = access }
      			)
      			assert(r and not err, tostring(err))
      			local want = { "https://www.googleapis.com/auth/userinfo.email" }
      			for _, scope in scopes do
      				table.insert(want, "https://www.googleapis.com/auth/" .. scope)
      			end
      			assert(m.equal(r.Scopes, want), "requested OAuth scopes")
      			r.Context.Auth.oauth.access_token = "fixture-token"
      			return r
      		end
      		do
      			local api = "https://docs.googleapis.com/v1/documents"
      			for _, access in { "read", "write" } do
      				local scope = "documents.readonly"
      				if access == "write" then
      					scope = "documents"
      				end
      				local r = google(access, { scope })
      				local reads = {
      					"GET " .. api .. "/d1?includeTabsContent=true",
      					"GET " .. api .. "/1DoC_x-9?fields=documentId%2Ctitle%2CrevisionId%2Ctabs",
      				}
      				m.routes(r, "Bearer fixture-token", true, reads)
      				m.rejectOverrides(r, reads)
      				local writes = { "POST " .. api, "POST " .. api .. "/d1:batchUpdate" }
      				m.routes(r, "Bearer fixture-token", (access == "write"), writes)
      				if access == "write" then
      					m.rejectOverrides(r, writes)
      				end
      				m.routes(r, "Bearer fixture-token", false, {
      					"POST https://oauth2.googleapis.com/token",
      					"GET https://www.googleapis.com/drive/v3/files",
      					"GET https://docs.googleapis.com.evil.test/v1/documents/d1",
      					"GET https://content.googleapis.com/v1/documents/d1",
      					"GET https://docs.googleapis.com/v2/documents/d1",
      					"GET " .. api,
      					"DELETE " .. api .. "/d1",
      					"PATCH " .. api .. "/d1",
      					"PUT " .. api .. "/d1",
      					"GET " .. api .. "/d1/tabs",
      					"GET " .. api .. "/%2e%2e/d1",
      					"GET " .. api .. "/d1%2F..%2Fx",
      					"POST " .. api .. "/d1/batchUpdate",
      					"POST https://docs.googleapis.com/batch",
      					"POST https://docs.googleapis.com/batch/docs/v1",
      				})
      			end
      		end
      	end,
      }
      
    • reads.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {data = "read"},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(table.remove(responses, 1))})
      		end}
      	end,
      	run = function(c)
      		local API = "https://docs.googleapis.com/v1/documents/"
      		local names = {}
      		for name in c do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == "getDocument,getDocumentText", table.concat(names, ","))
      
      		local function paragraph(...)
      			return {paragraph = {elements = {...}}}
      		end
      		local function run(content)
      			return {textRun = {content = content, textStyle = {}}}
      		end
      		local document = {documentId = "1DoC_x-9", title = "Plan", revisionId = "r1", tabs = {
      			{tabProperties = {tabId = "t.0", title = "Notes", index = 0}, documentTab = {body = {content = {
      				{sectionBreak = {}},
      				paragraph(run("Plan\n")),
      				paragraph(run("Call "), {person = {personProperties = {name = "Ana", email = "[email protected]"}}}, run(" on "),
      					{dateElement = {dateElementProperties = {displayText = "Oct 21, 2026"}}}, run(" about "),
      					{richLink = {richLinkProperties = {title = "Budget", uri = "https://docs.google.com/spreadsheets/d/s1"}}},
      					{inlineObjectElement = {inlineObjectId = "kix.1"}}, {person = {personProperties = {email = "[email protected]"}}}, run(" is "),
      					{dropdown = {dropdownProperties = {displayValue = "Done", selectedOptionId = "o2"}}}, run("\n")),
      				paragraph(run("Line\vbreak \u{E907}chart\n")),
      				{tableOfContents = {content = {paragraph(run("Contents\n"))}}},
      				{table = {rows = 1, columns = 2, tableRows = {{tableCells = {
      					{content = {paragraph(run("Item\n"))}},
      					{content = {paragraph(run("Cost\tUSD\n")), paragraph(run("line\v2\n"))}},
      				}}}}},
      				paragraph(run("\n")),
      			}}}, childTabs = {
      				{tabProperties = {tabId = "t.1", title = "Appendix", parentTabId = "t.0", nestingLevel = 1, index = 0}, documentTab = {body = {content = {paragraph(run("A\n"))}}}},
      			}},
      			{tabProperties = {tabId = "t.2", title = "Empty", index = 1}, documentTab = {body = {content = {{sectionBreak = {}}, paragraph(run("\n"))}}}},
      		}}
      		local fields = url.encode("documentId,title,revisionId,tabs(tabProperties,documentTab.body.content(paragraph.elements(textRun.content,person.personProperties,richLink.richLinkProperties,dateElement.dateElementProperties.displayText,dropdown.dropdownProperties.displayValue),table.tableRows.tableCells.content(paragraph.elements(textRun.content,person.personProperties,richLink.richLinkProperties,dateElement.dateElementProperties.displayText,dropdown.dropdownProperties.displayValue),table)),childTabs(tabProperties,documentTab.body.content(paragraph.elements(textRun.content,person.personProperties,richLink.richLinkProperties,dateElement.dateElementProperties.displayText,dropdown.dropdownProperties.displayValue),table.tableRows.tableCells.content(paragraph.elements(textRun.content,person.personProperties,richLink.richLinkProperties,dateElement.dateElementProperties.displayText,dropdown.dropdownProperties.displayValue),table)),childTabs(tabProperties,documentTab.body.content(paragraph.elements(textRun.content,person.personProperties,richLink.richLinkProperties,dateElement.dateElementProperties.displayText,dropdown.dropdownProperties.displayValue),table.tableRows.tableCells.content(paragraph.elements(textRun.content,person.personProperties,richLink.richLinkProperties,dateElement.dateElementProperties.displayText,dropdown.dropdownProperties.displayValue),table)))))")
      		responses = {json.encode(document), json.encode(document), json.encode(document), '{"documentId":"d1","title":"Empty"}'}
      		local all = c.getDocumentText({documentId = "https://docs.google.com/document/d/1DoC_x-9/edit?tab=t.0#heading=h.1"})
      		assert(requests[1].url == API .. "1DoC_x-9?includeTabsContent=true&suggestionsViewMode=PREVIEW_WITHOUT_SUGGESTIONS&fields=" .. fields, requests[1].url)
      		assert(all.documentId == "1DoC_x-9" and all.title == "Plan" and all.revisionId == "r1" and #all.tabs == 3)
      		assert(all.tabs[1].text == "Plan\nCall Ana on Oct 21, 2026 about [email protected] is Done\nLine\nbreak chart\nItem\tCost USD line 2\n\n", all.tabs[1].text)
      		assert(all.tabs[1].tabId == "t.0" and all.tabs[1].title == "Notes" and all.tabs[1].nestingLevel == 0 and all.tabs[1].parentTabId == nil)
      		assert(all.tabs[2].tabId == "t.1" and all.tabs[2].parentTabId == "t.0" and all.tabs[2].nestingLevel == 1 and all.tabs[2].text == "A\n")
      		assert(all.tabs[3].tabId == "t.2" and all.tabs[3].text == "\n")
      		local child = c.getDocumentText({documentId = "https://docs.google.com/document/u/1/d/d1/edit", tabId = "t.1", suggestionsViewMode = "PREVIEW_SUGGESTIONS_ACCEPTED"})
      		assert(#child.tabs == 1 and child.tabs[1].text == "A\n")
      		assert(requests[2].url == API .. "d1?includeTabsContent=true&suggestionsViewMode=PREVIEW_SUGGESTIONS_ACCEPTED&fields=" .. fields, requests[2].url)
      		local ok, err = pcall(c.getDocumentText, {documentId = "d1", tabId = "t.9"})
      		assert(not ok and string.find(tostring(err), "t.9 is not a tab", 1, true), tostring(err))
      		local empty = c.getDocumentText({documentId = "https://docs.google.com/a/example.com/document/d/d1/edit"})
      		assert(empty.title == "Empty" and json.encode(empty.tabs) == "[]" and requests[4].url == API .. "d1?includeTabsContent=true&suggestionsViewMode=PREVIEW_WITHOUT_SUGGESTIONS&fields=" .. fields, requests[4].url)
      
      		responses = {json.encode(document), '{"documentId":"d1","title":"Legacy","body":{"content":[]}}', '{"documentId":"d1","comments":[{"commentId":"c1"}]}'}
      		local full = c.getDocument({documentId = "1DoC_x-9"})
      		assert(full.tabs[1].childTabs[1].tabProperties.tabId == "t.1" and requests[5].url == API .. "1DoC_x-9?includeTabsContent=true", requests[5].url)
      		local legacy = c.getDocument({documentId = "d1", includeTabsContent = false, fields = "title,body"})
      		assert(legacy.title == "Legacy" and legacy.tabs == nil, "getDocument changed Google's JSON")
      		assert(requests[6].url == API .. "d1?includeTabsContent=false&fields=title%2Cbody", requests[6].url)
      		local commented = c.getDocument({documentId = "d1", suggestionsViewMode = "SUGGESTIONS_INLINE", commentsViewMode = "COMMENTS_VIEW_MODE_INCLUDED"})
      		assert(commented.comments[1].commentId == "c1")
      		assert(requests[7].url == API .. "d1?includeTabsContent=true&suggestionsViewMode=SUGGESTIONS_INLINE&commentsViewMode=COMMENTS_VIEW_MODE_INCLUDED", requests[7].url)
      		for _, req in requests do
      			assert(req.method == "GET" and req.body == nil, req.method .. " " .. req.url)
      			assert(req.headers == nil or req.headers.Authorization == nil, "connector set credentials")
      		end
      
      		local sent = #requests
      		local invalid = {
      			{},
      			{documentId = ""},
      			{documentId = ".."},
      			{documentId = "d/1"},
      			{documentId = "d1 x"},
      			{documentId = "https://docs.google.com/document/d/e/2PACX-1vR/pub"},
      			{documentId = "https://docs.google.com.example.com/document/d/d1/edit"},
      			{documentId = "https://example.com/?u=https://docs.google.com/document/d/d1"},
      			{documentId = "https://docs.google.com/spreadsheets/d/s1/edit"},
      			{documentId = "https://docs.google.com/document/#d/d1"},
      			{documentId = "https://docs.google.com/document/d/d1.x/edit"},
      			{documentId = "d1", key = "api-key"},
      			{documentId = "d1", includeTabsContent = {mode = "all"}},
      		}
      		for _, args in invalid do
      			assert(not pcall(c.getDocument, args), "getDocument accepted " .. json.encode(args))
      			assert(not pcall(c.getDocumentText, args), "getDocumentText accepted " .. json.encode(args))
      		end
      		assert(not pcall(c.getDocument, "d1"))
      		assert(not pcall(c.getDocumentText, "d1"))
      		assert(not pcall(c.getDocumentText, {documentId = "d1", fields = "title"}), "getDocumentText chooses its fields")
      		assert(not pcall(c.getDocumentText, {documentId = "d1", includeTabsContent = false}))
      		assert(not pcall(c.getDocumentText, {documentId = "d1", tabId = ""}))
      		assert(not pcall(c.getDocumentText, {documentId = "d1", commentsViewMode = "COMMENTS_VIEW_MODE_INCLUDED"}))
      		assert(not pcall(c.getDocumentText, {documentId = "d1", suggestionsViewMode = "SUGGESTIONS_INLINE"}), "getDocumentText would mix suggested and current text")
      		assert(not pcall(c.getDocumentText, {documentId = "d1", suggestionsViewMode = "DEFAULT_FOR_CURRENT_ACCESS"}))
      		assert(#requests == sent, "invalid input reached Google")
      		assert(#responses == 0)
      	end,
      }
      
    • writes.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {data = "write"},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(table.remove(responses, 1))})
      		end}
      	end,
      	run = function(c)
      		local API = "https://docs.googleapis.com/v1/documents"
      		local names = {}
      		for name in c do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == "batchUpdate,createDocument,getDocument,getDocumentText", table.concat(names, ","))
      		local function same(a, b)
      			if type(a) ~= "table" or type(b) ~= "table" then return a == b end
      			for key, value in a do if not same(value, b[key]) then return false end end
      			for key in b do if a[key] == nil then return false end end
      			return true
      		end
      		local function sent(href, body)
      			local req = requests[#requests]
      			assert(req.method == "POST" and req.url == href, req.method .. " " .. req.url)
      			assert(req.headers["Content-Type"][1] == "application/json" and req.headers.Authorization == nil)
      			assert(same(json.decode(req.body), body), req.body)
      		end
      
      		responses = {'{"documentId":"new","title":"Minutes","revisionId":"r1"}', '{"documentId":"untitled"}'}
      		assert(c.createDocument({title = "Minutes"}).documentId == "new")
      		sent(API, {title = "Minutes"})
      		assert(c.createDocument().documentId == "untitled")
      		assert(requests[#requests].body == "{}", requests[#requests].body)
      
      		responses = {'{"documentId":"d1","replies":[{"replaceAllText":{"occurrencesChanged":2}},{}],"writeControl":{"requiredRevisionId":"r2"}}'}
      		local edits = {
      			{replaceAllText = {containsText = {text = "{{client}}", matchCase = true}, replaceText = "Acme"}},
      			{insertText = {endOfSegmentLocation = {tabId = "t.1"}, text = "\nNext steps"}},
      		}
      		local reply = c.batchUpdate({documentId = "https://docs.google.com/document/d/d1/edit?tab=t.1", requests = edits, writeControl = {requiredRevisionId = "r1"}})
      		assert(reply.replies[1].replaceAllText.occurrencesChanged == 2 and reply.writeControl.requiredRevisionId == "r2")
      		sent(API .. "/d1:batchUpdate", {requests = edits, writeControl = {requiredRevisionId = "r1"}})
      
      		responses = {'{"documentId":"d1","replies":[{"insertComment":{"commentThread":{"commentId":"c1","anchorId":"a1"}}}],"suggestionResponses":[{}],"commentUpdateState":"ALL_SAVED"}'}
      		local comment = {{insertComment = {content = "Check this figure", range = {startIndex = 5, endIndex = 9}}}}
      		assert(c.batchUpdate({documentId = "d1", requests = comment, writeControl = {writeMode = "SUGGEST"}}).commentUpdateState == "ALL_SAVED")
      		sent(API .. "/d1:batchUpdate", {requests = comment, writeControl = {writeMode = "SUGGEST"}})
      
      		-- Google's system parameters stay out of the URL; Google rejects them as unknown body fields.
      		responses = {'{"documentId":"d1","replies":[{}]}'}
      		local page = {{insertPageBreak = {endOfSegmentLocation = {}}}}
      		c.batchUpdate({documentId = "d1", requests = page, key = "k", access_token = "t", alt = "media", fields = "x"})
      		sent(API .. "/d1:batchUpdate", {requests = page, key = "k", access_token = "t", alt = "media", fields = "x"})
      		assert(string.find(requests[#requests].body, '"endOfSegmentLocation":{}', 1, true), requests[#requests].body)
      
      		local count = #requests
      		assert(not pcall(c.createDocument, {documentId = "d1", title = "Copy"}), "createDocument assigns the documentId")
      		assert(not pcall(c.createDocument, "Minutes"))
      		assert(not pcall(c.batchUpdate, {documentId = "d1"}), "batchUpdate requires requests")
      		assert(not pcall(c.batchUpdate, {documentId = "d1", requests = {}}))
      		assert(not pcall(c.batchUpdate, {documentId = "d1", requests = "x"}))
      		assert(not pcall(c.batchUpdate, {documentId = "d1", requests = {insertText = {text = "x"}}}))
      		assert(not pcall(c.batchUpdate, {requests = page}), "batchUpdate requires documentId")
      		assert(not pcall(c.batchUpdate, {documentId = "d/1", requests = page}))
      		assert(not pcall(c.batchUpdate, {documentId = "https://docs.google.com/document/d/e/2PACX-1vR/pub", requests = page}))
      		assert(#requests == count, "invalid input reached Google")
      		assert(#responses == 0)
      	end,
      }