From bfb74e7700bb5c392903497c03bd204397e7e292 Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 10:31:43 -0700 Subject: [PATCH] Phase 11, part 2: module tools over MCP Agents get each module's tools by their scopes: reading tools with read, the others with read and act. Content (drafts and items; writing, editing and discarding drafts), Prospects (signals, review, outreach, suppression; outreach drafts and edits), SEO (the morning check, What to write next, links, changes; editing a proposal), Sites and Metrics (reading) and the Market (list, get, save). They call what the pages call, and what an agent changes is in the audit log as the agent. Nothing that leaves Supermarket is offered yet: that waits for approvals. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 33 +- cmd/supermarket/main.go | 2 +- internal/mcpserver/mcpserver.go | 10 +- internal/web/agenttools.go | 698 ++++++++++++++++++++++++++++++++ internal/web/agenttools_test.go | 164 ++++++++ internal/web/server_test.go | 2 +- 6 files changed, 903 insertions(+), 6 deletions(-) create mode 100644 internal/web/agenttools.go create mode 100644 internal/web/agenttools_test.go diff --git a/PLAN.md b/PLAN.md index 4ba260d..229a491 100644 --- a/PLAN.md +++ b/PLAN.md @@ -53,8 +53,8 @@ branch `phase10` (2026-11-25), not yet merged: schema 36, a new the visible changes are posting accounts, Connections, Activity, and a CSRF token in every form. -**Next: Phase 11, agents.** Part 1 (agent users and keys) is built on -branch `phase11`. Phase 12 still needs who adds Supermarket's client to +**Next: Phase 11, agents.** Parts 1 (agent users and keys) and 2 (module +tools over MCP) are built on branch `phase11`; part 3 (approvals) is next. Phase 12 still needs who adds Supermarket's client to Authelia. **Coming back to it (for the agent working on it):** @@ -2552,6 +2552,35 @@ single `mcp-token`. A commit after each part. The socket stays as it is (everything, no key). The server edition has no built-in Hermes: an admin makes an agent with the CRM scope. +**Part 2 built 2026-11-26** on `phase11`. +- The module tools live in the web package (`agenttools.go`), because they + call what the pages call (site scopes, What to write next, the AI clients); + `mcpserver.Handler` takes them as a hook and builds each agent's server + from its scopes, so an agent is never even offered a tool it can't use. + Every agent gets `profile_get`. +- **Content:** read: `content_drafts` (waiting, scheduled, published), + `content_items` (an entry's fetched items, or the company's own); act: + `content_create_draft` (the agent writes the text; the channel's rules + apply: Reddit needs a title and subreddit; the entry, signal and items + are checked), `content_edit_draft`, `content_discard_draft`. +- **Prospects:** read: `signals_list` (with the 90-day scorecard), + `prospects_review`, `outreach_list` (with replies), `suppression_list`; + act: `outreach_draft` (Supermarket's AI writes it, as on the page, so + suppression and the rest hold), `outreach_edit`, `suppress`. +- **SEO:** read: `seo_sites`, `seo_morning_check`, `seo_next`, `seo_links`, + `seo_changes`; act: `seo_edit_change` (a proposal's wording; the yes that + opens the pull request stays a person's). +- **Sites:** read: `sites_list`, `sites_new_pages`. **Metrics:** read: + `metrics_months` (the last 13). **The Market:** read: `market_list`, + `market_get` (with ids; `inventory_list` stays for Hermes and Claude + Code); act: `market_save` (adds, or replaces the entry of that name). +- Everything an agent changes is in the audit log as the agent; drafts and + outreach it writes show *by* its name. +- Not here, on purpose: anything that leaves Supermarket (publishing or + scheduling a post, queueing or sending an email, mailing-list adds, + pushing a page or opening a pull request). Those need part 3's + approvals, so an agent can't do them at all yet. + 1. **Agent users and their keys.** - An admin creates an agent on Settings → Users → *New agent*. It has a name, a description, and the modules it's given, each *read* or diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index 2b9087f..e2e6181 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -330,7 +330,7 @@ func run(log *slog.Logger) error { } // Agents reach /mcp with their keys. On the local edition, mcp-token is // the key of the built-in Hermes agent. - srv.MCP = mcpserver.Handler(database, version, srv.AgentAuth) + srv.MCP = mcpserver.Handler(database, version, srv.AgentAuth, srv.AgentTools) if local { if err := srv.EnsureHermes(token); err != nil { return err diff --git a/internal/mcpserver/mcpserver.go b/internal/mcpserver/mcpserver.go index 5fe7750..b0201ed 100644 --- a/internal/mcpserver/mcpserver.go +++ b/internal/mcpserver/mcpserver.go @@ -41,7 +41,10 @@ type Authenticator func(r *http.Request, key string) (*Caller, error) // Handler returns the /mcp handler. Each request needs an agent's key // ("Authorization: Bearer sm_…"), and is offered only the tools the // agent's scopes allow. -func Handler(d *db.DB, version string, auth Authenticator) http.Handler { +// +// more adds the app's module tools for the caller (the web package has +// them, as they call what its pages call); nil for none. +func Handler(d *db.DB, version string, auth Authenticator, more func(*mcp.Server, *Caller)) http.Handler { var mu sync.Mutex servers := map[string]*mcp.Server{} // by the scopes' signature: a few at most h := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server { @@ -54,6 +57,9 @@ func Handler(d *db.DB, version string, auth Authenticator) http.Handler { } srv := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil) addTools(srv, d, c) + if more != nil { + more(srv, c) + } servers[sig] = srv return srv }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true}) @@ -77,7 +83,7 @@ func Handler(d *db.DB, version string, auth Authenticator) http.Handler { type callerKey struct{} // scopes are what tools are offered by: each, read or act. -var scopes = []string{"market", "crm"} +var scopes = []string{"content", "prospects", "seo", "sites", "metrics", "market", "crm"} // signature names the tools a caller gets. func signature(c *Caller) string { diff --git a/internal/web/agenttools.go b/internal/web/agenttools.go new file mode 100644 index 0000000..3f0b80b --- /dev/null +++ b/internal/web/agenttools.go @@ -0,0 +1,698 @@ +package web + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "supermarket/internal/audit" + "supermarket/internal/backlinks" + "supermarket/internal/content" + "supermarket/internal/inventory" + "supermarket/internal/mcpserver" + "supermarket/internal/metrics" + "supermarket/internal/outreach" + "supermarket/internal/prospects" + "supermarket/internal/seo" + "supermarket/internal/signals" + "supermarket/internal/sites" +) + +// The modules' tools over MCP. Each calls what the module's pages call, +// so the rules hold for agents as for people. An agent is offered a +// module's reading tools with read, and its other tools with read and act. +// Nothing here sends anything out of Supermarket: publishing, scheduling, +// sending, pushing and mailing-list adds go through Approvals (part 3). + +// AgentTools adds the module tools a caller may use. +func (s *Server) AgentTools(srv *mcp.Server, c *mcpserver.Caller) { + may := func(module string, act bool) bool { return c == nil || c.Can(module, act) } + if may("content", false) { + s.contentReadTools(srv) + } + if may("content", true) { + s.contentActTools(srv, c) + } + if may("prospects", false) { + s.prospectsReadTools(srv) + } + if may("prospects", true) { + s.prospectsActTools(srv, c) + } + if may("seo", false) { + s.seoReadTools(srv) + } + if may("seo", true) { + s.seoActTools(srv, c) + } + if may("sites", false) { + s.sitesReadTools(srv) + } + if may("metrics", false) { + s.metricsReadTools(srv) + } + if may("market", false) { + s.marketReadTools(srv) + } + if may("market", true) { + s.marketActTools(srv, c) + } +} + +// toolJSON is a tool's answer, as JSON text. +func toolJSON(v any) (*mcp.CallToolResult, any, error) { + raw, err := json.MarshalIndent(v, "", " ") + if err != nil { + return nil, nil, err + } + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: string(raw)}}}, nil, nil +} + +// auditAgent records what an agent changed. +func (s *Server) auditAgent(c *mcpserver.Caller, action, target, detail string) { + e := audit.Entry{Kind: audit.Agent, Action: action, Target: target, Detail: detail} + if c != nil { + e.UserID, e.UserName = c.ID, c.Name + } + s.record(e) +} + +func callerID(c *mcpserver.Caller) int64 { + if c == nil { + return 0 + } + return c.ID +} + +type none struct{} + +type limitArgs struct { + Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 50"` +} + +func limitOf(n, def, max int) int { + if n <= 0 { + return def + } + return min(n, max) +} + +// --- Content --- + +type draftsArgs struct { + Status string `json:"status,omitempty" jsonschema:"waiting (in Posts, for review: the default), scheduled or published"` + Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 50"` +} + +type itemsArgs struct { + Entry string `json:"entry" jsonschema:"whose items: a Market entry's name, or own for the company's own products, feeds and pages"` + Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 30"` +} + +type draftArgs struct { + Channel string `json:"channel" jsonschema:"x, linkedin or reddit"` + Text string `json:"text" jsonschema:"the post; within the channel's limit (X: 280 characters, counting the source link as 23)"` + Title string `json:"title,omitempty" jsonschema:"Reddit only: the post's title"` + Subreddit string `json:"subreddit,omitempty" jsonschema:"Reddit only: where it goes, without r/"` + SourceURL string `json:"source_url,omitempty" jsonschema:"the link the post is about; added when publishing (on X after the text, on LinkedIn as a card)"` + Entry string `json:"entry,omitempty" jsonschema:"the Market entry it's about, or own; empty for none"` + SignalID int64 `json:"signal_id,omitempty" jsonschema:"the buying signal it's written for (signals_list), so its links count for it"` + ItemIDs []string `json:"item_ids,omitempty" jsonschema:"the fetched items it's written from (content_items), marked as used"` +} + +type editDraftArgs struct { + ID int64 `json:"id" jsonschema:"the draft's id"` + Text string `json:"text,omitempty" jsonschema:"the new text; empty keeps it"` + Title string `json:"title,omitempty" jsonschema:"Reddit only: the new title; empty keeps it"` +} + +type idArgs struct { + ID int64 `json:"id" jsonschema:"its id"` +} + +// draftView is a draft as agents see it. +type draftView struct { + ID int64 `json:"id"` + Channel string `json:"channel"` + Status string `json:"status"` + Title string `json:"title,omitempty"` + Subreddit string `json:"subreddit,omitempty"` + Text string `json:"text"` + SourceURL string `json:"source_url,omitempty"` + Entry string `json:"entry,omitempty"` + Length int `json:"length"` + Limit int `json:"limit"` + Problem string `json:"problem,omitempty"` + Error string `json:"error,omitempty"` + PublishAt time.Time `json:"publish_at,omitzero"` + PostURL string `json:"post_url,omitempty"` + PostedAs string `json:"posted_as,omitempty"` +} + +func viewDraft(d *content.Draft) draftView { + return draftView{ID: d.ID, Channel: d.Channel, Status: d.Status, Title: d.Title, Subreddit: d.Target, Text: d.Content, + SourceURL: d.SourceURL, Entry: d.InventoryName, Length: d.Length(), Limit: d.Limit(), Problem: d.Problem(), + Error: d.Error, PublishAt: d.PublishAt, PostURL: d.PostURL, PostedAs: d.PostedAs} +} + +func (s *Server) contentReadTools(srv *mcp.Server) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "content_drafts", + Description: "Posts: drafts waiting for review in Posts, scheduled ones, or published ones, newest first.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a draftsArgs) (*mcp.CallToolResult, any, error) { + statuses := []string{content.StatusDraft, content.StatusFailed} + switch a.Status { + case "", "waiting": + case "scheduled": + statuses = []string{content.StatusScheduled} + case "published": + statuses = []string{content.StatusPublished} + default: + return nil, nil, fmt.Errorf("no status %q: waiting, scheduled or published", a.Status) + } + list, err := content.ListDrafts(s.DB, limitOf(a.Limit, 50, 200), statuses...) + if err != nil { + return nil, nil, err + } + out := []draftView{} + for i := range list { + out = append(out, viewDraft(&list[i])) + } + return toolJSON(out) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "content_items", + Description: "Fetched items to write posts from: a Market entry's recent posts, videos and articles, or (entry: own) the company's own products, feeds and pages. Dismissed ones are left out.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a itemsArgs) (*mcp.CallToolResult, any, error) { + name := strings.TrimSpace(a.Entry) + if strings.EqualFold(name, "own") { + name = content.OwnName + } + if name == "" { + return nil, nil, errors.New("give the entry: a Market entry's name, or own") + } + items, err := content.ListItems(s.DB, name, false, limitOf(a.Limit, 30, 200)) + if err != nil { + return nil, nil, err + } + if items == nil { + items = []content.Item{} + } + return toolJSON(items) + }) +} + +func (s *Server) contentActTools(srv *mcp.Server, c *mcpserver.Caller) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "content_create_draft", + Description: "Write a post as a draft, waiting in Posts for review. Write it in the company's voice (profile_get). " + + "It isn't published: a person (or, later, an approval) does that.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a draftArgs) (*mcp.CallToolResult, any, error) { + ch, ok := content.ChannelByID(strings.ToLower(strings.TrimSpace(a.Channel))) + if !ok { + return nil, nil, fmt.Errorf("no channel %q: x, linkedin or reddit", a.Channel) + } + if strings.TrimSpace(a.Text) == "" { + return nil, nil, errors.New("the post is empty") + } + dr := content.Draft{Channel: ch.ID, Content: a.Text, SourceURL: strings.TrimSpace(a.SourceURL), ItemIDs: a.ItemIDs, + Kind: content.KindProduct, WrittenBy: callerID(c)} // about the company, unless an entry is given + if ch.ID == content.ChannelReddit { + dr.Title, dr.Target = strings.TrimSpace(a.Title), strings.TrimPrefix(strings.TrimSpace(a.Subreddit), "r/") + if dr.Title == "" || dr.Target == "" { + return nil, nil, errors.New("a Reddit post needs a title and a subreddit") + } + } + if e := strings.TrimSpace(a.Entry); strings.EqualFold(e, "own") { + dr.InventoryName, dr.Kind = content.OwnName, content.KindProduct + } else if e != "" { + entries, err := inventory.List(s.DB, "") + if err != nil { + return nil, nil, err + } + found := false + for _, en := range entries { + if strings.EqualFold(en.Name, e) { + dr.InventoryName, dr.Kind, found = en.Name, en.Relationship, true + } + } + if !found { + return nil, nil, fmt.Errorf("no Market entry %q", e) + } + } + if a.SignalID != 0 { + if _, err := signals.Get(s.DB, a.SignalID); err != nil { + return nil, nil, fmt.Errorf("no signal %d", a.SignalID) + } + dr.SignalID = a.SignalID + } + batch, err := content.CreateDrafts(s.DB, []content.Draft{dr}) + if err != nil { + return nil, nil, err + } + list, err := content.ListDrafts(s.DB, 20, content.StatusDraft) + if err != nil { + return nil, nil, err + } + for i := range list { + if list[i].Batch == batch { + s.auditAgent(c, "wrote-draft", ch.Name, fmt.Sprintf("draft %d", list[i].ID)) + return toolJSON(viewDraft(&list[i])) + } + } + return nil, nil, errors.New("the draft was written, but couldn't be read back") + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "content_edit_draft", + Description: "Change a draft waiting in Posts: its text, and a Reddit draft's title.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a editDraftArgs) (*mcp.CallToolResult, any, error) { + if strings.TrimSpace(a.Text) != "" { + if err := content.UpdateDraft(s.DB, a.ID, a.Text); err != nil { + return nil, nil, err + } + } + if strings.TrimSpace(a.Title) != "" { + if err := content.UpdateTitle(s.DB, a.ID, a.Title); err != nil { + return nil, nil, err + } + } + d, err := content.GetDraft(s.DB, a.ID) + if err != nil { + return nil, nil, err + } + s.auditAgent(c, "edited-draft", d.ChannelName(), fmt.Sprintf("draft %d", d.ID)) + return toolJSON(viewDraft(d)) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "content_discard_draft", + Description: "Drop a draft waiting in Posts.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a idArgs) (*mcp.CallToolResult, any, error) { + if err := content.DiscardDraft(s.DB, a.ID); err != nil { + return nil, nil, err + } + s.auditAgent(c, "deleted", fmt.Sprintf("draft %d", a.ID), "") + return toolJSON(map[string]string{"status": "discarded"}) + }) +} + +// --- Prospects --- + +type reviewArgs struct { + Status string `json:"status,omitempty" jsonschema:"new (waiting for review: the default), accepted or rejected"` + SignalID int64 `json:"signal_id,omitempty" jsonschema:"only those tagged with this signal"` + Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 50"` +} + +type outreachArgs struct { + Tab string `json:"tab,omitempty" jsonschema:"drafts (the default), queued, sent, replied or failed"` + Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 50"` +} + +type outreachDraftArgs struct { + ContactID int64 `json:"contact_id" jsonschema:"the person, from prospects_review"` + Channel string `json:"channel,omitempty" jsonschema:"email (the default) or linkedin"` +} + +type outreachEditArgs struct { + ID int64 `json:"id" jsonschema:"the outreach draft's id"` + Subject string `json:"subject,omitempty" jsonschema:"the new subject; empty keeps it"` + Body string `json:"body,omitempty" jsonschema:"the new text; empty keeps it"` +} + +type suppressArgs struct { + Value string `json:"value" jsonschema:"an email address, or a domain such as example.com"` + Reason string `json:"reason,omitempty" jsonschema:"why, in a few words (they asked us to stop, a competitor…)"` +} + +func (s *Server) prospectsReadTools(srv *mcp.Server) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "signals_list", + Description: "The buying signals being tested, with each one's funnel over the last 90 days: reached, replied, visited, booked, signed up, paid.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) { + list, err := signals.List(s.DB) + if err != nil { + return nil, nil, err + } + rows, err := signals.Scorecard(s.DB, signals.Filter{Since: time.Now().AddDate(0, 0, -90)}) + if err != nil { + return nil, nil, err + } + return toolJSON(map[string]any{"signals": nonNilList(list), "scorecard": nonNilList(rows)}) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "prospects_review", + Description: "Companies and people found as prospects, by status: new ones wait for a person to accept (for the CRM) or set aside.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a reviewArgs) (*mcp.CallToolResult, any, error) { + status := a.Status + if status == "" { + status = prospects.StatusNew + } + cs, ps, err := prospects.Review(s.DB, status, a.SignalID, limitOf(a.Limit, 50, 500)) + if err != nil { + return nil, nil, err + } + return toolJSON(map[string]any{"companies": nonNilList(cs), "people": nonNilList(ps)}) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "outreach_list", + Description: "Outreach messages: drafts, queued to send, sent, replied (with the replies) or failed.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a outreachArgs) (*mcp.CallToolResult, any, error) { + tab := a.Tab + if tab == "" { + tab = "drafts" + } + list, err := outreach.List(s.DB, tab, limitOf(a.Limit, 50, 200)) + if err != nil { + return nil, nil, err + } + return toolJSON(nonNilList(list)) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "suppression_list", + Description: "Emails and domains never to contact or add: checked before anything is drafted, queued or sent.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) { + list, err := prospects.Suppressions(s.DB) + if err != nil { + return nil, nil, err + } + return toolJSON(nonNilList(list)) + }) +} + +func (s *Server) prospectsActTools(srv *mcp.Server, c *mcpserver.Caller) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "outreach_draft", + Description: "Have Supermarket's AI write a first message to a prospect, as on the Outreach page, from the company's profile and the person's signal. " + + "It waits in Outreach → Drafts; sending is a person's.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a outreachDraftArgs) (*mcp.CallToolResult, any, error) { + channel := a.Channel + if channel == "" { + channel = outreach.ChannelEmail + } + if channel != outreach.ChannelEmail && channel != outreach.ChannelLinkedIn { + return nil, nil, fmt.Errorf("no channel %q: email or linkedin", a.Channel) + } + cl, p, err := s.draftClient() + if err != nil { + return nil, nil, err + } + set, _ := s.outreachSettings() + dctx, cancel := context.WithTimeout(ctx, 3*time.Minute) + defer cancel() + m, err := outreach.Draft(dctx, s.DB, cl, p, set, a.ContactID, channel, time.Now()) + if err != nil { + return nil, nil, err + } + _ = outreach.SetCreatedBy(s.DB, m.ID, callerID(c)) + s.auditAgent(c, "wrote-draft", "outreach to "+m.To, fmt.Sprintf("message %d", m.ID)) + return toolJSON(m) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "outreach_edit", + Description: "Change an outreach draft's subject or text.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a outreachEditArgs) (*mcp.CallToolResult, any, error) { + m, err := outreach.Get(s.DB, a.ID) + if err != nil { + return nil, nil, err + } + subject, body := m.Subject, m.Body + if strings.TrimSpace(a.Subject) != "" { + subject = a.Subject + } + if strings.TrimSpace(a.Body) != "" { + body = a.Body + } + if err := outreach.Edit(s.DB, a.ID, subject, body); err != nil { + return nil, nil, err + } + s.auditAgent(c, "edited-draft", "outreach to "+m.To, fmt.Sprintf("message %d", m.ID)) + m, err = outreach.Get(s.DB, a.ID) + if err != nil { + return nil, nil, err + } + return toolJSON(m) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "suppress", + Description: "Add an email address or a domain to the suppression list: no one there is drafted, queued, sent to or added to the CRM.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a suppressArgs) (*mcp.CallToolResult, any, error) { + v := strings.ToLower(strings.TrimSpace(a.Value)) + kind := "domain" + if strings.Contains(v, "@") { + kind = "email" + } + if v == "" { + return nil, nil, errors.New("give an email address or a domain") + } + if err := prospects.Suppress(s.DB, kind, v, a.Reason, time.Now()); err != nil { + return nil, nil, err + } + s.auditAgent(c, "suppressed", v, a.Reason) + return toolJSON(map[string]string{"status": "suppressed", "kind": kind, "value": v}) + }) +} + +// --- SEO --- + +type siteArgs struct { + Site int `json:"site,omitempty" jsonschema:"which website, by its number in seo_sites; 0 for the first"` +} + +type changeEditArgs struct { + ID int64 `json:"id" jsonschema:"the proposed change's id, from seo_changes"` + Title string `json:"title" jsonschema:"the page title it proposes"` + Description string `json:"description" jsonschema:"the meta description it proposes"` +} + +// seoSiteAt is a website by its number. +func (s *Server) seoSiteAt(i int) (*seoSite, error) { + for _, st := range s.seoSites() { + if st.Index == i { + return &st, nil + } + } + return nil, fmt.Errorf("no website %d: seo_sites lists them", i) +} + +func (s *Server) seoReadTools(srv *mcp.Server) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "seo_sites", + Description: "The company's websites, by number, with their Search Console property and when it was last synced.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) { + return toolJSON(nonNilList(s.seoSites())) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "seo_morning_check", + Description: "The morning check: this week against last, from Search Console: the pages and searches that really moved, clicks by day, gains and losses.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) { + st, err := s.seoSiteAt(a.Site) + if err != nil { + return nil, nil, err + } + if st.Property == "" { + return nil, nil, errors.New("this website has no Search Console property yet") + } + ch, err := seo.MorningCheck(s.DB, s.scope(*st), seo.LoadSettings(s.DB)) + if err != nil { + return nil, nil, err + } + if ch == nil { + return toolJSON(map[string]string{"status": "There isn't two weeks of Search Console data yet."}) + } + return toolJSON(ch) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "seo_next", + Description: "What to write next: pages, sections and posts worth making, from what converts, what's stalled, signals without pages and apps people mention, " + + "best first, each with why (the numbers behind it).", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) { + st, err := s.seoSiteAt(a.Site) + if err != nil { + return nil, nil, err + } + list, more, err := s.nextFor(*st, time.Now()) + if err != nil { + return nil, nil, err + } + type item struct { + Key, Kind, Title, Why string + Score float64 + } + out := []item{} + for _, sg := range list { + out = append(out, item{sg.Key, sg.Kind, sg.Title, sg.Why, sg.Score}) + } + return toolJSON(map[string]any{"suggestions": out, "more": more}) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "seo_links", + Description: "Links to the website: the ones known (and whether they still link), and the places worth asking for one.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) { + st, err := s.seoSiteAt(a.Site) + if err != nil { + return nil, nil, err + } + links, err := backlinks.Links(s.DB, st.URL) + if err != nil { + return nil, nil, err + } + return toolJSON(nonNilList(links)) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "seo_changes", + Description: "Changes to pages' titles and descriptions: proposed ones waiting for a person's yes, and those made, with what they did to clicks.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) { + st, err := s.seoSiteAt(a.Site) + if err != nil { + return nil, nil, err + } + list, err := seo.Changes(s.DB, auditKey(*st), 100) + if err != nil { + return nil, nil, err + } + return toolJSON(nonNilList(list)) + }) +} + +func (s *Server) seoActTools(srv *mcp.Server, c *mcpserver.Caller) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "seo_edit_change", + Description: "Rewrite a proposed change's title and description, before a person says yes to it. " + + "Saying yes (which opens the pull request) is a person's.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a changeEditArgs) (*mcp.CallToolResult, any, error) { + if err := seo.EditChange(s.DB, a.ID, a.Title, a.Description); err != nil { + return nil, nil, err + } + ch, err := seo.GetChange(s.DB, a.ID) + if err != nil { + return nil, nil, err + } + s.auditAgent(c, "edited-change", ch.Page, "") + return toolJSON(ch) + }) +} + +// --- Sites --- + +func (s *Server) sitesReadTools(srv *mcp.Server) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "sites_list", + Description: "The company's websites and the Gitea repository each is built from.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) { + return toolJSON(nonNilList(s.siteRepos())) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "sites_new_pages", + Description: "New pages being made for a website: their kind, signal, sections, and whether they're previewed or in a pull request.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) { + for _, st := range s.siteRepos() { + if st.Index == a.Site { + ps, err := sites.Pages(s.DB, st.URL) + if err != nil { + return nil, nil, err + } + return toolJSON(nonNilList(ps)) + } + } + return nil, nil, fmt.Errorf("no website %d: sites_list lists them", a.Site) + }) +} + +// --- Metrics --- + +func (s *Server) metricsReadTools(srv *mcp.Server) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "metrics_months", + Description: "MRR, customers, new, expansion, contraction, churn and NRR month by month (the last 13), from Stripe.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) { + m, err := metrics.Build(s.DB, time.Now()) + if err != nil { + return nil, nil, err + } + months := m.Months + if len(months) > 13 { + months = months[len(months)-13:] + } + return toolJSON(map[string]any{"currency": m.Currency, "months": nonNilList(months)}) + }) +} + +// --- The Market --- + +type marketEntry struct { + ID int64 `json:"id"` + inventory.Entry +} + +type marketGetArgs struct { + ID int64 `json:"id" jsonschema:"the entry's id, from market_list"` +} + +type marketSaveArgs struct { + inventory.Entry +} + +func (s *Server) marketReadTools(srv *mcp.Server) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "market_list", + Description: "The Market's entries with their ids: partners, competitors and projects watched, with accounts, keywords, talking points and prices.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) { + list, err := inventory.List(s.DB, "") + if err != nil { + return nil, nil, err + } + out := []marketEntry{} + for _, e := range list { + out = append(out, marketEntry{e.ID, e}) + } + return toolJSON(out) + }) + mcp.AddTool(srv, &mcp.Tool{ + Name: "market_get", + Description: "One Market entry, by id.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a marketGetArgs) (*mcp.CallToolResult, any, error) { + e, err := inventory.Get(s.DB, a.ID) + if err != nil { + return nil, nil, err + } + return toolJSON(marketEntry{e.ID, *e}) + }) +} + +func (s *Server) marketActTools(srv *mcp.Server, c *mcpserver.Caller) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "market_save", + Description: "Add a Market entry, or change the one with the same name (every field is replaced: read it first with market_get). " + + "relationship is partner, competitor or watch.", + }, func(ctx context.Context, _ *mcp.CallToolRequest, a marketSaveArgs) (*mcp.CallToolResult, any, error) { + e := a.Entry + list, err := inventory.List(s.DB, "") + if err != nil { + return nil, nil, err + } + action := "added" + for _, old := range list { + if strings.EqualFold(old.Name, strings.TrimSpace(e.Name)) { + e.ID, action = old.ID, "changed" + } + } + if err := inventory.Save(s.DB, &e); err != nil { + return nil, nil, err + } + s.auditAgent(c, "market-"+action, e.Name, "") + return toolJSON(marketEntry{e.ID, e}) + }) +} + +// nonNilList keeps an empty list a list in JSON ([] rather than null). +func nonNilList[T any](v []T) []T { + if v == nil { + return []T{} + } + return v +} diff --git a/internal/web/agenttools_test.go b/internal/web/agenttools_test.go new file mode 100644 index 0000000..e31720f --- /dev/null +++ b/internal/web/agenttools_test.go @@ -0,0 +1,164 @@ +package web + +import ( + "bytes" + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + "supermarket/internal/audit" + "supermarket/internal/content" + "supermarket/internal/profile" + "supermarket/internal/users" +) + +// mcpCall calls a tool with a key: its text, and whether it was an error. +func mcpCall(t *testing.T, h http.Handler, key, tool string, args map[string]any) (string, bool) { + t.Helper() + raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 2, "method": "tools/call", + "params": map[string]any{"name": tool, "arguments": args}}) + rec := do(h, http.MethodPost, "/mcp", bytes.NewReader(raw), map[string]string{ + "Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Authorization": "Bearer " + key}) + if rec.Code != http.StatusOK { + t.Fatalf("%s: %d %s", tool, rec.Code, rec.Body.String()) + } + var out struct { + Result struct { + Content []struct{ Text string } `json:"content"` + IsError bool `json:"isError"` + } `json:"result"` + Error *struct{ Message string } `json:"error"` + } + json.Unmarshal(rec.Body.Bytes(), &out) + if out.Error != nil { + return out.Error.Message, true + } + text := "" + if len(out.Result.Content) > 0 { + text = out.Result.Content[0].Text + } + return text, out.Result.IsError +} + +// newAgent makes an agent with scopes and returns its key. +func newAgent(t *testing.T, s *Server, name string, scopes map[string]users.Access) (*users.User, string) { + t.Helper() + u, err := users.CreateAgent(s.DB, name, "", time.Now()) + if err != nil { + t.Fatal(err) + } + if err := users.Join(s.DB, users.Team, u.ID, users.Member, scopes, time.Now()); err != nil { + t.Fatal(err) + } + key, _, err := users.NewKey(s.DB, u.ID, time.Time{}, time.Now()) + if err != nil { + t.Fatal(err) + } + return u, key +} + +func TestAgentModuleTools(t *testing.T) { + s, h := newTestServer(t, nil) + profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}}) + writer, key := newAgent(t, s, "Morning writer", map[string]users.Access{"content": users.Edit, "seo": users.View}) + + _, tools := mcpTools(h, key) + got := " " + strings.Join(tools, " ") + " " + for _, want := range []string{"profile_get", "content_drafts", "content_items", "content_create_draft", "content_edit_draft", + "seo_sites", "seo_morning_check", "seo_next", "seo_links", "seo_changes"} { + if !strings.Contains(got, " "+want+" ") { + t.Errorf("missing %s: %v", want, tools) + } + } + for _, not := range []string{"seo_edit_change", "crm_pending_actions", "market_save", "market_list", "outreach_list", "metrics_months", "sites_list"} { + if strings.Contains(got, " "+not+" ") { + t.Errorf("offered %s", not) + } + } + + // Reading SEO works (no Search Console yet: it says so). + if text, isErr := mcpCall(t, h, key, "seo_morning_check", map[string]any{"site": 0}); !isErr || !strings.Contains(text, "Search Console") { + t.Errorf("morning check: %v %s", isErr, text) + } + if text, isErr := mcpCall(t, h, key, "seo_next", map[string]any{}); isErr || !strings.Contains(text, `"suggestions"`) { + t.Errorf("next: %v %s", isErr, text) + } + // A tool it isn't offered fails. + if _, isErr := mcpCall(t, h, key, "seo_edit_change", map[string]any{"id": 1, "title": "x", "description": "y"}); !isErr { + t.Error("called a tool it doesn't have") + } + + // It writes a draft: it waits in Posts, by the agent. + text, isErr := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Widgets, now faster.", "source_url": "https://acme.example/new"}) + if isErr { + t.Fatalf("create: %s", text) + } + var d draftView + json.Unmarshal([]byte(text), &d) + if d.ID == 0 || d.Status != content.StatusDraft || d.Limit != 280 { + t.Errorf("draft %+v", d) + } + saved, _ := content.GetDraft(s.DB, d.ID) + if saved.WrittenBy != writer.ID { + t.Errorf("written by %d", saved.WrittenBy) + } + if body := do(h, http.MethodGet, "/posts", nil, nil).Body.String(); !strings.Contains(body, "by Morning writer") { + t.Error("Posts doesn't say which agent wrote it") + } + if _, isErr := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "reddit", "text": "x"}); !isErr { + t.Error("a Reddit draft without a title") + } + if _, isErr := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "myspace", "text": "x"}); !isErr { + t.Error("an unknown channel") + } + text, _ = mcpCall(t, h, key, "content_edit_draft", map[string]any{"id": d.ID, "text": "Widgets, faster than ever."}) + if !strings.Contains(text, "faster than ever") { + t.Errorf("edit: %s", text) + } + text, _ = mcpCall(t, h, key, "content_drafts", map[string]any{}) + if !strings.Contains(text, "faster than ever") { + t.Errorf("list: %s", text) + } + // What it did is in the log, as an agent. + entries, _ := audit.List(s.DB, audit.Filter{UserID: writer.ID}, 10) + if len(entries) != 2 || entries[0].Kind != audit.Agent || entries[1].Action != "wrote-draft" { + t.Errorf("log: %+v", entries) + } +} + +func TestAgentMarketAndProspectsTools(t *testing.T) { + s, h := newTestServer(t, nil) + _, key := newAgent(t, s, "Researcher", map[string]users.Access{"market": users.Edit, "prospects": users.View, "metrics": users.View}) + _, tools := mcpTools(h, key) + got := " " + strings.Join(tools, " ") + " " + for _, want := range []string{"market_list", "market_save", "signals_list", "prospects_review", "outreach_list", "suppression_list", "metrics_months"} { + if !strings.Contains(got, " "+want+" ") { + t.Errorf("missing %s", want) + } + } + for _, not := range []string{"outreach_draft", "suppress", "content_create_draft"} { + if strings.Contains(got, " "+not+" ") { + t.Errorf("offered %s", not) + } + } + text, isErr := mcpCall(t, h, key, "market_save", map[string]any{"name": "Rival", "relationship": "competitor", "description": "They sell widgets too."}) + if isErr || !strings.Contains(text, `"id":`) { + t.Fatalf("save: %s", text) + } + // The same name again changes it, not a second entry. + mcpCall(t, h, key, "market_save", map[string]any{"name": "rival", "relationship": "competitor", "description": "Cheaper widgets."}) + text, _ = mcpCall(t, h, key, "market_list", map[string]any{}) + if strings.Count(text, `"name"`) != 1 || !strings.Contains(text, "Cheaper widgets.") { + t.Errorf("list: %s", text) + } + if _, isErr := mcpCall(t, h, key, "market_save", map[string]any{"name": "X", "relationship": "friend"}); !isErr { + t.Error("bad relationship accepted") + } + for _, tool := range []string{"signals_list", "prospects_review", "outreach_list", "suppression_list", "metrics_months"} { + if text, isErr := mcpCall(t, h, key, tool, map[string]any{}); isErr { + t.Errorf("%s: %s", tool, text) + } + } +} diff --git a/internal/web/server_test.go b/internal/web/server_test.go index b6e02e2..e3f4865 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -56,7 +56,7 @@ func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) { PublicURL: "http://localhost:8470", Version: "test", MCPToken: testToken, Log: slog.New(slog.NewTextHandler(io.Discard, nil)), } - s.MCP = mcpserver.Handler(d, "test", s.AgentAuth) + s.MCP = mcpserver.Handler(d, "test", s.AgentAuth, s.AgentTools) if err := s.EnsureHermes(testToken); err != nil { t.Fatal(err) }