gmcp 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 41a8dfb444f066d7a4e2c51860bbefa84639ccb4ed7fdf6f7f4ed2186e0a7a45
4
+ data.tar.gz: 1c130067070a75a5c21402b72e57be49a5fff07bf30e86142ea84cfdbb7e8639
5
+ SHA512:
6
+ metadata.gz: e6bb96b8b7a0bf91d9732f262af4f2df4ccfb0103dcd621f2a6c4c4ab13cfc6ec840ddd9764bc32f612ad15d2e5c18cdbf2fd8c8eccfe3db297958b96adc5b0b
7
+ data.tar.gz: 72df437e3f879a56c909bb1beb1c8d5daaab939b5e7e9663073c91b7b9aec1ccd8b06bfc5f0c33e93e696878963242eaf6364badc95b29edaf22675be8b90d70
data/CHANGELOG.md ADDED
@@ -0,0 +1,96 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here.
4
+ This project adheres to [Semantic Versioning](https://semver.org/).
5
+
6
+ ## [0.5.0]
7
+
8
+ ### Fixed
9
+
10
+ - Access tokens refresh while the server runs; calls no longer start failing after an hour.
11
+ - Failed Google API calls return an error instead of reporting success.
12
+ - Every tool reports failures as an MCP error with the cause.
13
+ - Token files are owner-only, and none are created for accounts that were never authorized.
14
+ - The OAuth callback listens on loopback only and requires the flow's `state`.
15
+ - `gmcp_authorize` accepts only accounts in `GMCP_ACCOUNTS`.
16
+ - `bin/gmcp-auth` reports a failed authorization immediately.
17
+ - `gmail_reply` threads correctly and answers `Reply-To`.
18
+ - Outgoing mail rejects header injection and encodes non-ASCII subjects and names.
19
+ - `calendar_rsvp` works, and honors `calendar_id`.
20
+ - Calendars whose ids contain `#` (holidays, contacts) are reachable.
21
+ - `calendar_get_event` honors `calendar_id`.
22
+ - `drive_read_file` reads Docs, Sheets and Slides (exported as text or CSV) and plain text files.
23
+ - `voice_list` and `voice_search` work on the current Voice API.
24
+ - A rejected Voice session recovers on the next call.
25
+
26
+ ### Changed
27
+
28
+ - `gmail_search` returns date, sender and subject for each message.
29
+ - `gmail_list_attachments` returns a `part_id`; downloads keep their filenames.
30
+ - `calendar_list_events` defaults to upcoming events and shows readable start times.
31
+ - Calendar events accept `YYYY-MM-DD` for all-day events and an optional `time_zone`; attendees receive invitations.
32
+ - `calendar_list_events`, `drive_search` and `drive_list_folder` return a `page_token` when more results exist.
33
+ - Drive search and listing include shared drives.
34
+ - Voice reads its session from the Chrome profile signed in as the account. Voice tools take `account:` and are limited to `GMCP_ACCOUNTS`. No Safari or Full Disk Access needed.
35
+ - `voice_mark_read` takes a `thread_id`.
36
+
37
+ ### Removed
38
+
39
+ - `voice_archive`, `voice_delete` and the `voice.trash` capability.
40
+ - Safari cookie support.
41
+
42
+ ## [0.4.0]
43
+
44
+ ### Fixed
45
+
46
+ - `gmail_get_message` and `calendar_get_event` return the record instead of an object id.
47
+ - Message bodies decode to UTF-8 using the part's declared charset.
48
+
49
+ ### Added
50
+
51
+ - `gmail_get_message` returns decoded headers and body text.
52
+ - `Gmail::Message#headers`, `#header`, `#body_text` and `#to_summary`.
53
+
54
+ ### Changed
55
+
56
+ - `him` resolves from RubyGems, so `gem install gmcp` works.
57
+
58
+ ## [0.3.1]
59
+
60
+ ### Fixed
61
+
62
+ - Setup instructions register the server with `claude mcp add` and use `GMCP_ACCOUNTS`.
63
+
64
+ ### Added
65
+
66
+ - README covers publishing the OAuth app, which avoids weekly re-authorization.
67
+
68
+ ## [0.3.0]
69
+
70
+ ### Fixed
71
+
72
+ - One process serves several accounts safely; concurrent calls for different accounts no longer interfere.
73
+
74
+ ## [0.2.0]
75
+
76
+ ### Added
77
+
78
+ - Capability scoping with `GMCP_CAPABILITIES`; ungranted tools are never registered.
79
+ - Gmail pagination, batch archive/trash/modify, attachments and one-click unsubscribe.
80
+ - Google Voice support (macOS).
81
+ - `bin/gmail_survey`, a read-only per-sender inbox survey.
82
+ - `GMCP_CREDENTIALS_FILE` to override the `credentials.json` location.
83
+
84
+ ### Changed
85
+
86
+ - `bin/gmcp` prints its accounts and capabilities at startup.
87
+ - `gmcp_authorize` pre-selects the requested account on the consent screen.
88
+
89
+ ### Fixed
90
+
91
+ - A revoked refresh token no longer stops the server from starting.
92
+ - `bin/gmcp-auth` works with Google's current OAuth flow.
93
+
94
+ ## [0.1.0]
95
+
96
+ - Gmail, Calendar and Drive tools.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Twilight Coders LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,248 @@
1
+ # GMCP
2
+
3
+ Google Workspace MCP server (Gmail, Calendar, Drive) for Claude Code.
4
+
5
+ Built on [`him`](https://github.com/TwilightCoders/him) (REST ORM), the
6
+ [official Ruby MCP SDK](https://github.com/modelcontextprotocol/ruby-sdk),
7
+ and Google's OAuth2 library (`googleauth`).
8
+
9
+ ## Why
10
+
11
+ The built-in claude.ai Gmail/Calendar connectors have limited OAuth scopes —
12
+ no trash, no labels, no send, no Drive access. GMCP runs as a local stdio MCP
13
+ server with full `gmail.modify`, `calendar.events`, and `drive.readonly` scopes.
14
+
15
+ ## Tools
16
+
17
+ **Gmail (9 tools)**
18
+ `gmail_search`, `gmail_get_message`, `gmail_list_labels`, `gmail_trash_message`,
19
+ `gmail_archive_message`, `gmail_label_message`, `gmail_send`, `gmail_create_draft`, `gmail_reply`
20
+
21
+ **Calendar (7 tools)**
22
+ `calendar_list_calendars`, `calendar_list_events`, `calendar_get_event`,
23
+ `calendar_create_event`, `calendar_update_event`, `calendar_delete_event`, `calendar_rsvp`
24
+
25
+ **Drive (3 tools)**
26
+ `drive_search`, `drive_list_folder`, `drive_read_file`
27
+
28
+ ## Setup
29
+
30
+ ### 1. Google Cloud project
31
+
32
+ 1. Go to <https://console.cloud.google.com/>
33
+ 2. Create a project (or use an existing one)
34
+ 3. Enable the Gmail, Google Calendar, and Google Drive APIs
35
+ 4. Under **APIs & Services → Credentials**, create an OAuth 2.0 Client ID
36
+ - Application type: **Desktop app**
37
+ 5. Download the JSON file and save it to `~/.config/gmcp/credentials.json`
38
+ 6. Under **Google Auth Platform → Audience**, click **Publish app**
39
+
40
+ Step 6 is not optional for day-to-day use. While the consent screen is in
41
+ **Testing**, Google expires every refresh token after **7 days**, so each account
42
+ silently stops working about a week after you authorize it and the server reports
43
+ `invalid_grant`. Publishing to **In production** removes that expiry.
44
+
45
+ Publishing is not the same as verification. An unverified production app still
46
+ shows a "Google hasn't verified this app" interstitial (**Advanced → Go to …**)
47
+ on each authorization, and is capped at 100 users. Full verification of the
48
+ restricted `gmail.modify` scope requires an annual third-party security
49
+ assessment, which is not worth doing for a personal install — accept the
50
+ interstitial.
51
+
52
+
53
+ ### 2. Install
54
+
55
+ ```bash
56
+ gem install gmcp
57
+ ```
58
+
59
+ Or from source:
60
+ ```bash
61
+ git clone https://github.com/TwilightCoders/GMCP ~/.gmcp
62
+ cd ~/.gmcp && bundle install
63
+ ```
64
+
65
+ ### 3. Wire up Claude Code
66
+
67
+ MCP servers are configured in `.claude.json`, not `settings.json`. Let the CLI
68
+ write it so it lands in the config directory your sessions actually read
69
+ (`$CLAUDE_CONFIG_DIR/.claude.json` when that is set, `~/.claude.json` otherwise):
70
+
71
+ ```sh
72
+ GMCP=~/.gmcp # wherever you cloned it
73
+
74
+ claude mcp add gmcp --scope user \
75
+ --env "GMCP_ACCOUNTS=you@example.com,work@example.com" \
76
+ --env "GMCP_CAPABILITIES=gmcp.authorize,gmail.read,calendar.read,drive.read" \
77
+ --env "BUNDLE_GEMFILE=$GMCP/Gemfile" \
78
+ -- "$(which ruby)" "$GMCP/bin/gmcp"
79
+ ```
80
+
81
+ `--scope user` registers it for every session on the machine; `--scope project`
82
+ writes a `.mcp.json` next to a single repo, which is how you give one project a
83
+ wider grant than the default (see **`GMCP_CAPABILITIES`** below).
84
+
85
+ If you use a Ruby version manager, point the command at its shim rather than a
86
+ versioned binary, so a Ruby upgrade does not silently break every session. With
87
+ `rbenv`, add `--env "RBENV_DIR=$GMCP"` and the shim resolves the version from
88
+ GMCP's own `.ruby-version`, regardless of which directory the session runs in.
89
+
90
+ Verify with `claude mcp get gmcp`. On startup the server prints its accounts and
91
+ capabilities to stderr — that stderr is the only place an operator can see what a
92
+ given process was actually granted.
93
+
94
+ ### 4. Authorize from Claude
95
+
96
+ Ask Claude to call `gmcp_authorize`, or run `bin/gmcp-auth <account>` from a terminal. Either opens your browser and captures the redirect on a temporary local callback server — there is nothing to copy and paste. (Google retired the out-of-band code flow in 2022.)
97
+
98
+ Tokens are stored owner-only at `~/.config/gmcp/<account>/token.yaml`, and access tokens refresh automatically while the server runs. If a refresh token is revoked, the server still starts — the account is left unbound and reports that it needs re-authorizing, rather than taking the whole server down.
99
+
100
+ ## Multiple accounts and capability scoping
101
+
102
+ GMCP is scoped along two independent axes. Both are environment variables read
103
+ once at process start, so a given `bin/gmcp` process has a fixed, inspectable
104
+ reach — it prints both to stderr on startup.
105
+
106
+ ### `GMCP_ACCOUNTS` — which mailboxes
107
+
108
+ Comma-separated. Each account keeps its own OAuth token at
109
+ `~/.config/gmcp/<account>/token.yaml`, and every Gmail/Calendar/Drive tool takes
110
+ an optional `account:` argument selecting among them (defaulting to the first).
111
+
112
+ ```sh
113
+ GMCP_ACCOUNTS=personal@example.com,work@example.com bin/gmcp
114
+ ```
115
+
116
+ Authorize each one separately with `gmcp_authorize(account: "...")`.
117
+
118
+ ### `GMCP_CAPABILITIES` — which verbs
119
+
120
+ Comma-separated capability names from `config/capabilities.yml`. Capabilities
121
+ gate **registration**: a tool whose capability was not granted is never defined
122
+ on the MCP server, so it never appears in `tools/list` and cannot be called no
123
+ matter what the client sends.
124
+
125
+ ```sh
126
+ # a read-only assistant
127
+ GMCP_CAPABILITIES=gmail.read,calendar.read bin/gmcp
128
+
129
+ # one that may also send
130
+ GMCP_CAPABILITIES=gmail.read,gmail.send bin/gmcp
131
+ ```
132
+
133
+ | Capability | Grants |
134
+ |---|---|
135
+ | `gmcp.authorize` | Start the OAuth flow (opens a browser) |
136
+ | `gmail.read` | Search (paginated), read, list labels, list attachments, inspect unsubscribe options |
137
+ | `gmail.modify_labels` | Add/remove labels and archive, single or batched (archiving *is* removing `INBOX`) |
138
+ | `gmail.trash` | Trash a message, single or batched |
139
+ | `gmail.send` | Send, draft, reply |
140
+ | `gmail.download` | Write attachment bytes to a local directory |
141
+ | `gmail.unsubscribe` | RFC 8058 one-click unsubscribe — leaves Google, tells a third party the address is live |
142
+ | `calendar.read` | List calendars, read events |
143
+ | `calendar.write` | Create, update, RSVP |
144
+ | `calendar.delete` | Delete an event |
145
+ | `drive.read` | Search, list folders, read files |
146
+ | `voice.read` | List/search Voice; report an account's Voice number |
147
+ | `voice.modify` | Mark a conversation read |
148
+
149
+ `config/capabilities.yml` is the source of truth; a spec asserts it matches the
150
+ tools actually registered, so it cannot silently drift.
151
+
152
+ ### Bulk work
153
+
154
+ `gmail_search` returns one line per message (id, date, sender, subject) and
155
+ paginates. It returns a `page_token` whenever more results exist; pass it back
156
+ to walk a whole mailbox. `calendar_list_events`, `drive_search` and
157
+ `drive_list_folder` page the same way. In Ruby, `Message.each_page` handles the
158
+ cursor for you and is bounded by `max_pages` so a runaway cursor cannot spin.
159
+
160
+ ```ruby
161
+ GMCP::Gmail::Message.each_page('in:inbox', max_results: 500) do |page|
162
+ page[:messages].each { |m| ... }
163
+ end
164
+ ```
165
+
166
+ Acting on the result is batched — `gmail_batch_archive`, `gmail_batch_trash`,
167
+ and `gmail_batch_modify` take up to 1000 ids in one request rather than one
168
+ round trip per message. Gmail returns nothing per-message, so a partial failure
169
+ is not distinguishable; re-read if you need per-message confirmation.
170
+
171
+ Attachments are two steps: `gmail_list_attachments` (under `gmail.read`) gives
172
+ you filenames and `part_id`s, `gmail_download_attachment` (under
173
+ `gmail.download`) writes one to a directory you name. There is no default destination, the
174
+ filename is reduced to a basename so it cannot escape that directory, and an
175
+ existing file is never overwritten.
176
+
177
+ ### Contract: unset and empty mean opposite things
178
+
179
+ This distinction is the whole security boundary. It is not a convenience.
180
+
181
+ | Value | Meaning |
182
+ |---|---|
183
+ | `GMCP_CAPABILITIES` **not set** | **Every** capability. For a human running `bin/gmcp` by hand with no grant system in front of it. |
184
+ | `GMCP_CAPABILITIES=""` | **No** capabilities. The explicit empty grant set for an identity that was granted nothing. |
185
+
186
+ **An automated launcher must always set the variable explicitly, including when
187
+ the grant set is empty.** Omitting the key because there are no grants fails
188
+ open and hands the process everything. There is no wildcard value, and unknown
189
+ entries are dropped rather than trusted, so a grant cannot widen itself by typo.
190
+
191
+ ### Account isolation
192
+
193
+ Models are bound to a *resolver*, not to a concrete API: `him` calls `use_api`
194
+ at request time if it responds to `:call`, so `GMCP::ApiBinding` installs a
195
+ lambda once and swaps the account per fiber via `Thread.current`.
196
+ `Server.with_account` scopes a binding to a block and restores whatever was
197
+ bound before, so two concurrent tool calls for different accounts cannot see
198
+ each other's APIs, and a nested call cannot leak its account to its caller.
199
+
200
+ A request with nothing bound raises `ApiBinding::NotBound` rather than falling
201
+ back to whichever account the previous caller happened to leave behind.
202
+
203
+ This was not always true. Until 0.3.0 the account was written onto the model
204
+ class itself, so isolation depended on never running two requests at once —
205
+ which is not isolation, only an absence of opportunity. Per-process separation
206
+ was the recommendation because it was the only thing that actually held.
207
+
208
+ **Capability separation is still per-process**, because `GMCP_CAPABILITIES` is
209
+ read once at startup and decides which tools get registered at all. One process
210
+ per capability set; that process may now serve several accounts safely.
211
+
212
+ ### Connectors and account scoping
213
+
214
+ GMCP models `gmail`, `google_calendar`, `drive`, and `voice` as separate
215
+ connectors, served by one process. Each declares in `config/capabilities.yml`
216
+ whether `GMCP_ACCOUNTS` constrains it and where its credential lives:
217
+
218
+ | Connector | `account_scoping` | `credential_source` | `GMCP_ACCOUNTS` constrains it? |
219
+ |---|---|---|---|
220
+ | `gmcp` | `enforced` | `local_file` | yes |
221
+ | `gmail` | `enforced` | `local_file` | yes |
222
+ | `google_calendar` | `enforced` | `local_file` | yes |
223
+ | `drive` | `enforced` | `local_file` | yes |
224
+ | `voice` | `enforced` | `delegated` (Chrome) | yes |
225
+
226
+ Voice has no usable OAuth path — the token-to-cookie exchange is reserved for
227
+ Chromium — so `GMCP::Voice::Session` uses the Google session of the **Chrome
228
+ profile signed in as the requested account**, found by email in Chrome's profile
229
+ list. Voice tools take `account:` like the rest and are limited to
230
+ `GMCP_ACCOUNTS`; an account with no Chrome profile has no Voice. Chrome keeps
231
+ the session fresh as you use it, so there is no separate sign-in.
232
+
233
+ Chrome encrypts its cookies with a key in the macOS Keychain ("Chrome Safe
234
+ Storage"). The first Voice call asks for access; choose **Always Allow**.
235
+ Voice is macOS-only for that reason.
236
+
237
+ ## Development
238
+
239
+ ```bash
240
+ bundle install
241
+ bundle exec rake spec
242
+ ```
243
+
244
+ Ruby 3.4.9+ required.
245
+
246
+ ## License
247
+
248
+ MIT. See `LICENSE.txt`.
data/bin/gmail_survey ADDED
@@ -0,0 +1,167 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Read-only Gmail survey. Pages through messages matching a query, fetches
5
+ # minimal metadata (From, Subject, List-Unsubscribe, label IDs, internalDate)
6
+ # for each, and aggregates into per-sender stats.
7
+ #
8
+ # Usage: bin/gmail_survey [--query "<gmail query>"] [--limit N] [--out PATH]
9
+ #
10
+ # Defaults to a broad sample so we can spot the bulk-win senders quickly.
11
+
12
+ # Bundler only in a checkout; an installed gem resolves through RubyGems.
13
+ require 'bundler/setup' if File.exist?(File.expand_path('../Gemfile', __dir__))
14
+ require_relative '../lib/gmcp'
15
+ require 'json'
16
+ require 'optparse'
17
+ require 'time'
18
+
19
+ # Unbuffered so progress is visible when stdout is a pipe, not just a TTY.
20
+ $stdout.sync = true
21
+
22
+ options = {
23
+ query: '', # all mail
24
+ limit: 3000,
25
+ out: 'gmail_survey.json',
26
+ account: ENV['GMCP_ACCOUNT'] || ENV['GMCP_ACCOUNTS']&.split(',')&.first&.strip
27
+ }
28
+ OptionParser.new do |o|
29
+ o.on('--query Q') { |v| options[:query] = v }
30
+ o.on('--limit N') { |v| options[:limit] = v.to_i }
31
+ o.on('--out PATH') { |v| options[:out] = v }
32
+ o.on('--account A') { |v| options[:account] = v }
33
+ end.parse!
34
+
35
+ abort 'No account configured (set GMCP_ACCOUNT or pass --account)' unless options[:account]
36
+
37
+ conn = GMCP::Apis.build_for_account(account: options[:account])[:gmail].connection
38
+
39
+ def extract_email(from_header)
40
+ return nil unless from_header
41
+ m = from_header.match(/<([^>]+)>/) || from_header.match(/(\S+@\S+\.\S+)/)
42
+ m ? m[1].downcase : from_header.strip.downcase
43
+ end
44
+
45
+ def extract_domain(email)
46
+ email.to_s.split('@', 2)[1]&.downcase
47
+ end
48
+
49
+ # Faraday collapses repeated `metadataHeaders` params, so we ask for full
50
+ # metadata format and just pick the headers we need. Slightly larger payload
51
+ # but predictable.
52
+ def metadata_url(id)
53
+ "messages/#{id}?format=metadata"
54
+ end
55
+
56
+ # 1. Page through messages.list collecting IDs.
57
+ ids = []
58
+ page_token = nil
59
+ batch = 0
60
+ loop do
61
+ batch += 1
62
+ params = { maxResults: 500 }
63
+ params[:q] = options[:query] unless options[:query].empty?
64
+ params[:pageToken] = page_token if page_token
65
+ body = conn.get('messages', params).body
66
+ data = body[:data] || body['data'] || body
67
+ msgs = data[:messages] || data['messages'] || []
68
+ ids.concat(msgs.map { |m| m[:id] || m['id'] })
69
+ page_token = data[:nextPageToken] || data['nextPageToken']
70
+ print "\rlisting: #{ids.length} ids in #{batch} pages..."
71
+ break if page_token.nil? || ids.length >= options[:limit]
72
+ end
73
+ ids = ids.first(options[:limit])
74
+ puts "\nlisted #{ids.length} message IDs"
75
+
76
+ # 2. Fetch metadata for each.
77
+ records = []
78
+ ids.each_with_index do |id, i|
79
+ body = conn.get(metadata_url(id)).body
80
+ data = body[:data] || body['data'] || body
81
+ payload = data[:payload] || data['payload'] || {}
82
+ hdrs = payload[:headers] || payload['headers'] || []
83
+ pick = lambda do |name|
84
+ h = hdrs.find { |hh| (hh[:name] || hh['name']).to_s.downcase == name.downcase }
85
+ h && (h[:value] || h['value'])
86
+ end
87
+
88
+ from = pick.call('From')
89
+ subject = pick.call('Subject')
90
+ list_unsub = pick.call('List-Unsubscribe')
91
+ email = extract_email(from)
92
+ domain = extract_domain(email)
93
+ labels = data[:labelIds] || data['labelIds'] || []
94
+ ts_ms = (data[:internalDate] || data['internalDate']).to_i
95
+
96
+ records << {
97
+ id: id,
98
+ from: from,
99
+ email: email,
100
+ domain: domain,
101
+ subject: subject&.[](0, 120),
102
+ has_list: !list_unsub.nil?,
103
+ labels: labels,
104
+ is_unread: labels.include?('UNREAD'),
105
+ in_inbox: labels.include?('INBOX'),
106
+ in_trash: labels.include?('TRASH'),
107
+ in_spam: labels.include?('SPAM'),
108
+ is_promo: labels.include?('CATEGORY_PROMOTIONS'),
109
+ is_update: labels.include?('CATEGORY_UPDATES'),
110
+ is_social: labels.include?('CATEGORY_SOCIAL'),
111
+ ts_ms: ts_ms,
112
+ ts_iso: ts_ms.positive? ? Time.at(ts_ms / 1000).utc.iso8601 : nil
113
+ }
114
+
115
+ if (i + 1) % 50 == 0 || i == ids.length - 1
116
+ print "\rfetched metadata: #{i + 1}/#{ids.length}"
117
+ end
118
+ end
119
+ puts
120
+
121
+ # 3. Aggregate.
122
+ by_sender = Hash.new { |h, k| h[k] = { count: 0, unread: 0, trashed: 0, newsletters: 0,
123
+ in_inbox: 0, promo: 0, update: 0, social: 0,
124
+ last_ts: 0, sample_subjects: [] } }
125
+ records.each do |r|
126
+ key = r[:email] || '(unknown)'
127
+ s = by_sender[key]
128
+ s[:count] += 1
129
+ s[:unread] += 1 if r[:is_unread]
130
+ s[:trashed] += 1 if r[:in_trash]
131
+ s[:newsletters] += 1 if r[:has_list]
132
+ s[:in_inbox] += 1 if r[:in_inbox]
133
+ s[:promo] += 1 if r[:is_promo]
134
+ s[:update] += 1 if r[:is_update]
135
+ s[:social] += 1 if r[:is_social]
136
+ s[:last_ts] = [s[:last_ts], r[:ts_ms]].max
137
+ s[:sample_subjects] << r[:subject] if s[:sample_subjects].length < 3 && r[:subject]
138
+ end
139
+
140
+ # 4. Write everything to JSON for further analysis.
141
+ File.write(options[:out], JSON.pretty_generate({
142
+ query: options[:query],
143
+ limit: options[:limit],
144
+ fetched: records.length,
145
+ records: records,
146
+ by_sender: by_sender.transform_values { |v| v.merge(last_iso: v[:last_ts].positive? ? Time.at(v[:last_ts] / 1000).utc.iso8601 : nil) }
147
+ }))
148
+
149
+ # 5. Print top-line stats.
150
+ total = records.length
151
+ puts
152
+ puts "=== Summary (n = #{total}) ==="
153
+ puts " unread: #{records.count { |r| r[:is_unread] }}"
154
+ puts " in inbox: #{records.count { |r| r[:in_inbox] }}"
155
+ puts " in trash: #{records.count { |r| r[:in_trash] }}"
156
+ puts " newsletters: #{records.count { |r| r[:has_list] }}"
157
+ puts " promo cat: #{records.count { |r| r[:is_promo] }}"
158
+ puts " updates cat: #{records.count { |r| r[:is_update] }}"
159
+ puts
160
+ puts "=== Top 25 senders by volume ==="
161
+ printf "%6s %6s %6s %6s %s\n", 'count', 'unread', 'trash', 'newsl', 'sender'
162
+ by_sender.sort_by { |_, v| -v[:count] }.first(25).each do |email, s|
163
+ printf "%6d %6d %6d %6d %s\n",
164
+ s[:count], s[:unread], s[:trashed], s[:newsletters], email
165
+ end
166
+ puts
167
+ puts "Wrote #{options[:out]}"
data/bin/gmcp ADDED
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # Bundler only in a checkout; an installed gem resolves through RubyGems.
4
+ require 'bundler/setup' if File.exist?(File.expand_path('../Gemfile', __dir__))
5
+ require_relative '../lib/gmcp'
6
+
7
+ accounts = if ENV['GMCP_ACCOUNTS']
8
+ ENV['GMCP_ACCOUNTS'].split(',').map(&:strip).reject(&:empty?)
9
+ elsif ENV['GMCP_ACCOUNT']
10
+ [ENV['GMCP_ACCOUNT']]
11
+ else
12
+ abort 'Set GMCP_ACCOUNTS (comma-separated) or GMCP_ACCOUNT to the Google account(s) to use'
13
+ end
14
+
15
+ # stderr, not stdout — stdout is the MCP stdio transport. This is the one place
16
+ # an operator can see what a given process was actually granted.
17
+ warn "GMCP: accounts = #{accounts.join(', ')}"
18
+ warn "GMCP: capabilities = #{GMCP::Capabilities.summary}"
19
+
20
+ # Some connectors resolve their principal outside GMCP, so the account list
21
+ # above does not bound them. Say so rather than letting it imply containment.
22
+ unscoped = GMCP::Capabilities.unscoped_grants
23
+ unless unscoped.empty?
24
+ by_connector = unscoped.group_by { |cap| GMCP::Capabilities.connector_for(cap).fetch('name') }
25
+ by_connector.each do |connector, caps|
26
+ verb = caps.one? ? 'reaches' : 'reach'
27
+ warn "GMCP: NOTE — #{caps.join(', ')} #{verb} the #{connector} principal, which " \
28
+ 'GMCP_ACCOUNTS does NOT narrow.'
29
+ end
30
+ warn 'GMCP: NOTE — call voice_account to see which account that currently is.' if by_connector.key?('voice')
31
+ end
32
+
33
+ GMCP::Server.run!(accounts: accounts)
data/bin/gmcp-auth ADDED
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # Authorize a Google account for GMCP from the command line.
4
+ #
5
+ # bin/gmcp-auth <account>
6
+ #
7
+ # Opens the OAuth consent page in a browser and captures the redirect on a
8
+ # local callback server. Use this when the gmcp_authorize MCP tool isn't
9
+ # reachable (server down, tools not loaded in the current session).
10
+ #
11
+ # Google shut off the out-of-band (urn:ietf:wg:oauth:2.0:oob) flow in 2022, so
12
+ # there is no copy-the-code path any more — the loopback redirect is the only
13
+ # option for a desktop client, and it is what Auth.authorize_interactive!
14
+ # implements.
15
+
16
+ # Bundler only in a checkout; an installed gem resolves through RubyGems.
17
+ require 'bundler/setup' if File.exist?(File.expand_path('../Gemfile', __dir__))
18
+ require_relative '../lib/gmcp'
19
+
20
+ # Unbuffered so progress is visible when stdout is a pipe, not just a TTY.
21
+ $stdout.sync = true
22
+
23
+ # Generous by default: this waits on a human completing a browser consent
24
+ # screen, not on a machine. Override with GMCP_AUTH_TIMEOUT (seconds).
25
+ TIMEOUT = Integer(ENV.fetch('GMCP_AUTH_TIMEOUT', 900))
26
+
27
+ account = ARGV[0]
28
+ if account.nil? || account.empty?
29
+ abort "Usage: #{File.basename($PROGRAM_NAME)} <account>\n" \
30
+ " e.g. #{File.basename($PROGRAM_NAME)} you@example.com"
31
+ end
32
+
33
+ unless File.exist?(GMCP::Auth.credentials_path)
34
+ abort "credentials.json not found at #{GMCP::Auth.credentials_path}\n\n" \
35
+ "1. https://console.cloud.google.com/ → APIs & Services → Credentials\n" \
36
+ "2. Create an OAuth 2.0 Client ID (Desktop app)\n" \
37
+ "3. Save the JSON to that path"
38
+ end
39
+
40
+ result = Queue.new
41
+ url = GMCP::Auth.authorize_interactive!(
42
+ account: account,
43
+ timeout: TIMEOUT,
44
+ on_success: ->(_acct) { result << :authorized },
45
+ on_failure: ->(_acct, error) { result << error }
46
+ )
47
+
48
+ puts "Authorizing #{account} — a browser window should have opened."
49
+ puts
50
+ puts "If it did not, open this manually:"
51
+ puts " #{url}"
52
+ puts
53
+ puts 'Waiting for the callback…'
54
+
55
+ case (outcome = result.pop(timeout: TIMEOUT))
56
+ when nil then abort "Timed out after #{TIMEOUT}s with no callback. Nothing was stored."
57
+ when Exception then abort "Authorization failed: #{outcome.class}: #{outcome.message}"
58
+ end
59
+
60
+ # Prove the stored token actually works rather than trusting the callback.
61
+ begin
62
+ GMCP::Auth.access_token(account: account)
63
+ rescue StandardError => e
64
+ abort "Callback completed but the stored token does not work: #{e.class}: #{e.message}"
65
+ end
66
+
67
+ puts "Authorized #{account}."
68
+ puts "Token stored at #{GMCP::Auth.token_path(account)}"