// Package mcpserver exposes the app's data and actions to agents over MCP: // at /mcp behind a bearer token (Claude Code), and on a Unix socket in the // data folder (Hermes). package mcpserver import ( "context" "crypto/subtle" "encoding/json" "errors" "log/slog" "net" "net/http" "os" "strings" "github.com/modelcontextprotocol/go-sdk/mcp" "supermarket/internal/bridge" "supermarket/internal/db" "supermarket/internal/inventory" "supermarket/internal/profile" ) // Handler returns the /mcp handler. Requests without "Authorization: Bearer // " 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}) 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 { w.Header().Set("WWW-Authenticate", `Bearer realm="supermarket"`) http.Error(w, "unauthorized", http.StatusUnauthorized) return } h.ServeHTTP(w, r) }) } func newServer(d *db.DB, version string) *mcp.Server { server := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil) addTools(server, d) return server } // ServeSocket serves MCP on a Unix socket at path, one stdio-style session // (newline-delimited JSON-RPC) per connection, until ctx ends. // // This is how Hermes reaches the app. CoreDesktop runs Hermes in a sandbox // with its own network, where 127.0.0.1:8470 isn't this computer's, so Hermes // runs `socat STDIO UNIX-CONNECT:` as a stdio MCP server instead. The // socket has no token: it is only usable by you (the umask makes it 0700), // and anything that can open it can read mcp-token in the same folder anyway. func ServeSocket(ctx context.Context, d *db.DB, version, path string, log *slog.Logger) error { // A socket left by the last run would make Listen fail. if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { return err } ln, err := net.Listen("unix", path) if err != nil { return err } if err := os.Chmod(path, 0o600); err != nil { ln.Close() return err } go func() { <-ctx.Done() ln.Close() }() server := newServer(d, version) for { conn, err := ln.Accept() if err != nil { if ctx.Err() != nil { return nil } return err } go func() { defer conn.Close() err := server.Run(ctx, &mcp.IOTransport{Reader: conn, Writer: conn}) if err != nil && ctx.Err() == nil && !errors.Is(err, net.ErrClosed) { log.Debug("MCP socket session ended", "err", err) } }() } } func jsonResult(v any) (*mcp.CallToolResult, error) { raw, err := json.MarshalIndent(v, "", " ") if err != nil { return nil, err } return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: string(raw)}}}, nil } type noArgs struct{} type inventoryArgs struct { Relationship string `json:"relationship,omitempty" jsonschema:"only entries with this relationship: partner, competitor or watch; empty for all"` } type checkinArgs struct { Agent string `json:"agent" jsonschema:"who is checking in, e.g. hermes"` MCPHubTools []string `json:"mcphub_tools" jsonschema:"names of the tools the agent has from the Core's mcphub MCP server"` Note string `json:"note,omitempty" jsonschema:"a short note on anything that failed"` } func addTools(s *mcp.Server, d *db.DB) { 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.", }, func(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) (*mcp.CallToolResult, any, error) { p, err := profile.Load(d) if err != nil { return nil, nil, err } res, err := jsonResult(p) return res, nil, err }) mcp.AddTool(s, &mcp.Tool{ Name: "inventory_list", Description: "The inventory: 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: "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 }) }