Files
davidandClaude Opus 5.5 aa6c3ca390 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>
2026-11-25 11:22:22 -07:00

214 lines
6.3 KiB
Go

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()}})
}