package web import ( "context" "errors" "fmt" "net/http" "strconv" "strings" "time" "github.com/modelcontextprotocol/go-sdk/mcp" "supermarket/internal/approvals" "supermarket/internal/content" "supermarket/internal/mcpserver" "supermarket/internal/outreach" "supermarket/internal/posting" "supermarket/internal/prospects" "supermarket/internal/seo" "supermarket/internal/users" ) // Approvals. Anything an agent asks to send out of Supermarket waits here // for a person: members with edit on its module, or admins. They can edit // it first, approve or refuse it, and let the agent take that class of // action on its own from then on, with a cap per day. Agents read untrusted // text (signals, replies, search results), so nothing goes out on an // agent's word alone until a person has said this kind may. // The classes of action. const ( classEmailFirst = "email-first" // a first email to a prospect classEmailReply = "email-reply" // a reply in an existing conversation ) func classPost(account int64) string { return "post:" + strconv.FormatInt(account, 10) } func classList(list string) string { return "list:" + list } func classSEO(site string) string { return "seo-change:" + site } func classKind(class string) string { k, _, _ := strings.Cut(class, ":"); return k } func classParam(class string) string { _, p, _ := strings.Cut(class, ":"); return p } func classModule(class string) string { switch classKind(class) { case "post": return "content" case "seo-change": return "seo" } return "prospects" } // classLabel says what a class lets an agent do. func (s *Server) classLabel(class string) string { switch classKind(class) { case "post": id, _ := strconv.ParseInt(classParam(class), 10, 64) if a, err := posting.Get(s.DB, id); err == nil { return "publish posts to " + a.Label() } return "publish posts to an account since signed out" case classEmailFirst: return "send a first email to a prospect" case classEmailReply: return "send a reply in an existing conversation" case "list": return "add people to the mailing list " + classParam(class) case "seo-change": return "apply SEO changes to " + classParam(class) } return class } // agentViewer is an agent as a viewer: for the checks people get too // (posting to an account). func (s *Server) agentViewer(id int64) *viewer { u, err := users.ByID(s.DB, id) if err != nil || u.Status != users.Active { return &viewer{} } m, err := users.MembershipOf(s.DB, users.Team, id) if err != nil { return &viewer{} } return &viewer{User: u, Member: m} } // ask is how an agent's request to send something out starts: done at // once if the agent may do this on its own (within its cap), else waiting // for a person. It returns what to tell the agent. func (s *Server) ask(ctx context.Context, c *mcpserver.Caller, r *approvals.Request) (string, error) { r.Agent, r.Module = callerID(c), classModule(r.Class) if p, err := approvals.Pending(s.DB, r.Class, r.Target); err != nil { return "", err } else if p != nil { return fmt.Sprintf("Already waiting for approval (request %d): nothing more to do; approvals_status says when it's decided.", p.ID), nil } now := time.Now() // The cap per day on what an agent asks to send out, approved or not. lim, err := users.LimitsOf(s.DB, r.Agent) if err != nil { return "", err } if n, err := approvals.AskedSince(s.DB, r.Agent, now.Add(-24*time.Hour)); err != nil { return "", err } else if n >= lim.OutPerDay { return "", fmt.Errorf("this agent may ask to send out %d things a day, and has: try again tomorrow, or ask an admin to raise its limit", lim.OutPerDay) } ok, err := approvals.Allowed(s.DB, r.Agent, r.Class, now) if err != nil { return "", err } if !ok { if err := approvals.Add(s.DB, r, now); err != nil { return "", err } s.auditAgent(c, "asked-approval", r.Summary, fmt.Sprintf("request %d", r.ID)) return fmt.Sprintf("Waiting for approval (request %d): a person approves or refuses it in Supermarket's Approvals. approvals_status says when it's decided.", r.ID), nil } // On its own: carried out now, and recorded. result, runErr := s.carryOut(ctx, r, s.agentViewer(r.Agent)) r.Status, r.Result = approvals.Done, result if runErr != nil { r.Status, r.Result = approvals.Failed, runErr.Error() } if err := approvals.Add(s.DB, r, now); err != nil { return "", err } s.auditAgent(c, "did-on-its-own", r.Summary, r.Result) if runErr != nil { return "", runErr } return "Done (allowed on its own): " + result, nil } // carryOut does what a request asked, as as (the person approving it, or // the agent on its own). func (s *Server) carryOut(ctx context.Context, r *approvals.Request, as *viewer) (string, error) { now := time.Now() switch classKind(r.Class) { case "post": account, _ := strconv.ParseInt(classParam(r.Class), 10, 64) a, err := posting.Get(s.DB, account) if err != nil { return "", errors.New("that posting account was signed out") } if !s.mayPostAs(as, a) { return "", fmt.Errorf("%s may not post as %s (Settings → Posting accounts)", whoName(as), a.Label()) } if err := content.SetAccount(s.DB, r.Target, account); err != nil { return "", err } if as.User != nil { _ = content.SetPostedBy(s.DB, r.Target, as.User.ID) } if at := r.Params["at"]; at != "" { when, err := time.Parse(time.RFC3339, at) if err != nil { return "", err } if !when.After(now) { when = now // its time passed while it waited: now } if err := content.Schedule(s.DB, r.Target, when); err != nil { return "", err } return "scheduled for " + when.Local().Format("2 Jan 2006 15:04"), nil } pctx, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() d, err := content.Publish(pctx, s.DB, s.publishers(), s.tagger(), r.Target) if err != nil { return "", err } return "published as " + d.PostedAs + ": " + d.PostURL, nil case classEmailFirst, classEmailReply: if err := outreach.Queue(s.DB, r.Target, now); err != nil { return "", err } return "queued: it goes out in turn, within the sending hours", nil case "list": lctx, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() if err := s.addToListID(lctx, r.Target, classParam(r.Class), false); err != nil { return "", err } return "added to the mailing list", nil case "seo-change": if s.gitea() == nil { return "", errors.New("Gitea isn't connected (Settings → Search engines)") } ch, err := seo.GetChange(s.DB, r.Target) if err != nil { return "", err } var site *seoSite for _, st := range s.seoSites() { if auditKey(st) == ch.Site { site = &st } } if site == nil { return "", errors.New("that change's website isn't in the profile any more") } if err := seo.Decide(s.DB, r.Target, true, now); err != nil { return "", err } ap := s.applier(*site) go func() { actx, cancel := context.WithTimeout(context.Background(), 15*time.Minute) defer cancel() if err := ap.Apply(actx, s.DB, r.Target); err != nil { s.Log.Warn("seo: making the pull request", "change", r.Target, "err", err) } }() return "approved: the pull request is being made", nil } return "", fmt.Errorf("no class %q", r.Class) } func whoName(v *viewer) string { if v.User != nil { return displayName(v.User) } return "you" } // The Approvals page. // approvalView is a waiting request, with what's needed to edit it. type approvalView struct { approvals.Request Agent string ClassLabel string Draft *content.Draft Accounts []*posting.Account // for a post: where the viewer may send it Message *outreach.Message Change *seo.Change At time.Time } type approvalsData struct { Waiting []approvalView Recent []approvalView Allowed []grantView } type grantView struct { approvals.Grant Agent string Mine bool // the viewer may withdraw it } // decides says whether a viewer may decide a request in a module. func decides(v *viewer, module string) bool { return v.can(module, true) } // waitingFor counts what waits for the viewer: the sidebar's number. func (s *Server) waitingFor(v *viewer) int { if v == nil { return 0 } list, err := approvals.List(s.DB, approvals.Waiting, 0, 500) if err != nil { return 0 } n := 0 for _, r := range list { if decides(v, r.Module) { n++ } } return n } func (s *Server) agentName(id int64) string { if u, err := users.ByID(s.DB, id); err == nil { return u.Name } return "an agent since removed" } func (s *Server) viewApproval(r approvals.Request, v *viewer) approvalView { av := approvalView{Request: r, Agent: s.agentName(r.Agent), ClassLabel: s.classLabel(r.Class)} switch classKind(r.Class) { case "post": av.Draft, _ = content.GetDraft(s.DB, r.Target) if av.Draft != nil { av.Accounts = s.usableAccounts(v)[av.Draft.Channel] } if at := r.Params["at"]; at != "" { av.At, _ = time.Parse(time.RFC3339, at) } case classEmailFirst, classEmailReply: av.Message, _ = outreach.Get(s.DB, r.Target) case "seo-change": av.Change, _ = seo.GetChange(s.DB, r.Target) } return av } func (s *Server) approvalsPage(w http.ResponseWriter, r *http.Request) { s.renderApprovals(w, r, "") } func (s *Server) renderApprovals(w http.ResponseWriter, r *http.Request, errMsg string) { v := viewerOf(r) waiting, err := approvals.List(s.DB, approvals.Waiting, 0, 200) if err != nil { s.serverError(w, err) return } recent, err := approvals.List(s.DB, "", 0, 60) if err != nil { s.serverError(w, err) return } var d approvalsData for _, req := range waiting { if decides(v, req.Module) { d.Waiting = append(d.Waiting, s.viewApproval(req, v)) } } for _, req := range recent { if req.Status != approvals.Waiting && v.can(req.Module, false) && len(d.Recent) < 30 { d.Recent = append(d.Recent, approvalView{Request: req, Agent: s.agentName(req.Agent), ClassLabel: s.classLabel(req.Class)}) } } grants, err := approvals.Grants(s.DB, 0) if err != nil { s.serverError(w, err) return } for _, g := range grants { if v.can(g.Module, false) { d.Allowed = append(d.Allowed, grantView{Grant: g, Agent: s.agentName(g.Agent), Mine: decides(v, g.Module)}) } } s.render(w, r, "approvals", page{Title: "Approvals", Nav: "approvals", Error: errMsg, Data: d}) } // approvalAction approves or refuses a request: POST /approvals/{id}/{action}. func (s *Server) approvalAction(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } v := viewerOf(r) id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64) req, err := approvals.Get(s.DB, id) if errors.Is(err, approvals.ErrNotFound) { http.NotFound(w, r) return } if err != nil { s.serverError(w, err) return } if !decides(v, req.Module) { s.forbidden(w, r) return } by := int64(0) if v.User != nil { by = v.User.ID } now := time.Now() switch r.PathValue("action") { case "refuse": if err := approvals.Claim(s.DB, id, by, approvals.Refused, now); err != nil { s.renderApprovals(w, r, sentence(err.Error())+".") return } s.audit(r, "refused", req.Summary, "asked by "+s.agentName(req.Agent)) redirect(w, r, "/approvals", "refused") case "approve": // Edits first, as on the module's own page. if err := s.editApproval(r, req); err != nil { s.renderApprovals(w, r, sentence(err.Error())+".") return } if err := approvals.Claim(s.DB, id, by, approvals.Done, now); err != nil { s.renderApprovals(w, r, sentence(err.Error())+".") return } req, _ = approvals.Get(s.DB, id) result, runErr := s.carryOut(r.Context(), req, v) _ = approvals.Finish(s.DB, id, runErr) if runErr == nil { _ = approvals.SetResult(s.DB, id, result) } s.audit(r, "approved", req.Summary, "asked by "+s.agentName(req.Agent)+": "+result) if r.PostFormValue("trust") == "on" { cap, _ := strconv.Atoi(r.PostFormValue("cap")) g := approvals.Grant{Agent: req.Agent, Class: req.Class, Label: s.classLabel(req.Class), Module: req.Module, DailyCap: max(cap, 0), GrantedBy: by} if err := approvals.Allow(s.DB, g, now); err != nil { s.serverError(w, err) return } s.audit(r, "allowed-on-its-own", s.agentName(req.Agent), g.Label+capText(g.DailyCap)) } if runErr != nil { s.renderApprovals(w, r, "Approved, but it didn't work: "+runErr.Error()) return } redirect(w, r, "/approvals", "approved-request") default: http.NotFound(w, r) } } func capText(cap int) string { if cap <= 0 { return ", no cap" } return fmt.Sprintf(", up to %d a day", cap) } // editApproval saves what the person changed before approving: a post's // text and account, an email's subject and text, a change's wording. func (s *Server) editApproval(r *http.Request, req *approvals.Request) error { f := r.PostForm switch classKind(req.Class) { case "post": if text, ok := f["content"]; ok { if err := content.UpdateDraft(s.DB, req.Target, text[0]); err != nil { return err } } if title, ok := f["title"]; ok && strings.TrimSpace(title[0]) != "" { if err := content.UpdateTitle(s.DB, req.Target, title[0]); err != nil { return err } } if acc := f.Get("account"); acc != "" && acc != classParam(req.Class) { // Another account: the request becomes that class. id, _ := strconv.ParseInt(acc, 10, 64) if _, err := posting.Get(s.DB, id); err != nil { return errors.New("choose an account") } req.Class = classPost(id) if _, err := s.DB.Exec(`UPDATE approvals SET class = ? WHERE id = ?`, req.Class, req.ID); err != nil { return err } } case classEmailFirst, classEmailReply: if body, ok := f["body"]; ok { if err := outreach.Edit(s.DB, req.Target, f.Get("subject"), body[0]); err != nil { return err } } case "seo-change": if t, ok := f["title"]; ok { if err := seo.EditChange(s.DB, req.Target, t[0], f.Get("description")); err != nil { return err } } } return nil } // approvalWithdraw takes back what an agent may do on its own. func (s *Server) approvalWithdraw(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } agent, _ := strconv.ParseInt(r.PostFormValue("agent"), 10, 64) class := r.PostFormValue("class") if !decides(viewerOf(r), classModule(class)) { s.forbidden(w, r) return } if err := approvals.Withdraw(s.DB, agent, class); err != nil { s.serverError(w, err) return } s.audit(r, "withdrew-on-its-own", s.agentName(agent), s.classLabel(class)) back := "/approvals" if strings.HasPrefix(r.Referer(), s.PublicURL+"/settings/agents/") { back = strings.TrimPrefix(r.Referer(), s.PublicURL) } redirect(w, r, back, "withdrawn-class") } // The tools that ask. type publishArgs struct { DraftID int64 `json:"draft_id" jsonschema:"the draft, from content_drafts or content_create_draft"` AccountID int64 `json:"account_id,omitempty" jsonschema:"the posting account (posting_accounts); empty: the draft's own, or the company's for its channel"` At string `json:"at,omitempty" jsonschema:"when to publish, as 2026-11-27T09:00 (Supermarket's time zone) or RFC 3339; empty: as soon as it's approved"` } type sendArgs struct { MessageID int64 `json:"message_id" jsonschema:"the outreach draft, from outreach_list or outreach_draft"` } type listAddArgs struct { ContactID int64 `json:"contact_id" jsonschema:"the person, from prospects_review"` ListID string `json:"list_id" jsonschema:"the Listmonk list's id; only double opt-in lists, which ask the person first"` } type changeArgs struct { ChangeID int64 `json:"change_id" jsonschema:"the proposed change, from seo_changes"` } type statusArgs struct { ID int64 `json:"id,omitempty" jsonschema:"one request; empty for the agent's last 30"` } func (s *Server) approvalTools(srv *mcp.Server, c *mcpserver.Caller) { may := func(module string) bool { return c == nil || c.Can(module, true) } mcp.AddTool(srv, &mcp.Tool{ Name: "approvals_status", Description: "Your requests to send things out, and whether a person approved (and what happened), refused, or hasn't decided yet; and what you may do on your own.", }, func(ctx context.Context, _ *mcp.CallToolRequest, a statusArgs) (*mcp.CallToolResult, any, error) { if a.ID != 0 { r, err := approvals.Get(s.DB, a.ID) if err != nil || r.Agent != callerID(c) { return nil, nil, approvals.ErrNotFound } return toolJSON(r) } list, err := approvals.List(s.DB, "", callerID(c), 30) if err != nil { return nil, nil, err } grants, err := approvals.Grants(s.DB, callerID(c)) if err != nil { return nil, nil, err } return toolJSON(map[string]any{"requests": nonNilList(list), "allowed_on_your_own": nonNilList(grants)}) }) if may("content") { mcp.AddTool(srv, &mcp.Tool{ Name: "posting_accounts", Description: "The social accounts posts can go out from, with their ids, and whether you may post to each.", }, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) { av := s.agentViewer(callerID(c)) type acct struct { ID int64 `json:"id"` Account string `json:"account"` Channel string `json:"channel"` Working bool `json:"working"` MayPost bool `json:"you_may_post"` } out := []acct{} for _, a := range s.postingAccounts() { out = append(out, acct{a.ID, a.Label(), posting.Channel(a.Network), s.working(a), s.mayPostAs(av, a)}) } return toolJSON(out) }) mcp.AddTool(srv, &mcp.Tool{ Name: "content_publish", Description: "Ask to publish a draft, now or at a time, from a posting account. It waits for a person's approval unless you may publish " + "to that account on your own; the answer says which.", }, func(ctx context.Context, _ *mcp.CallToolRequest, a publishArgs) (*mcp.CallToolResult, any, error) { d, err := content.GetDraft(s.DB, a.DraftID) if err != nil { return nil, nil, err } if !d.Editable() { return nil, nil, errors.New("this draft was published, discarded, or is being published") } if p := d.Problem(); p != "" { return nil, nil, errors.New(p + ": fix it first (content_edit_draft)") } acct := a.AccountID if acct == 0 { ac, err := s.draftAccount(d) if err != nil { return nil, nil, err } if ac == nil { return nil, nil, fmt.Errorf("%s has no posting account: one must be connected first", d.ChannelName()) } acct = ac.ID } ac, err := posting.Get(s.DB, acct) if err != nil || posting.Channel(ac.Network) != d.Channel { return nil, nil, errors.New("that isn't an account for this draft's channel (posting_accounts)") } if !s.mayPostAs(s.agentViewer(callerID(c)), ac) { return nil, nil, fmt.Errorf("you may not post as %s: an admin can allow it on Settings → Posting accounts", ac.Label()) } params := map[string]string{} what := "Publish" if strings.TrimSpace(a.At) != "" { at, err := parseAgentTime(a.At) if err != nil { return nil, nil, err } params["at"] = at.UTC().Format(time.RFC3339) what = "Schedule, for " + at.Local().Format("2 Jan 15:04") + "," } msg, err := s.ask(ctx, c, &approvals.Request{Class: classPost(acct), Target: d.ID, Params: params, Summary: fmt.Sprintf("%s a post to %s", what, ac.Label())}) if err != nil { return nil, nil, err } return toolJSON(map[string]string{"status": msg}) }) } if may("prospects") { mcp.AddTool(srv, &mcp.Tool{ Name: "outreach_send", Description: "Ask to send an outreach email draft (it's queued, and goes out within the sending hours). It waits for a person's approval " + "unless you may send that kind on your own (a first email, or a reply in a conversation).", }, func(ctx context.Context, _ *mcp.CallToolRequest, a sendArgs) (*mcp.CallToolResult, any, error) { m, err := outreach.Get(s.DB, a.MessageID) if err != nil { return nil, nil, err } if m.Channel != outreach.ChannelEmail { return nil, nil, errors.New("LinkedIn messages are sent by hand, by a person") } if m.Status != outreach.StatusDraft && m.Status != outreach.StatusFailed { return nil, nil, fmt.Errorf("this message is %s, not a draft", m.Status) } class := classEmailFirst if prev, err := outreach.ForContacts(s.DB, []int64{m.ContactID}); err == nil { for _, o := range prev[m.ContactID] { if o.ID != m.ID && !o.SentAt.IsZero() { class = classEmailReply } } } kind := "a first email" if class == classEmailReply { kind = "a reply" } msg, err := s.ask(ctx, c, &approvals.Request{Class: class, Target: m.ID, Summary: "Send " + kind + " to " + m.To}) if err != nil { return nil, nil, err } return toolJSON(map[string]string{"status": msg}) }) mcp.AddTool(srv, &mcp.Tool{ Name: "mailing_list_add", Description: "Ask to add a person to a double opt-in mailing list (Listmonk asks them first). It waits for a person's approval unless you may add to that list on your own.", }, func(ctx context.Context, _ *mcp.CallToolRequest, a listAddArgs) (*mcp.CallToolResult, any, error) { p, err := prospects.GetContact(s.DB, a.ContactID) if err != nil { return nil, nil, err } if strings.TrimSpace(a.ListID) == "" { return nil, nil, errors.New("give the list's id") } msg, err := s.ask(ctx, c, &approvals.Request{Class: classList(strings.TrimSpace(a.ListID)), Target: p.ID, Summary: "Add " + p.Name() + " (" + p.Email + ") to mailing list " + a.ListID}) if err != nil { return nil, nil, err } return toolJSON(map[string]string{"status": msg}) }) } if may("seo") { mcp.AddTool(srv, &mcp.Tool{ Name: "seo_apply_change", Description: "Ask to apply a proposed title and description change (a pull request on the site). It waits for a person's approval unless you may apply changes to that site on your own.", }, func(ctx context.Context, _ *mcp.CallToolRequest, a changeArgs) (*mcp.CallToolResult, any, error) { ch, err := seo.GetChange(s.DB, a.ChangeID) if err != nil { return nil, nil, err } msg, err := s.ask(ctx, c, &approvals.Request{Class: classSEO(ch.Site), Target: ch.ID, Summary: "Change the title and description of " + ch.Page}) if err != nil { return nil, nil, err } return toolJSON(map[string]string{"status": msg}) }) } } // parseAgentTime reads a time an agent gives: RFC 3339, or local // 2006-01-02T15:04. It must be ahead, within a year. func parseAgentTime(v string) (time.Time, error) { v = strings.TrimSpace(v) t, err := time.Parse(time.RFC3339, v) if err != nil { if t, err = time.ParseInLocation(dateTimeLocal, v, time.Local); err != nil { return time.Time{}, fmt.Errorf("%q isn't a time: give 2026-11-27T09:00, or RFC 3339", v) } } now := time.Now() if t.Before(now.Add(-time.Minute)) { return time.Time{}, errors.New("that time has passed") } if t.After(now.AddDate(1, 0, 0)) { return time.Time{}, errors.New("that's more than a year away") } return t, nil }