Skip to main content

agentmux_srv_core/backend/google/
gmail.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The `Gmail` tool's read actions (G3), named after Google's Gmail MCP tools
5//! (SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md ยง5):
6//! `search_threads`, `get_thread`, `list_labels`.
7//!
8//! As with Calendar and Drive, each action is a [`plan`] (the request, from
9//! the agent's arguments) and a [`shape`] (Google's answer, trimmed and
10//! capped); neither touches the network or a token. Google's thread search
11//! answers with ids and a snippet only, so `search_threads` takes one more
12//! request per thread shown ([`summary_plan`]) for who wrote it, the subject
13//! and the date. Mail is written by other people: every text that comes back
14//! is cut to a length and the tool marks it untrusted (D6).
15
16use base64::Engine as _;
17use serde::Deserialize;
18use serde_json::{json, Map, Value};
19
20use super::gmail_sender::{raw_headers, search_check, sender_check, RAW_THREAD_CHARS};
21use super::{clip, GoogleRequest, SCOPE_PREFIX};
22
23const API: &str = "https://gmail.googleapis.com/gmail/v1/users/me";
24
25/// The read actions, in the order the tool lists them.
26pub const READ_ACTIONS: [&str; 3] = ["search_threads", "get_thread", "list_labels"];
27
28const DEFAULT_RESULTS: u32 = 10;
29const MAX_RESULTS: u32 = 25;
30/// Threads of a search that get a subject and sender (one request each).
31pub const SUMMARIZED: usize = 10;
32/// A message's text, a thread's messages and the text of a whole thread are cut to these.
33const BODY_CHARS: usize = 20_000;
34const MESSAGES: usize = 30;
35const THREAD_CHARS: usize = 120_000;
36const SNIPPET_CHARS: usize = 300;
37const ADDRESS_CHARS: usize = 300;
38const ATTACHMENTS: usize = 20;
39/// Stored text parts one `get_thread` fetches, and the longest one it takes (base64 characters).
40pub const EXTERNAL_PARTS: usize = 10;
41pub const EXTERNAL_PART_CHARS: usize = 3_000_000;
42
43/// The arguments the read actions take. Unknown fields are ignored.
44#[derive(Debug, Default, Clone, Deserialize)]
45pub struct GmailArgs {
46    /// `search_threads`: Gmail's own search syntax (`from:alice newer_than:7d`).
47    #[serde(default)]
48    pub query: Option<String>,
49    /// `search_threads`: only threads with this label id (from `list_labels`).
50    #[serde(default)]
51    pub label_id: Option<String>,
52    /// `get_thread`: a thread id from `search_threads`.
53    #[serde(default)]
54    pub thread_id: Option<String>,
55    /// `get_thread`: `raw` adds each message's header lines as they came.
56    #[serde(default)]
57    pub headers: Option<String>,
58    #[serde(default)]
59    pub max_results: Option<u32>,
60    #[serde(default)]
61    pub page_token: Option<String>,
62    /// `create_draft`, `update_draft`: the recipients, the subject and the text of the mail.
63    #[serde(default)]
64    pub to: Option<Vec<String>>,
65    #[serde(default)]
66    pub cc: Option<Vec<String>>,
67    #[serde(default)]
68    pub bcc: Option<Vec<String>>,
69    #[serde(default)]
70    pub subject: Option<String>,
71    #[serde(default)]
72    pub body: Option<String>,
73    /// `update_draft`, `send_draft`: a draft id from `create_draft`.
74    #[serde(default)]
75    pub draft_id: Option<String>,
76    /// `label_thread`: label ids (from `list_labels`) to put on the thread and to take off it.
77    #[serde(default)]
78    pub add_label_ids: Option<Vec<String>>,
79    #[serde(default)]
80    pub remove_label_ids: Option<Vec<String>>,
81}
82
83/// The scopes an action can run with: any one is enough. Only `gmail.readonly` is asked for
84/// here, but an account connected with a wider Gmail scope still works.
85pub fn needs(_action: &str) -> &'static [&'static str] {
86    &["gmail.readonly", "gmail.modify", "gmail.metadata"]
87}
88
89/// Google's full-mail scope, which every Gmail action accepts. AgentMux never asks for it, but an
90/// account connected with it elsewhere has it.
91const FULL_MAIL: &str = "https://mail.google.com/";
92
93/// Whether `granted` (full scope URLs, or bare names) has the Gmail scope `name` (`gmail.readonly`,
94/// ...), or the full-mail scope that covers them all.
95pub(super) fn has_scope(granted: &[String], name: &str) -> bool {
96    granted.iter().any(|g| g == FULL_MAIL || g.strip_prefix(SCOPE_PREFIX).unwrap_or(g) == name)
97}
98
99/// Whether `granted` (full scope URLs, or bare names) covers `action`. `gmail.metadata` can't
100/// search or read bodies, so it covers `list_labels` alone.
101pub fn granted_for(action: &str, granted: &[String]) -> bool {
102    match action {
103        "list_labels" => needs(action).iter().any(|n| has_scope(granted, n)),
104        _ => has_scope(granted, "gmail.readonly") || has_scope(granted, "gmail.modify"),
105    }
106}
107
108/// An id in a URL path: Gmail's are hex, but accept letters, digits, `-` and `_`.
109pub(super) fn id_arg(name: &str, v: Option<&str>) -> Result<String, String> {
110    let id = v.map(str::trim).unwrap_or("");
111    if id.is_empty() {
112        return Err(format!("this action needs {name}: one from search_threads"));
113    }
114    if id.len() > 64 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
115        return Err(format!("\"{}\" isn't a Gmail id", clip(id, 40)));
116    }
117    Ok(id.to_string())
118}
119
120pub(super) fn url_of(tail: &[&str]) -> Result<String, String> {
121    let mut url = url::Url::parse(API).map_err(|e| e.to_string())?;
122    url.path_segments_mut().map_err(|_| "bad Gmail API URL".to_string())?.extend(tail);
123    Ok(url.to_string())
124}
125
126pub(super) fn get(url: String, query: Vec<(&'static str, String)>) -> GoogleRequest {
127    GoogleRequest { method: reqwest::Method::GET, url, query, body: None, text: false }
128}
129
130/// The request to Google for a read action.
131pub fn plan(action: &str, args: &GmailArgs) -> Result<GoogleRequest, String> {
132    match action {
133        "search_threads" => {
134            let mut q = vec![("maxResults", args.max_results.unwrap_or(DEFAULT_RESULTS).clamp(1, MAX_RESULTS).to_string())];
135            if let Some(text) = args.query.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
136                q.push(("q", clip(text, 500)));
137            }
138            if let Some(l) = args.label_id.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
139                q.push(("labelIds", clip(l, 100)));
140            }
141            if let Some(t) = args.page_token.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
142                q.push(("pageToken", t.to_string()));
143            }
144            Ok(get(url_of(&["threads"])?, q))
145        }
146        "get_thread" => {
147            raw_headers_arg(args)?;
148            Ok(get(url_of(&["threads", &id_arg("thread_id", args.thread_id.as_deref())?])?, vec![("format", "full".to_string())]))
149        }
150        "list_labels" => Ok(get(url_of(&["labels"])?, Vec::new())),
151        other => Err(format!("Gmail has no action \"{other}\"; one of {}", READ_ACTIONS.join(", "))),
152    }
153}
154
155/// Whether `get_thread` is asked for the raw header lines (`headers: "raw"`); any other word is refused.
156pub fn raw_headers_arg(args: &GmailArgs) -> Result<bool, String> {
157    match args.headers.as_deref().map(str::trim).filter(|h| !h.is_empty()) {
158        None => Ok(false),
159        Some(h) if h.eq_ignore_ascii_case("raw") => Ok(true),
160        Some(h) => Err(format!("headers can only be \"raw\", not \"{}\"", clip(h, 20))),
161    }
162}
163
164/// The request for a found thread's headers, for the line `search_threads` shows: who wrote it, the
165/// subject and date, and what its sender check reads (Google's verdicts, the Reply-To), in the same call.
166pub fn summary_plan(thread_id: &str) -> Result<GoogleRequest, String> {
167    let id = id_arg("thread_id", Some(thread_id))?;
168    let mut q = vec![("format", "metadata".to_string())];
169    for h in ["From", "Subject", "Date", "Authentication-Results", "Reply-To"] {
170        q.push(("metadataHeaders", h.to_string()));
171    }
172    Ok(get(url_of(&["threads", &id])?, q))
173}
174
175pub(super) fn s<'a>(v: &'a Value, ptr: &str) -> &'a str {
176    v.pointer(ptr).and_then(Value::as_str).unwrap_or("")
177}
178
179/// A header's value (names compare case-insensitively), or empty.
180pub(super) fn header<'a>(payload: &'a Value, name: &str) -> &'a str {
181    payload
182        .get("headers")
183        .and_then(Value::as_array)
184        .and_then(|h| h.iter().find(|h| s(h, "/name").eq_ignore_ascii_case(name)))
185        .map(|h| s(h, "/value"))
186        .unwrap_or("")
187}
188
189/// Header values hold what the sender typed: one line, cut.
190pub(super) fn line(v: &str, max: usize) -> String {
191    clip(&v.split_whitespace().collect::<Vec<_>>().join(" "), max)
192}
193
194/// `search_threads`' answer: Google's list and, for the first [`SUMMARIZED`] threads, what
195/// [`summary_plan`] found (`summaries[i]` is the answer for thread `i`, null when it failed).
196pub fn shape_search(list: &Value, summaries: &[Value]) -> Value {
197    let threads: Vec<Value> = list
198        .get("threads")
199        .and_then(Value::as_array)
200        .map(|a| {
201            a.iter()
202                .enumerate()
203                .map(|(i, t)| {
204                    let mut m = Map::new();
205                    m.insert("id".into(), json!(s(t, "/id")));
206                    let snippet = s(t, "/snippet");
207                    if !snippet.is_empty() {
208                        m.insert("snippet".into(), json!(line(snippet, SNIPPET_CHARS)));
209                    }
210                    if let Some(sum) = summaries.get(i).filter(|v| !v.is_null()) {
211                        let msgs = sum.get("messages").and_then(Value::as_array).cloned().unwrap_or_default();
212                        if let Some(first) = msgs.first() {
213                            let p = first.get("payload").unwrap_or(&Value::Null);
214                            m.insert("subject".into(), json!(line(header(p, "Subject"), ADDRESS_CHARS)));
215                            m.insert("from".into(), json!(line(header(p, "From"), ADDRESS_CHARS)));
216                        }
217                        if let Some(last) = msgs.last() {
218                            let p = last.get("payload").unwrap_or(&Value::Null);
219                            m.insert("last_date".into(), json!(line(header(p, "Date"), 60)));
220                            m.insert("sender_check".into(), search_check(p, &label_ids(last)));
221                        }
222                        m.insert("messages".into(), json!(msgs.len()));
223                    }
224                    Value::Object(m)
225                })
226                .collect()
227        })
228        .unwrap_or_default();
229    let mut out = Map::new();
230    out.insert("threads".into(), json!(threads));
231    let next = s(list, "/nextPageToken");
232    if !next.is_empty() {
233        out.insert("next_page_token".into(), json!(next));
234    }
235    Value::Object(out)
236}
237
238/// A readable text part (not a file) whose text Gmail keeps outside the message, as an
239/// `attachmentId`, instead of in `body.data`: a long mail can be stored this way.
240fn is_external_text(part: &Value) -> bool {
241    part.get("filename").and_then(Value::as_str).is_none_or(str::is_empty)
242        && matches!(s(part, "/mimeType"), "text/plain" | "text/html")
243        && s(part, "/body/data").is_empty()
244        && !s(part, "/body/attachmentId").is_empty()
245}
246
247/// The `(message id, attachment id)` of every readable text part of `thread` whose text must be
248/// fetched separately, at most [`EXTERNAL_PARTS`].
249pub fn external_text_parts(thread: &Value) -> Vec<(String, String)> {
250    fn walk(part: &Value, mid: &str, out: &mut Vec<(String, String)>) {
251        if out.len() < EXTERNAL_PARTS && is_external_text(part) {
252            out.push((mid.to_string(), s(part, "/body/attachmentId").to_string()));
253        }
254        for p in part.get("parts").and_then(Value::as_array).into_iter().flatten() {
255            walk(p, mid, out);
256        }
257    }
258    let mut out = Vec::new();
259    for m in thread.get("messages").and_then(Value::as_array).into_iter().flatten() {
260        walk(m.get("payload").unwrap_or(&Value::Null), s(m, "/id"), &mut out);
261    }
262    out
263}
264
265/// The request for one stored text part.
266pub fn part_plan(message_id: &str, attachment_id: &str) -> Result<GoogleRequest, String> {
267    let m = id_arg("message id", Some(message_id))?;
268    // An attachment id is long and URL-safe base64-ish; it is a path segment, so no `/` or `..`.
269    if attachment_id.is_empty() || attachment_id.len() > 2048 || !attachment_id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
270        return Err("not an attachment id".to_string());
271    }
272    Ok(get(url_of(&["messages", &m, "attachments", attachment_id])?, Vec::new()))
273}
274
275/// Put the fetched text (`parts`: attachment id to the part's base64url data) into the thread's
276/// parts that name it.
277pub fn fill_external(thread: &mut Value, parts: &std::collections::HashMap<String, String>) {
278    fn walk(part: &mut Value, parts: &std::collections::HashMap<String, String>) {
279        if is_external_text(part) {
280            if let Some(data) = parts.get(s(part, "/body/attachmentId")).cloned() {
281                part["body"]["data"] = json!(data);
282            }
283        }
284        if let Some(children) = part.get_mut("parts").and_then(Value::as_array_mut) {
285            for p in children {
286                walk(p, parts);
287            }
288        }
289    }
290    for m in thread.get_mut("messages").and_then(Value::as_array_mut).into_iter().flatten() {
291        if let Some(p) = m.get_mut("payload") {
292            walk(p, parts);
293        }
294    }
295}
296
297/// Whether a text part of `payload` is still stored outside it (it could not be fetched, or was
298/// too large to).
299pub(super) fn has_unloaded_text(payload: &Value) -> bool {
300    is_external_text(payload) || payload.get("parts").and_then(Value::as_array).is_some_and(|ps| ps.iter().any(has_unloaded_text))
301}
302
303/// The charset a part's `Content-Type` header declares (`text/plain; charset="ISO-8859-1"`), if any.
304fn charset_of(part: &Value) -> Option<String> {
305    let ct = header(part, "Content-Type").to_ascii_lowercase();
306    let after = ct.split("charset=").nth(1)?;
307    let name = after.split(';').next()?.trim().trim_matches('"').trim_matches('\'');
308    (!name.is_empty()).then(|| name.to_string())
309}
310
311/// Gmail's text parts are base64url; decode one in the charset its part declares (UTF-8 when none is
312/// declared or the name is unknown), replacing what doesn't decode.
313fn decode(data: &str, charset: Option<&str>) -> String {
314    let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(data.trim_end_matches('=')) else {
315        return String::new();
316    };
317    let enc = charset.and_then(|c| encoding_rs::Encoding::for_label(c.as_bytes())).unwrap_or(encoding_rs::UTF_8);
318    enc.decode(&bytes).0.into_owned()
319}
320
321/// HTML as plain text: tags dropped, the common entities decoded, `script` and `style` removed.
322/// One pass over the text, whatever the mail holds: the lowercase copy is made once (ASCII
323/// lowercasing keeps every byte offset), and a `script` or `style` with no end swallows the rest,
324/// as a browser reads it.
325fn html_text(html: &str) -> String {
326    let lower = html.to_ascii_lowercase();
327    let mut out = String::with_capacity(html.len() / 2);
328    let mut at = 0;
329    while let Some(rel) = html[at..].find('<') {
330        let open = at + rel;
331        out.push_str(&html[at..open]);
332        let tag = &lower[open + 1..];
333        if let Some(name) = ["script", "style"].into_iter().find(|n| tag.starts_with(n)) {
334            let Some(end) = lower[open..].find(&format!("</{name}")) else {
335                return finish_text(out);
336            };
337            let closing = open + end;
338            at = html[closing..].find('>').map_or(html.len(), |i| closing + i + 1);
339            continue;
340        }
341        let block = ["br", "p", "/p", "div", "/div", "li", "tr"].iter().any(|t| tag.starts_with(t));
342        if block {
343            out.push('\n');
344        }
345        at = html[open..].find('>').map_or(html.len(), |i| open + i + 1);
346    }
347    out.push_str(&html[at..]);
348    finish_text(out)
349}
350
351fn finish_text(text: String) -> String {
352    text.replace("&nbsp;", " ").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#39;", "'").replace("&amp;", "&")
353}
354
355/// The decoded text of every readable part of `payload` of type `mime`, in order (files are not).
356pub(super) fn text_of_mime(payload: &Value, mime: &str) -> Vec<String> {
357    fn collect(part: &Value, mime: &str, out: &mut Vec<String>) {
358        if part.get("filename").and_then(Value::as_str).is_some_and(|f| !f.is_empty()) {
359            return;
360        }
361        if s(part, "/mimeType") == mime {
362            let data = s(part, "/body/data");
363            if !data.is_empty() {
364                out.push(decode(data, charset_of(part).as_deref()));
365            }
366        }
367        if let Some(parts) = part.get("parts").and_then(Value::as_array) {
368            for p in parts {
369                collect(p, mime, out);
370            }
371        }
372    }
373    let mut out = Vec::new();
374    collect(payload, mime, &mut out);
375    out
376}
377
378/// The message's readable text: its `text/plain` parts, else its `text/html` parts as text.
379pub(super) fn body_text(payload: &Value) -> String {
380    let plain = text_of_mime(payload, "text/plain");
381    if !plain.is_empty() {
382        return plain.join("\n");
383    }
384    html_alternative(payload)
385}
386
387/// The message's `text/html` parts as text (empty when it has none).
388pub(super) fn html_alternative(payload: &Value) -> String {
389    html_text(&text_of_mime(payload, "text/html").join("\n"))
390}
391
392/// Blank lines collapsed to one and the ends trimmed.
393pub(super) fn tidy(text: &str) -> String {
394    let mut out = String::new();
395    let mut blank = 0;
396    for l in text.replace('\r', "").lines() {
397        if l.trim().is_empty() {
398            blank += 1;
399            if blank > 1 {
400                continue;
401            }
402        } else {
403            blank = 0;
404        }
405        out.push_str(l.trim_end());
406        out.push('\n');
407    }
408    out.trim().to_string()
409}
410
411/// A message's attachments: name, type and size. Their bytes are not fetched.
412pub(super) fn attachments(payload: &Value) -> Vec<Value> {
413    fn walk(part: &Value, out: &mut Vec<Value>) {
414        let name = s(part, "/filename");
415        if !name.is_empty() && out.len() < ATTACHMENTS {
416            out.push(json!({ "filename": line(name, 200), "mime_type": s(part, "/mimeType"), "size": part.pointer("/body/size").and_then(Value::as_u64).unwrap_or(0) }));
417        }
418        if let Some(parts) = part.get("parts").and_then(Value::as_array) {
419            for p in parts {
420                walk(p, out);
421            }
422        }
423    }
424    let mut out = Vec::new();
425    walk(payload, &mut out);
426    out
427}
428
429/// A message's label ids.
430fn label_ids(m: &Value) -> Vec<&str> {
431    m.get("labelIds").and_then(Value::as_array).map(|l| l.iter().filter_map(Value::as_str).collect()).unwrap_or_default()
432}
433
434/// One message of a thread. `raw` is what is left of the raw header budget when the headers were asked for.
435fn shape_message(m: &Value, budget: &mut usize, raw: Option<&mut usize>) -> Value {
436    let p = m.get("payload").unwrap_or(&Value::Null);
437    let mut out = Map::new();
438    out.insert("id".into(), json!(s(m, "/id")));
439    for (h, k) in [("From", "from"), ("To", "to"), ("Cc", "cc"), ("Subject", "subject"), ("Date", "date")] {
440        let v = header(p, h);
441        if !v.is_empty() {
442            out.insert(k.into(), json!(line(v, ADDRESS_CHARS)));
443        }
444    }
445    if let Some(l) = m.get("labelIds").and_then(Value::as_array) {
446        out.insert("labels".into(), json!(l.iter().filter_map(Value::as_str).collect::<Vec<_>>()));
447    }
448    out.insert("sender_check".into(), sender_check(p, &label_ids(m)));
449    if let Some(raw_budget) = raw {
450        out.insert("raw_headers".into(), raw_headers(p, raw_budget));
451    }
452    let text = tidy(&body_text(p));
453    let room = BODY_CHARS.min(*budget);
454    let shown = clip(&text, room);
455    *budget = budget.saturating_sub(shown.chars().count());
456    // `clip` adds an ellipsis, so a text one character over the room is as long as it was.
457    if text.chars().count() > room {
458        out.insert("body_cut".into(), json!(true));
459    }
460    out.insert("body".into(), json!(shown));
461    let files = attachments(p);
462    if !files.is_empty() {
463        out.insert("attachments".into(), json!(files));
464    }
465    if has_unloaded_text(p) {
466        out.insert("body_note".into(), json!("part of this mail's text is stored outside the message and was not loaded (too large, or Google did not return it)"));
467    }
468    Value::Object(out)
469}
470
471/// A thread's answer: each message with its text and sender check, and with its raw header lines when
472/// `raw` (`headers: "raw"`).
473pub fn shape_thread(body: &Value, raw: bool) -> Value {
474    let mut out = Map::new();
475    let all = body.get("messages").and_then(Value::as_array).cloned().unwrap_or_default();
476    let (mut budget, mut raw_budget) = (THREAD_CHARS, RAW_THREAD_CHARS);
477    let shown: Vec<Value> = all.iter().take(MESSAGES).map(|m| shape_message(m, &mut budget, raw.then_some(&mut raw_budget))).collect();
478    out.insert("id".into(), json!(s(body, "/id")));
479    out.insert("messages".into(), json!(shown));
480    // A draft sitting in the thread (saved, not sent) is said first, so a summary of the thread can't skip it.
481    let drafts = all.iter().filter(|m| label_ids(m).contains(&"DRAFT")).count();
482    if drafts > 0 {
483        out.insert("unsent_drafts".into(), json!(drafts));
484    }
485    if all.len() > MESSAGES {
486        out.insert("messages_not_shown".into(), json!(all.len() - MESSAGES));
487    }
488    Value::Object(out)
489}
490
491/// Google's answer to a read action, trimmed for the agent.
492pub fn shape(action: &str, body: &Value) -> Value {
493    let mut out = Map::new();
494    match action {
495        "search_threads" => return shape_search(body, &[]),
496        "get_thread" => return shape_thread(body, false),
497        "list_labels" => {
498            let labels: Vec<Value> = body
499                .get("labels")
500                .and_then(Value::as_array)
501                .map(|a| a.iter().map(|l| json!({ "id": s(l, "/id"), "name": line(s(l, "/name"), 200), "type": s(l, "/type") })).collect())
502                .unwrap_or_default();
503            out.insert("labels".into(), json!(labels));
504        }
505        _ => {}
506    }
507    Value::Object(out)
508}
509
510/// The ids a read touched, for the account's log (D7): never the search words or the mail.
511pub fn logged_ids(action: &str, args: &GmailArgs) -> String {
512    match action {
513        "get_thread" => args.thread_id.as_deref().map(str::trim).unwrap_or("").to_string(),
514        _ => String::new(),
515    }
516}
517
518#[cfg(test)]
519#[path = "gmail_tests.rs"]
520mod tests;