Phase 11, part 1: agents and their keys
Agents are users of kind agent, each given modules to read, or to read and act on, and the CRM scope. Admins make them under Settings → Agents, on every edition; keys (sm_…) are shown once and kept as hashes, can expire, be rotated (the old one works a day) or revoked, and record their last use. /mcp takes agent keys and offers each agent only the tools its scopes allow. On the local edition, mcp-token is the key of a built-in Hermes agent with the CRM and the Market. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+192
-127
@@ -5,7 +5,6 @@ package mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -14,6 +13,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
@@ -25,27 +25,86 @@ import (
|
||||
"supermarket/internal/profile"
|
||||
)
|
||||
|
||||
// Handler returns the /mcp handler. Requests without "Authorization: Bearer
|
||||
// <token>" are refused.
|
||||
func Handler(d *db.DB, token, version string) http.Handler {
|
||||
server := newServer(d, version)
|
||||
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server },
|
||||
&mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})
|
||||
// Caller is the agent a request comes from, and what it may do.
|
||||
type Caller struct {
|
||||
ID int64
|
||||
Name string
|
||||
// Can says whether the agent may read (act false) or change things in
|
||||
// a module or scope (market, crm, …).
|
||||
Can func(scope string, act bool) bool
|
||||
}
|
||||
|
||||
// Authenticator finds the caller of a request from its bearer key; an
|
||||
// error refuses it.
|
||||
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 {
|
||||
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 {
|
||||
c, _ := r.Context().Value(callerKey{}).(*Caller)
|
||||
sig := signature(c)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if srv, ok := servers[sig]; ok {
|
||||
return srv
|
||||
}
|
||||
srv := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil)
|
||||
addTools(srv, d, c)
|
||||
servers[sig] = srv
|
||||
return srv
|
||||
}, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
if !ok || token == "" || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 {
|
||||
key, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
var c *Caller
|
||||
var err error
|
||||
if ok && key != "" {
|
||||
c, err = auth(r, strings.TrimSpace(key))
|
||||
}
|
||||
if !ok || key == "" || err != nil || c == nil {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="supermarket"`)
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
h.ServeHTTP(w, r)
|
||||
h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), callerKey{}, c)))
|
||||
})
|
||||
}
|
||||
|
||||
type callerKey struct{}
|
||||
|
||||
// scopes are what tools are offered by: each, read or act.
|
||||
var scopes = []string{"market", "crm"}
|
||||
|
||||
// signature names the tools a caller gets.
|
||||
func signature(c *Caller) string {
|
||||
if c == nil {
|
||||
return "*"
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, sc := range scopes {
|
||||
switch {
|
||||
case c.Can(sc, true):
|
||||
b.WriteString(sc + ":act,")
|
||||
case c.Can(sc, false):
|
||||
b.WriteString(sc + ":read,")
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// can says whether the caller (nil: the local socket, everything) may use
|
||||
// a scope.
|
||||
func can(c *Caller, scope string, act bool) bool {
|
||||
return c == nil || c.Can(scope, act)
|
||||
}
|
||||
|
||||
func newServer(d *db.DB, version string) *mcp.Server {
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil)
|
||||
addTools(server, d)
|
||||
addTools(server, d, nil)
|
||||
return server
|
||||
}
|
||||
|
||||
@@ -159,7 +218,8 @@ type checkinArgs struct {
|
||||
Note string `json:"note,omitempty" jsonschema:"a short note on anything that failed"`
|
||||
}
|
||||
|
||||
func addTools(s *mcp.Server, d *db.DB) {
|
||||
// addTools adds the tools the caller may use (nil: all).
|
||||
func addTools(s *mcp.Server, d *db.DB, c *Caller) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "profile_get",
|
||||
Description: "The company profile: what the company sells, its products, target customers, voice, websites, social accounts and keywords.",
|
||||
@@ -172,123 +232,128 @@ func addTools(s *mcp.Server, d *db.DB) {
|
||||
return res, nil, err
|
||||
})
|
||||
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "inventory_list",
|
||||
Description: "The Market: partners (whose news we amplify), competitors (whom we position against) and projects we watch, with their accounts, keywords and talking points.",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, args inventoryArgs) (*mcp.CallToolResult, any, error) {
|
||||
entries, err := inventory.List(d, strings.ToLower(strings.TrimSpace(args.Relationship)))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if entries == nil {
|
||||
entries = []inventory.Entry{}
|
||||
}
|
||||
res, err := jsonResult(entries)
|
||||
return res, nil, err
|
||||
})
|
||||
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "crm_pending_actions",
|
||||
Description: "The CRM work Supermarket has queued for you: records to create in EspoCRM, and whether to copy recently " +
|
||||
"changed CRM records back to Supermarket. Call it at the start of each CRM run and follow its instructions exactly.",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) (*mcp.CallToolResult, any, error) {
|
||||
now := time.Now()
|
||||
actions, err := crm.Claim(d, now, 25)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
out := pendingResult{Instructions: crmInstructions, Actions: []pendingAction{}}
|
||||
for _, a := range actions {
|
||||
out.Actions = append(out.Actions, pendingAction{ID: a.ID, Do: a.Kind, Entity: a.Entity, Fields: a.Fields, FindExisting: a.Match})
|
||||
}
|
||||
due, since, err := crm.SyncDue(d, now)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if due {
|
||||
if err := crm.StartSync(d, now); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
req := &syncRequest{Entities: crm.SyncEntities, Fields: crmSyncFields}
|
||||
if !since.IsZero() {
|
||||
// A little overlap, so nothing changed during the last sync is missed.
|
||||
req.ModifiedSince = since.Add(-10 * time.Minute).UTC().Format("2006-01-02 15:04:05")
|
||||
}
|
||||
out.Sync = req
|
||||
}
|
||||
res, err := jsonResult(out)
|
||||
return res, nil, err
|
||||
})
|
||||
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "crm_report_result",
|
||||
Description: "Report the result of one action from crm_pending_actions: created (with the new record's id), existing (with the matching record's id), or failed (with the error).",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, args reportArgs) (*mcp.CallToolResult, any, error) {
|
||||
err := crm.Report(d, args.ID, crm.Result{Outcome: strings.ToLower(strings.TrimSpace(args.Outcome)), EspoID: args.EspoID, Error: args.Error}, time.Now())
|
||||
if err != nil {
|
||||
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}}}, nil, nil
|
||||
}
|
||||
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "Recorded."}}}, nil, nil
|
||||
})
|
||||
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "crm_ingest",
|
||||
Description: "Send Supermarket the CRM records crm_pending_actions asked you to sync, in batches; set done=true on the last call.",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, args ingestArgs) (*mcp.CallToolResult, any, error) {
|
||||
entity := strings.TrimSpace(args.Entity)
|
||||
known := false
|
||||
for _, e := range crm.SyncEntities {
|
||||
known = known || strings.EqualFold(e, entity)
|
||||
if strings.EqualFold(e, entity) {
|
||||
entity = e
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{
|
||||
Text: "entity must be one of " + strings.Join(crm.SyncEntities, ", ")}}}, nil, nil
|
||||
}
|
||||
now := time.Now()
|
||||
var recs []crm.Record
|
||||
skipped := 0
|
||||
for _, f := range args.Records {
|
||||
r, err := crm.RecordFrom(entity, f, now)
|
||||
if can(c, "market", false) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "inventory_list",
|
||||
Description: "The Market: partners (whose news we amplify), competitors (whom we position against) and projects we watch, with their accounts, keywords and talking points.",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, args inventoryArgs) (*mcp.CallToolResult, any, error) {
|
||||
entries, err := inventory.List(d, strings.ToLower(strings.TrimSpace(args.Relationship)))
|
||||
if err != nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
recs = append(recs, r)
|
||||
}
|
||||
if err := crm.Ingest(d, recs); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if args.Done {
|
||||
if err := crm.FinishSync(d, now); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
msg := fmt.Sprintf("Stored %d %s record(s).", len(recs), entity)
|
||||
if skipped > 0 {
|
||||
msg += fmt.Sprintf(" Skipped %d without an id.", skipped)
|
||||
}
|
||||
if args.Done {
|
||||
msg += " Sync finished."
|
||||
}
|
||||
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: msg}}}, nil, nil
|
||||
})
|
||||
if entries == nil {
|
||||
entries = []inventory.Entry{}
|
||||
}
|
||||
res, err := jsonResult(entries)
|
||||
return res, nil, err
|
||||
})
|
||||
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "bridge_checkin",
|
||||
Description: "Tell Supermarket that the agent can reach it and the Core's mcphub MCP server. Call it with the names of the mcphub tools you have.",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, args checkinArgs) (*mcp.CallToolResult, any, error) {
|
||||
agent := strings.TrimSpace(args.Agent)
|
||||
if agent == "" {
|
||||
agent = "unknown"
|
||||
}
|
||||
if err := bridge.Record(d, bridge.Checkin{Agent: agent, MCPHubTools: args.MCPHubTools, Note: strings.TrimSpace(args.Note)}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{
|
||||
Text: "Checked in. Supermarket has recorded the mcphub tools you can use.",
|
||||
}}}, nil, nil
|
||||
})
|
||||
}
|
||||
// The CRM queue, worked through the Core (Hermes' bridge).
|
||||
if can(c, "crm", true) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "crm_pending_actions",
|
||||
Description: "The CRM work Supermarket has queued for you: records to create in EspoCRM, and whether to copy recently " +
|
||||
"changed CRM records back to Supermarket. Call it at the start of each CRM run and follow its instructions exactly.",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) (*mcp.CallToolResult, any, error) {
|
||||
now := time.Now()
|
||||
actions, err := crm.Claim(d, now, 25)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
out := pendingResult{Instructions: crmInstructions, Actions: []pendingAction{}}
|
||||
for _, a := range actions {
|
||||
out.Actions = append(out.Actions, pendingAction{ID: a.ID, Do: a.Kind, Entity: a.Entity, Fields: a.Fields, FindExisting: a.Match})
|
||||
}
|
||||
due, since, err := crm.SyncDue(d, now)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if due {
|
||||
if err := crm.StartSync(d, now); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
req := &syncRequest{Entities: crm.SyncEntities, Fields: crmSyncFields}
|
||||
if !since.IsZero() {
|
||||
// A little overlap, so nothing changed during the last sync is missed.
|
||||
req.ModifiedSince = since.Add(-10 * time.Minute).UTC().Format("2006-01-02 15:04:05")
|
||||
}
|
||||
out.Sync = req
|
||||
}
|
||||
res, err := jsonResult(out)
|
||||
return res, nil, err
|
||||
})
|
||||
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "crm_report_result",
|
||||
Description: "Report the result of one action from crm_pending_actions: created (with the new record's id), existing (with the matching record's id), or failed (with the error).",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, args reportArgs) (*mcp.CallToolResult, any, error) {
|
||||
err := crm.Report(d, args.ID, crm.Result{Outcome: strings.ToLower(strings.TrimSpace(args.Outcome)), EspoID: args.EspoID, Error: args.Error}, time.Now())
|
||||
if err != nil {
|
||||
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}}}, nil, nil
|
||||
}
|
||||
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "Recorded."}}}, nil, nil
|
||||
})
|
||||
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "crm_ingest",
|
||||
Description: "Send Supermarket the CRM records crm_pending_actions asked you to sync, in batches; set done=true on the last call.",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, args ingestArgs) (*mcp.CallToolResult, any, error) {
|
||||
entity := strings.TrimSpace(args.Entity)
|
||||
known := false
|
||||
for _, e := range crm.SyncEntities {
|
||||
known = known || strings.EqualFold(e, entity)
|
||||
if strings.EqualFold(e, entity) {
|
||||
entity = e
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{
|
||||
Text: "entity must be one of " + strings.Join(crm.SyncEntities, ", ")}}}, nil, nil
|
||||
}
|
||||
now := time.Now()
|
||||
var recs []crm.Record
|
||||
skipped := 0
|
||||
for _, f := range args.Records {
|
||||
r, err := crm.RecordFrom(entity, f, now)
|
||||
if err != nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
recs = append(recs, r)
|
||||
}
|
||||
if err := crm.Ingest(d, recs); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if args.Done {
|
||||
if err := crm.FinishSync(d, now); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
msg := fmt.Sprintf("Stored %d %s record(s).", len(recs), entity)
|
||||
if skipped > 0 {
|
||||
msg += fmt.Sprintf(" Skipped %d without an id.", skipped)
|
||||
}
|
||||
if args.Done {
|
||||
msg += " Sync finished."
|
||||
}
|
||||
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: msg}}}, nil, nil
|
||||
})
|
||||
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "bridge_checkin",
|
||||
Description: "Tell Supermarket that the agent can reach it and the Core's mcphub MCP server. Call it with the names of the mcphub tools you have.",
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, args checkinArgs) (*mcp.CallToolResult, any, error) {
|
||||
agent := strings.TrimSpace(args.Agent)
|
||||
if agent == "" {
|
||||
agent = "unknown"
|
||||
}
|
||||
if err := bridge.Record(d, bridge.Checkin{Agent: agent, MCPHubTools: args.MCPHubTools, Note: strings.TrimSpace(args.Note)}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{
|
||||
Text: "Checked in. Supermarket has recorded the mcphub tools you can use.",
|
||||
}}}, nil, nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user