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/<tool> 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 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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/<tool> 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()}})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
{{define "content"}}{{with .Data}}
|
||||
<h1>Supermarket's JSON API</h1>
|
||||
<p class="lede">For scripts that aren't MCP clients. It's the same tools agents use over MCP (<code>{{.MCP}}</code>), as plain HTTP, with the same keys, scopes, limits and approvals.</p>
|
||||
|
||||
<section class="card">
|
||||
<h2>Using it</h2>
|
||||
<p>Every call needs an agent's key, made under Settings → Agents: <code>Authorization: Bearer sm_…</code>. A key is given modules, each to read or to read and act; it can call only the tools those allow.</p>
|
||||
<ul>
|
||||
<li><code>GET {{.Base}}/tools</code>: what your key may call, with each tool's input schema.</li>
|
||||
<li><code>POST {{.Base}}/<tool></code>: call a tool. The body is a JSON object of its arguments (or empty); the answer is JSON.</li>
|
||||
</ul>
|
||||
<pre>curl -s -X POST {{.Base}}/content_drafts \
|
||||
-H "Authorization: Bearer $SUPERMARKET_KEY" \
|
||||
-H "Content-Type: application/json" -d '{"status": "waiting"}'</pre>
|
||||
<p><strong>Errors</strong> are <code>{"error": "…"}</code>: 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.</p>
|
||||
<p><strong>Sending things out</strong> (<code>content_publish</code>, <code>outreach_send</code>, <code>mailing_list_add</code>, <code>seo_apply_change</code>) waits for a person's approval in Supermarket, unless that kind was allowed on its own; the answer says which, and <code>approvals_status</code> says what was decided.</p>
|
||||
</section>
|
||||
|
||||
{{range .Docs}}
|
||||
<section class="card api-tool" id="{{.Name}}">
|
||||
<h2><code>POST /api/v1/{{.Name}}</code> <span class="pill">{{.Scope}}</span></h2>
|
||||
<p>{{.Description}}</p>
|
||||
<details><summary class="small">Arguments (JSON Schema)</summary><pre>{{.Schema}}</pre></details>
|
||||
</section>
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
Reference in New Issue
Block a user