Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Tool reference: [recallkitchen.com/docs/#mcp](https://recallkitchen.com/docs/#mc
Two ways to call tools:

1. **API key (recommended)** — free, higher limits. Create a key in the app under [Integrations](https://app.recallkitchen.com/#/integrations). Send `X-API-Key: rk_...` (required for Grok) or `Authorization: Bearer rk_...` (Claude Code, Cursor).
2. **x402** — anonymous USDC on Base (~$0.025 / call). Set `X402_EVM_PRIVATE_KEY`. Watch, inventory, and notification tools still need an API key.
2. **x402** — anonymous USDC on Base (~$0.025 / call). Set `X402_EVM_PRIVATE_KEY`. Watch, inventory, and notification tools still need an API key. The Go client refuses to sign more than 0.05 USDC per call unless you raise `MaxPaymentPerCall` / `X402_MAX_PAYMENT_PER_CALL`.

Grok's HTTP MCP client treats `Authorization: Bearer` as OAuth. Use `X-API-Key` for Grok.

Expand Down Expand Up @@ -83,6 +83,15 @@ hits, err := cc.SearchRecallsByIdentifier(ctx, rkmcp.IdentifierOptions{UPC: "012

`APIKey` is also read from `RK_API_KEY` or `RECALL_KITCHEN_API_KEY`. The client sends `X-API-Key`. Anonymous clients can set `EVMPrivateKey` / `X402_EVM_PRIVATE_KEY` instead.

With x402, the client only pays in USDC on Base and signs at most `MaxPaymentPerCall` per tool call (a decimal USDC amount, default `"0.05"`; also read from `X402_MAX_PAYMENT_PER_CALL`). A larger request fails with `rkmcp.ErrPaymentExceedsMax` and nothing is signed. Another asset or network fails with `rkmcp.ErrPaymentUnsupported`.

```go
cc, err := rkmcp.NewClient(rkmcp.Config{
EVMPrivateKey: os.Getenv("X402_EVM_PRIVATE_KEY"),
MaxPaymentPerCall: "0.05", // USDC
})
```

Module: `github.com/Recall-Kitchen/rk-mcp/go`.

## Examples
Expand Down
1 change: 1 addition & 0 deletions examples/go/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Set a free API key (preferred) or an x402 private key:
export RK_API_KEY=rk_...
# or
export X402_EVM_PRIVATE_KEY=0x...
export X402_MAX_PAYMENT_PER_CALL=0.05 # optional; max USDC signed per call (default 0.05)
```

Create a key at [app.recallkitchen.com/#/integrations](https://app.recallkitchen.com/#/integrations).
Expand Down
17 changes: 17 additions & 0 deletions go/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,15 @@ type Config struct {
// accepted as Authorization: Bearer). When set, search tools skip x402.
APIKey string

// EVMPrivateKey pays for tool calls with x402 (USDC on Base) when APIKey
// is unset. Also read from X402_EVM_PRIVATE_KEY.
EVMPrivateKey string

// MaxPaymentPerCall is the most USDC the client will sign for one tool
// call, as a decimal string such as "0.05". Larger requests fail with
// ErrPaymentExceedsMax and nothing is signed. Also read from
// X402_MAX_PAYMENT_PER_CALL. Defaults to DefaultMaxPaymentPerCall.
MaxPaymentPerCall string
}

var (
Expand Down Expand Up @@ -91,11 +99,20 @@ func NewClient(config Config) (Client, error) {
if paymentClient == nil {
return out, ErrX402NotConfigured
}
maxPayment, err := parseMaxPayment(config)
if err != nil {
session.Close()
return nil, err
}

out.x402Session = x402mcp.NewX402MCPClient(session, paymentClient, x402mcp.Options{
AutoPayment: x402mcp.BoolPtr(true),
OnPaymentRequested: func(context x402mcp.PaymentRequiredContext) (bool, error) {
// x402mcp signs Accepts[0], so that is the option to check.
price := context.PaymentRequired.Accepts[0]
if err := checkPayment(context.ToolName, price, maxPayment); err != nil {
return false, err
}
fmt.Printf("\nPayment required for tool: %s\n", context.ToolName)
fmt.Printf(" Amount: %s (%s)\n", price.Amount, price.Asset)
fmt.Printf(" Network: %s\n", price.Network)
Expand Down
73 changes: 73 additions & 0 deletions go/payment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package rkmcp

import (
"cmp"
"errors"
"fmt"
"math/big"
"os"
"strings"

x402types "github.com/x402-foundation/x402/go/types"
)

const (
// baseNetwork is Base mainnet (CAIP-2), the only network the client pays on.
baseNetwork = "eip155:8453"
// baseUSDC is the USDC contract on Base. Amounts are in its atomic units (6 decimals).
baseUSDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
usdcDecimals = 6

// DefaultMaxPaymentPerCall is the most the client signs for one tool call
// when Config.MaxPaymentPerCall is unset: 0.05 USDC, twice Recall Kitchen's
// $0.025 per-call price.
DefaultMaxPaymentPerCall = "0.05"
)

var (
// ErrPaymentExceedsMax is returned when a server asks for more than
// Config.MaxPaymentPerCall. Nothing is signed.
ErrPaymentExceedsMax = errors.New("x402 payment exceeds MaxPaymentPerCall")

// ErrPaymentUnsupported is returned when a server asks for payment in an
// asset or on a network the client does not pay with. Nothing is signed.
ErrPaymentUnsupported = errors.New("x402 payment option not supported")
)

// parseMaxPayment converts a decimal USDC amount (e.g. "0.05") into atomic units.
func parseMaxPayment(config Config) (*big.Int, error) {
raw := strings.TrimSpace(cmp.Or(config.MaxPaymentPerCall, os.Getenv("X402_MAX_PAYMENT_PER_CALL"), DefaultMaxPaymentPerCall))
raw = strings.TrimPrefix(raw, "$")

r, ok := new(big.Rat).SetString(raw)
if !ok || r.Sign() < 0 || strings.ContainsAny(raw, "eE/") {
return nil, fmt.Errorf("invalid MaxPaymentPerCall %q: want a decimal USDC amount like %q", raw, DefaultMaxPaymentPerCall)
}
r.Mul(r, new(big.Rat).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(usdcDecimals), nil)))
if !r.IsInt() {
return nil, fmt.Errorf("invalid MaxPaymentPerCall %q: USDC has at most %d decimal places", raw, usdcDecimals)
}
return new(big.Int).Set(r.Num()), nil
}

// checkPayment refuses a payment requirement that is not USDC on Base or that
// asks for more than maxAtomic.
func checkPayment(tool string, req x402types.PaymentRequirements, maxAtomic *big.Int) error {
if req.Network != baseNetwork || !strings.EqualFold(req.Asset, baseUSDC) {
return fmt.Errorf("%w: %s asks for asset %s on %s; only USDC on Base (%s) is paid", ErrPaymentUnsupported, tool, req.Asset, req.Network, baseNetwork)
}
amount, ok := new(big.Int).SetString(strings.TrimSpace(req.Amount), 10)
if !ok || amount.Sign() < 0 {
return fmt.Errorf("%w: %s asks for invalid amount %q", ErrPaymentUnsupported, tool, req.Amount)
}
if amount.Cmp(maxAtomic) > 0 {
return fmt.Errorf("%w: %s asks for %s USDC, max is %s USDC", ErrPaymentExceedsMax, tool, formatUSDC(amount), formatUSDC(maxAtomic))
}
return nil
}

func formatUSDC(atomic *big.Int) string {
s := new(big.Rat).SetFrac(atomic, new(big.Int).Exp(big.NewInt(10), big.NewInt(usdcDecimals), nil)).FloatString(usdcDecimals)
s = strings.TrimRight(s, "0")
return strings.TrimSuffix(s, ".")
}
176 changes: 176 additions & 0 deletions go/payment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package rkmcp

import (
"context"
"encoding/json"
"errors"
"math/big"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"

mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/require"
x402types "github.com/x402-foundation/x402/go/types"
)

// testEVMKey is the well-known first Hardhat/Anvil development key. It holds no funds.
const testEVMKey = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"

func TestParseMaxPayment(t *testing.T) {
t.Setenv("X402_MAX_PAYMENT_PER_CALL", "")

cases := map[string]int64{
"": 50_000, // default 0.05 USDC
"0.025": 25_000,
"$0.10": 100_000,
"1": 1_000_000,
"0": 0,
"0.0001": 100,
}
for in, want := range cases {
got, err := parseMaxPayment(Config{MaxPaymentPerCall: in})
require.NoError(t, err, in)
require.Equal(t, big.NewInt(want), got, in)
}

for _, in := range []string{"abc", "-1", "0.0000001", "1e3", "1/2"} {
_, err := parseMaxPayment(Config{MaxPaymentPerCall: in})
require.Error(t, err, in)
}

t.Setenv("X402_MAX_PAYMENT_PER_CALL", "0.5")
got, err := parseMaxPayment(Config{})
require.NoError(t, err)
require.Equal(t, big.NewInt(500_000), got)
}

func TestCheckPayment(t *testing.T) {
maxAtomic := big.NewInt(50_000)
req := func(amount string) x402types.PaymentRequirements {
return x402types.PaymentRequirements{Scheme: "exact", Network: baseNetwork, Asset: baseUSDC, Amount: amount}
}

require.NoError(t, checkPayment("t", req("25000"), maxAtomic))
require.NoError(t, checkPayment("t", req("50000"), maxAtomic))

err := checkPayment("t", req("50001"), maxAtomic)
require.ErrorIs(t, err, ErrPaymentExceedsMax)

err = checkPayment("t", req("1000000000"), maxAtomic) // 1,000 USDC
require.ErrorIs(t, err, ErrPaymentExceedsMax)
require.Contains(t, err.Error(), "1000 USDC")
require.Contains(t, err.Error(), "0.05 USDC")

for _, amount := range []string{"", "abc", "-1", "0.5"} {
require.ErrorIs(t, checkPayment("t", req(amount), maxAtomic), ErrPaymentUnsupported, amount)
}

other := req("1")
other.Asset = "0x0000000000000000000000000000000000000001"
require.ErrorIs(t, checkPayment("t", other, maxAtomic), ErrPaymentUnsupported)

other = req("1")
other.Network = "eip155:1"
require.ErrorIs(t, checkPayment("t", other, maxAtomic), ErrPaymentUnsupported)
}

// paywallServer starts a local MCP server whose get_product_recall tool asks
// for an x402 payment of amount (USDC atomic units) and counts paid calls.
func paywallServer(t *testing.T, amount string) (url string, paid *atomic.Int32) {
t.Helper()
paid = new(atomic.Int32)

server := mcpsdk.NewServer(&mcpsdk.Implementation{Name: "test", Version: "test"}, nil)
server.AddTool(&mcpsdk.Tool{
Name: "get_product_recall",
InputSchema: json.RawMessage(`{"type":"object"}`),
}, func(ctx context.Context, req *mcpsdk.CallToolRequest) (*mcpsdk.CallToolResult, error) {
if _, ok := req.Params.Meta["x402/payment"]; ok {
paid.Add(1)
return &mcpsdk.CallToolResult{
Content: []mcpsdk.Content{&mcpsdk.TextContent{Text: `{"id":"r1","title":"paid"}`}},
}, nil
}
pr := x402types.PaymentRequired{
X402Version: 2,
Error: "payment required",
Resource: &x402types.ResourceInfo{URL: "mcp://tool/get_product_recall"},
Accepts: []x402types.PaymentRequirements{{
Scheme: "exact",
Network: baseNetwork,
Asset: baseUSDC,
Amount: amount,
PayTo: "0x000000000000000000000000000000000000dEaD",
MaxTimeoutSeconds: 60,
Extra: map[string]any{"name": "USD Coin", "version": "2"},
}},
}
body, err := json.Marshal(pr)
if err != nil {
return nil, err
}
var structured map[string]any
if err := json.Unmarshal(body, &structured); err != nil {
return nil, err
}
return &mcpsdk.CallToolResult{
IsError: true,
StructuredContent: structured,
Content: []mcpsdk.Content{&mcpsdk.TextContent{Text: string(body)}},
}, nil
})

ts := httptest.NewServer(mcpsdk.NewStreamableHTTPHandler(func(*http.Request) *mcpsdk.Server { return server }, nil))
t.Cleanup(ts.Close)
return ts.URL, paid
}

func TestClient_X402MaxPayment(t *testing.T) {
t.Setenv("RK_API_KEY", "")
t.Setenv("RECALL_KITCHEN_API_KEY", "")
t.Setenv("X402_MAX_PAYMENT_PER_CALL", "")

t.Run("over cap is refused", func(t *testing.T) {
url, paid := paywallServer(t, "1000000000") // 1,000 USDC
cc, err := NewClient(Config{ServerURL: url, Timeout: 5 * time.Second, EVMPrivateKey: testEVMKey})
require.NoError(t, err)
t.Cleanup(func() { _ = cc.Close() })

_, err = cc.GetProductRecall(context.Background(), "r1")
require.Error(t, err)
require.True(t, errors.Is(err, ErrPaymentExceedsMax), err.Error())
require.Zero(t, paid.Load())
})

t.Run("at price is paid", func(t *testing.T) {
url, paid := paywallServer(t, "25000") // 0.025 USDC
cc, err := NewClient(Config{ServerURL: url, Timeout: 5 * time.Second, EVMPrivateKey: testEVMKey})
require.NoError(t, err)
t.Cleanup(func() { _ = cc.Close() })

got, err := cc.GetProductRecall(context.Background(), "r1")
require.NoError(t, err)
require.Equal(t, "r1", got.ID)
require.EqualValues(t, 1, paid.Load())
})

t.Run("custom cap", func(t *testing.T) {
url, paid := paywallServer(t, "25000")
cc, err := NewClient(Config{ServerURL: url, Timeout: 5 * time.Second, EVMPrivateKey: testEVMKey, MaxPaymentPerCall: "0.01"})
require.NoError(t, err)
t.Cleanup(func() { _ = cc.Close() })

_, err = cc.GetProductRecall(context.Background(), "r1")
require.ErrorIs(t, err, ErrPaymentExceedsMax)
require.Zero(t, paid.Load())
})

t.Run("invalid cap", func(t *testing.T) {
url, _ := paywallServer(t, "25000")
_, err := NewClient(Config{ServerURL: url, Timeout: 5 * time.Second, EVMPrivateKey: testEVMKey, MaxPaymentPerCall: "lots"})
require.ErrorContains(t, err, "invalid MaxPaymentPerCall")
})
}
Loading