Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ require (
charm.land/glamour/v2 v2.0.1
charm.land/lipgloss/v2 v2.0.6
github.com/basecamp/actioncable-client/go/v2 v2.0.2
github.com/basecamp/hey-sdk/go v0.35.0
github.com/basecamp/hey-sdk/go v0.35.1
github.com/basecamp/mcp v0.0.0-20261119020105-1a6d02c5380a
github.com/charmbracelet/x/ansi v0.11.9
github.com/fsnotify/fsnotify v1.10.1
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuP
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/basecamp/actioncable-client/go/v2 v2.0.2 h1:h2Sl15gj2lI/EX5E0EUxjyYgf0LF9Gn1zqEUInSrUpc=
github.com/basecamp/actioncable-client/go/v2 v2.0.2/go.mod h1:3Y0N9V5LXclT5nQWcPhq/+6rj4eKXgKAX8dx15X8yB8=
github.com/basecamp/hey-sdk/go v0.35.0 h1:gV9Y8JweijV8vKeIQvkYj1Kk+liq3iuJNoOnUgVD4BA=
github.com/basecamp/hey-sdk/go v0.35.0/go.mod h1:ILC2upnVketSzbZTcN1iICeCpjCqvYpIflYcEVrgigw=
github.com/basecamp/hey-sdk/go v0.35.1 h1:azrn9JoilQaQ3QDBtZb4hiROmQFUyEIWWVWFq65wSTw=
github.com/basecamp/hey-sdk/go v0.35.1/go.mod h1:g4+w+Htmntp03iF9L7afzWyPVYeQzxFUYONlw9r4R+s=
github.com/basecamp/mcp v0.0.0-20261119020105-1a6d02c5380a h1:5SI0hmC3B5wLusmAG917J9HGWnU2JLV+S2Ek8A0ABxk=
github.com/basecamp/mcp v0.0.0-20261119020105-1a6d02c5380a/go.mod h1:K3sgTH90CIR6Ed0XPnivIBqNIpw6aeOlcXThBrZ+2gc=
github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w=
Expand Down
40 changes: 3 additions & 37 deletions internal/cmd/draft.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type draftOutput struct {

func draftOutputFor(id int64, edit *generated.MessageEditState) draftOutput {
out := draftOutput{
From: edit.Sender.EmailAddress,
From: hey.DraftSentAs(edit).EmailAddress,
ID: id,
Subject: edit.Subject,
Body: htmlutil.ToMarkdown(edit.Content),
Expand All @@ -48,9 +48,6 @@ func draftOutputFor(id int64, edit *generated.MessageEditState) draftOutput {
IsReply: edit.IsReply,
AppURL: draftAppURL(id),
}
if edit.Sender.Id == 0 {
out.From = edit.Creator.EmailAddress
}
if !edit.ScheduledDeliveryAt.IsZero() {
at := edit.ScheduledDeliveryAt
out.ScheduledDeliveryAt = &at
Expand Down Expand Up @@ -80,37 +77,6 @@ func parseDraftID(arg string) (int64, error) {
return id, nil
}

// draftContentFrom is the edit state as the full DraftContent an update resends. HEY
// revises a draft from the whole request, so every verb that writes one starts here.
func draftContentFrom(edit *generated.MessageEditState) hey.DraftContent {
content := hey.DraftContent{
Subject: edit.Subject,
Content: edit.Content,
To: addressEmails(edit.Addressed.Directly),
CC: addressEmails(edit.Addressed.Copied),
BCC: addressEmails(edit.Addressed.Blindcopied),

// The identity the draft was saved as rides every rewrite, or a draft
// composed from a shared or alternate address would be handed back to
// the account default by its first edit or the final send.
ActingSenderID: edit.Sender.Id,
}
if content.ActingSenderID == 0 {
// HEY omits sender when the draft is sent as its creator contact.
content.ActingSenderID = edit.Creator.Id
}
if !edit.ScheduledDeliveryAt.IsZero() {
// HEY's API reads a schedule's date and hour in UTC (ApiRequest sets
// Time.zone to UTC for every JSON request), so the served UTC moment is
// said back as its own UTC date and hour — the exact round-trip, whatever
// clock the host or the identity keeps. Proven live: an identity-zone
// conversion here moved a 09:00Z delivery to 04:00Z on the first edit.
at := edit.ScheduledDeliveryAt.UTC()
content.Schedule = &hey.DraftSchedule{Date: at.Format("2006-01-02"), Hour: at.Hour()}
}
return content
}

// preservableSchedule refuses an edit that could not keep the draft's scheduled
// delivery where it is. HEY's API expresses a schedule as a whole UTC hour, so an
// instant between hours — set from a HEY app on a fractional-offset clock like
Expand Down Expand Up @@ -262,7 +228,7 @@ func (c *draftEditCommand) run(cmd *cobra.Command, args []string) error {
if scheduleErr := preservableSchedule(edit); scheduleErr != nil {
return scheduleErr
}
content := draftContentFrom(edit)
content := hey.DraftContentFromEdit(edit)

flags := cmd.Flags()
fieldFlagged := flags.Changed("from")
Expand Down Expand Up @@ -402,7 +368,7 @@ func (c *draftSendCommand) run(cmd *cobra.Command, args []string) error {
if edit == nil {
return apierr.ErrNotFound("draft", args[0])
}
content := draftContentFrom(edit)
content := hey.DraftContentFromEdit(edit)
if len(content.To)+len(content.CC)+len(content.BCC) == 0 {
return apierr.ErrUsageHint("the draft has no recipients", fmt.Sprintf("hey draft edit %d --to <email>", draftID))
}
Expand Down
6 changes: 3 additions & 3 deletions internal/cmd/thread_reply.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ type replyRecipients = mail.ReplyRecipients
// either: HEY never derives one,
// so a reply sent without it saves drafts that read "No subject" in Drafts.
// ActingSenderID is the identity the reply goes out as: the sender HEY resolved for
// the thread (or an explicit --from override), which on a shared or alternate address
// is not the account default; zero
// (the prefill named none, or was unreachable) leaves the SDK on the account default.
// the thread, else the acting user's own contact (or an explicit --from override),
// which on a shared or alternate address is not the account default; zero (the
// prefill was unreachable) leaves the SDK on the account default.
type threadReplyTarget struct {
EntryID int64
AccountID int64
Expand Down
16 changes: 10 additions & 6 deletions internal/mail/reply_prefill.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ type ReplyPrefill struct {
// ReplyPrefillFromServer asks HEY how a reply to the entry starts out
// (GET /entries/{id}/replies/new): the "Re: …" subject the reply carries; the sender
// it goes out as — resolved from the entry's own to and from addresses, so a thread on
// a shared or alternate address answers as that address, not the account default, and
// named only when it differs from the acting user; and its recipients — the entry's
// a shared or alternate address answers as that address, not the account default, or
// else the acting user's own contact; and its recipients — the entry's
// sender moved onto the To line and the acting user's own addresses, aliases and
// catch-alls excluded — the exclusion no client can compute locally, and the reason
// a reply used to be able to CC its writer back to themselves. A false answer sends
Expand All @@ -52,13 +52,17 @@ func ReplyPrefillFromServer(ctx context.Context, client *hey.Client, entryID int
if err != nil || prefilled == nil {
return ReplyPrefill{}, false
}
// HEY names the prefill's sender only when it differs from the acting user's
// own contact, the creator; zero would leave the SDK on the account's default
// sender, which need not be that address.
sentAs := hey.ReplySentAs(prefilled)
prefill := ReplyPrefill{
Subject: prefilled.Subject,
ActingSenderID: prefilled.Sender.Id,
ActingSenderID: sentAs.Id,
Sender: ReplySender{
ID: prefilled.Sender.Id,
Name: prefilled.Sender.Name,
EmailAddress: prefilled.Sender.EmailAddress,
ID: sentAs.Id,
Name: sentAs.Name,
EmailAddress: sentAs.EmailAddress,
},
Addressed: ReplyRecipients{
To: contactEmails(prefilled.Addressed.Directly),
Expand Down
23 changes: 23 additions & 0 deletions internal/mail/reply_prefill_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,29 @@ func TestReplyPrefillFromServer(t *testing.T) {
}
}

// HEY names the prefill's sender only when it differs from the acting user's own
// contact, so a reply from the person's own address carries the creator alone. That
// creator is the identity it goes out as: zero would leave the SDK on the account's
// default sender, which need not be the person's own address.
func TestReplyPrefillFromServerGoesOutAsTheCreatorWithoutASender(t *testing.T) {
client := replyPrefillClient(t, `{
"subject": "Re: Weekly sync", "is_reply": true,
"creator": {"id": 77, "name": "Maria", "email_address": "maria@hey.com"},
"addressed": {"directly": [{"id": 31, "email_address": "rick@example.com"}]}
}`)

prefill, ok := ReplyPrefillFromServer(context.Background(), client, 12)
if !ok {
t.Fatal("an addressed prefill answers; no fallback is needed")
}
if prefill.ActingSenderID != 77 {
t.Errorf("acting sender = %d, want the creator's 77", prefill.ActingSenderID)
}
if want := (ReplySender{ID: 77, Name: "Maria", EmailAddress: "maria@hey.com"}); prefill.Sender != want {
t.Errorf("sender = %+v, want %+v", prefill.Sender, want)
}
}

// The subject and sender are answered even when the recipients are not: on a thread
// with yourself, everyone HEY excludes is everyone there is, and only the recipients
// need the caller's local fallback.
Expand Down
8 changes: 8 additions & 0 deletions internal/mcpserver/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ func (d dispatcher) handle(ctx context.Context, dom gateway.Domain, op gateway.O
return gateway.ErrorResult("%v", err), nil
}

if full.ID == "UpdateMessage" {
kept, err := keepSavedSender(ctx, d.api, full.Action, params)
if err != nil {
return gateway.ErrorResult("%v", err), nil
}
params = kept
}

path, body, err := buildRequest(full, params)
if err != nil {
return gateway.ErrorResult("%v", err), nil
Expand Down
77 changes: 76 additions & 1 deletion internal/mcpserver/drafts.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package mcpserver

import (
"context"
"encoding/json"
"errors"
"fmt"
Expand All @@ -9,8 +10,10 @@ import (
"net/url"
"regexp"
"slices"
"strconv"
"strings"

"github.com/basecamp/hey-sdk/go/pkg/generated"
hey "github.com/basecamp/hey-sdk/go/pkg/hey"

"github.com/basecamp/mcp/catalog"
Expand Down Expand Up @@ -83,6 +86,56 @@ func draftOnly(action string, params map[string]any) (map[string]any, error) {
return out, nil
}

// draftEditPath is GetMessageEdit's path, where keepSavedSender reads the
// identity a draft was saved as. TestDraftEditPathIsTheModels holds it to the
// catalog.
const draftEditPath = "/messages/{messageId}/edit.json"

// keepSavedSender gives an update_message that leaves out acting_sender_id the
// identity the draft was saved as: its sender, else its creator
// (hey.DraftSentAs). HEY revises a draft from the whole request, and a revision
// without acting_sender_id drops the draft's sender, so a draft saved from a
// shared or alternate address would quietly move to the account's own. A
// sender the caller chose is left as it is. params is not modified.
func keepSavedSender(ctx context.Context, api API, action string, params map[string]any) (map[string]any, error) {
if given, ok := params["acting_sender_id"]; ok && given != nil {
return params, nil
}
id, err := scalarString(params["messageId"])
if _, given := params["messageId"]; !given || err != nil {
// buildRequest names the missing or unusable path parameter.
return params, nil //nolint:nilerr // reported by buildRequest instead
}
unread := func(why string) error {
return fmt.Errorf("%s keeps the address a draft sends from, and couldn't read draft %s's: %s. Nothing was changed. Pass acting_sender_id to choose it",
action, id, why)
}
resp, err := api.Get(ctx, strings.ReplaceAll(draftEditPath, "{messageId}", url.PathEscape(id)))
if err != nil {
return nil, unread(err.Error())
}
var edit generated.MessageEditState
var page struct {
Postings any `json:"postings"`
}
if json.Unmarshal(resp.Data, &edit) != nil || json.Unmarshal(resp.Data, &page) != nil {
return nil, unread("HEY's answer was unreadable")
}
// HEY answers the edit page of a sent or deleted draft by redirecting to
// the Imbox, which the client follows; only the draft's own answer names
// the identity it was saved as.
if strconv.FormatInt(edit.Id, 10) != id || page.Postings != nil {
return nil, unread("it isn't a draft any more: it was sent or deleted")
}
sentAs := hey.DraftSentAs(&edit).Id
if sentAs == 0 {
return nil, unread("HEY named no sender for it")
}
out := maps.Clone(params)
out["acting_sender_id"] = sentAs
return out, nil
}

// savedAsDraft reports whether HEY acknowledged a draft save: 204 and a
// Location naming the draft (haystack's respond_with_location_url). Anything
// else is unconfirmed. Delivery answers the sent message, and an entry HEY
Expand Down Expand Up @@ -185,7 +238,7 @@ func draftResult(resp *hey.Response, sendable bool) map[string]any {

// draftDoc leads the description of each draft-first operation, so describe
// tells the caller what this server does rather than what the wire can do.
const draftDoc = "Through hey mcp this only saves a draft: entry.status is always \"drafted\", and entry takes only addressed. It never delivers or schedules mail, and a request to send, schedule or triage is refused before HEY is contacted. Updating a scheduled draft clears its schedule. To deliver, " + howToSend + ". HEY's description of the endpoint follows; its delivery and scheduling paths aren't reachable here.\n\n"
const draftDoc = "Through hey mcp this only saves a draft: entry.status is always \"drafted\", and entry takes only addressed. It never delivers or schedules mail, and a request to send, schedule or triage is refused before HEY is contacted. Updating a scheduled draft clears its schedule. Updating a draft without acting_sender_id keeps the address it sends from. To deliver, " + howToSend + ". HEY's description of the endpoint follows; its delivery and scheduling paths aren't reachable here.\n\n"

// holdToDrafts rewrites each draft-first operation in the catalog to
// describe the draft-only contract: its summary (which the tool description
Expand All @@ -203,6 +256,12 @@ func holdToDrafts(cat *catalog.Catalog) error {
if err != nil {
return fmt.Errorf("%s: %w", op.ID, err)
}
if op.ID == "UpdateMessage" {
// The model reuses CreateMessage's body, which requires
// acting_sender_id; an update may leave it out to keep the
// address the draft sends from (keepSavedSender).
dropRequired(body, "acting_sender_id")
}
op.Body = body
op.Summary = strings.TrimSuffix(op.Summary, ".") + " (saved as a draft, never sent)"
op.Doc = draftDoc + op.Doc
Expand All @@ -211,6 +270,22 @@ func holdToDrafts(cat *catalog.Catalog) error {
return nil
}

// dropRequired takes name out of a JSON schema's required list.
func dropRequired(schema map[string]any, name string) {
required, _ := schema["required"].([]any)
kept := make([]any, 0, len(required))
for _, r := range required {
if r != name {
kept = append(kept, r)
}
}
if len(kept) == 0 {
delete(schema, "required")
return
}
schema["required"] = kept
}

// draftBody returns a copy of body whose entry allows only draftEntryKeys,
// with status pinned to "drafted".
func draftBody(body map[string]any) (map[string]any, error) {
Expand Down
Loading
Loading