Skip to main content

agentmux_srv_core/backend/google/
drive.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The `Drive` tool's read actions (G2), named after Google's Drive MCP tools
5//! (SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md §5):
6//! `search_files`, `get_file_metadata`, `read_file_content`. On `drive.file` an
7//! account reaches only the files the person picked (Google's desktop picker,
8//! §3.3) and the ones AgentMux made, so a search is over those and nothing else.
9//!
10//! As with Calendar, each action is a [`plan`] (the request, from the agent's
11//! arguments) and a [`shape`] (Google's answer, trimmed and capped); neither
12//! touches the network or a token. `read_file_content` takes two requests: the
13//! file's metadata decides whether it is exported ([`content_plan`]).
14
15use serde::Deserialize;
16use serde_json::{json, Map, Value};
17
18use super::{clip, GoogleRequest, SCOPE_PREFIX, TEXT_CAP};
19
20const API: &str = "https://www.googleapis.com/drive/v3";
21
22/// The read actions, in the order the tool lists them. `pick_files` is not one: it asks
23/// the person, and srv answers it itself.
24pub const READ_ACTIONS: [&str; 3] = ["search_files", "get_file_metadata", "read_file_content"];
25
26const DEFAULT_RESULTS: u32 = 25;
27const MAX_RESULTS: u32 = 100;
28/// A file in a shared drive is left out of a list, and refused by a get or a download, unless the
29/// request says it understands shared drives (Workspace accounts; harmless on a personal one).
30fn shared_drives(list: bool) -> Vec<(&'static str, String)> {
31    let mut q = vec![("supportsAllDrives", "true".to_string())];
32    if list {
33        q.push(("includeItemsFromAllDrives", "true".to_string()));
34    }
35    q
36}
37
38/// The fields of a file Google is asked for.
39const FILE_FIELDS: &str = "id,name,mimeType,modifiedTime,size,webViewLink,owners(emailAddress)";
40
41/// The arguments the read actions take. Unknown fields are ignored.
42#[derive(Debug, Default, Clone, Deserialize)]
43pub struct DriveArgs {
44    /// `get_file_metadata`, `read_file_content`: a file id from `search_files`.
45    #[serde(default)]
46    pub file_id: Option<String>,
47    /// `search_files`: words to look for in names and contents.
48    #[serde(default)]
49    pub query: Option<String>,
50    #[serde(default)]
51    pub max_results: Option<u32>,
52    #[serde(default)]
53    pub page_token: Option<String>,
54}
55
56/// The scopes an action can run with: any one is enough. `drive.readonly` and `drive` are
57/// never asked for here, but an account connected with them still works.
58pub fn needs(_action: &str) -> &'static [&'static str] {
59    &["drive.file", "drive.readonly", "drive"]
60}
61
62/// Whether `granted` (full scope URLs, or bare names) covers `action`.
63pub fn granted_for(action: &str, granted: &[String]) -> bool {
64    needs(action)
65        .iter()
66        .any(|n| granted.iter().any(|g| g.strip_prefix(SCOPE_PREFIX).unwrap_or(g) == *n))
67}
68
69fn file_id(args: &DriveArgs) -> Result<String, String> {
70    let id = args.file_id.as_deref().map(str::trim).unwrap_or("");
71    if id.is_empty() {
72        return Err("this action needs file_id: a file id from search_files".to_string());
73    }
74    if id.len() > 128 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
75        return Err(format!("\"{}\" isn't a Drive file id", clip(id, 40)));
76    }
77    Ok(id.to_string())
78}
79
80fn file_url(id: &str, tail: Option<&str>) -> Result<String, String> {
81    let mut url = url::Url::parse(API).map_err(|e| e.to_string())?;
82    {
83        let mut seg = url.path_segments_mut().map_err(|_| "bad Drive API URL".to_string())?;
84        seg.push("files").push(id);
85        if let Some(t) = tail {
86            seg.push(t);
87        }
88    }
89    Ok(url.to_string())
90}
91
92/// A string for Drive's `q`: backslashes and single quotes escaped.
93fn quoted(s: &str) -> String {
94    s.replace('\\', "\\\\").replace('\'', "\\'")
95}
96
97fn get(url: String, query: Vec<(&'static str, String)>) -> GoogleRequest {
98    GoogleRequest { method: reqwest::Method::GET, url, query, body: None, text: false }
99}
100
101/// The request to Google for a read action; for `read_file_content`, the file's metadata,
102/// which [`content_plan`] turns into the request for its text.
103pub fn plan(action: &str, args: &DriveArgs) -> Result<GoogleRequest, String> {
104    match action {
105        "search_files" => {
106            let text = args.query.as_deref().map(str::trim).unwrap_or("");
107            let q = if text.is_empty() {
108                "trashed = false".to_string()
109            } else {
110                format!("fullText contains '{}' and trashed = false", quoted(&clip(text, 200)))
111            };
112            let mut query = vec![
113                ("q", q),
114                ("pageSize", args.max_results.unwrap_or(DEFAULT_RESULTS).clamp(1, MAX_RESULTS).to_string()),
115                ("fields", format!("nextPageToken,files({FILE_FIELDS})")),
116            ];
117            query.extend(shared_drives(true));
118            if text.is_empty() {
119                query.push(("orderBy", "modifiedTime desc".to_string()));
120            }
121            if let Some(t) = args.page_token.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
122                query.push(("pageToken", t.to_string()));
123            }
124            Ok(get(format!("{API}/files"), query))
125        }
126        "get_file_metadata" | "read_file_content" => {
127            let mut query = vec![("fields", FILE_FIELDS.to_string())];
128            query.extend(shared_drives(false));
129            Ok(get(file_url(&file_id(args)?, None)?, query))
130        }
131        other => Err(format!("Drive has no action \"{other}\"; one of {}, pick_files", READ_ACTIONS.join(", "))),
132    }
133}
134
135/// How a file is read as text: Google's native documents are exported, plain text is
136/// downloaded, anything else can't be.
137pub fn content_plan(meta: &Value) -> Result<GoogleRequest, String> {
138    let id = s(meta, "/id");
139    let mime = s(meta, "/mimeType");
140    let export = match mime {
141        "application/vnd.google-apps.document" | "application/vnd.google-apps.presentation" => Some("text/plain"),
142        "application/vnd.google-apps.spreadsheet" => Some("text/csv"),
143        _ => None,
144    };
145    let mut req = if let Some(to) = export {
146        get(file_url(id, Some("export"))?, vec![("mimeType", to.to_string())])
147    } else if is_text(mime) {
148        let mut query = vec![("alt", "media".to_string())];
149        query.extend(shared_drives(false));
150        get(file_url(id, None)?, query)
151    } else {
152        return Err(format!(
153            "{} is a {} file, which can't be read as text here. Only Google Docs, Sheets and Slides (exported) and plain-text files can",
154            clip(s(meta, "/name"), 80),
155            if mime.is_empty() { "unknown-type" } else { mime }
156        ));
157    };
158    req.text = true;
159    Ok(req)
160}
161
162fn is_text(mime: &str) -> bool {
163    mime.starts_with("text/")
164        || matches!(
165            mime,
166            "application/json" | "application/xml" | "application/x-yaml" | "application/yaml" | "application/javascript" | "application/x-sh"
167        )
168        || mime.ends_with("+json")
169        || mime.ends_with("+xml")
170}
171
172fn s<'a>(v: &'a Value, ptr: &str) -> &'a str {
173    v.pointer(ptr).and_then(Value::as_str).unwrap_or("")
174}
175
176fn shape_file(f: &Value) -> Value {
177    let mut out = Map::new();
178    for (src, dst) in [
179        ("/id", "id"),
180        ("/name", "name"),
181        ("/mimeType", "mime_type"),
182        ("/modifiedTime", "modified"),
183        ("/size", "size"),
184        ("/webViewLink", "link"),
185        ("/owners/0/emailAddress", "owner"),
186    ] {
187        let v = s(f, src);
188        if !v.is_empty() {
189            out.insert(dst.to_string(), json!(v));
190        }
191    }
192    Value::Object(out)
193}
194
195/// Google's answer to `search_files` or `get_file_metadata`, trimmed for the agent.
196pub fn shape(action: &str, body: &Value) -> Value {
197    match action {
198        "search_files" => {
199            let files: Vec<Value> = body.get("files").and_then(Value::as_array).map(|a| a.iter().map(shape_file).collect()).unwrap_or_default();
200            let mut out = Map::new();
201            out.insert("files".into(), json!(files));
202            let t = s(body, "/nextPageToken");
203            if !t.is_empty() {
204                out.insert("next_page_token".into(), json!(t));
205            }
206            Value::Object(out)
207        }
208        "get_file_metadata" => shape_file(body),
209        _ => Value::Null,
210    }
211}
212
213/// `read_file_content`'s answer: the file's details and its text, as far as it was read.
214pub fn shape_content(meta: &Value, reply: &Value) -> Value {
215    let mut out = Map::new();
216    out.insert("file".into(), shape_file(meta));
217    out.insert("content".into(), json!(s(reply, "/text")));
218    if reply.get("truncated").and_then(Value::as_bool) == Some(true) {
219        out.insert("truncated".into(), json!(format!("only the first {} bytes of the file are shown", TEXT_CAP)));
220    }
221    if s(meta, "/mimeType") == "application/vnd.google-apps.spreadsheet" {
222        out.insert("note".into(), json!("a Sheet is exported as CSV: its first sheet only"));
223    }
224    Value::Object(out)
225}
226
227/// The ids a read touched, for the account's log (D7): file ids, never what was in them.
228pub fn logged_ids(action: &str, args: &DriveArgs) -> String {
229    match action {
230        "get_file_metadata" | "read_file_content" => args.file_id.as_deref().map(str::trim).unwrap_or("").to_string(),
231        _ => String::new(),
232    }
233}
234
235#[cfg(test)]
236#[path = "drive_tests.rs"]
237mod tests;