From aa6c3ca390b65a955df6cd469ec22ce8096defed Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 11:22:22 -0700 Subject: [PATCH] Phase 11, part 5: the JSON API /api/v1 offers the MCP tools as plain HTTP for scripts: GET /api/v1/tools lists what a key may call, POST /api/v1/ calls one with JSON. Each call goes through /mcp internally, so keys, scopes, limits, logging and approvals are the same. /api/v1/docs documents every tool. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 36 +++-- README.md | 2 +- internal/mcpserver/mcpserver.go | 26 ++++ internal/web/access.go | 2 + internal/web/api.go | 213 +++++++++++++++++++++++++++ internal/web/api_test.go | 89 +++++++++++ internal/web/auth.go | 2 +- internal/web/server.go | 3 + internal/web/static/app.css | 1 + internal/web/templates/api-docs.html | 26 ++++ 10 files changed, 387 insertions(+), 13 deletions(-) create mode 100644 internal/web/api.go create mode 100644 internal/web/api_test.go create mode 100644 internal/web/templates/api-docs.html diff --git a/PLAN.md b/PLAN.md index 0b2154d..eeca61a 100644 --- a/PLAN.md +++ b/PLAN.md @@ -43,19 +43,19 @@ fixed. Since then: - Listmonk mailing lists, with their opt-outs synced to suppression. - Phase 9: the groundwork for the server and multi-tenant editions. -The local edition runs as before, its database at schema 36 once Phase 10 -is merged. The server edition runs; multi-tenant checks its settings but -won't start until Phase 13. +The local edition runs as before, its database at schema 39 with Phase 11. +The server edition runs; multi-tenant checks its settings but won't start +until Phase 13. -**Phase 10 (users, sign-in and roles; the server edition) is built** on -branch `phase10` (2026-11-25), not yet merged: schema 36, a new -`compose.server.yaml` and `install-server.sh`. On the local edition, -the visible changes are posting accounts, Connections, Activity, and a -CSRF token in every form. +**Phase 10 (users, sign-in and roles; the server edition) is built and +merged** (2026-11-25): a new `compose.server.yaml` and `install-server.sh`. -**Next: Phase 11, agents.** Parts 1–4 (agent users and keys, module tools -over MCP, approvals, limits and visibility) are built on branch `phase11`; -part 5 (a JSON API) can wait until someone needs it. Phase 12 still needs who adds Supermarket's client to +**Phase 11 (agents) is built** (2026-11-26): agent users and keys, module +tools over MCP, approvals, limits and visibility, and the JSON API. Schema +39. + +**Next: Phase 12, signing in with the Core (OIDC).** Still open: who adds +Supermarket's client to Authelia. Phase 12 still needs who adds Supermarket's client to Authelia. **Coming back to it (for the agent working on it):** @@ -2642,6 +2642,20 @@ single `mcp-token`. A commit after each part. two agents with the same scopes shared one, and the tools recorded the first as the writer of what both wrote. Now each agent has its own. +**Part 5 built 2026-11-26** on `phase11`. **Phase 11 is built.** +- `/api/v1`: `GET /api/v1/tools` (what the key may call, with each tool's + input schema) and `POST /api/v1/` (the arguments as a JSON object; + the tool's answer as JSON). Each call is handed to `/mcp` internally, as + the same JSON-RPC call with the same key and address, so the keys, + scopes, limits, pause, call log, audit and approvals are exactly MCP's: + there's one set of tools, not two. +- Errors are `{"error": …}`: 401 (key), 403 (paused), 404 (a tool the key + isn't given), 400 (arguments), 422 (the tool said no), 429 (calls a + minute). No form token: the API, like `/mcp`, has its key instead. +- `/api/v1/docs` (no key needed) documents every tool, by scope, from the + tools themselves (an in-memory MCP session lists them), with how to call + them and an example. + 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/README.md b/README.md index 2228057..5332a3d 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,7 @@ The old terminal app used `http://localhost:8080/callback`; you can remove that - The port is published on `127.0.0.1` only, so other machines can't reach it, whatever the firewall says. - The local edition has no login, so it protects itself from web pages open in the same browser: it only answers requests addressed to `localhost` (against DNS rebinding), and refuses form posts that don't come from its own pages: each form carries a random token that another site can't know, and the browser's `Origin` must be the app's own. - The container runs as you, with a read-only filesystem, no Linux capabilities and `no-new-privileges`. It can write only its data folder. -- `/mcp` requires an agent's key (Settings → Agents). The key in `mcp-token` belongs to the built-in Hermes agent, which may work the CRM queue and read the Market; each agent gets only the tools for what it was given. +- `/mcp`, and the same tools as a JSON API at `/api/v1` (documented at `/api/v1/docs`), require an agent's key (Settings → Agents). Anything an agent asks to send out waits on Approvals for a person, unless that kind was allowed on its own. The key in `mcp-token` belongs to the built-in Hermes agent, which may work the CRM queue and read the Market; each agent gets only the tools for what it was given. ## The server edition diff --git a/internal/mcpserver/mcpserver.go b/internal/mcpserver/mcpserver.go index c21ac68..5f730dd 100644 --- a/internal/mcpserver/mcpserver.go +++ b/internal/mcpserver/mcpserver.go @@ -413,3 +413,29 @@ func addTools(s *mcp.Server, d *db.DB, c *Caller) { }) } } + +// AllTools lists every tool there is, as an agent with every scope would +// see it: for the API's documentation. +func AllTools(ctx context.Context, d *db.DB, version string, more func(*mcp.Server, *Caller)) ([]*mcp.Tool, error) { + srv := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil) + addTools(srv, d, nil) + if more != nil { + more(srv, nil) + } + ct, st := mcp.NewInMemoryTransports() + ss, err := srv.Connect(ctx, st, nil) + if err != nil { + return nil, err + } + defer ss.Close() + cs, err := mcp.NewClient(&mcp.Implementation{Name: "docs"}, nil).Connect(ctx, ct, nil) + if err != nil { + return nil, err + } + defer cs.Close() + res, err := cs.ListTools(ctx, nil) + if err != nil { + return nil, err + } + return res.Tools, nil +} diff --git a/internal/web/access.go b/internal/web/access.go index 0de64a5..b6a9a7f 100644 --- a/internal/web/access.go +++ b/internal/web/access.go @@ -28,6 +28,8 @@ var routeAreas = map[string]string{ "/static": areaPublic, "=/favicon.ico": areaPublic, "=/healthz": areaPublic, "=/mcp": areaPublic, "/signin": areaPublic, "=/signout": areaPublic, "=/forgot": areaPublic, "/reset": areaPublic, "/setup": areaPublic, "/invite": areaPublic, + // The JSON API: its own keys, like /mcp. + "/api": areaPublic, "=/": areaSignedIn, "=/search": areaSignedIn, "/settings/account": areaSignedIn, "/users": areaSignedIn, "=/settings": areaSignedIn, diff --git a/internal/web/api.go b/internal/web/api.go new file mode 100644 index 0000000..a0653b4 --- /dev/null +++ b/internal/web/api.go @@ -0,0 +1,213 @@ +package web + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sort" + "strings" + "sync" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "supermarket/internal/mcpserver" +) + +// The JSON API, for scripts that aren't MCP clients: /api/v1. It's the MCP +// tools as plain HTTP, with the same keys, scopes, limits, logging and +// approvals, because each call is handed to the agent's MCP server: +// +// GET /api/v1/tools what this key may call, with each one's input schema +// POST /api/v1/ call it: the arguments as a JSON object; the answer as JSON +// GET /api/v1/docs every tool, documented (no key needed) + +const apiMaxBody = 1 << 20 + +// apiError writes {"error": msg}. +func apiError(w http.ResponseWriter, code int, msg string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + _ = json.NewEncoder(w).Encode(map[string]string{"error": msg}) +} + +// rpc hands one JSON-RPC call to /mcp, with the request's key, and returns +// the HTTP status and the JSON-RPC response. +func (s *Server) rpc(r *http.Request, method string, params any) (int, *rpcResponse, string) { + body, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params}) + req := httptest.NewRequestWithContext(r.Context(), http.MethodPost, "/mcp", bytes.NewReader(body)) + req.RemoteAddr = r.RemoteAddr + for _, h := range []string{"Authorization", "X-Forwarded-For"} { + if v := r.Header.Get(h); v != "" { + req.Header.Set(h, v) + } + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + rec := httptest.NewRecorder() + s.MCP.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + return rec.Code, nil, strings.TrimSpace(rec.Body.String()) + } + var out rpcResponse + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + return http.StatusBadGateway, nil, "unreadable answer" + } + return http.StatusOK, &out, "" +} + +type rpcResponse struct { + Result json.RawMessage `json:"result"` + Error *struct { + Code int `json:"code"` + Message string `json:"message"` + } `json:"error"` +} + +// apiTools lists what the key may call. +func (s *Server) apiTools(w http.ResponseWriter, r *http.Request) { + code, res, msg := s.rpc(r, "tools/list", map[string]any{}) + if res == nil { + apiError(w, code, msg) + return + } + var list struct { + Tools []struct { + Name string `json:"name"` + Description string `json:"description"` + InputSchema any `json:"inputSchema"` + } `json:"tools"` + } + if res.Error != nil { + apiError(w, http.StatusBadRequest, res.Error.Message) + return + } + _ = json.Unmarshal(res.Result, &list) + type tool struct { + Name string `json:"name"` + Description string `json:"description"` + Call string `json:"call"` + Input any `json:"input_schema"` + } + out := []tool{} + for _, t := range list.Tools { + out = append(out, tool{t.Name, t.Description, "POST /api/v1/" + t.Name, t.InputSchema}) + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"tools": out}) +} + +// apiCall calls one tool. +func (s *Server) apiCall(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("tool") + args := map[string]any{} + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, apiMaxBody)) + if err != nil { + apiError(w, http.StatusRequestEntityTooLarge, "the body is over 1 MB") + return + } + if len(bytes.TrimSpace(raw)) > 0 { + if err := json.Unmarshal(raw, &args); err != nil { + apiError(w, http.StatusBadRequest, "the body must be a JSON object of the tool's arguments") + return + } + } + code, res, msg := s.rpc(r, "tools/call", map[string]any{"name": name, "arguments": args}) + if res == nil { + apiError(w, code, msg) + return + } + if res.Error != nil { + // An unknown tool, or one this key isn't given; or arguments that + // don't fit its schema; or a limit. + status := http.StatusBadRequest + switch { + case strings.Contains(res.Error.Message, "unknown tool"): + status = http.StatusNotFound + case strings.Contains(res.Error.Message, "too many calls"): + status = http.StatusTooManyRequests + case strings.Contains(res.Error.Message, "paused"): + status = http.StatusForbidden + } + apiError(w, status, res.Error.Message) + return + } + var result struct { + Content []struct { + Text string `json:"text"` + } `json:"content"` + IsError bool `json:"isError"` + } + _ = json.Unmarshal(res.Result, &result) + text := "" + if len(result.Content) > 0 { + text = result.Content[0].Text + } + if result.IsError { + apiError(w, http.StatusUnprocessableEntity, text) + return + } + w.Header().Set("Content-Type", "application/json") + if json.Valid([]byte(text)) { + _, _ = w.Write([]byte(text)) + return + } + _ = json.NewEncoder(w).Encode(map[string]string{"result": text}) +} + +// The documentation: every tool, from the tools themselves. + +var ( + apiDocsOnce sync.Once + apiDocsTools []*mcp.Tool + apiDocsErr error +) + +type apiDoc struct { + Name, Description, Scope, Schema string +} + +// toolScope says which scope offers a tool, for the docs. +func toolScope(name string) string { + switch { + case name == "profile_get" || name == "approvals_status": + return "every agent" + case strings.HasPrefix(name, "crm_") || name == "bridge_checkin": + return "CRM through the Core" + case name == "inventory_list" || strings.HasPrefix(name, "market_"): + return "Market" + case strings.HasPrefix(name, "content_") || name == "posting_accounts": + return "Content" + case strings.HasPrefix(name, "seo_"): + return "SEO" + case strings.HasPrefix(name, "sites_"): + return "Sites" + case strings.HasPrefix(name, "metrics_"): + return "Metrics" + } + return "Prospects" +} + +func (s *Server) apiDocs(w http.ResponseWriter, r *http.Request) { + apiDocsOnce.Do(func() { + apiDocsTools, apiDocsErr = mcpserver.AllTools(r.Context(), s.DB, s.Version, s.AgentTools) + }) + if apiDocsErr != nil { + s.serverError(w, apiDocsErr) + return + } + var docs []apiDoc + for _, t := range apiDocsTools { + schema, _ := json.MarshalIndent(t.InputSchema, "", " ") + docs = append(docs, apiDoc{t.Name, t.Description, toolScope(t.Name), string(schema)}) + } + sort.SliceStable(docs, func(i, j int) bool { + if docs[i].Scope != docs[j].Scope { + return docs[i].Scope < docs[j].Scope + } + return docs[i].Name < docs[j].Name + }) + s.render(w, r, "api-docs", page{Title: "API", Bare: true, Data: map[string]any{ + "Docs": docs, "Base": s.PublicURL + "/api/v1", "MCP": s.mcpURL()}}) +} diff --git a/internal/web/api_test.go b/internal/web/api_test.go new file mode 100644 index 0000000..ac168b7 --- /dev/null +++ b/internal/web/api_test.go @@ -0,0 +1,89 @@ +package web + +import ( + "bytes" + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + "supermarket/internal/users" +) + +func apiDo(h http.Handler, method, path, key, body string) (int, map[string]any) { + var rd *bytes.Reader + if body != "" { + rd = bytes.NewReader([]byte(body)) + } else { + rd = bytes.NewReader(nil) + } + hdr := map[string]string{"Content-Type": "application/json", csrfHeader: ""} + if key != "" { + hdr["Authorization"] = "Bearer " + key + } + rec := do(h, method, path, rd, hdr) + var out map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + var list []any + if json.Unmarshal(rec.Body.Bytes(), &list) == nil { + out = map[string]any{"list": list} + } + } + return rec.Code, out +} + +func TestJSONAPI(t *testing.T) { + s, h := newTestServer(t, nil) + agent, key := newAgent(t, s, "Script", map[string]users.Access{"content": users.Edit, "market": users.View}) + + // Without a key, or a wrong one: 401. No form token needed. + if code, _ := apiDo(h, http.MethodGet, "/api/v1/tools", "", ""); code != http.StatusUnauthorized { + t.Errorf("no key: %d", code) + } + if code, _ := apiDo(h, http.MethodPost, "/api/v1/content_drafts", "sm_wrong", "{}"); code != http.StatusUnauthorized { + t.Errorf("wrong key: %d", code) + } + code, out := apiDo(h, http.MethodGet, "/api/v1/tools", key, "") + raw, _ := json.Marshal(out) + if code != http.StatusOK || !strings.Contains(string(raw), `"name":"content_create_draft"`) || strings.Contains(string(raw), "seo_next") || + !strings.Contains(string(raw), `"input_schema"`) { + t.Fatalf("tools: %d %s", code, raw) + } + // A call, its JSON answer. + code, out = apiDo(h, http.MethodPost, "/api/v1/content_create_draft", key, `{"channel": "x", "text": "From a script."}`) + if code != http.StatusOK || out["status"] != "draft" || out["text"] != "From a script." { + t.Fatalf("create: %d %v", code, out) + } + code, out = apiDo(h, http.MethodPost, "/api/v1/content_drafts", key, "") + if code != http.StatusOK || len(out["list"].([]any)) != 1 { + t.Errorf("list: %d %v", code, out) + } + // Errors. + if code, out := apiDo(h, http.MethodPost, "/api/v1/content_create_draft", key, `{"channel": "myspace", "text": "x"}`); code != http.StatusUnprocessableEntity || out["error"] == nil { + t.Errorf("tool says no: %d %v", code, out) + } + if code, _ := apiDo(h, http.MethodPost, "/api/v1/seo_next", key, `{}`); code != http.StatusNotFound { + t.Errorf("not given: %d", code) + } + if code, _ := apiDo(h, http.MethodPost, "/api/v1/content_drafts", key, `[1, 2]`); code != http.StatusBadRequest { + t.Errorf("not an object: %d", code) + } + // The same limits and log as MCP. + if calls, _ := users.RecentCalls(s.DB, agent.ID, 10); len(calls) < 3 || calls[len(calls)-1].Tool != "content_create_draft" { + t.Errorf("calls %+v", calls) + } + users.Pause(s.DB, agent.ID, true, 0, time.Now()) + if code, _ := apiDo(h, http.MethodPost, "/api/v1/content_drafts", key, ""); code != http.StatusForbidden { + t.Errorf("paused: %d", code) + } + + // The docs: every tool, no key. + rec := do(h, http.MethodGet, "/api/v1/docs", nil, nil) + body := rec.Body.String() + for _, want := range []string{`id="content_publish"`, `id="seo_morning_check"`, `id="crm_pending_actions"`, `id="metrics_months"`, "Authorization: Bearer"} { + if !strings.Contains(body, want) { + t.Errorf("docs lack %s", want) + } + } +} diff --git a/internal/web/auth.go b/internal/web/auth.go index e7674bc..3fb4934 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -215,7 +215,7 @@ func (s *Server) csrf(next http.Handler) http.Handler { if c, err := r.Cookie(name); err == nil && len(c.Value) >= 32 { token = c.Value } - if !safeMethod(r.Method) && r.URL.Path != "/mcp" { + if !safeMethod(r.Method) && r.URL.Path != "/mcp" && !strings.HasPrefix(r.URL.Path, "/api/v1/") { if token == "" || !sameToken(token, sentToken(r)) { http.Error(w, "This form has expired: reload the page and try again.", http.StatusForbidden) return diff --git a/internal/web/server.go b/internal/web/server.go index 5003c75..9a79d51 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -344,6 +344,9 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("GET /settings/about", s.aboutPage) mux.HandleFunc("GET /settings/connections", s.connectionsPage) mux.HandleFunc("GET /settings/activity", s.activityPage) + mux.HandleFunc("GET /api/v1/docs", s.apiDocs) + mux.HandleFunc("GET /api/v1/tools", s.apiTools) + mux.HandleFunc("POST /api/v1/{tool}", s.apiCall) mux.HandleFunc("GET /approvals", s.approvalsPage) mux.HandleFunc("POST /approvals/allowed/withdraw", s.approvalWithdraw) mux.HandleFunc("POST /approvals/{id}/{action}", s.approvalAction) diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 88085dc..f1fb950 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -526,3 +526,4 @@ ul.accounts form.inline { margin: 0 0 0 auto; } fieldset.post-as { border: 0; padding: 0; margin: 0.5rem 0; } fieldset.post-as label { display: inline-flex; margin-right: 1rem; } input.tiny { width: 5.5rem; display: inline-block; } +.bare-main:has(.api-tool) { max-width: 52rem; } diff --git a/internal/web/templates/api-docs.html b/internal/web/templates/api-docs.html new file mode 100644 index 0000000..78932a3 --- /dev/null +++ b/internal/web/templates/api-docs.html @@ -0,0 +1,26 @@ +{{define "content"}}{{with .Data}} +

Supermarket's JSON API

+

For scripts that aren't MCP clients. It's the same tools agents use over MCP ({{.MCP}}), as plain HTTP, with the same keys, scopes, limits and approvals.

+ +
+

Using it

+

Every call needs an agent's key, made under Settings → Agents: Authorization: Bearer sm_…. A key is given modules, each to read or to read and act; it can call only the tools those allow.

+
    +
  • GET {{.Base}}/tools: what your key may call, with each tool's input schema.
  • +
  • POST {{.Base}}/<tool>: call a tool. The body is a JSON object of its arguments (or empty); the answer is JSON.
  • +
+
curl -s -X POST {{.Base}}/content_drafts \
+  -H "Authorization: Bearer $SUPERMARKET_KEY" \
+  -H "Content-Type: application/json" -d '{"status": "waiting"}'
+

Errors are {"error": "…"}: 401 for a wrong key, 403 for a paused agent, 404 for a tool your key isn't given, 400 for arguments that don't fit, 422 when the tool says no (a draft that's too long), 429 over the agent's calls a minute.

+

Sending things out (content_publish, outreach_send, mailing_list_add, seo_apply_change) waits for a person's approval in Supermarket, unless that kind was allowed on its own; the answer says which, and approvals_status says what was decided.

+
+ +{{range .Docs}} +
+

POST /api/v1/{{.Name}} {{.Scope}}

+

{{.Description}}

+
Arguments (JSON Schema)
{{.Schema}}
+
+{{end}} +{{end}}{{end}}