mcp-gmailcal 0.10.0

A MCP server for google mail, calendar, and contacts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use crate::auth::TokenManager;
use crate::config::Config;
use crate::errors::{PeopleApiError, PeopleResult};
use log::{debug, error};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::Mutex;

const PEOPLE_API_BASE_URL: &str = "https://people.googleapis.com/v1";

// Alias for backward compatibility within this module
type Result<T> = PeopleResult<T>;

// Contact information representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contact {
    pub resource_name: String,
    pub name: Option<PersonName>,
    pub email_addresses: Vec<EmailAddress>,
    pub phone_numbers: Vec<PhoneNumber>,
    pub organizations: Vec<Organization>,
    pub photos: Vec<Photo>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersonName {
    pub display_name: String,
    pub given_name: Option<String>,
    pub family_name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmailAddress {
    pub value: String,
    pub type_: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhoneNumber {
    pub value: String,
    pub type_: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Organization {
    pub name: Option<String>,
    pub title: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Photo {
    pub url: String,
    pub default: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContactList {
    pub contacts: Vec<Contact>,
    pub next_page_token: Option<String>,
    pub total_items: Option<u32>,
}

// People API client
#[derive(Debug, Clone)]
pub struct PeopleClient {
    client: Client,
    token_manager: Arc<Mutex<TokenManager>>,
}

impl PeopleClient {
    pub fn new(config: &Config) -> Self {
        let client = Client::new();
        // Reuse the Gmail token manager since they share the same OAuth flow
        let token_manager = Arc::new(Mutex::new(TokenManager::new(config)));

        Self {
            client,
            token_manager,
        }
    }

    // Get a list of contacts
    pub async fn list_contacts(&self, max_results: Option<u32>) -> Result<ContactList> {
        let token = self
            .token_manager
            .lock()
            .await
            .get_token(&self.client)
            .await
            .map_err(|e| PeopleApiError::AuthError(e.to_string()))?;

        let mut url = format!("{}/people/me/connections", PEOPLE_API_BASE_URL);

        // Build query parameters
        let mut query_parts = Vec::new();

        // Request specific fields
        let fields = [
            "names",
            "emailAddresses",
            "phoneNumbers",
            "organizations",
            "photos",
        ];
        query_parts.push(format!("personFields={}", fields.join(",")));

        if let Some(max) = max_results {
            query_parts.push(format!("pageSize={}", max));
        }

        if !query_parts.is_empty() {
            url = format!("{}?{}", url, query_parts.join("&"));
        }

        debug!("Listing contacts from: {}", url);

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await
            .map_err(|e| PeopleApiError::NetworkError(e.to_string()))?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "<no response body>".to_string());
            return Err(PeopleApiError::ApiError(format!(
                "Failed to list contacts. Status: {}, Error: {}",
                status, error_text
            )));
        }

        let json_response = response
            .json::<serde_json::Value>()
            .await
            .map_err(|e| PeopleApiError::ParseError(e.to_string()))?;

        let mut contacts = Vec::new();

        if let Some(connections) = json_response.get("connections").and_then(|v| v.as_array()) {
            for connection in connections {
                if let Ok(contact) = self.parse_contact(connection) {
                    contacts.push(contact);
                } else {
                    // Log parsing error but continue with other contacts
                    error!("Failed to parse contact: {:?}", connection);
                }
            }
        }

        let next_page_token = json_response
            .get("nextPageToken")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let total_items = json_response
            .get("totalItems")
            .and_then(|v| v.as_u64())
            .map(|n| n as u32);

        Ok(ContactList {
            contacts,
            next_page_token,
            total_items,
        })
    }

    // Search contacts by query
    pub async fn search_contacts(
        &self,
        query: &str,
        max_results: Option<u32>,
    ) -> Result<ContactList> {
        let token = self
            .token_manager
            .lock()
            .await
            .get_token(&self.client)
            .await
            .map_err(|e| PeopleApiError::AuthError(e.to_string()))?;

        let mut url = format!("{}/people:searchContacts", PEOPLE_API_BASE_URL);

        // Build query parameters
        let mut query_parts = Vec::new();

        // Add search query
        query_parts.push(format!("query={}", query));

        // Request specific fields
        let fields = [
            "names",
            "emailAddresses",
            "phoneNumbers",
            "organizations",
            "photos",
        ];
        query_parts.push(format!("readMask={}", fields.join(",")));

        if let Some(max) = max_results {
            query_parts.push(format!("pageSize={}", max));
        }

        if !query_parts.is_empty() {
            url = format!("{}?{}", url, query_parts.join("&"));
        }

        debug!("Searching contacts: {}", url);

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await
            .map_err(|e| PeopleApiError::NetworkError(e.to_string()))?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "<no response body>".to_string());
            return Err(PeopleApiError::ApiError(format!(
                "Failed to search contacts. Status: {}, Error: {}",
                status, error_text
            )));
        }

        let json_response = response
            .json::<serde_json::Value>()
            .await
            .map_err(|e| PeopleApiError::ParseError(e.to_string()))?;

        let mut contacts = Vec::new();

        if let Some(results) = json_response.get("results").and_then(|v| v.as_array()) {
            for result in results {
                if let Some(person) = result.get("person") {
                    if let Ok(contact) = self.parse_contact(person) {
                        contacts.push(contact);
                    } else {
                        // Log parsing error but continue with other contacts
                        error!("Failed to parse contact: {:?}", person);
                    }
                }
            }
        }

        let next_page_token = json_response
            .get("nextPageToken")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let total_items = json_response
            .get("totalPeople")
            .and_then(|v| v.as_u64())
            .map(|n| n as u32);

        Ok(ContactList {
            contacts,
            next_page_token,
            total_items,
        })
    }

    // Get contact by resource name
    pub async fn get_contact(&self, resource_name: &str) -> Result<Contact> {
        let token = self
            .token_manager
            .lock()
            .await
            .get_token(&self.client)
            .await
            .map_err(|e| PeopleApiError::AuthError(e.to_string()))?;

        let mut url = format!("{}/{}", PEOPLE_API_BASE_URL, resource_name);

        // Build query parameters for fields
        let fields = [
            "names",
            "emailAddresses",
            "phoneNumbers",
            "organizations",
            "photos",
        ];
        url = format!("{}?personFields={}", url, fields.join(","));

        debug!("Getting contact: {}", url);

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await
            .map_err(|e| PeopleApiError::NetworkError(e.to_string()))?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "<no response body>".to_string());
            return Err(PeopleApiError::ApiError(format!(
                "Failed to get contact. Status: {}, Error: {}",
                status, error_text
            )));
        }

        let json_response = response
            .json::<serde_json::Value>()
            .await
            .map_err(|e| PeopleApiError::ParseError(e.to_string()))?;

        self.parse_contact(&json_response)
    }

    // Helper method to parse a contact from API response
    fn parse_contact(&self, data: &serde_json::Value) -> Result<Contact> {
        let resource_name = data
            .get("resourceName")
            .and_then(|v| v.as_str())
            .ok_or_else(|| PeopleApiError::ParseError("Missing resourceName".to_string()))?
            .to_string();

        // Parse name
        let name = if let Some(names) = data.get("names").and_then(|v| v.as_array()) {
            if let Some(primary_name) = names.first() {
                let display_name = primary_name
                    .get("displayName")
                    .and_then(|v| v.as_str())
                    .unwrap_or("Unknown")
                    .to_string();

                let given_name = primary_name
                    .get("givenName")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());

                let family_name = primary_name
                    .get("familyName")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());

                Some(PersonName {
                    display_name,
                    given_name,
                    family_name,
                })
            } else {
                None
            }
        } else {
            None
        };

        // Parse email addresses
        let mut email_addresses = Vec::new();
        if let Some(emails) = data.get("emailAddresses").and_then(|v| v.as_array()) {
            for email in emails {
                if let Some(value) = email.get("value").and_then(|v| v.as_str()) {
                    let type_ = email
                        .get("type")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());

                    email_addresses.push(EmailAddress {
                        value: value.to_string(),
                        type_,
                    });
                }
            }
        }

        // Parse phone numbers
        let mut phone_numbers = Vec::new();
        if let Some(phones) = data.get("phoneNumbers").and_then(|v| v.as_array()) {
            for phone in phones {
                if let Some(value) = phone.get("value").and_then(|v| v.as_str()) {
                    let type_ = phone
                        .get("type")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());

                    phone_numbers.push(PhoneNumber {
                        value: value.to_string(),
                        type_,
                    });
                }
            }
        }

        // Parse organizations
        let mut organizations = Vec::new();
        if let Some(orgs) = data.get("organizations").and_then(|v| v.as_array()) {
            for org in orgs {
                let name = org
                    .get("name")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());

                let title = org
                    .get("title")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());

                organizations.push(Organization { name, title });
            }
        }

        // Parse photos
        let mut photos = Vec::new();
        if let Some(pics) = data.get("photos").and_then(|v| v.as_array()) {
            for pic in pics {
                if let Some(url) = pic.get("url").and_then(|v| v.as_str()) {
                    let default = pic
                        .get("default")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false);

                    photos.push(Photo {
                        url: url.to_string(),
                        default,
                    });
                }
            }
        }

        Ok(Contact {
            resource_name,
            name,
            email_addresses,
            phone_numbers,
            organizations,
            photos,
        })
    }
}