mailmate 2.1.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 +4 -4
- data/README.md +18 -8
- data/docs/Composing and threading.md +2 -0
- data/docs/MCP results.md +68 -0
- data/lib/mailmate/cli/draft.rb +5 -1
- data/lib/mailmate/cli/message.rb +40 -41
- data/lib/mailmate/cli/search.rb +101 -6
- data/lib/mailmate/cli/send.rb +23 -1
- data/lib/mailmate/config.rb +8 -1
- data/lib/mailmate/eml_lookup.rb +8 -0
- data/lib/mailmate/html_markdown.rb +126 -0
- data/lib/mailmate/mcp.rb +312 -70
- data/lib/mailmate/reply_prefill.rb +37 -6
- data/lib/mailmate/search_syntax.rb +1 -1
- data/lib/mailmate/version.rb +1 -1
- metadata +4 -2
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
|
|
23
|
-
#
|
|
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
|
-
|
|
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
|
|
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 (`
|
|
98
|
-
searched as literal text
|
|
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,
|
|
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,
|
|
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:
|
|
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
|
-
|
|
395
|
-
|
|
396
|
-
|
|
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
|
-
#
|
|
442
|
-
# the truncation facts as one JSON object,
|
|
443
|
-
# of the prose notices.
|
|
444
|
-
#
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
argv
|
|
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
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
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 = [
|
|
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 = [
|
|
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
|
-
|
|
496
|
-
return nil if
|
|
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 =
|
|
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 =
|
|
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
|
-
|
|
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
|
-
|
|
539
|
-
|
|
540
|
-
|
|
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 = [
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require_relative "header_value"
|
|
4
|
+
require_relative "html_markdown"
|
|
4
5
|
|
|
5
6
|
module Mailmate
|
|
6
7
|
# @api public
|
|
@@ -138,30 +139,47 @@ module Mailmate
|
|
|
138
139
|
# Reply: email-classic "On <date>, <sender> wrote:" + a `> `-prefixed body.
|
|
139
140
|
# Forward: the conventional un-prefixed forwarded-message block with its
|
|
140
141
|
# own header summary, since the recipient has never seen the original.
|
|
142
|
+
#
|
|
143
|
+
# Which body gets quoted, in both modes: the HTML part rendered to
|
|
144
|
+
# markdown first — so the quote reads as the author laid it out
|
|
145
|
+
# (headings, links, emphasis) rather than as the text/plain alternative
|
|
146
|
+
# senders often neglect — then the plain part, then an honest placeholder
|
|
147
|
+
# when neither yields text (an HTML-only source with reverse_markdown not
|
|
148
|
+
# installed). A quote is never silently empty, and raw HTML is never
|
|
149
|
+
# quoted. (Until 2026-09-04 a reply preferred the plain part and a forward
|
|
150
|
+
# of an HTML-only message quoted nothing at all — the bug that prompted
|
|
151
|
+
# this: a bank alert forwarded as a bare header block.)
|
|
141
152
|
def derive_quoted_body(mail, mode)
|
|
142
|
-
body = plain_body(mail)
|
|
143
153
|
from = presence(mail["from"]&.value.to_s.strip) || "(unknown sender)"
|
|
144
154
|
date = mail["date"]&.value.to_s.strip
|
|
145
155
|
|
|
146
156
|
if mode == "forward"
|
|
157
|
+
body = quotable_body(mail) || FORWARD_PLACEHOLDER
|
|
147
158
|
header = ["---------- Forwarded message ----------",
|
|
148
159
|
"From: #{from}",
|
|
149
160
|
("Date: #{date}" unless date.empty?),
|
|
150
161
|
"Subject: #{mail.subject.to_s.strip}",
|
|
151
162
|
("To: #{mail['to'].value}" if mail["to"])].compact.join("\n")
|
|
152
|
-
return "#{header}\n\n#{body}"
|
|
163
|
+
return "#{header}\n\n#{body.sub(/\n+\z/, '')}\n"
|
|
153
164
|
end
|
|
154
165
|
|
|
155
166
|
attribution = date.empty? ? "#{from} wrote:" : "On #{date}, #{from} wrote:"
|
|
156
|
-
|
|
167
|
+
body = quotable_body(mail)
|
|
168
|
+
return "#{attribution}\n> #{REPLY_PLACEHOLDER}\n" if body.nil?
|
|
157
169
|
|
|
158
170
|
quoted = body.sub(/\n+\z/, "").split("\n", -1).map { |l| "> #{l}".rstrip }.join("\n")
|
|
159
171
|
"#{attribution}\n#{quoted}\n"
|
|
160
172
|
end
|
|
161
173
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
174
|
+
REPLY_PLACEHOLDER = "[no plain-text alternative — paste the original manually]"
|
|
175
|
+
FORWARD_PLACEHOLDER = "[the original has no readable text — it is HTML-only and the reverse_markdown gem is not installed; attach it or paste manually]"
|
|
176
|
+
|
|
177
|
+
# HTML-as-markdown, else plain text, else nil.
|
|
178
|
+
def quotable_body(mail)
|
|
179
|
+
presence(html_body_markdown(mail)) || presence(plain_body(mail))
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# The text/plain alternative, or "" when the message is HTML-only.
|
|
165
183
|
def plain_body(mail)
|
|
166
184
|
part = mail.multipart? ? mail.text_part : mail
|
|
167
185
|
return "" if part.nil?
|
|
@@ -172,6 +190,19 @@ module Mailmate
|
|
|
172
190
|
""
|
|
173
191
|
end
|
|
174
192
|
|
|
193
|
+
# The text/html part rendered to markdown (Mailmate::HtmlMarkdown), or ""
|
|
194
|
+
# when there is no HTML part or the optional converter is missing.
|
|
195
|
+
# `decoded` (not `body.decoded`) so the part's declared charset — the
|
|
196
|
+
# iso-8859-1 of a bank alert — is transcoded to UTF-8 before parsing.
|
|
197
|
+
def html_body_markdown(mail)
|
|
198
|
+
part = mail.multipart? ? mail.html_part : (mail.content_type.to_s.downcase.include?("text/html") ? mail : nil)
|
|
199
|
+
return "" if part.nil?
|
|
200
|
+
|
|
201
|
+
Mailmate::HtmlMarkdown.convert(part.decoded.to_s).to_s
|
|
202
|
+
rescue StandardError
|
|
203
|
+
""
|
|
204
|
+
end
|
|
205
|
+
|
|
175
206
|
# Mail's address fields raise on malformed input often enough that a reply
|
|
176
207
|
# to a slightly-broken message shouldn't blow up the whole derivation.
|
|
177
208
|
def addresses(field)
|