Skip to Content
Wrap an existing REST API

Wrap an existing REST API

You don’t need a new backend. One small MCP server can sit in front of the REST API you already run, turning each endpoint agents need into a tool.

Pick the endpoints

Start with three to five things people actually ask for. A shop might expose check_stock, record_sale and daily_summary, not every route in its API. Each tool gets a verb name, a one-sentence description and a typed input.

The whole server

About 50 lines of Go, using the official SDK. The handler calls your API and returns a short sentence the agent can repeat to a person.

main.go
package main import ( "context" "encoding/json" "fmt" "net/http" "net/url" "github.com/modelcontextprotocol/go-sdk/mcp" ) // Your existing REST API. const api = "https://api.duka.co.tz/v1" type StockArgs struct { SKU string `json:"sku" jsonschema:"product code, e.g. SOAP-250"` } func main() { s := mcp.NewServer(&mcp.Implementation{Name: "duka-mcp", Version: "1.0.0"}, nil) mcp.AddTool(s, &mcp.Tool{ Name: "check_stock", Description: "How many units of a product are in stock, by SKU.", }, func(ctx context.Context, req *mcp.CallToolRequest, in StockArgs) (*mcp.CallToolResult, any, error) { // Pass the agent's own key straight through to your API. r, _ := http.NewRequestWithContext(ctx, "GET", api+"/stock/"+url.PathEscape(in.SKU), nil) r.Header.Set("Authorization", "Bearer "+req.Extra.Header.Get("X-Api-Key")) resp, err := http.DefaultClient.Do(r) if err != nil { return nil, nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, nil, fmt.Errorf("stock lookup failed: %s", resp.Status) } var out struct{ Units int `json:"units"` } json.NewDecoder(resp.Body).Decode(&out) text := fmt.Sprintf("%d units of %s in stock.", out.Units, in.SKU) return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: text}}}, nil, nil }) http.Handle("/mcp", mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return s }, nil)) http.ListenAndServe(":8080", nil) }

Keys

Don’t give the wrapper a master key. Declare a header such as X-Api-Key when you connect the server, and forward whatever the agent sends to your API. The gateway passes it through untouched and never stores or logs it, so each user only sees their own data.

Ship it

  • Run it anywhere that serves HTTPS: the same box as your API, a container, or a serverless function that keeps connections open.
  • Check that initialize and tools/list answer, then paste the URL into Connect a server.
  • Log X-MCP-Co-Tz-Request-Id so you can match a user’s failed call to your own logs.
Last updated on