mailmate 2.2.0 → 2.3.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 34b3eb13fdd2c2a9ec690ec623a543c074014dc1e6b3f82aa3abe6e6cb8de2c7
4
- data.tar.gz: 11417aa45bfa1980f946b6838ca4451c79e6fb2244976c5879253c37b96cbb72
3
+ metadata.gz: 3c815c1297c45d238f61e5347b0364313ffd11756c2077ddeea3bf849a5e77aa
4
+ data.tar.gz: 203c5079d6e02159c034d70dd38dc9ea47fbd7428f02eef83f653dd6ae678d5c
5
5
  SHA512:
6
- metadata.gz: d724662f4b0084dbbe7bb712f4678976b30654d26fa67479d038d203034c951a95d90b08c5e7266c7461103299ddb9c6dab03cd8ff3c83d09c7d2a6a9e0c7321
7
- data.tar.gz: 1a56382a2a6792e0a0df2fc5e83ad26c51158238720c21bc9f7d222b3047dc013eb473dbee623ad0b23f6c53075489603b37d41f789f3019551bda0532443213
6
+ metadata.gz: 3dd3ae18a5b4986885a497617b4aa4a4a6d3151277231a5717115edce495c7d0b61020215ddc436f51ba66e57ae7252f623bc5279750680e3b033e444e4948d7
7
+ data.tar.gz: d86e703f660e7a0058ef76d2942a7bf933e3ef5e96141e650de12091f836ac31dd5ac81586460df5b1f98e3a5f08d35d7674cb5c2a85fa1c47b39e17b170871b
data/README.md CHANGED
@@ -152,6 +152,8 @@ Or add manually to `~/.claude.json` under `"mcpServers"`:
152
152
 
153
153
  For Claude Desktop, use the same command path in `claude_desktop_config.json` as shown under the one-line installer. Restart Claude Desktop after any change to server code or config.
154
154
 
155
+ Every tool answers in its text content. `search` takes a `format` argument (`csv`, the default, or `json` or `yaml`, the same as `mmsearch --format`). A JSON answer, from `search` with `format: "json"` or from `resolve_id`, is also returned as `structuredContent`, and it is the same object. Nothing else carries `structuredContent`, because clients such as Claude Code and Claude Desktop show it *instead of* the text whenever it is present. The rule and its tests are described in [docs/MCP results.md](<docs/MCP results.md>).
156
+
155
157
  ## Example usage
156
158
 
157
159
  ### `mmsearch` — find messages
@@ -195,13 +197,15 @@ mmsearch 'f acme' --limit 10 --sort from
195
197
  | `<header>:<term>` | Any indexed header contains (`delivered-to:joe`). A header this store has never seen is a usage error, not an empty result. |
196
198
  | `!<value>` | Negate, e.g. `f !smith` = From does NOT contain smith; works on dates too (`d !3d` = more than 3 days ago). |
197
199
 
198
- Dates match on the **display-zone day** — the same day the `date`/`time` output columns show. An impossible date term or combination (`d 2026-02-31`, `d >2026 d <2025`) is a usage error, not a silent empty result. Familiar foreign `key:value` tokens (`from:bob`, `date:today`, `after:2026-08-01`, `older_than:2w`) are auto-translated to quicksearch with each rewrite announced on stderr; unrecognized keys (`is:unread`) are searched as literal text, and an empty result says so.
200
+ Dates match on the **display-zone day** — the same day the `date`/`time` output columns show. An impossible date term or combination (`d 2026-02-31`, `d >2026 d <2025`) is a usage error, not a silent empty result. Familiar foreign `key:value` tokens (`from:bob`, `date:today`, `after:2026-08-01`, `older_than:2w`) are auto-translated to quicksearch with each rewrite announced on stderr; unrecognized keys (`filename:pdf`) are searched as literal text, and an empty result says so.
199
201
 
200
202
  The `--mailbox` argument accepts an account, an `account/path`, a bare mailbox name matched across accounts, or a **smart-mailbox name** (e.g. `Newsletters`, `Receipts`, `Priority`) whose filter is ANDed into the search.
201
203
 
202
204
  **Output fields.** Default columns are `flags date time direction party subject`. Prefix a field list with `+` to add to the defaults; a bare list replaces them (include `id` yourself if you want it).
203
205
 
204
- **Limiting and ordering.** `--limit N` returns the N *newest* matches, chosen after the full scan; `--limit-by KEY[:asc|desc]` changes which rows survive (`date:asc` = the N oldest). `--sort KEY[:asc|desc]` orders the emitted rows independently, so `--limit 10 --sort from` is the ten newest shown by sender. Bare `--sort asc|desc|none` still means date; a bare key reads the way the key does (date/time newest-first, text A→Z); ties break newest-first. A truncated result says so on stderr (`[limit] showing 200 of 319 matches …`) so stdout stays clean CSV. `--scan-limit N` is a different thing: it stops the *scan* after N matches in undefined order — a speed bound for slow `--all` body scans, never a way to pick rows. (Before 2.0, `--limit` had those scan-cap semantics: N arbitrary matches, however sorted.) `--offset N` skips the first N rows of that ordering before taking `--limit` — rows 1001–1200 newest-first is `--offset 1000 --limit 200`; offsets drift as mail arrives, so a date term (`d <2026-08-25`) is the stable way to page a live mailbox. `--stats` replaces the prose notices with one machine-readable line, first on stderr — `stats: {"schema":1,"matches":321,"returned":3,"scan_capped":false,…}` — whose keys are additive-only; scripts and the MCP server read that instead of parsing prose.
206
+ **Limiting and ordering.** `--limit N` returns the N *newest* matches, chosen after the full scan; `--limit-by KEY[:asc|desc]` changes which rows survive (`date:asc` = the N oldest). `--sort KEY[:asc|desc]` orders the emitted rows independently, so `--limit 10 --sort from` is the ten newest shown by sender. Bare `--sort asc|desc|none` still means date; a bare key reads the way the key does (date/time newest-first, text A→Z); ties break newest-first. A truncated result says so on stderr (`[limit] showing 200 of 319 matches …`) so stdout stays clean CSV. `--scan-limit N` is a different thing: it stops the *scan* after N matches in undefined order — a speed bound for slow `--all` body scans, never a way to pick rows. (Before 2.0, `--limit` had those scan-cap semantics: N arbitrary matches, however sorted.) `--offset N` skips the first N rows of that ordering before taking `--limit` — rows 1001–1200 newest-first is `--offset 1000 --limit 200`; offsets drift as mail arrives, so a date term (`d <2026-08-25`) is the stable way to page a live mailbox. `--stats` replaces the prose notices with one machine-readable line, first on stderr — `stats: {"schema":1,"matches":321,"returned":3,"scan_capped":false,…}` — whose keys are additive-only; scripts read that instead of parsing prose, and the MCP server's CSV search asks for it so the model sees the true match total.
207
+
208
+ **Structured output.** `--format json` or `--format yaml` writes one document on stdout in place of the CSV: `{schema, stats, fields, rows, notices}`, where `stats` is the `--stats` object, `rows` holds one object per message keyed by field name (`{"id": "183715", "subject": "…"}`), and `notices` holds every message a `--stats` CSV run would have printed on stderr after the stats line, such as query translations and zero-result hints. Truncation is reported in `stats` (`matches` against `returned`), not as a notice. On success nothing goes to stderr, so the document alone is the whole answer. JSON and YAML are the same object in two spellings. A failed run writes no document and explains on stderr, as the CSV run does. `--format csv` is the default.
205
209
 
206
210
  | Field | What it shows |
207
211
  |---|---|
@@ -237,9 +241,13 @@ mmmessage 183715 --mailmate
237
241
 
238
242
  # Render an HTML-only message as clean markdown (no-op for text/plain bodies)
239
243
  mmmessage 183715 --markdown
244
+
245
+ # Every identifier as JSON: eml_id, message_id, message_url (portable),
246
+ # mid_url (drives MailMate locally), path, mailbox
247
+ mmmessage 183715 --resolve
240
248
  ```
241
249
 
242
- `--markdown` uses `reverse_markdown` + Nokogiri preprocessing to drop `<style>`/`<script>` blocks and strip newsletter preview-text padding (zero-width chars, runs of non-breaking / figure / narrow spaces, etc.). Conversion quality is good for plain replies/threads and rough for marketing-newsletter HTML (which uses nested layout tables); the raw source is still available with `--raw`.
250
+ `--markdown` uses `reverse_markdown` + Nokogiri preprocessing (`Mailmate::HtmlMarkdown`, shared with the quoted original of a reply/forward): it drops `<head>`/`<style>`/`<script>`/comments, hidden (`display:none`) elements and tracking pixels, strips newsletter preview-text padding (zero-width chars, non-breaking spaces), and — the part that makes transactional mail readable — unwraps nested *layout* tables into flowing text while keeping real data tables (a regular grid of short cells) as markdown tables. The raw source is still available with `--raw`.
243
251
 
244
252
  ### `mmopen` — open a message in MailMate's UI
245
253
 
@@ -364,10 +372,12 @@ mm-send -t friend@example.com -c cc@example.com -s "Status update" --send-now <<
364
372
  - on to the next
365
373
  EOF
366
374
 
367
- # Attach files (positional args after options)
368
- mm-send -t friend@example.com -s "Photos" /path/to/photo1.jpg /path/to/photo2.jpg <<<"See attached."
375
+ # Attach files: list them FIRST (see below)
376
+ mm-send /path/to/photo1.jpg /path/to/photo2.jpg -t friend@example.com -s "Photos" <<<"See attached."
369
377
  ```
370
378
 
379
+ **Attachments go first.** emate's `-f`/`-t`/`-c`/`-b`/`-s`/`--header` each take any number of values, so a file path right after one of them is read as another recipient or subject. The attachment is then dropped without an error. Put attachment paths before every flag, or right after a flag that takes no value such as `--send-now`. mm-send appends its own `--markup markdown` last for the same reason (fixed in 2.2.2; earlier versions put it first, which swallowed a leading attachment and turned off markdown rendering).
380
+
371
381
  #### Replies, forwards, and threading
372
382
 
373
383
  **A `Re:` subject does not thread.** Modern clients thread on headers, so a reply without `In-Reply-To` / `References` shows up in the recipient's client as a brand-new conversation — and nothing in your own view reveals it. MailMate generates the outgoing `Message-ID` itself; that part is never your job.
@@ -0,0 +1,68 @@
1
+ # MCP results
2
+
3
+ **This is the canonical description of what `mailmate-mcp` tool results look like.** The MCP code (`attach_structured_content!` in `lib/mailmate/mcp.rb`), the README, and the tool descriptions point here rather than restating it.
4
+
5
+ ## The rule
6
+
7
+ 1. **The text is always the complete answer**, in the format the caller asked for.
8
+ 2. **`structuredContent` is sent only when that answer is JSON**, and it is the same object as the text parsed as JSON. Today that is `search` with `format: "json"`, and `resolve_id`.
9
+ 3. **Errors never carry `structuredContent`.**
10
+ 4. **No tool declares an `outputSchema`.** Declaring one obliges the server to send `structuredContent` on every result of that tool, which a CSV search deliberately does not.
11
+
12
+ The caller chooses the format with an argument, such as `search`'s `format: csv | json | yaml`. That argument means the same thing as the matching CLI flag (`mmsearch --format`). The server never looks at which client is calling.
13
+
14
+ ## Why
15
+
16
+ An MCP result can carry two copies of its answer, the `content` text and `structuredContent`. **Clients pick one of the two to show, and the server cannot control which.** Measured on 2026-11-28 against Claude Code 2.1.330, using a test server that put different markers in each:
17
+
18
+ | The tool returned | The model received |
19
+ |---|---|
20
+ | Text only | The text |
21
+ | Text and `structuredContent` | Only `structuredContent`, serialized to JSON |
22
+ | `structuredContent` only | `structuredContent`, serialized to JSON |
23
+ | Both, with an `outputSchema` declared | Only `structuredContent` |
24
+ | Both, with `isError: true` | Only the text |
25
+
26
+ Claude Desktop behaves the same way according to the report in brianmd/mailmate#2. Other clients may show only the text. A server that puts different information in the two copies is therefore wrong for some client, whichever way it splits them.
27
+
28
+ That is what happened from 2.1.0 to 2.2.2. A CSV `search` also sent `structuredContent: {stats: …}`, so Claude Code and Claude Desktop showed the match count and none of the rows, and lost the query-translation notice too.
29
+
30
+ **Why not choose by client?** Each client names itself in `initialize` (`clientInfo`), but its behavior changes between versions without notice, and the protocol leaves the choice to the client. A table of client quirks would quietly go stale. Making both copies complete works for every client.
31
+
32
+ **Why not a flag for "structured or text"?** The model making the call cannot choose which copy its client shows, so such a flag would really select an envelope the client may ignore. The thing the caller does choose is the format of the data, and the rule above derives the envelope from it.
33
+
34
+ ## How it is tested
35
+
36
+ - `test/test_mcp_protocol.rb` starts the real `exe/mailmate-mcp` against a throwaway mail store, speaks JSON-RPC to it, and checks the result of every read-side tool except `verify` against the rule. Run against 2.2.2 it fails on the CSV search.
37
+ - `test/test_mcp_contract.rb` checks, for every tool and every input property, that the property changes what reaches the CLI, that the CLI's own parser accepts the arguments built (including a value that starts with a dash), and that arguments the schema does not allow are rejected. `send` and `draft` pass most flags through to MailMate's `emate`, so for those two the check is our own flag parsing plus a list of the `emate` flags the tools may use. Because every tool runs its CLI in-process, the CLI tests then cover the behavior behind each tool.
38
+ - `test/test_mcp.rb` holds the specific mappings, such as which `search` format sends `structuredContent`.
39
+
40
+ ## Arguments are checked against the schema
41
+
42
+ Every call is checked against the tool's own `inputSchema` before anything runs (`argument_problems` in `lib/mailmate/mcp.rb`). An unknown argument, a missing required one, a value of the wrong type, or a value outside an `enum` is rejected with a result marked `isError` that lists every problem, suggests the nearest valid name for a misspelling, and lists the valid arguments. It is a tool error and not a protocol error, so the model sees the message and can correct the call, as 2025-11-25 asks.
43
+
44
+ Before 2.3.0 the handlers read the keys they knew and ignored the rest. A misspelled `limt: 5` ran an unlimited search, `headers_only: "false"` turned the flag on because a non-empty string is truthy, and `limit: "ten"` became `--limit 0`, each without a word.
45
+
46
+ Two leniencies are deliberate, and both are lossless. `null` means "not given", for every argument. An integer is accepted where a string is expected, because ids are typed as strings and often arrive as integers.
47
+
48
+ ## Values are never read as options
49
+
50
+ Each tool turns its arguments into a command line for the matching CLI, and two rules keep a value from being mistaken for an option.
51
+
52
+ **Queries, ids and action words follow a `--`.** That marker ends option parsing, so a value that starts with a dash stays a value. Before 2.3.0 the documented negation `-is:unread` failed as an invalid option, a query of `-a` silently became `--all`, and a Message-ID that starts with a dash could not be read. A search given `fields` but no `query` also sent an empty query, which searched all mail, where the default is today's.
53
+
54
+ **`send` and `draft` refuse option-shaped values.** Their arguments end up on the command line of MailMate's `emate`, which reads any option-shaped token as an option wherever it sits. A `from`, `to`, `cc`, `bcc` or `subject` that starts with a dash followed by a letter is refused, an attachment must be an absolute path, and only one of `reply_to`, `reply_all_to` and `forward` may be given. Before 2.3.0 an attachment of `--send-now=true` passed straight through, and `mm-draft` refused only the exact token `--send-now`. `mm-draft` now refuses both spellings, on every token. Whether `emate` honors the `=true` spelling was not tested, since the test would send mail.
55
+
56
+ ## Results are always valid UTF-8
57
+
58
+ A JSON string must be valid UTF-8, and mail is not always. `message` with `raw: true` returns the file's bytes, and some messages carry stray Latin-1 bytes. Tool output is converted before it is sent: valid UTF-8 passes through unchanged and any other byte becomes U+FFFD, the replacement character. Before 2.3.0 such a result could not be serialized. For exact bytes, read the file at the `path` that `resolve_id` returns.
59
+
60
+ ## Protocol versions
61
+
62
+ `initialize` echoes the client's requested version when the server supports it. That is the 2025-11-25 lifecycle rule. The supported list is `SUPPORTED_PROTOCOL_VERSIONS` in `lib/mailmate/mcp.rb`: 2025-11-25, 2025-06-18 and 2024-11-05. The server behaves the same under all three. The newer fields it sends, `structuredContent` and tool `title` from 2025-06-18 and tool annotations from 2025-03-26, are extra fields that an older client ignores. Before 2.3.0 the server answered 2024-11-05 to every client while already sending those fields.
63
+
64
+ For any other request the server offers the newest version it supports that is not newer than the request, and its newest of all when there is none. 2025-03-26 is left off the list on purpose: it is the one revision that obliges a server to accept JSON-RPC batches, which this server rejects. A client asking for it is offered 2024-11-05, which a client of that age also speaks.
65
+
66
+ Two 2025-11-25 rules apply directly. An unknown tool is a JSON-RPC error (`-32602`), while a tool that ran and failed is a result with `isError`. And JSON-RPC batches, which exist only in 2025-03-26, get an `Invalid Request` error (`-32600`). Before 2.3.0 a batch, or any line that was not a JSON object, crashed the server. A message without an `id` is a notification, so it is never answered and never runs a tool.
67
+
68
+ The 2026-07-28 revision is not supported. It drops the `initialize` handshake: each request carries its own version, servers must implement `server/discover`, and every result carries `resultType`. Clients still open with `initialize` (Claude Code 2.1.330 requests 2025-11-25), and that revision allows a server to support both styles, so adding it can wait until clients start using it.
@@ -25,7 +25,11 @@ module Mailmate
25
25
  # Returns the exit status. Refuses `--send-now` (exit 2); otherwise
26
26
  # delegates verbatim to `Mailmate::CLI::Send`.
27
27
  def run(argv)
28
- if argv.include?("--send-now")
28
+ # emate (CLI11) also takes the `--send-now=VALUE` spelling, and reads
29
+ # an option-shaped token as an option wherever it sits, so the check
30
+ # is on every token and on both spellings. An exact-string match
31
+ # here let `--send-now=true` through.
32
+ if argv.any? { |arg| arg.to_s.match?(/\A--send-now(\z|=)/) }
29
33
  warn "mm-draft: refusing --send-now — mm-draft only ever creates drafts. Use mm-send to send."
30
34
  return 2
31
35
  end
@@ -1,6 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "optparse"
4
+ require "json"
5
+ require "mailmate/eml_lookup"
6
+ require "mailmate/header_reader"
7
+ require "mailmate/mid_url"
4
8
  # `mail` is required lazily inside run() — the --raw and --mailmate paths
5
9
  # never parse the message, so they shouldn't pay ~50 ms loading the gem.
6
10
 
@@ -35,6 +39,8 @@ module Mailmate
35
39
  return 1
36
40
  end
37
41
 
42
+ return print_identifiers(eml_id, path) if opts[:resolve]
43
+
38
44
  if opts[:mailmate]
39
45
  require_relative "open"
40
46
  # Hand off to mmopen — same id resolution already done, but Open re-resolves
@@ -56,9 +62,9 @@ module Mailmate
56
62
  end
57
63
 
58
64
  def parse_options(argv)
59
- opts = { raw: false, text_only: false, mailmate: false, markdown: false }
65
+ opts = { raw: false, text_only: false, mailmate: false, markdown: false, resolve: false }
60
66
  OptionParser.new do |o|
61
- o.banner = "Usage: mmmessage <id> [--raw|--text-only|--mailmate|--markdown]"
67
+ o.banner = "Usage: mmmessage <id> [--raw|--text-only|--mailmate|--markdown|--resolve]"
62
68
  o.separator ""
63
69
  o.separator "<id> can be a local eml-id (e.g. 183715), an RFC Message-ID"
64
70
  o.separator "(with or without angle brackets, e.g. <abc@example.com>), or"
@@ -68,23 +74,37 @@ module Mailmate
68
74
  o.on("--text-only", "Output decoded body only (no headers block)") { opts[:text_only] = true }
69
75
  o.on("--mailmate", "Open in MailMate's UI instead of printing (alias for `mmopen <id>`)") { opts[:mailmate] = true }
70
76
  o.on("--markdown", "Render HTML body as clean markdown (no-op for plain-text messages)") { opts[:markdown] = true }
77
+ o.on("--resolve", "Print the message's identifiers as JSON instead: eml_id, message_id, message_url (portable), mid_url (drives MailMate locally), path, mailbox") { opts[:resolve] = true }
71
78
  end.parse!(argv)
72
79
  opts
73
80
  end
74
81
 
82
+ # `--resolve`: every identifier for one message, as one JSON object.
83
+ # The MCP `resolve_id` tool is this, verbatim.
84
+ def print_identifiers(eml_id, path)
85
+ message_id = Mailmate::HeaderReader.message_id(path)
86
+ $stdout.puts JSON.pretty_generate(
87
+ eml_id: eml_id,
88
+ message_id: message_id,
89
+ message_url: message_id ? Mailmate::MidUrl.message_url_for(message_id) : nil,
90
+ mid_url: message_id ? Mailmate::MidUrl.for(message_id) : nil,
91
+ path: path,
92
+ mailbox: Mailmate::EmlLookup.mailbox_for(path),
93
+ )
94
+ 0
95
+ end
96
+
75
97
  def usage_error(msg)
76
98
  warn "mmmessage: #{msg}"
77
- warn "Usage: mmmessage <id> [--raw|--text-only|--mailmate|--markdown]"
99
+ warn "Usage: mmmessage <id> [--raw|--text-only|--mailmate|--markdown|--resolve]"
78
100
  warn " <id> is either an eml-id (digits) or an RFC Message-ID."
79
101
  2
80
102
  end
81
103
 
82
104
  def print_headers(mail, eml_id, path)
83
- imap_root = Mailmate.config.imap_root
84
- mailbox = path.sub("#{imap_root}/", "").sub(%r{/Messages/[^/]+\.eml\z}, "")
85
105
  $stdout.puts "eml-id: #{eml_id}"
86
106
  $stdout.puts "path: #{path}"
87
- $stdout.puts "mailbox: #{mailbox}"
107
+ $stdout.puts "mailbox: #{Mailmate::EmlLookup.mailbox_for(path)}"
88
108
  $stdout.puts "from: #{Array(mail.from).join(", ")}" if mail.from
89
109
  $stdout.puts "to: #{Array(mail.to).join(", ")}" if mail.to
90
110
  $stdout.puts "cc: #{Array(mail.cc).join(", ")}" if mail.cc
@@ -5,6 +5,7 @@ require "optparse"
5
5
  require "date"
6
6
  require "csv"
7
7
  require "json"
8
+ require "yaml"
8
9
  require "stringio"
9
10
 
10
11
  module Mailmate
@@ -89,7 +90,7 @@ module Mailmate
89
90
  mailbox: "all", limit: nil, offset: 0, scan_limit: nil, limit_by: DEFAULT_LIMIT_BY,
90
91
  headers_only: false, all: false,
91
92
  exclude_quoted: false,
92
- header: true, align: true, sort: DEFAULT_SORT, stats: false,
93
+ header: true, align: true, sort: DEFAULT_SORT, stats: false, format: "csv",
93
94
  }
94
95
 
95
96
  parser = build_parser(opts)
@@ -100,6 +101,7 @@ module Mailmate
100
101
  return 2
101
102
  end
102
103
 
104
+ return run_document(argv, opts) unless opts[:format] == "csv"
103
105
  return search(argv, opts) unless opts[:stats]
104
106
 
105
107
  # --stats promises one machine-readable line FIRST on stderr, but
@@ -120,6 +122,81 @@ module Mailmate
120
122
  end
121
123
  end
122
124
 
125
+ # `--format json|yaml`: ONE document on stdout carrying everything the
126
+ # CSV run says across both streams: the stats object, the field list,
127
+ # the rows (one object per row, keyed by field name), and every notice
128
+ # the run would have written to stderr (translation, dead-branch and
129
+ # zero-result hints), one string per notice. Nothing is left on stderr
130
+ # on success, because a consumer reading only the document (an MCP
131
+ # client that shows only structuredContent, say) must not lose a
132
+ # notice. JSON and YAML are two spellings of the same object; the
133
+ # stats are the `--stats` object, so `--stats` adds nothing here. A
134
+ # failed run (usage error, unknown field, no mailbox) writes no
135
+ # document and says why on stderr, exactly as the CSV run does.
136
+ FORMATS = %w[csv json yaml].freeze
137
+ DOCUMENT_SCHEMA = 1
138
+
139
+ # Records each write separately, so one `warn` stays one notice even
140
+ # when it spans lines.
141
+ class NoticeCollector < StringIO
142
+ attr_reader :notices
143
+
144
+ def initialize
145
+ super
146
+ @notices = []
147
+ end
148
+
149
+ def write(*parts)
150
+ @notices << parts.join.chomp
151
+ super
152
+ end
153
+ end
154
+
155
+ def run_document(argv, opts)
156
+ opts[:stats] = true # fills stats_result; suppresses the [limit] prose it replaces
157
+ opts[:document] = {} # emit_output stores fields + rows here instead of printing
158
+ collector = NoticeCollector.new
159
+ real_err = $stderr
160
+ $stderr = collector
161
+ code =
162
+ begin
163
+ search(argv, opts)
164
+ ensure
165
+ $stderr = real_err
166
+ end
167
+ unless code.zero? && opts[:stats_result]
168
+ $stderr.print collector.string
169
+ return code
170
+ end
171
+
172
+ fields = opts[:document][:fields]
173
+ doc = {
174
+ schema: DOCUMENT_SCHEMA,
175
+ stats: opts[:stats_result],
176
+ fields: fields,
177
+ rows: opts[:document][:rows].map { |cells| fields.zip(cells.map { document_text(_1) }).to_h },
178
+ notices: collector.notices,
179
+ }
180
+ # One object, two spellings: round-trip through JSON so YAML sees
181
+ # plain string keys and the two can never disagree on content.
182
+ plain = JSON.parse(JSON.generate(doc))
183
+ $stdout.puts(opts[:format] == "yaml" ? YAML.dump(plain) : JSON.generate(plain))
184
+ 0
185
+ end
186
+
187
+ # A cell as it goes into the document. JSON strings must be valid
188
+ # UTF-8, and a cell can arrive tagged binary or carrying a stray
189
+ # Latin-1 byte from a header or an IMAP keyword. Valid UTF-8 passes
190
+ # through untouched; any other byte becomes U+FFFD, so one odd
191
+ # message cannot cost the caller the whole document.
192
+ def document_text(cell)
193
+ return cell unless cell.is_a?(String)
194
+ return cell if cell.encoding == Encoding::UTF_8 && cell.valid_encoding?
195
+
196
+ text = cell.dup.force_encoding(Encoding::UTF_8)
197
+ text.valid_encoding? ? text : text.scrub("�")
198
+ end
199
+
123
200
  # The `--stats` contract: this prefix, then one JSON object, on the
124
201
  # first stderr line. `matches`, `returned` and `scan_capped` are always
125
202
  # present; keys are additive-only, and `schema` increments only on a
@@ -140,7 +217,9 @@ module Mailmate
140
217
  if (notice = Mailmate::SearchSyntax.translation_notice(translations))
141
218
  warn notice
142
219
  end
143
- fields_arg = (opts[:fields] || argv[1] || DEFAULT_FIELDS).to_s.strip
220
+ # A blank fields list means "not given": zero columns is never what
221
+ # anyone asked for, and it printed one empty line per message.
222
+ fields_arg = [opts[:fields], argv[1]].map { _1.to_s.strip }.find { !_1.empty? } || DEFAULT_FIELDS
144
223
  # `+...` means "defaults plus these"; bare list = exactly those columns.
145
224
  # Defaults already include `id` as the first column, so `+x` keeps id
146
225
  # automatic while a bare list lets callers omit it (useful for
@@ -277,6 +356,7 @@ module Mailmate
277
356
  # for existing invocations), `none` (sort only), `KEY`, or `KEY:DIR`.
278
357
  def parse_order(value, allow_none: false)
279
358
  v = value.to_s.strip
359
+ raise OptionParser::InvalidArgument, "an empty value (give a field, asc or desc)" if v.empty?
280
360
  return :none if v == "none" && allow_none
281
361
  return { key: "date", dir: v.to_sym } if %w[asc desc].include?(v)
282
362
  key, dir = v.split(":", 2)
@@ -358,7 +438,8 @@ module Mailmate
358
438
  OptionParser.new do |o|
359
439
  o.banner = "Usage: mmsearch [search-string] [fields] [options]"
360
440
  o.separator ""
361
- o.separator "Search MailMate's `.eml` files. Output is CSV with column-aligned padding."
441
+ o.separator "Search MailMate's `.eml` files. Output is CSV with column-aligned padding,"
442
+ o.separator "or one JSON/YAML document with --format."
362
443
  o.separator ""
363
444
  o.separator "POSITIONAL ARGS"
364
445
  o.separator " search-string Quicksearch expression. Default: 'd 1d'. Pass '' to disable."
@@ -371,7 +452,10 @@ module Mailmate
371
452
  o.on("--mailbox X", "Mailbox to search (default: all)") { |v| opts[:mailbox] = v }
372
453
  o.on("--fields F", "Fields list (alt to 2nd positional)") { |v| opts[:fields] = v }
373
454
  o.on("--limit N", Integer,
374
- "Return at most N rows: the top N by --limit-by (default: the N newest), taken after the full scan. Announces truncation on stderr.") { |n| opts[:limit] = n }
455
+ "Return at most N rows: the top N by --limit-by (default: the N newest), taken after the full scan. Announces truncation on stderr.") { |n|
456
+ raise OptionParser::InvalidArgument, "#{n}: limit cannot be negative" if n.negative?
457
+ opts[:limit] = n
458
+ }
375
459
  o.on("--limit-by KEY[:DIR]",
376
460
  "Which rows --limit keeps. KEY is any output field; DIR is asc|desc (bare date/time = desc, text keys = asc). Default: date:desc") { |v| opts[:limit_by] = parse_order(v) }
377
461
  o.on("--offset N", Integer,
@@ -380,7 +464,10 @@ module Mailmate
380
464
  opts[:offset] = n
381
465
  }
382
466
  o.on("--scan-limit N", Integer,
383
- "Stop SCANNING after N matches, in undefined order — a speed bound for slow --all body scans, never a way to pick rows. Announces on stderr.") { |n| opts[:scan_limit] = n }
467
+ "Stop SCANNING after N matches, in undefined order — a speed bound for slow --all body scans, never a way to pick rows. Announces on stderr.") { |n|
468
+ raise OptionParser::InvalidArgument, "#{n}: scan-limit must be at least 1" if n < 1
469
+ opts[:scan_limit] = n
470
+ }
384
471
  o.on("--headers-only", "Skip body matching entirely") { opts[:headers_only] = true }
385
472
  o.on("--all", "Include un-indexed messages in body matching by lazily reading and parsing each .eml. Slow (tens of seconds to minutes on large archives). Default behavior matches MailMate's UI: only check messages MailMate has body-indexed — fast, but bounded.") { opts[:all] = true }
386
473
  o.on("--exclude-quoted", "Match body only against #unquoted text — skip MailMate's #quoted index (forwarded/replied-to text). Tightens search to fresh content; gets you closer to MailMate UI's body-search result set, at the cost of missing hits in quoted sections.") { opts[:exclude_quoted] = true }
@@ -390,6 +477,8 @@ module Mailmate
390
477
  "Order of the emitted rows. asc|desc|none alone mean date; or any output field, e.g. from, subject:desc (bare date/time = desc, text keys = asc). Ties break newest-first. Default: date:asc") { |v| opts[:sort] = parse_order(v, allow_none: true) }
391
478
  o.on("--stats",
392
479
  "Write one machine-readable line FIRST on stderr — stats: {\"schema\":1,\"matches\":M,\"returned\":N,\"scan_capped\":false,...} — in place of the [limit]/[scan-limit] prose. Keys are additive-only; other stderr follows it.") { opts[:stats] = true }
480
+ o.on("--format FMT", FORMATS,
481
+ "csv (default) | json | yaml. json/yaml write ONE document on stdout: {schema, stats, fields, rows: [{field: value}], notices: [...]}, i.e. the --stats object, one object per row, and every stderr notice. --no-header, --no-align and --stats don't apply.") { |v| opts[:format] = v }
393
482
  o.on("--european",
394
483
  "Slash dates are day-first: d 9/8/2026 = Aug 9 (default: month-first American)") { opts[:european] = true }
395
484
  o.separator ""
@@ -1415,7 +1504,7 @@ module Mailmate
1415
1504
  case field
1416
1505
  when "id" then eml_id
1417
1506
  when "path" then path
1418
- when "mailbox" then path.sub("#{Mailmate.config.imap_root}/", "").sub(%r{/Messages/[^/]+\.eml\z}, "")
1507
+ when "mailbox" then Mailmate::EmlLookup.mailbox_for(path)
1419
1508
  when "date"
1420
1509
  t = message_time(eml_id, mail)
1421
1510
  Mailmate.localize(t)&.strftime("%Y-%m-%d")
@@ -1550,6 +1639,12 @@ module Mailmate
1550
1639
  end
1551
1640
 
1552
1641
  def emit_output(rows, fields, opts)
1642
+ if opts[:document]
1643
+ opts[:document][:fields] = fields
1644
+ opts[:document][:rows] = rows
1645
+ return
1646
+ end
1647
+
1553
1648
  header_row = fields.map { |f| HEADER_LABELS[f] || f }
1554
1649
 
1555
1650
  if opts[:align]
@@ -30,6 +30,14 @@ module Mailmate
30
30
  explicitly win; fields you omit follow normal reply rules. --header
31
31
  stays available as the escape hatch when the parent isn't indexed.
32
32
 
33
+ Attachments
34
+ Attachments are bare file paths. emate's address, subject and header
35
+ flags take any number of values, so a path right after one of them
36
+ is read as another recipient or subject, silently. List attachments
37
+ FIRST, or after a flag that takes no value such as --send-now.
38
+
39
+ mm-send /path/a.pdf -t friend@x -s "Docs" --send-now <<<"Attached."
40
+
33
41
  Identity selection
34
42
  `-f <address>` picks which of MailMate's configured identities sends.
35
43
  Without `-f`, MailMate uses its default identity. See `mmdiscover` to
@@ -81,7 +89,7 @@ module Mailmate
81
89
  # interactive `mm-send --help` waiting for Ctrl-D.
82
90
  body = help ? "" : $stdin.read.to_s
83
91
  body = append_quote(body, derived) if derived
84
- out, err, status = Open3.capture3(EMATE_PATH, "mailto", "--markup", "markdown", *argv, stdin_data: body)
92
+ out, err, status = Open3.capture3(EMATE_PATH, "mailto", *emate_args(argv), stdin_data: body)
85
93
  $stdout.write(out)
86
94
  $stderr.write(err)
87
95
  # exitstatus is nil for a signal-killed child; the exe shims do
@@ -89,6 +97,20 @@ module Mailmate
89
97
  status.exitstatus || 1
90
98
  end
91
99
 
100
+ # The enforced `--markup markdown` goes LAST. emate parses with CLI11,
101
+ # where -f/-t/-c/-b/-r/-s/-m/--header each take any number of values:
102
+ # every bare word after one of them is read as another value until the
103
+ # next flag. Prepended, `--markup markdown photo.jpg -t …` read the
104
+ # photo as a second markup value, which dropped the attachment AND the
105
+ # markdown rendering while emate still exited 0 (2026-10-13: tenant
106
+ # mail from markdownr's compose popup, which lists attachments first).
107
+ # Last, nothing follows it to swallow. A caller's `--` ends option
108
+ # parsing, so the flag goes in front of that instead.
109
+ def emate_args(argv)
110
+ at = argv.index("--") || argv.length
111
+ argv.dup.insert(at, "--markup", "markdown")
112
+ end
113
+
92
114
  # Flags this wrapper consumes itself. Everything else in argv is emate's
93
115
  # and passes through untouched — that pass-through is the design, so the
94
116
  # scan below is deliberately literal rather than an OptionParser (which
@@ -47,8 +47,15 @@ module Mailmate
47
47
 
48
48
  # Derived paths. Each follows from app_support_dir; if a user has a
49
49
  # non-default MailMate install, overriding app_support_dir flows through.
50
+ # MailMate stores mail under `Messages.noindex/` on most installs, but some
51
+ # long-lived installs still use the older `Messages/` folder name. Prefer
52
+ # `Messages.noindex` (also the answer when neither exists yet), and fall
53
+ # back to `Messages` only when that is the one actually on disk.
50
54
  def imap_root
51
- File.join(app_support_dir, "Messages.noindex", "IMAP")
55
+ noindex = File.join(app_support_dir, "Messages.noindex", "IMAP")
56
+ legacy = File.join(app_support_dir, "Messages", "IMAP")
57
+ return legacy if !File.directory?(noindex) && File.directory?(legacy)
58
+ noindex
52
59
  end
53
60
 
54
61
  def db_headers
@@ -24,6 +24,14 @@ module Mailmate
24
24
  via_index(eml_id) || via_glob(eml_id)
25
25
  end
26
26
 
27
+ # The account/mailbox path a message lives in, e.g.
28
+ # "acct/INBOX.mailbox": the path below the IMAP root, minus the
29
+ # trailing "/Messages/<id>.eml". The one derivation behind mmsearch's
30
+ # `mailbox` column, mmmessage's header block and `mmmessage --resolve`.
31
+ def self.mailbox_for(path)
32
+ path.sub("#{Mailmate.config.imap_root}/", "").sub(%r{/Messages/[^/]+\.eml\z}, "")
33
+ end
34
+
27
35
  # Reverse-lookup: given an RFC Message-ID (with or without angle brackets),
28
36
  # return the local eml-id (integer) or nil. Backed by a value→id map built
29
37
  # once per index snapshot (one O(n) pass, then O(1) lookups) — the map is
@@ -4,7 +4,7 @@ module Mailmate
4
4
  # @api public
5
5
  #
6
6
  # HTML → clean markdown, shared by `mmmessage --markdown` (terminal reading)
7
- # and ReplyPrefill (quoting an HTML-only parent in a forward or reply).
7
+ # and ReplyPrefill (quoting an HTML parent in a forward or reply).
8
8
  #
9
9
  # Depends on reverse_markdown (which pulls nokogiri), an OPTIONAL dependency
10
10
  # so the base install stays free of native extensions. `available?` says
@@ -12,16 +12,33 @@ module Mailmate
12
12
  # each caller decides what an honest fallback looks like for its surface —
13
13
  # mmmessage prints the raw HTML with a hint, a prefill uses a placeholder.
14
14
  #
15
- # Three passes beyond plain reverse_markdown, all learned from newsletters:
16
- # 1. Drop <style> / <script> blocks and HTML comments before conversion —
17
- # pure clutter that reverse_markdown otherwise dumps as inline text.
18
- # 2. Strip zero-width spacers used to control inbox preview text (U+034F,
19
- # U+200B/C/D, U+FEFF) and turn non-breaking spaces into plain ones, or
20
- # the output carries long runs of `͏ `.
21
- # 3. Trim trailing whitespace per line and collapse 3+ blank lines to one.
15
+ # reverse_markdown alone is fine for hand-written HTML and hopeless for
16
+ # transactional/marketing mail, which is built from nested LAYOUT tables:
17
+ # every wrapper becomes a pipe-table fragment (`| |`, `| &nbsp; |`) and the
18
+ # message reads as noise (RubyGems' push notice, 2026-09-04). So the DOM is
19
+ # cleaned before conversion:
20
+ # 1. Drop <head>, <style>, <script> and HTML comments (MSO conditionals,
21
+ # template markers like `<!-- tdMobZ1BottomNew-->`).
22
+ # 2. Drop elements hidden inline (`display:none` — preheaders, mobile-only
23
+ # duplicates) and tracking/spacer images (declared ≤ 2px).
24
+ # 3. Unwrap LAYOUT tables into flowing blocks (rows → div, cells → span),
25
+ # keeping DATA tables (a regular grid of short inline cells, ≥ 2 rows ×
26
+ # ≥ 2 columns, no nested tables) as markdown tables. Innermost first.
27
+ # 4. Normalize the text itself: zero-width spacers used for inbox preview
28
+ # padding (U+034F, U+200B/C/D, U+FEFF) removed, non-breaking spaces
29
+ # made ordinary — in the DOM, so reverse_markdown never sees a U+00A0
30
+ # to spell as `&nbsp;`.
31
+ # 5. Convert with unknown tags BYPASSED (content kept, tag dropped) —
32
+ # reverse_markdown would otherwise print <footer>/<section>/<center>
33
+ # verbatim — then trim trailing whitespace per line and collapse 3+
34
+ # blank lines to one.
22
35
  module HtmlMarkdown
23
36
  extend self
24
37
 
38
+ ZERO_WIDTH = /[͏​‌‍]/
39
+ NBSP_LIKE = /[   -    ]/
40
+ BLOCKISH = "img, div, p, table, ul, ol, h1, h2, h3, h4, h5, h6, br, blockquote, pre"
41
+
25
42
  def available?
26
43
  require "nokogiri"
27
44
  require "reverse_markdown"
@@ -35,20 +52,75 @@ module Mailmate
35
52
  return nil unless available?
36
53
 
37
54
  doc = Nokogiri::HTML(html.to_s)
38
- doc.css("style, script").remove
39
- # Comments too: newsletter templates leave `<!-- tdMobZ1BottomNew-->`
40
- # markers that reverse_markdown would otherwise print verbatim.
41
- doc.xpath("//comment()").remove
42
- md = ReverseMarkdown.convert(doc.to_html)
43
- # U+034F combining grapheme joiner, U+200B ZWSP, U+200C ZWNJ,
44
- # U+200D ZWJ, U+FEFF BOM/ZWNBSP — newsletter preview-text padding.
45
- md.gsub!(/[\u034F\u200B\u200C\u200D\uFEFF]/, "")
46
- # Non-breaking spaces (and their Unicode cousins) → plain spaces so the
47
- # per-line rstrip below can collapse the padding they hold open.
48
- md.gsub!(/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/, " ")
55
+ clean!(doc)
56
+ # unknown_tags: :bypass — reverse_markdown's default PASSES THROUGH tags it
57
+ # doesn't know, and it doesn't know HTML5 sectioning (<footer>, <header>,
58
+ # <section>, <center>…), so a bank alert's footer arrived as raw markup.
59
+ # Bypass keeps the content and drops the tag.
60
+ md = ReverseMarkdown.convert(doc.to_html, unknown_tags: :bypass)
49
61
  md = md.lines.map(&:rstrip).join("\n")
50
62
  md.gsub!(/\n{3,}/, "\n\n")
51
63
  md.strip
52
64
  end
65
+
66
+ # The DOM passes, in order. Public so a caller can inspect the cleaned
67
+ # HTML; `convert` is what everyone actually wants.
68
+ def clean!(doc)
69
+ doc.css("head, style, script").remove
70
+ doc.xpath("//comment()").remove
71
+ doc.css("[style]").each { |n| n.remove if n["style"].to_s.match?(/display\s*:\s*none/i) }
72
+ doc.css("img").each { |img| img.remove if spacer_image?(img) }
73
+ unwrap_layout_tables!(doc)
74
+ doc.xpath("//text()").each do |t|
75
+ s = t.content
76
+ cleaned = s.gsub(ZERO_WIDTH, "").gsub(NBSP_LIKE, " ")
77
+ t.content = cleaned if cleaned != s
78
+ end
79
+ doc
80
+ end
81
+
82
+ private
83
+
84
+ def spacer_image?(img)
85
+ %w[width height].any? do |attr|
86
+ v = img[attr].to_s.strip
87
+ v.match?(/\A\d+(px)?\z/) && v.to_i <= 2
88
+ end
89
+ end
90
+
91
+ # Innermost first, so a data table nested in a layout wrapper is judged
92
+ # on its own shape before the wrapper around it is dissolved.
93
+ def unwrap_layout_tables!(doc)
94
+ tables = doc.css("table").to_a
95
+ tables.sort_by { |t| -t.ancestors("table").size }.each do |t|
96
+ next if data_table?(t)
97
+
98
+ t.css("td, th").each do |c|
99
+ c.name = "span"
100
+ c.add_next_sibling(Nokogiri::XML::Text.new(" ", doc))
101
+ end
102
+ t.css("tr").each { |r| r.name = "div" }
103
+ t.css("thead, tbody, tfoot, caption, colgroup").each { |n| n.name = "div" }
104
+ t.name = "div"
105
+ t.attributes.each_key { |k| t.remove_attribute(k) }
106
+ end
107
+ end
108
+
109
+ # A table we keep as a table: at least two rows with the same cell count
110
+ # (≥ 2), no table inside it, and only short inline content in its cells.
111
+ # Everything else — single-column stacks, image frames, spacer rows,
112
+ # anything nesting another table — is layout.
113
+ def data_table?(table)
114
+ return false if table.at_css("table")
115
+
116
+ rows = table.xpath("./tr|./thead/tr|./tbody/tr|./tfoot/tr")
117
+ return false if rows.size < 2
118
+
119
+ counts = rows.map { |r| r.xpath("./td|./th").size }
120
+ return false unless counts.uniq.size == 1 && counts.first >= 2
121
+
122
+ cells = rows.flat_map { |r| r.xpath("./td|./th").to_a }
123
+ cells.none? { |c| c.at_css(BLOCKISH) || c.text.strip.length > 200 }
124
+ end
53
125
  end
54
126
  end
data/lib/mailmate/mcp.rb CHANGED
@@ -13,24 +13,54 @@ require "mailmate/cli/draft"
13
13
  require "mailmate/cli/open"
14
14
  require "mailmate/cli/mailboxes"
15
15
  require "mailmate/cli/tags"
16
- require "mailmate/eml_lookup"
17
- require "mailmate/header_reader"
18
- require "mailmate/mid_url"
19
16
 
20
17
  module Mailmate
21
18
  # Stdio MCP server (JSON-RPC 2.0, line-delimited). Exposes the gem's CLIs —
22
- # search, message, modify, send, draft — plus a resolve_id helper that round-trips
23
- # between local eml-id, RFC Message-ID, and the cross-machine message:// URL.
19
+ # search, message, modify, verify, send, draft, open, list_mailboxes,
20
+ # list_tags, and resolve_id (`mmmessage --resolve`, which round-trips between
21
+ # local eml-id, RFC Message-ID, and the cross-machine message:// URL).
24
22
  #
25
23
  # In-process: each tool call runs the corresponding `Mailmate::CLI::*.run`
26
24
  # method with a synthesized argv, capturing stdout/stderr from the existing
27
- # CLI rather than re-implementing each command.
25
+ # CLI rather than re-implementing each command. Every tool does; keep it so,
26
+ # because test/test_mcp_contract.rb relies on it. What a result looks like
27
+ # is docs/MCP results.md.
28
28
  module MCP
29
29
  extend self
30
30
 
31
- PROTOCOL_VERSION = "2024-11-05"
31
+ # Protocol revisions this server answers to, newest first. `initialize`
32
+ # echoes the client's requested version when it is listed here (the
33
+ # 2025-11-25 lifecycle rule). The server's behavior is the same under
34
+ # every listed revision: what it uses (structuredContent and tool
35
+ # titles, 2025-06-18; annotations, 2025-03-26) is extra fields an older
36
+ # client ignores. Until 2.3.0 it answered 2024-11-05 to everyone while
37
+ # sending 2025-06-18 fields.
38
+ #
39
+ # 2025-03-26 is deliberately absent: it is the one revision that
40
+ # obliges a server to accept JSON-RPC batches, which this server
41
+ # rejects. A client asking for it is offered 2024-11-05, the newest
42
+ # listed revision that is not newer than its request, which a client
43
+ # of that vintage also speaks.
44
+ #
45
+ # Not listed: 2026-07-28, the stateless revision with no initialize
46
+ # handshake, which needs per-request versions, server/discover and
47
+ # resultType. Clients still open with initialize (Claude Code 2.1.330
48
+ # requests 2025-11-25), so this server stays in the handshake era.
49
+ SUPPORTED_PROTOCOL_VERSIONS = %w[2025-11-25 2025-06-18 2024-11-05].freeze
50
+ PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS.first
32
51
  SERVER_NAME = "mailmate"
33
52
 
53
+ # The requested version when supported. Otherwise the newest supported
54
+ # version that is not newer than the request (version names are dates,
55
+ # so they compare as strings), and the newest of all when the request
56
+ # is not a version-shaped string or predates everything listed.
57
+ def negotiate_protocol_version(requested)
58
+ return requested if SUPPORTED_PROTOCOL_VERSIONS.include?(requested)
59
+ return PROTOCOL_VERSION unless requested.is_a?(String) && requested.match?(/\A\d{4}-\d{2}-\d{2}\z/)
60
+
61
+ SUPPORTED_PROTOCOL_VERSIONS.find { _1 <= requested } || PROTOCOL_VERSION
62
+ end
63
+
34
64
  # Server-level guidance returned from `initialize`. This is the gem's
35
65
  # operational doctrine — the things a caller must know to drive MailMate
36
66
  # correctly that don't fit in a single tool's description. It travels with
@@ -87,15 +117,16 @@ module Mailmate
87
117
  annotations: { title: "Search mail", readOnlyHint: true },
88
118
  description: <<~DESC.strip,
89
119
  Search MailMate's .eml files using MailMate's quicksearch syntax.
90
- Returns column-aligned CSV. Same engine as the `mmsearch` CLI.
120
+ Returns column-aligned CSV by default, or one JSON/YAML document
121
+ with `format`. Same engine as the `mmsearch` CLI.
91
122
 
92
123
  The only native key:value specs are the state forms below
93
124
  (is:unread, has:attachment). Other familiar foreign tokens
94
125
  (`from:bob`, `date:today`, `after:2026-08-01`, `older_than:2w`) are
95
126
  auto-translated to quicksearch, and the rewrite is announced in the
96
127
  result — that announcement means your query was translated, not
97
- that it failed. Unrecognized keys (`in:inbox`, `filename:pdf`) are
98
- searched as literal text and match nothing, silently.
128
+ that it failed. Unrecognized keys (`filename:pdf`, `larger:5M`) are
129
+ searched as literal text; an empty result says so.
99
130
 
100
131
  #{Mailmate::SearchSyntax.reference(indent: " ")}
101
132
 
@@ -127,13 +158,19 @@ module Mailmate
127
158
  type: "string",
128
159
  description: "Account, mailbox path, or smart-mailbox name. Default: all.",
129
160
  },
130
- limit: { type: "integer", description: "Return at most N rows — the top N by limit_by (default: the N newest), taken after the full scan. Truncation is announced on stderr, which is included in the result." },
161
+ limit: { type: "integer", minimum: 0, description: "Return at most N rows — the top N by limit_by (default: the N newest), taken after the full scan. Truncation is announced on stderr, which is included in the result." },
131
162
  limit_by: { type: "string", description: "Which rows limit keeps: KEY[:asc|desc], KEY any output field (bare date/time = desc, text keys = asc). Default: date:desc (the N newest)." },
132
- offset: { type: "integer", description: "Skip the first N rows of the limit_by ordering before taking limit (rows 1001-1200 = offset 1000, limit 200). Offsets drift as mail arrives; a date term in the query (d <2026-08-25) is the stable way to page." },
133
- scan_limit: { type: "integer", description: "Stop SCANNING after N matches, in undefined order — a speed bound for slow body scans, never a way to pick rows. Prefer limit." },
163
+ offset: { type: "integer", minimum: 0, description: "Skip the first N rows of the limit_by ordering before taking limit (rows 1001-1200 = offset 1000, limit 200). Offsets drift as mail arrives; a date term in the query (d <2026-08-25) is the stable way to page." },
164
+ scan_limit: { type: "integer", minimum: 1, description: "Stop SCANNING after N matches, in undefined order — a speed bound for slow body scans, never a way to pick rows. Prefer limit." },
134
165
  headers_only: { type: "boolean", description: "Skip body matching (much faster on text searches)." },
135
166
  sort: { type: "string", description: "Order of the emitted rows: asc|desc|none (by date), or KEY[:asc|desc] for any output field, e.g. from, subject:desc. Ties break newest-first. Default: asc (date)." },
136
167
  european: { type: "boolean", description: "Slash dates in the query are day-first (d 9/8/2026 = Aug 9). Default: month-first American." },
168
+ format: {
169
+ type: "string", enum: Mailmate::CLI::Search::FORMATS,
170
+ description: "csv (default): aligned CSV, then the stats line and any notices after [stderr]. " \
171
+ "json / yaml: one document {schema, stats, fields, rows: [{field: value}], notices: [...]}. " \
172
+ "json also returns that object as structuredContent.",
173
+ },
137
174
  },
138
175
  additionalProperties: false,
139
176
  },
@@ -238,7 +275,7 @@ module Mailmate
238
275
  name: "send",
239
276
  title: "Send mail",
240
277
  annotations: { title: "Send mail", readOnlyHint: false, destructiveHint: true },
241
- description: "Send mail via MailMate's `emate` (markdown body). Recipients and subject via fields; body is the markdown source. For replies, set `in_reply_to` and `references` so recipients' clients thread the message — without them a `Re:` subject alone is not enough. MailMate generates the outgoing Message-ID automatically.",
278
+ description: "Send mail via MailMate's `emate` (markdown body). Recipients and subject via fields; body is the markdown source. For replies, pass `reply_to` (or `reply_all_to`, or `forward`): the threading headers, recipient and subject are derived from the parent. A `Re:` subject alone does not thread. MailMate generates the outgoing Message-ID automatically.",
242
279
  inputSchema: {
243
280
  type: "object",
244
281
  properties: {
@@ -265,7 +302,7 @@ module Mailmate
265
302
  name: "draft",
266
303
  title: "Compose draft",
267
304
  annotations: { title: "Compose draft", readOnlyHint: false, destructiveHint: false },
268
- description: "Compose a draft via MailMate's `emate` (markdown body) — IDENTICAL to `send` but it never sends: the draft opens in MailMate and waits. There is no `send_now` option; use this whenever the instruction is 'write/compose but don't send'. For replies, set `in_reply_to` and `references` so the draft threads correctly. MailMate generates the outgoing Message-ID automatically.",
305
+ description: "Compose a draft via MailMate's `emate` (markdown body) — IDENTICAL to `send` but it never sends: the draft opens in MailMate and waits. There is no `send_now` option; use this whenever the instruction is 'write/compose but don't send'. For replies, pass `reply_to` (or `reply_all_to`, or `forward`): the threading headers, recipient and subject are derived from the parent. MailMate generates the outgoing Message-ID automatically.",
269
306
  inputSchema: {
270
307
  type: "object",
271
308
  properties: {
@@ -359,10 +396,13 @@ module Mailmate
359
396
  stdin.binmode
360
397
  stdout.binmode
361
398
  stdout.sync = true
399
+ # Settle the first-run config notice now, on the server's own stderr.
400
+ # Left to fire lazily, it landed inside the first tool call's result.
401
+ Mailmate.ensure_configured!(stdin: stdin)
362
402
  loop do
363
403
  line = stdin.gets
364
404
  break if line.nil?
365
- line = line.strip
405
+ line = utf8(line).strip
366
406
  next if line.empty?
367
407
  begin
368
408
  msg = JSON.parse(line)
@@ -370,18 +410,37 @@ module Mailmate
370
410
  write(stdout, jsonrpc_error(nil, -32700, "Parse error: #{e.message}"))
371
411
  next
372
412
  end
413
+ # A batch (JSON array) or a bare value is valid JSON but not a
414
+ # request. It used to reach handle, raise there, and kill the
415
+ # server, taking every tool away for the rest of the session.
416
+ unless msg.is_a?(Hash)
417
+ what = msg.is_a?(Array) ? "JSON-RPC batches are not supported" : "expected a JSON object"
418
+ write(stdout, jsonrpc_error(nil, -32600, "Invalid Request: #{what}"))
419
+ next
420
+ end
373
421
  handle(msg, stdout)
374
422
  end
375
423
  0
376
424
  end
377
425
 
426
+ TOOL_NAMES = TOOLS.map { _1[:name] }.freeze
427
+
378
428
  def handle(msg, stdout)
379
429
  method = msg["method"]
380
430
  id = msg["id"]
431
+ params = msg["params"].is_a?(Hash) ? msg["params"] : {}
432
+ unless method.is_a?(String)
433
+ write(stdout, jsonrpc_error(id, -32600, "Invalid Request: no method"))
434
+ return
435
+ end
436
+ # A message without an id is a notification: never answered, and
437
+ # never a reason to run a tool.
438
+ return unless msg.key?("id")
439
+
381
440
  case method
382
441
  when "initialize"
383
442
  write(stdout, jsonrpc_result(id, {
384
- protocolVersion: PROTOCOL_VERSION,
443
+ protocolVersion: negotiate_protocol_version(params["protocolVersion"]),
385
444
  capabilities: { tools: {} },
386
445
  serverInfo: { name: SERVER_NAME, version: Mailmate::VERSION },
387
446
  instructions: INSTRUCTIONS,
@@ -391,18 +450,35 @@ module Mailmate
391
450
  when "tools/list"
392
451
  write(stdout, jsonrpc_result(id, { tools: TOOLS }))
393
452
  when "tools/call"
394
- params = msg["params"] || {}
395
- result = dispatch(params["name"], params["arguments"] || {})
396
- write(stdout, jsonrpc_result(id, result))
453
+ # An unknown tool is a protocol error (2025-11-25, server/tools);
454
+ # a tool that ran and failed is a result with isError.
455
+ unless TOOL_NAMES.include?(params["name"])
456
+ write(stdout, jsonrpc_error(id, -32602, "Unknown tool: #{params["name"].inspect}"))
457
+ return
458
+ end
459
+ # Omitted (or null) arguments mean none; anything else that is not
460
+ # an object is rejected by dispatch's argument check.
461
+ args = params["arguments"].nil? ? {} : params["arguments"]
462
+ write(stdout, jsonrpc_result(id, dispatch(params["name"], args)))
397
463
  when "ping"
398
464
  write(stdout, jsonrpc_result(id, {}))
399
465
  else
400
466
  # Unknown method — error if it has an id (request), drop if not.
401
467
  write(stdout, jsonrpc_error(id, -32601, "Method not found: #{method}")) unless id.nil?
402
468
  end
469
+ rescue StandardError => e
470
+ # Last line of defense for the persistent server: a request that
471
+ # breaks the handler gets an error reply, and the loop goes on.
472
+ write(stdout, jsonrpc_error(id, -32603, "Internal error: #{e.class}: #{e.message}")) unless id.nil?
403
473
  end
404
474
 
405
475
  def dispatch(name, args)
476
+ if (tool = TOOLS.find { _1[:name] == name })
477
+ problems = argument_problems(tool, args)
478
+ return invalid_arguments(tool, problems) unless problems.empty?
479
+ # null means "not given", for every tool and every argument.
480
+ args = args.compact
481
+ end
406
482
  case name
407
483
  when "search" then call_search(args)
408
484
  when "message" then call_message(args)
@@ -426,6 +502,109 @@ module Mailmate
426
502
  text_error("Tool '#{name}' called exit(#{e.status}) — treated as failure, server still running.")
427
503
  end
428
504
 
505
+ # ---- argument validation ----------------------------------------------
506
+ #
507
+ # Every call is checked against the tool's own inputSchema before any
508
+ # handler runs, so the schema is the contract and not a suggestion.
509
+ # Without this the handlers read the keys they know and ignore the rest:
510
+ # a misspelled `limt: 5` ran an unlimited search, `headers_only: "false"`
511
+ # (a string, so truthy) turned the flag ON, and `limit: "ten"` became
512
+ # `--limit 0`, each without a word. A rejected call is a result with
513
+ # isError (2025-11-25: input validation errors are tool execution
514
+ # errors, so the model sees the message and can correct the call).
515
+ #
516
+ # Covers what these schemas use: required, additionalProperties: false,
517
+ # type, enum, minimum, and array items. Two deliberate leniencies, both
518
+ # lossless: null means "not given", and an integer is accepted where a
519
+ # string is expected (ids are schema-typed as strings and often arrive
520
+ # as integers).
521
+
522
+ # Returns a list of problem strings; empty when the arguments are valid.
523
+ def argument_problems(tool, args)
524
+ return ["arguments must be an object, got #{json_type(args)}"] unless args.is_a?(Hash)
525
+
526
+ schema = tool[:inputSchema]
527
+ props = (schema[:properties] || {}).transform_keys(&:to_s)
528
+ given = args.reject { |_, v| v.nil? }
529
+ problems = []
530
+
531
+ Array(schema[:required]).map(&:to_s).each do |key|
532
+ problems << "missing required argument #{key.inspect}" unless given.key?(key)
533
+ end
534
+ given.each do |key, value|
535
+ if (prop = props[key.to_s])
536
+ problem = value_problem(prop, value)
537
+ problems << "#{key.to_s.inspect} #{problem}" if problem
538
+ elsif schema[:additionalProperties] == false
539
+ hint = closest_name(key.to_s, props.keys)
540
+ problems << "unknown argument #{key.to_s.inspect}#{hint && " (did you mean #{hint.inspect}?)"}"
541
+ end
542
+ end
543
+ problems
544
+ end
545
+
546
+ # nil when `value` satisfies `schema`, else what is wrong with it.
547
+ def value_problem(schema, value)
548
+ ok =
549
+ case schema[:type]
550
+ when "string" then value.is_a?(String) || value.is_a?(Integer)
551
+ when "boolean" then value == true || value == false
552
+ when "integer" then value.is_a?(Integer) || (value.is_a?(Float) && value.finite? && value == value.floor)
553
+ when "number" then value.is_a?(Numeric)
554
+ when "array" then value.is_a?(Array)
555
+ when "object" then value.is_a?(Hash)
556
+ else true
557
+ end
558
+ return "must be #{article(schema[:type])}, got #{json_type(value)} #{show(value)}" unless ok
559
+
560
+ if schema[:enum] && !schema[:enum].include?(value)
561
+ return "must be one of #{schema[:enum].join(", ")}, got #{show(value)}"
562
+ end
563
+ if schema[:minimum] && value < schema[:minimum]
564
+ return "must be at least #{schema[:minimum]}, got #{show(value)}"
565
+ end
566
+ if schema[:type] == "array" && schema[:items]
567
+ value.each_with_index do |item, i|
568
+ problem = value_problem(schema[:items], item)
569
+ return "item #{i} #{problem}" if problem
570
+ end
571
+ end
572
+ nil
573
+ end
574
+
575
+ def article(type) = "#{%w[integer array object].include?(type) ? "an" : "a"} #{type}"
576
+
577
+ # A value as shown in an error message. Infinity and NaN are numbers
578
+ # JSON cannot write, so fall back to Ruby's spelling for them.
579
+ def show(value) = (JSON.generate(value) rescue value.inspect)[0, 60]
580
+
581
+ def json_type(value)
582
+ case value
583
+ when nil then "null"
584
+ when true, false then "boolean"
585
+ when Integer then "integer"
586
+ when Numeric then "number"
587
+ when String then "string"
588
+ when Array then "array"
589
+ when Hash then "object"
590
+ else value.class.name
591
+ end
592
+ end
593
+
594
+ # The valid name a misspelling most likely meant, or nil. did_you_mean
595
+ # ships with Ruby; if a stripped-down runtime lacks it, skip the hint.
596
+ def closest_name(name, candidates)
597
+ return nil unless defined?(DidYouMean::SpellChecker)
598
+ DidYouMean::SpellChecker.new(dictionary: candidates).correct(name).first
599
+ end
600
+
601
+ def invalid_arguments(tool, problems)
602
+ valid = (tool[:inputSchema][:properties] || {}).keys
603
+ text_error("Invalid arguments for #{tool[:name]}; nothing was run.\n" \
604
+ "#{problems.map { "- #{_1}" }.join("\n")}\n" \
605
+ "Valid arguments: #{valid.empty? ? "(none)" : valid.join(", ")}")
606
+ end
607
+
429
608
  # ---- tool handlers ----------------------------------------------------
430
609
 
431
610
  def call_search(args)
@@ -438,35 +617,63 @@ module Mailmate
438
617
  argv.push("--headers-only") if args["headers_only"]
439
618
  argv.push("--sort", args["sort"].to_s) if args["sort"]
440
619
  argv.push("--european") if args["european"]
441
- # Always ask for the stats line: it carries the true match total and
442
- # the truncation facts as one JSON object, first on stderr, in place
443
- # of the prose notices. It stays in the text (readable as-is) and is
444
- # ALSO surfaced as structuredContent for clients that render it.
445
- argv.push("--stats")
446
- # Positionals: search-string then fields. Only include if the caller
447
- # gave us either — otherwise let the CLI apply its defaults.
448
- if args.key?("query") || args["fields"]
449
- argv << (args["query"] || "")
450
- argv << args["fields"].to_s if args["fields"]
620
+ # CSV (the default) always asks for the stats line: it carries the
621
+ # true match total and the truncation facts as one JSON object, in
622
+ # place of the prose notices. json/yaml documents carry the stats
623
+ # themselves.
624
+ format = (args["format"] || "csv").to_s
625
+ if format == "csv"
626
+ argv.push("--stats")
627
+ else
628
+ argv.push("--format", format)
451
629
  end
630
+ # Fields go by flag and the query is passed only when given, so a
631
+ # call with `fields` and no `query` gets the CLI's default query
632
+ # (today). It used to send "" as the query, which searched ALL mail.
633
+ argv.push("--fields", args["fields"].to_s) if args["fields"]
634
+ argv.push(*positional(args["query"])) if args.key?("query")
452
635
  res = run_cli(Mailmate::CLI::Search, argv)
453
- if (m = res[:content].first[:text].match(/^#{Regexp.escape(Mailmate::CLI::Search::STATS_PREFIX)}(\{.*\})$/))
454
- stats = (JSON.parse(m[1]) rescue nil)
455
- res[:structuredContent] = { stats: stats } if stats
456
- end
636
+ attach_structured_content!(res) if format == "json"
637
+ res
638
+ end
639
+
640
+ # The rule every tool result follows (docs/MCP results.md): the text is
641
+ # always the complete answer in the format the caller asked for, and
642
+ # structuredContent is sent ONLY when that format is JSON, as the very
643
+ # same object. Clients pick one of the two to show, and which one is
644
+ # theirs to decide: Claude Code and Claude Desktop show only
645
+ # structuredContent when it is present, so a structured result that
646
+ # held less than the text (search's stats-only object, 2.1.0 to 2.2.2)
647
+ # hid every row from them. Errors carry no structuredContent; clients
648
+ # show the text of an error result.
649
+ def attach_structured_content!(res)
650
+ return res if res[:isError]
651
+ doc = (JSON.parse(res[:content].first[:text]) rescue nil)
652
+ res[:structuredContent] = doc if doc.is_a?(Hash)
457
653
  res
458
654
  end
459
655
 
656
+ # Caller-supplied positionals (a query, an id, action words) always
657
+ # follow a "--", which ends option parsing. Without it a value that
658
+ # starts with "-" was parsed as an option: the documented negation
659
+ # `-is:unread` failed as "invalid option", a query of `-a` silently
660
+ # became --all, and a Message-ID such as `-abc@example.com` (they
661
+ # exist) could not be read at all. Flags therefore go BEFORE this.
662
+ def positional(*values)
663
+ ["--", *values.map(&:to_s)]
664
+ end
665
+
460
666
  def call_message(args)
461
- argv = [args["id"].to_s]
667
+ argv = []
462
668
  argv << "--raw" if args["raw"]
463
669
  argv << "--text-only" if args["text_only"]
464
670
  argv << "--markdown" if args["markdown"]
671
+ argv.push(*positional(args["id"]))
465
672
  run_cli(Mailmate::CLI::Message, argv)
466
673
  end
467
674
 
468
675
  def call_modify(args)
469
- argv = [args["id"].to_s] + Array(args["actions"]).map(&:to_s)
676
+ argv = []
470
677
  argv << "--dry-run" if args["dry_run"]
471
678
  argv << "--verify" if args["verify"]
472
679
  case args["check"]
@@ -474,6 +681,7 @@ module Mailmate
474
681
  when "defer" then argv << "--emit-check"
475
682
  end
476
683
  argv << "--keep-window" if args["keep_window"]
684
+ argv.push(*positional(args["id"], *Array(args["actions"])))
477
685
  run_cli(Mailmate::CLI::Modify, argv)
478
686
  end
479
687
 
@@ -492,15 +700,48 @@ module Mailmate
492
700
  # unless another field is present", so the check moved here — dropping it
493
701
  # entirely would let a `to`-less call through to open an empty composer.
494
702
  def recipient_check(args)
495
- return nil if args["to"] || args["reply_to"] || args["reply_all_to"]
496
- return nil if args["forward"] && args["to"]
703
+ given = ->(key) { !args[key].to_s.strip.empty? }
704
+ return nil if given.("to") || given.("reply_to") || given.("reply_all_to")
497
705
 
498
706
  text_error("no recipient: pass `to`, or `reply_to`/`reply_all_to` to derive it from the parent. " \
499
707
  "(`forward` derives the subject and body but not the recipient — pass `to` with it.)")
500
708
  end
501
709
 
710
+ PARENT_FLAGS = { "forward" => "--forward", "reply_all_to" => "--reply-all-to", "reply_to" => "--reply-to" }.freeze
711
+ EMATE_VALUES = %w[from to cc bcc subject].freeze
712
+ # What emate's parser (CLI11) takes for an option and not a value: a
713
+ # dash or two, then something that is not a space or the start of a
714
+ # number. "- agenda" and "-5% off" are values; "-x" and "--send-now=1"
715
+ # are options.
716
+ OPTION_LIKE = /\A--?[^\s\d.-]/.freeze
717
+
718
+ # Everything wrong with a compose call that the schema cannot express,
719
+ # as an error result, or nil. The argv built from these arguments is
720
+ # handed to emate, where ANY token that looks like an option is read as
721
+ # one, wherever it sits. An attachment of "--send-now=true" was
722
+ # therefore a send switch that the draft tool's exact-match guard did
723
+ # not see; "--header" or "--encrypt" in a subject would be read the
724
+ # same way. Such a value has never worked as a value, so refusing it
725
+ # loses nothing.
726
+ def compose_check(args)
727
+ problems = []
728
+ parents = PARENT_FLAGS.keys.select { args[_1] }
729
+ problems << "pass only one of #{PARENT_FLAGS.keys.join(", ")} (got #{parents.join(" and ")})" if parents.size > 1
730
+ EMATE_VALUES.each do |key|
731
+ next unless args[key].to_s.match?(OPTION_LIKE)
732
+ problems << "#{key.inspect} starts with \"-\", which MailMate's emate reads as an option, not a value"
733
+ end
734
+ Array(args["attachments"]).each do |path|
735
+ next if path.to_s.start_with?("/")
736
+ problems << "attachment #{path.to_s.inspect} must be an absolute path (starting with \"/\")"
737
+ end
738
+ return recipient_check(args) if problems.empty?
739
+
740
+ text_error("Invalid arguments; nothing was composed.\n#{problems.map { "- #{_1}" }.join("\n")}")
741
+ end
742
+
502
743
  def call_send(args)
503
- (err = recipient_check(args)) and return err
744
+ (err = compose_check(args)) and return err
504
745
 
505
746
  argv = compose_argv(args)
506
747
  argv << "--send-now" if args["send_now"]
@@ -510,7 +751,7 @@ module Mailmate
510
751
  # `draft` mirrors `send` but never sends — it has no send_now option and
511
752
  # routes through CLI::Draft, which refuses `--send-now` outright.
512
753
  def call_draft(args)
513
- (err = recipient_check(args)) and return err
754
+ (err = compose_check(args)) and return err
514
755
 
515
756
  argv = compose_argv(args)
516
757
  with_stdin(args["body"].to_s) { run_cli(Mailmate::CLI::Draft, argv) }
@@ -519,7 +760,10 @@ module Mailmate
519
760
  # Shared message-composition argv for both send and draft (everything bar
520
761
  # the body, which is piped on stdin, and the send-only `--send-now`).
521
762
  def compose_argv(args)
522
- argv = []
763
+ # Attachments FIRST. emate reads every bare path after a multi-value
764
+ # flag (-s, --header, …) as another value of that flag, so appended
765
+ # after them they were silently lost. See CLI::Send#emate_args.
766
+ argv = Array(args["attachments"]).map(&:to_s)
523
767
  argv.push("-f", args["from"].to_s) if args["from"]
524
768
  argv.push("-t", args["to"].to_s) if args["to"]
525
769
  argv.push("-c", args["cc"].to_s) if args["cc"]
@@ -535,21 +779,18 @@ module Mailmate
535
779
  # parent, the step that is easy to get subtly wrong and impossible to
536
780
  # notice afterwards (a mis-built chain sends fine and simply doesn't
537
781
  # thread).
538
- if (parent = args["reply_to"] || args["reply_all_to"] || args["forward"])
539
- flag = if args["forward"] then "--forward"
540
- elsif args["reply_all_to"] then "--reply-all-to"
541
- else "--reply-to"
542
- end
543
- argv.push(flag, parent.to_s)
782
+ # compose_check has already refused a call naming two parents.
783
+ if (key = PARENT_FLAGS.keys.find { args[_1] })
784
+ argv.push(PARENT_FLAGS[key], args[key].to_s)
544
785
  argv << "--no-quote" if args["quote"] == false
545
786
  end
546
- Array(args["attachments"]).each { |p| argv << p.to_s }
547
787
  argv
548
788
  end
549
789
 
550
790
  def call_open(args)
551
- argv = [args["id"].to_s]
791
+ argv = []
552
792
  argv << "--print" if args["print_only"]
793
+ argv.push(*positional(args["id"]))
553
794
  run_cli(Mailmate::CLI::Open, argv)
554
795
  end
555
796
 
@@ -566,26 +807,10 @@ module Mailmate
566
807
  run_cli(Mailmate::CLI::Tags, argv)
567
808
  end
568
809
 
810
+ # `mmmessage --resolve`, verbatim. Its answer is always JSON, so it
811
+ # follows the JSON half of the result rule (see attach_structured_content!).
569
812
  def call_resolve(args)
570
- eml_id = Mailmate::EmlLookup.resolve_id(args["id"].to_s)
571
- return text_error("Not found: #{args["id"].inspect}") if eml_id.nil? || eml_id.zero?
572
-
573
- path = Mailmate::EmlLookup.path_for(eml_id)
574
- return text_error("Not found: #{eml_id}.eml") unless path
575
-
576
- message_id = Mailmate::HeaderReader.message_id(path)
577
- mailbox = path.sub("#{Mailmate.config.imap_root}/", "")
578
- .sub(%r{/Messages/[^/]+\.eml\z}, "")
579
-
580
- payload = {
581
- eml_id: eml_id,
582
- message_id: message_id,
583
- message_url: message_id ? Mailmate::MidUrl.message_url_for(message_id) : nil,
584
- mid_url: message_id ? Mailmate::MidUrl.for(message_id) : nil,
585
- path: path,
586
- mailbox: mailbox,
587
- }
588
- { content: [{ type: "text", text: JSON.pretty_generate(payload) }] }
813
+ attach_structured_content!(run_cli(Mailmate::CLI::Message, ["--resolve", *positional(args["id"])]))
589
814
  end
590
815
 
591
816
  # ---- protocol helpers -------------------------------------------------
@@ -599,7 +824,17 @@ module Mailmate
599
824
  text << "[stderr]\n" << err
600
825
  end
601
826
  text = "(no output)" if text.empty?
602
- { content: [{ type: "text", text: text }], isError: code != 0 }
827
+ { content: [{ type: "text", text: utf8(text) }], isError: code != 0 }
828
+ end
829
+
830
+ # A JSON string must be valid UTF-8, and CLI output is not always:
831
+ # `mmmessage --raw` switches the capture to binary, and mail carries
832
+ # stray Latin-1 bytes. Unscrubbed, such a result could not be
833
+ # serialized at all and the call failed with a protocol error. Valid
834
+ # UTF-8 passes through untouched; any other byte becomes U+FFFD.
835
+ def utf8(text)
836
+ text = text.dup.force_encoding(Encoding::UTF_8)
837
+ text.valid_encoding? ? text : text.scrub("�")
603
838
  end
604
839
 
605
840
  def with_captured_io
@@ -634,7 +869,14 @@ module Mailmate
634
869
  end
635
870
 
636
871
  def write(stdout, obj)
637
- stdout.write(JSON.generate(obj) + "\n")
872
+ line =
873
+ begin
874
+ JSON.generate(obj)
875
+ rescue StandardError => e
876
+ # Never let an unserializable reply take the server down.
877
+ JSON.generate(jsonrpc_error(nil, -32603, "Internal error: reply could not be serialized (#{e.class})"))
878
+ end
879
+ stdout.write(line + "\n")
638
880
  stdout.flush
639
881
  end
640
882
 
@@ -180,7 +180,7 @@ module Mailmate
180
180
  width = TRANSLATIONS_HELP.map { |from, _| from.length }.max
181
181
  lines = TRANSLATIONS_HELP.map { |from, to| "#{indent} #{from.ljust(width)} -> #{to}" }
182
182
  lines << ""
183
- lines << "#{indent}Keys with no equivalent (is: has: in: filename: ...) are searched as"
183
+ lines << "#{indent}Keys with no equivalent (filename: larger: in:trash ...) are searched as"
184
184
  lines << "#{indent}literal text; an empty result will call them out."
185
185
  lines.join("\n")
186
186
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Mailmate
4
- VERSION = "2.2.0"
4
+ VERSION = "2.3.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mailmate
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.0
4
+ version: 2.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Brian Murphy-Dye
@@ -111,6 +111,7 @@ files:
111
111
  - README.md
112
112
  - config.yml.example
113
113
  - docs/Composing and threading.md
114
+ - docs/MCP results.md
114
115
  - exe/mailmate-mcp
115
116
  - exe/mm-draft
116
117
  - exe/mm-mailboxes
@@ -183,7 +184,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
183
184
  - !ruby/object:Gem::Version
184
185
  version: '0'
185
186
  requirements: []
186
- rubygems_version: 4.0.19
187
+ rubygems_version: 3.6.9
187
188
  specification_version: 4
188
189
  summary: Ruby toolkit for MailMate on macOS — search, read, modify, send, and smart-mailbox
189
190
  evaluation