All connectors

Google Drive

OfficialFiles

Pending Google approval. Google is still reviewing Houston's access to Google Drive. Until Google approves it, you will see a Google hasn't verified this app screen while connecting with Google: select Advanced, then continue to Houston.

Google Drive

Help agents find the files and documents you need without hunting through folders.

  • Search My Drive and shared drives, and check file details and sharing.
  • Download files and export Google Docs, Sheets and Slides as Markdown, text, CSV, PDF or Office formats.
  • With Write access: upload files, create folders, rename, move, copy, trash and share files.

Read access cannot change, share or delete your files.

Setup instructions

Connect your Google account

  1. Choose the level for Access:
    • Read to let agents search, read, download and export your files in My Drive and shared drives, and see who they are shared with.
    • Write to also let agents create folders and files, upload files and new versions, rename, move and copy them, share them and remove access, move them to the trash and delete them permanently.
  2. Choose an available sign-in option, choose your account, and approve the permissions Google lists. With Connect with Google, if Google shows a checkbox per permission, tick them all: Houston refuses a partial grant.

Houston calls Google Drive only when your agent asks it to and never syncs your files in the background. Connect with Google asks only for the permissions of the access level you choose, so connecting Google Drive does not grant access to your other Google services.

If you connect with Composio, it requires full Google Drive access. Houston limits its use to the access level you select.

Advanced: changing access and troubleshooting
  • To change the access level, edit the connection and connect the same account again. With Connect with Google, Google then asks for the new set of permissions.
  • To revoke access, remove the connection in Houston, or remove Composio (or Houston for direct sign-in) from your Google Account's third-party connections. This also affects other connections using that app.
  • Google Workspace administrators can block third-party apps. If Google refuses the connection, ask your administrator to allow the app shown on Google's consent screen.

Files

  • connector.luau
    -- Google Drive API v3. Arguments and results keep Google's native field names.
    local API = "https://www.googleapis.com/drive/v3"
    local UPLOAD = "https://www.googleapis.com/upload/drive/v3"
    local FOLDER = "application/vnd.google-apps.folder"
    
    -- 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 FILE_FIELDS = "id,name,mimeType,size,createdTime,modifiedTime,parents,webViewLink,trashed,description,owners(displayName,emailAddress)"
    local FILE = {fields = FILE_FIELDS, supportsAllDrives = true}
    local FILE_QUERY = {"fields", "supportsAllDrives"}
    local ALL_DRIVES = {supportsAllDrives = true}
    local endpoints: {[string]: Endpoint} = {
    	getAbout = {method = "GET", path = "/about", defaults = {fields = "user,storageQuota"}, query = {"fields"},
    		help = "getAbout({fields?}) -> {user, storageQuota}. The connected account and its storage use."},
    	listFiles = {method = "GET", path = "/files", list = "files",
    		defaults = {fields = "nextPageToken,incompleteSearch,files(" .. FILE_FIELDS .. ")", supportsAllDrives = true, includeItemsFromAllDrives = true},
    		query = {"q", "pageSize", "pageToken", "orderBy", "fields", "corpora", "driveId", "spaces", "includeItemsFromAllDrives", "supportsAllDrives"},
    		help = "listFiles({q?, pageSize?, pageToken?, orderBy?, corpora?, driveId?, fields?}) -> {files, nextPageToken?, incompleteSearch}. q uses Drive search syntax, e.g. \"name contains 'report' and trashed = false\" or \"'<folderId>' in parents\". pageSize ≤1000. Includes shared drives."},
    	getFile = {method = "GET", path = "/files/{fileId}", defaults = FILE, query = FILE_QUERY,
    		help = "getFile({fileId, fields?}) -> file metadata. Pass fields='*' for every field."},
    	listDrives = {method = "GET", path = "/drives", list = "drives", query = {"q", "pageSize", "pageToken"},
    		help = "listDrives({q?, pageSize?, pageToken?}) -> {drives, nextPageToken?}. Shared drives the account can access."},
    	listPermissions = {method = "GET", path = "/files/{fileId}/permissions", list = "permissions",
    		defaults = {fields = "nextPageToken,permissions(id,type,role,emailAddress,domain,displayName)", supportsAllDrives = true},
    		query = {"pageSize", "pageToken", "fields", "supportsAllDrives"},
    		help = "listPermissions({fileId, pageSize?, pageToken?}) -> {permissions, nextPageToken?}. Who can access a file."},
    	createFile = {method = "POST", path = "/files", access = "data:write", body = true, defaults = FILE, query = FILE_QUERY,
    		help = "createFile({name, mimeType?, parents?, description?, ...}) -> file. Metadata only: creates folders (mimeType='" .. FOLDER .. "'), shortcuts or empty Google Docs. Use uploadFile for content."},
    	updateFile = {method = "PATCH", path = "/files/{fileId}", access = "data:write", body = true, defaults = FILE, query = {"addParents", "removeParents", "fields", "supportsAllDrives"},
    		help = "updateFile({fileId, addParents?, removeParents?, name?, description?, trashed?, ...}) -> file. Renames, moves (addParents/removeParents as comma-separated folder IDs) or trashes (trashed=true)."},
    	copyFile = {method = "POST", path = "/files/{fileId}/copy", access = "data:write", body = true, defaults = FILE, query = FILE_QUERY,
    		help = "copyFile({fileId, name?, parents?}) -> the new file."},
    	deleteFile = {method = "DELETE", path = "/files/{fileId}", access = "data:write", defaults = ALL_DRIVES, query = {"supportsAllDrives"},
    		help = "deleteFile({fileId}) -> {success=true}. Permanently deletes, skipping the trash; prefer updateFile({fileId, trashed=true})."},
    	createPermission = {method = "POST", path = "/files/{fileId}/permissions", access = "data:write", body = true, defaults = ALL_DRIVES,
    		query = {"sendNotificationEmail", "emailMessage", "transferOwnership", "supportsAllDrives", "fields"},
    		help = "createPermission({fileId, type='user'|'group'|'domain'|'anyone', role='reader'|'commenter'|'writer'|..., emailAddress?, domain?, sendNotificationEmail?, emailMessage?}) -> permission. Shares a file."},
    	deletePermission = {method = "DELETE", path = "/files/{fileId}/permissions/{permissionId}", access = "data:write", defaults = ALL_DRIVES, query = {"supportsAllDrives"},
    		help = "deletePermission({fileId, permissionId}) -> {success=true}. Revokes access."},
    }
    
    -- Downloads stream the response body to a session file.
    local downloads: {[string]: Endpoint} = {
    	downloadFile = {method = "GET", path = "/files/{fileId}", defaults = {alt = "media", supportsAllDrives = true}, query = {"alt", "supportsAllDrives", "acknowledgeAbuse"},
    		help = "downloadFile({fileId, path}) -> {path, url, size}. Saves a stored file's bytes to a session path; url is a signed Houston download link. Google Docs, Sheets and Slides have no stored bytes: use exportFile."},
    	exportFile = {method = "GET", path = "/files/{fileId}/export", query = {"mimeType"},
    		help = "exportFile({fileId, mimeType, path}) -> {path, url, size}. Converts a Google Doc, Sheet or Slides file, e.g. mimeType='text/markdown', 'text/plain', 'text/csv', 'application/pdf' or an Office format. Exports are limited to 10 MB."},
    }
    
    local function download(name: string, endpoint: Endpoint, input: any): Options
    	local args = options(input)
    	local path = text(args.path, "path")
    	args.path = nil
    	local response = await(http.request({method = "GET", url = target(name, endpoint, args)}))
    	if response.statusCode < 200 or response.statusCode >= 300 then fail(name, response) end
    	local output = fs.open(path, "w")
    	output:write(response.body)
    	await(output:close())
    	return {path = path, url = await(fs.signedGetUrl(path)), size = await(fs.stat(path)).size}
    end
    
    -- Resumable upload: Google returns a session URL for the metadata, then receives the streamed file.
    local function upload(input: any): any
    	local args = options(input)
    	local path = text(args.path, "path")
    	local fileId = if args.fileId == nil then nil else text(args.fileId, "fileId")
    	local contentType = text(args.contentType or "application/octet-stream", "contentType")
    	args.path, args.fileId, args.contentType = nil, nil, nil
    	if fileId == nil and args.name == nil then args.name = string.match(path, "[^/]+$") end
    	local start = UPLOAD .. "/files" .. (if fileId then "/" .. url.segment(fileId, "fileId") else "") .. "?uploadType=resumable&supportsAllDrives=true&fields=" .. url.encode(FILE_FIELDS)
    	local session = await(http.request({method = if fileId then "PATCH" else "POST", url = start, body = json.encode(args),
    		headers = {["Content-Type"] = {"application/json; charset=UTF-8"}, ["X-Upload-Content-Type"] = {contentType}}}))
    	if session.statusCode < 200 or session.statusCode >= 300 then fail("uploadFile", session) end
    	session.body:close()
    	local location = session.headers.location
    	if not location or not location[1] then
    		houston.fail({operation = "uploadFile", layer = "upstream", upstream_status = session.statusCode, retryable = false, message = "Google returned no upload session URL"})
    	end
    	return decode("uploadFile", await(http.request({method = "PUT", url = location[1], headers = {["Content-Type"] = {contentType}}, body = fs.open(path, "r")})))
    end
    
    exportEndpoints(endpoints)
    -- DELETE /files/trash is Drive's emptyTrash, which the {fileId} route would otherwise reach.
    local deleteFile = exports.deleteFile
    if deleteFile then
    	exports.deleteFile = function(args: any): any
    		assert(type(args) ~= "table" or args.fileId ~= "trash", "fileId 'trash' is not a file")
    		return deleteFile(args)
    	end
    end
    for name, endpoint in downloads do
    	export(name, nil, function(args: Options): Options return download(name, endpoint, args) end, endpoint.help)
    end
    
    -- Fixed-signature file lookup shared with other storage connectors.
    export("statFile", nil, function(...: any): {id: string, name: string, isFolder: boolean, size: number?}
    	assert(select("#", ...) == 1, "statFile takes exactly one file ID")
    	local id = text((...), "file ID")
    	local file = call("statFile", "GET", API .. "/files/" .. url.segment(id, "file ID") .. "?fields=id%2Cname%2CmimeType%2Csize&supportsAllDrives=true")
    	local size = if file.size == nil then nil else tonumber(file.size)
    	if type(file.id) ~= "string" or file.id == "" or type(file.name) ~= "string"
    		or (file.size ~= nil and (size == nil or size < 0 or size % 1 ~= 0 or size > 9007199254740991)) then
    		houston.fail({operation = "statFile", layer = "upstream", retryable = false, message = "Google returned invalid file metadata"})
    	end
    	return {id = file.id, name = file.name, isFolder = file.mimeType == FOLDER, size = size}
    end, "statFile(fileId) -> {id, name, isFolder, size?}. One positional file ID; size is absent for folders and Google Docs.")
    
    export("uploadFile", "data:write", upload, "uploadFile({path, name?, parents?, mimeType?, contentType?, fileId?, ...metadata}) -> file. Streams a session file to Drive. name defaults to the path's basename; contentType describes the bytes (default application/octet-stream). Setting mimeType to a Google type converts, e.g. a .docx with mimeType='application/vnd.google-apps.document'. With fileId, replaces that file's content (and applies any metadata). A failed upload may leave nothing or a complete file: check with listFiles before retrying.")
    
    exports.help = helpWith({
    	"Google Drive API v3. Operations take one named options object with Google's camelCase fields and return Google's JSON unchanged; deletes return {success=true}. Shared drives are included by default.",
    	"File metadata defaults to " .. FILE_FIELDS .. "; pass fields to choose others ('*' for all). Lists return one page: pass nextPageToken as pageToken until it is absent.",
    	"Files move through session paths: downloads save to a path and return a signed URL, uploads read from a path. Never inline file bytes.",
    	"No hidden paging or retries. Errors report the HTTP status, Google's message and reason. A failed or timed-out write may already have succeeded; check before repeating.",
    	"Example: listFiles({q=\"mimeType = 'application/pdf' and trashed = false\", orderBy='modifiedTime desc', pageSize=20}); exportFile({fileId='...', mimeType='text/markdown', path='notes.md'}).",
    })
    return exports
    
  • houston.json
    {
      "schema_version": 2,
      "name": "Google Drive",
      "warning": "**Pending Google approval.** Google is still reviewing Houston's access to Google Drive. Until Google approves it, you will see a *Google hasn't verified this app* screen while connecting with Google: select **Advanced**, then continue to Houston.",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "access": [
        {
          "name": "data",
          "label": "Access",
          "levels": [
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "write",
              "label": "Write"
            }
          ],
          "default": "read"
        }
      ],
      "auth": {
        "composio": {
          "type": "composio",
          "label": "Connect with Composio",
          "description": "Composio requires full Google Drive access. Houston limits its use to the access level you select.",
          "order": 2,
          "app": "googledrive",
          "auth_config_id": "{{publisher.composio_auth_config_id}}",
          "api_key": "{{publisher.composio_api_key}}",
          "account": {
            "method": "GET",
            "url": "https://www.googleapis.com/drive/v3/about?fields=user",
            "label": "/user/emailAddress"
          }
        },
        "oauth": {
          "type": "oauth2",
          "label": "Connect with Google",
          "order": 1,
          "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/drive.readonly"
              ]
            },
            {
              "if": "{{ is access.data \"write\" }}",
              "values": [
                "https://www.googleapis.com/auth/drive"
              ]
            }
          ],
          "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
        },
        "composio_auth_config_id": {
          "type": "string",
          "label": "Composio Google Drive auth config ID",
          "description": "Create a Google Drive OAuth2 auth config using Composio-managed credentials and the https://www.googleapis.com/auth/drive scope. Copy its ac_ ID here. Leave blank to offer only direct Google sign-in.",
          "order": 3
        },
        "composio_api_key": {
          "type": "secret",
          "label": "Composio project API key",
          "description": "Use an API key from the project that owns the Google Drive auth config, with Proxy execute enabled. Composio is offered only when both fields are filled in.",
          "order": 4
        }
      },
      "proxy": [
        {
          "match": {
            "protocol": "http",
            "host": [
              "www.googleapis.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/drive/v3/about",
              "/drive/v3/files",
              "/drive/v3/files/{fileId}",
              "/drive/v3/files/{fileId}/export",
              "/drive/v3/files/{fileId}/permissions",
              "/drive/v3/drives"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          }
        },
        {
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "protocol": "http",
            "host": [
              "www.googleapis.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/drive/v3/files",
              "/drive/v3/files/{fileId}/copy",
              "/drive/v3/files/{fileId}/permissions",
              "/upload/drive/v3/files"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          }
        },
        {
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "protocol": "http",
            "host": [
              "www.googleapis.com"
            ],
            "method": [
              "PATCH"
            ],
            "path": [
              "/drive/v3/files/{fileId}",
              "/upload/drive/v3/files/{fileId}"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          }
        },
        {
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "protocol": "http",
            "host": [
              "www.googleapis.com"
            ],
            "method": [
              "DELETE"
            ],
            "path": [
              "/drive/v3/files/{fileId}",
              "/drive/v3/files/{fileId}/permissions/{permissionId}"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          }
        },
        {
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "protocol": "http",
            "host": [
              "www.googleapis.com"
            ],
            "method": [
              "PUT"
            ],
            "path": [
              "/upload/drive/v3/files",
              "/upload/drive/v3/files/{fileId}"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Find, read and organize files in Google Drive.
    ---
    # Google Drive
    
    Help agents find the files and documents you need without hunting through folders.
    
    - Search My Drive and shared drives, and check file details and sharing.
    - Download files and export Google Docs, Sheets and Slides as Markdown, text,
      CSV, PDF or Office formats.
    - With **Write** access: upload files, create folders, rename, move,
      copy, trash and share files.
    
    Read access cannot change, share or delete your files.
    
  • SETUP.md
    # Connect your Google account
    
    1. Choose the level for **Access**:
       - **Read** to let agents search, read, download and export your files in My
         Drive and shared drives, and see who they are shared with.
       - **Write** to also let agents create folders and files, upload files and new
         versions, rename, move and copy them, share them and remove access, move
         them to the trash and delete them permanently.
    2. Choose an available sign-in option, choose your account, and approve the
       permissions Google lists. With Connect with Google, if Google shows a
       checkbox per permission, tick them all: Houston refuses a partial grant.
    
    Houston calls Google Drive only when your agent asks it to and never syncs your
    files in the background. Connect with Google asks only for the permissions of
    the access level you choose, so connecting Google Drive does not grant access to
    your other Google services.
    
    > If you connect with Composio, it requires full Google Drive access. Houston
    > limits its use to the access level you select.
    
    ## Advanced: changing access and troubleshooting
    
    - To change the access level, edit the connection and connect the same account
      again. With Connect with Google, Google then asks for the new set of
      permissions.
    - To revoke access, remove the connection in Houston, or remove Composio (or
      Houston for direct sign-in) from
      [your Google Account's third-party connections](https://myaccount.google.com/connections).
      This also affects other connections using that app.
    - Google Workspace administrators can block third-party apps. If Google refuses
      the connection, ask your administrator to allow the app shown on Google's
      consent screen.
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = {},
      				config = {},
      				endpoint = { "GET", "https://www.googleapis.com/drive/v3/files" },
      				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,
      }
      
    • behavior.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 = {}, {}
      		fs = fixture.files()
      		http = {request = function(req)
      			table.insert(requests, req)
      			if req.body ~= nil and type(req.body) ~= "string" then req.body = await(req.body:readAll()) end
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local response = table.remove(responses, 1)
      			return fixture.operation({statusCode = response.status or 200, headers = response.headers or {}, body = fixture.reader(response.body or "")})
      		end}
      	end,
      	run = function(c)
      		local API = "https://www.googleapis.com/drive/v3"
      		responses = {{body = '{"files":[{"id":"f1"}],"nextPageToken":"next+1"}'}, {body = '{"files":[]}'}}
      		local page = c.listFiles({q = "name contains 'a b'", pageToken = "start+1"})
      		assert(page.nextPageToken == "next+1" and page.files[1].id == "f1")
      		local url = requests[1].url
      		assert(string.sub(url, 1, #API + 7) == API .. "/files?" and string.find(url, "q=name%20contains%20%27a%20b%27", 1, true) and string.find(url, "pageToken=start%2B1", 1, true), url)
      		assert(string.find(url, "supportsAllDrives=true", 1, true) and string.find(url, "includeItemsFromAllDrives=true", 1, true) and string.find(url, "fields=nextPageToken%2CincompleteSearch%2Cfiles%28id%2Cname", 1, true), url)
      		c.listFiles({fields = "files(id)", includeItemsFromAllDrives = false})
      		assert(string.find(requests[2].url, "fields=files%28id%29", 1, true) and string.find(requests[2].url, "includeItemsFromAllDrives=false", 1, true), requests[2].url)
      
      		assert(not pcall(c.statFile, ""))
      		assert(not pcall(c.statFile, 42))
      		assert(not pcall(c.statFile, "file", "extra"))
      		assert(not pcall(c.statFile))
      		assert(#requests == 2, "bad arguments reached Google")
      		responses = {{body = '{"id":"f1","name":"Report","mimeType":"text/plain","size":"42"}'}, {body = '{"id":"dir","name":"Folder","mimeType":"application/vnd.google-apps.folder"}'}}
      		local file = c.statFile("f1")
      		assert(file.id == "f1" and file.name == "Report" and file.size == 42 and file.isFolder == false)
      		assert(requests[3].url == API .. "/files/f1?fields=id%2Cname%2CmimeType%2Csize&supportsAllDrives=true", requests[3].url)
      		local folder = c.statFile("dir")
      		assert(folder.isFolder and folder.size == nil)
      		for _, size in {'"-1"', '"0.5"', '"9007199254740992"', '"big"'} do
      			responses = {{body = '{"id":"bad","name":"Bad","size":' .. size .. '}'}}
      			assert(not pcall(c.statFile, "bad"), "accepted size " .. size)
      		end
      
      		local bytes = string.char(0, 255, 13, 10) .. "binary payload"
      		responses = {{body = bytes}, {body = "# Notes"}}
      		local saved = c.downloadFile({fileId = "f:1", path = "downloads/report.bin"})
      		assert(requests[#requests].url == API .. "/files/f%3A1?alt=media&supportsAllDrives=true", requests[#requests].url)
      		assert(saved.path == "downloads/report.bin" and saved.url == "https://houston.test/downloads/report.bin" and saved.size == #bytes)
      		local fd = fs.open("downloads/report.bin", "r")
      		assert(await(fd:readAll()) == bytes)
      		await(fd:close())
      		local exported = c.exportFile({fileId = "doc", mimeType = "text/markdown", path = "notes.md"})
      		assert(requests[#requests].url == API .. "/files/doc/export?mimeType=text%2Fmarkdown" and exported.size == 7)
      		responses = {{status = 403, body = '{"error":{"code":403,"message":"Only files with binary content can be downloaded.","errors":[{"reason":"fileNotDownloadable"}]}}'}}
      		local ok, err = pcall(c.downloadFile, {fileId = "doc", path = "doc.bin"})
      		assert(not ok and string.find(tostring(err), "fileNotDownloadable", 1, true), tostring(err))
      		assert(not pcall(c.downloadFile, {fileId = "f1"}), "download requires a path")
      		local sent = #requests
      		for _, id in {"f/1", "..", "f%2F1", "f\\1", "f\t1"} do
      			local rejected, problem = pcall(c.downloadFile, {fileId = id, path = "x.bin"})
      			assert(not rejected and problem.code == "invalid_argument" and string.find(problem.message, "fileId must be one", 1, true))
      			assert(not pcall(c.statFile, id))
      		end
      		assert(#requests == sent, "invalid IDs must not reach the network")
      
      		local upload = fs.open("uploads/report.pdf", "w")
      		upload:write(bytes)
      		await(upload:close())
      		local session = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xyz"
      		responses = {{headers = {location = {session}}}, {body = '{"id":"up","name":"report.pdf"}'}}
      		local created = c.uploadFile({path = "uploads/report.pdf", parents = {"dir"}, contentType = "application/pdf"})
      		assert(created.id == "up")
      		local start, put = requests[#requests - 1], requests[#requests]
      		assert(start.method == "POST" and string.find(start.url, "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true&fields=", 1, true) == 1, start.url)
      		assert(start.headers["X-Upload-Content-Type"][1] == "application/pdf")
      		local metadata = json.decode(start.body)
      		assert(metadata.name == "report.pdf" and metadata.parents[1] == "dir" and metadata.path == nil and metadata.contentType == nil)
      		assert(put.method == "PUT" and put.url == session and put.body == bytes and put.headers["Content-Type"][1] == "application/pdf")
      		responses = {{headers = {location = {session}}}, {body = '{"id":"up"}'}}
      		c.uploadFile({path = "uploads/report.pdf", fileId = "up"})
      		start = requests[#requests - 1]
      		assert(start.method == "PATCH" and string.find(start.url, "/upload/drive/v3/files/up?", 1, true) and start.body == "{}", start.body)
      		responses = {{}}
      		assert(not pcall(c.uploadFile, {path = "uploads/report.pdf"}), "upload without a session URL")
      		sent = #requests
      		for _, id in {"..", "up/1", "up%2F1"} do assert(not pcall(c.uploadFile, {path = "uploads/report.pdf", fileId = id})) end
      		assert(not pcall(c.deleteFile, {fileId = "trash"}), "DELETE /files/trash would empty the trash")
      		assert(#requests == sent, "invalid file IDs must not reach Google")
      
      		responses = {{body = '{"id":"moved"}'}, {status = 204}}
      		c.updateFile({fileId = "f1", addParents = "dir", name = "Renamed"})
      		local update = requests[#requests]
      		assert(update.method == "PATCH" and string.find(update.url, API .. "/files/f1?addParents=dir", 1, true) and json.decode(update.body).name == "Renamed")
      		assert(c.deletePermission({fileId = "f1", permissionId = "p1"}).success)
      		assert(requests[#requests].url == API .. "/files/f1/permissions/p1?supportsAllDrives=true")
      		assert(#responses == 0)
      	end,
      }
      
    • composio.luau
      return {
      	scenario = {
      		publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret", composio_auth_config_id = "ac_fixture", composio_api_key = "fixture-secret"},
      		config = {}, auth_method = "composio", auth_config = {},
      	},
      	access = {data = "read"},
      	configure = function()
      		http = {request = function(req)
      			assert(req.method == "GET" and req.url == "https://www.googleapis.com/drive/v3/about?fields=user%2CstorageQuota" and req.headers == nil)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader('{"user":{"emailAddress":"[email protected]"},"storageQuota":{"usage":"42"}}')})
      		end}
      	end,
      	run = function(c)
      		local about = c.getAbout()
      		assert(about.user.emailAddress == "[email protected]" and about.storageQuota.usage == "42")
      		assert(type(c.downloadFile) == "function" and c.uploadFile == nil)
      	end,
      }
      
    • composio_policy.luau
      return {
      	contract = function(m)
      		local google = {client_id = "google-client", client_secret = "google-secret"}
      		local publisher = table.clone(google)
      		publisher.composio_auth_config_id = "ac_fixture"
      		publisher.composio_api_key = "fixture-secret"
      		for _, field in {"composio_api_key", "composio_auth_config_id"} do
      			local incomplete = table.clone(publisher)
      			incomplete[field] = nil
      			local _, err = m.resolve(incomplete, {}, nil, "composio")
      			assert(err, "Incomplete Composio settings must require " .. field)
      		end
      		for _, settings in {{}, {composio_auth_config_id = "", composio_api_key = ""}, {composio_auth_config_id = "ac_fixture"}, {composio_api_key = "fixture-secret"}, publisher} do
      			local values = table.clone(google)
      			for key, value in settings do
      				values[key] = value
      			end
      			local form, err = m.draft(values, {}, nil, "oauth")
      			assert(form and not err, tostring(err))
      			for _, method in form.Methods do
      				local offered = method.key == "oauth" or settings == publisher
      				assert(method.eligible == offered and method.available == offered, "Sign-in choices must reflect complete publisher settings")
      			end
      			local resolved, resolveError = m.resolve(values, {}, nil, "oauth")
      			assert(resolved and not resolveError, "Optional Composio settings must not prevent Google sign-in")
      		end
      		local api = "https://www.googleapis.com/drive/v3"
      		local upload = "https://www.googleapis.com/upload/drive/v3"
      		for _, access in {"read", "write"} do
      			local r, err = m.resolve(publisher, {}, nil, "composio", {data = access})
      			assert(r and not err, tostring(err))
      			local reads = {"GET " .. api .. "/about?fields=user", "GET " .. api .. "/files?q=trashed%3Dfalse", "GET " .. api .. "/files/f1?alt=media", "GET " .. api .. "/files/f1/export?mimeType=text%2Fplain", "GET " .. api .. "/drives"}
      			m.routes(r, "", true, reads)
      			m.rejectOverrides(r, reads)
      			m.routes(r, "", access == "write", {"POST " .. api .. "/files", "PATCH " .. api .. "/files/f1", "DELETE " .. api .. "/files/f1/permissions/p1", "POST " .. upload .. "/files?uploadType=resumable", "PUT " .. upload .. "/files?uploadType=resumable&upload_id=xyz"})
      			m.refused(r, "", {"POST https://backend.composio.dev/api/v3.1/tools/execute/proxy", "GET https://www.googleapis.com/gmail/v1/users/me/profile", "POST " .. api .. "/drives"})
      		end
      	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://www.googleapis.com/drive/v3"
      			local upload = "https://www.googleapis.com/upload/drive/v3"
      			for _, access in { "read", "write" } do
      				local scope = "drive.readonly"
      				if access == "write" then
      					scope = "drive"
      				end
      				local r = google(access, { scope })
      				local reads = {
      					"GET " .. api .. "/about?fields=user",
      					"GET " .. api .. "/files?q=trashed%3Dfalse",
      					"GET " .. api .. "/files/f1",
      					"GET " .. api .. "/files/f1?alt=media",
      					"GET " .. api .. "/files/f1/export?mimeType=text%2Fplain",
      					"GET " .. api .. "/files/f1/permissions",
      					"GET " .. api .. "/drives",
      				}
      				m.routes(r, "Bearer fixture-token", true, reads)
      				m.rejectOverrides(r, reads)
      				local writes = {
      					"POST " .. api .. "/files",
      					"PATCH " .. api .. "/files/f1",
      					"POST " .. api .. "/files/f1/copy",
      					"DELETE " .. api .. "/files/f1",
      					"POST " .. api .. "/files/f1/permissions",
      					"DELETE " .. api .. "/files/f1/permissions/p1",
      					"POST " .. upload .. "/files?uploadType=resumable",
      					"PATCH " .. upload .. "/files/f1?uploadType=resumable",
      					"PUT " .. upload .. "/files?uploadType=resumable&upload_id=xyz",
      					"PUT " .. upload .. "/files/f1?uploadType=resumable&upload_id=xyz",
      				}
      				m.routes(r, "Bearer fixture-token", (access == "write"), writes)
      				m.routes(
      					r,
      					"Bearer fixture-token",
      					(access == "write"),
      					{ "DELETE " .. api .. "/files/trash" }
      				)
      				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/calendar/v3/calendars/primary",
      					"GET https://www.googleapis.com.evil.test/drive/v3/files",
      					"GET https://content.googleapis.com/drive/v3/files",
      					"POST https://www.googleapis.com/batch/drive/v3",
      					"POST " .. api .. "/drives",
      					"DELETE " .. api .. "/drives/d1",
      					"PATCH " .. api .. "/files/f1/permissions/p1",
      					"POST " .. api .. "/files/f1/watch",
      					"POST " .. api .. "/changes/watch",
      					"GET " .. api .. "/changes",
      					"POST " .. api .. "/files/f1/comments",
      					"GET " .. api .. "/files/f1/revisions",
      					"PUT " .. api .. "/files/f1",
      					"POST " .. api .. "/files/generateIds",
      					"GET " .. api .. "/files/f1/permissions/p1",
      					"POST " .. upload .. "/files/f1",
      					"GET " .. upload .. "/files/f1",
      					"GET " .. api .. "/files/%2e%2e/about",
      					"GET " .. api .. "/files/f1%2F..%2Fx",
      				})
      			end
      		end
      		do
      			local drive = google("read", { "drive.readonly" })
      			m.routes(
      				drive,
      				"Bearer fixture-token",
      				true,
      				{ "GET https://www.googleapis.com/drive/v3/files/x" }
      			)
      			m.refused(
      				drive,
      				"method override",
      				{ "GET https://www.googleapis.com/drive/v3/files/x?$httpMethod=PATCH" }
      			)
      		end
      	end,
      }
      
    • read_only.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {data = "read"},
      	run = function(c)
      		local names = {}
      		for name in c do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == "downloadFile,exportFile,getAbout,getFile,listDrives,listFiles,listPermissions,statFile", "read-only got " .. table.concat(names, ","))
      	end,
      }