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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm install
- run: npm ci
- run: npm run lint
- run: npm run typecheck
- run: npm test
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ out
.env.*.local
*.log
.DS_Store
*.tsbuildinfo
35 changes: 32 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,39 @@ Base Receipt checks:
2. The server validates them and returns a 15-minute HMAC-signed payment request.
3. The browser sends a directly attributed USDC call through MetaMask on **Base Mainnet**.
4. The browser sends only the transaction hash and signed request to `/api/verify`.
5. The server calls `getPaymentStatus()` and checks the verified amount and recipient.
5. The server reads the Base transaction and receipt, then checks successful direct-USDC settlement, sender, amount, recipient and the Base Receipt attribution suffix.
6. The payment ID is atomically claimed and persisted.
7. A verified receipt is returned with a BaseScan transaction link.

## Agent interface

The same order and verification handlers are exposed through stateless MCP Streamable HTTP at `/mcp`. The mobile-friendly `/agents` page explains the integration; `/api/agent` publishes machine-readable capabilities.

| MCP tool | Input | Result |
| --- | --- | --- |
| `prepare_base_payment` | Decimal USDC `amount`, EVM `recipient` | Signed 15-minute order, `orderToken`, and unsigned transaction data containing the Base Receipt Builder Code |
| `issue_base_receipt` | Transaction hash as `paymentId`, original `orderToken` | The receipt returned by the existing settlement verifier and durable claim store, or a tool error |

The service never signs or broadcasts a blockchain transaction and never receives wallet keys. An agent's caller-controlled wallet must review the amount, recipient, chain ID (8453), USDC contract and calldata before submitting a direct transfer. Both tools are marked non-read-only: preparation creates a fresh signed order; receipt issuance persists a claim. The returned order token must be kept for verification within its validity window. Repeating issuance with the same valid order preserves the existing claim; another order cannot reuse that payment.

Example MCP tool arguments:

```json
{"amount":"0.01","recipient":"0xYourRecipientAddress"}
```

```json
{"paymentId":"0xYourTransactionHash","orderToken":"token-returned-by-prepare_base_payment"}
```

Replace the placeholders with actual values. Preserve the returned attributed calldata. The current verifier supports direct EOA-to-USDC calls, not smart-account or batched calls. Preparing an order is not evidence of payment, and a receipt does not prove delivery of goods or services.

No Base Receipt API key is required. The endpoint accepts POST, returns 405 for GET/DELETE, bounds request bodies to 64 KiB, and rejects foreign browser Origin headers. The server creates no long-lived MCP session. This release adds no transaction submission, paid canary or synthetic activity.

The MCP transport uses the [official TypeScript SDK](https://ts.sdk.modelcontextprotocol.io/server). Tests exercise SDK discovery, exact unsigned transfer data, attribution, validation, and propagation of receipt errors. Existing browser payment handlers are reused in-process without making internal HTTP calls.

Maintainers can check a running deployment with `node scripts/check-agent.mjs <application-origin>`. This performs discovery, prepares one unsigned 0.01 USDC request, validates its calldata, and confirms invalid signatures are rejected. It never submits a payment or stores a receipt, and does not print the order token.

## Replay protection

For local development, claims are kept in process memory.
Expand All @@ -57,7 +86,7 @@ Never commit either value.
## Development

```bash
npm install
npm ci
npm run dev
```

Expand All @@ -76,7 +105,7 @@ The app intentionally uses `testnet: false`. Payments are real Base Mainnet USDC

## Base App and Builder Codes

Base Receipt is registered and domain-verified in Base Dashboard with Builder Code `bc_87fjmj1l`. The external-web payment call appends the ERC-8021 suffix directly to the USDC transfer calldata, while receipt verification remains independent of attribution.
Base Receipt is registered and domain-verified in Base Dashboard with Builder Code `bc_87fjmj1l`. Browser payments and agent-prepared transactions append the ERC-8021 suffix directly to the USDC transfer calldata. The server requires this attribution alongside settlement evidence before issuing a receipt.

## Status

Expand Down
39 changes: 39 additions & 0 deletions app/agents/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import Link from "next/link";

export default function AgentsPage() {
return (
<main className="shell">
<section className="hero">
<p className="eyebrow">BASE RECEIPT · FOR AGENTS</p>
<h1>Payment intent. Verified receipt.</h1>
<p className="lede">Prepare a Base USDC payment request through MCP, submit it with your own wallet, and turn the confirmed transfer into a server-verified receipt.</p>
</section>
<section className="card agentDocs">
<h2>Connect your agent</h2>
<p>Streamable HTTP endpoint:</p>
<code className="endpoint">https://base-receipt-six.vercel.app/mcp</code>
<p>The endpoint accepts MCP requests over HTTP POST. No Base Receipt API key is required.</p>
<Link className="explorerLink" href="/api/agent">View machine-readable capabilities ↗</Link>
</section>
<section className="card agentDocs">
<h2>Two tools, one receipt flow</h2>
<ol>
<li><code>prepare_base_payment</code> accepts a decimal USDC amount and recipient. It returns a signed order valid for 15 minutes, an order token, and unsigned transaction data with Builder Code <code>bc_87fjmj1l</code>.</li>
<li>Your wallet reviews and submits the returned direct USDC transfer on Base Mainnet, chain ID <code>8453</code>. Preserve the returned calldata, including its attribution suffix.</li>
<li><code>issue_base_receipt</code> accepts the transaction hash as <code>paymentId</code> and the original <code>orderToken</code>. It verifies settlement and persists the receipt claim.</li>
</ol>
<p>Preparation example:</p>
<pre>{'{"amount":"0.01","recipient":"0xYourRecipientAddress"}'}</pre>
<p>Replace the placeholder with the intended recipient. The service prepares transaction data; wallet approval and payment submission stay with the caller.</p>
</section>
<section className="card agentDocs">
<h2>What the receipt proves</h2>
<p>The server checks a successful direct USDC transfer, the exact amount and recipient, the sender and Base Receipt attribution. A payment already claimed by another order is rejected.</p>
<p>Use the same signed order when retrying within its validity window. The current verifier supports direct wallet transfers; smart-account and batched payment flows are not supported.</p>
<p>Preparing an order does not establish payment or product adoption. A receipt proves the checked transfer, not delivery of goods or services.</p>
<Link className="explorerLink" href="/">Open the wallet payment page</Link>
<p><a className="explorerLink" href="https://github.com/Mabolla/base-receipt">Source and integration documentation ↗</a></p>
</section>
</main>
);
}
7 changes: 7 additions & 0 deletions app/api/agent/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { AGENT_CAPABILITIES } from "@/lib/agent-mcp";

export const runtime = "nodejs";

export function GET() {
return Response.json(AGENT_CAPABILITIES);
}
1 change: 1 addition & 0 deletions app/globals.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions app/mcp/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { POST as prepare } from "../api/orders/route";
import { POST as verify } from "../api/verify/route";
import { handleReceiptMcpRequest, methodNotAllowed } from "@/lib/agent-mcp";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const maxDuration = 30;

export function POST(request: Request) {
return handleReceiptMcpRequest(request, { prepare, verify });
}

export const GET = methodNotAllowed;
export const DELETE = methodNotAllowed;
2 changes: 2 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";

import { FormEvent, useState } from "react";
import Link from "next/link";
import { payAttributed } from "@/lib/base-payment";

type Receipt = { orderId: string; paymentId: string; sender: string | null; amount: string; recipient: string; status: string };
Expand Down Expand Up @@ -55,6 +56,7 @@ export default function Home() {
<p className="eyebrow">BASE RECEIPT · MAINNET</p>
<h1>Pay once. Verify it. Keep the receipt.</h1>
<p className="lede">A focused USDC payment flow on Base. The browser initiates payment; the server independently verifies settlement, amount and recipient before issuing a receipt.</p>
<Link className="explorerLink" href="/agents">Integrate an agent via MCP ↗</Link>
</section>

<section className="card">
Expand Down
93 changes: 93 additions & 0 deletions lib/agent-mcp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { Attribution } from "ox/erc8021";
import { decodeFunctionData, erc20Abi } from "viem";
import { describe, expect, it, vi } from "vitest";
import { handleReceiptMcpRequest, type ReceiptHandlers } from "./agent-mcp";
import { BASE_USDC, BUILDER_CODE } from "./base-payment";

function handlers() {
return {
prepare: vi.fn(async (request: Request) => {
const input = await request.json();
return Response.json({ order: { ...input, orderId: "test-order", expiresAt: 123456789 }, token: "test-token" });
}),
verify: vi.fn<ReceiptHandlers["verify"]>(async () => Response.json({ error: "This payment was already used for another request" }, { status: 409 })),
};
}

async function connect(dependencies: ReceiptHandlers) {
const client = new Client({ name: "receipt-test", version: "1.0.0" });
const transport = new StreamableHTTPClientTransport(new URL("https://receipt.example/mcp"), {
fetch: async (input, init) => handleReceiptMcpRequest(new Request(input as RequestInfo, init), dependencies),
});
await client.connect(transport);
return client;
}

describe("Base Receipt agent interface", () => {
it("discovers accurate write annotations and returns unsigned attributed transfer data", async () => {
const dependencies = handlers();
const client = await connect(dependencies);
try {
const listed = await client.listTools();
expect(listed.tools.map(tool => tool.name)).toEqual(["prepare_base_payment", "issue_base_receipt"]);
expect(listed.tools.every(tool => tool.annotations?.readOnlyHint === false)).toBe(true);
const result = await client.callTool({ name: "prepare_base_payment", arguments: { amount: "0.01", recipient: "0x1111111111111111111111111111111111111111" } });
expect(result.isError).not.toBe(true);
const value = result.structuredContent as { orderToken: string; submission: string; transaction: { to: string; data: `0x${string}`; chainId: number } };
expect(value.orderToken).toBe("test-token");
expect(value.submission).toBe("requires_caller_wallet");
expect(value.transaction.chainId).toBe(8453);
expect(value.transaction.to).toBe(BASE_USDC);
expect(decodeFunctionData({ abi: erc20Abi, data: value.transaction.data }).args).toEqual(["0x1111111111111111111111111111111111111111", BigInt(10000)]);
expect(Attribution.fromData(value.transaction.data)?.codes).toEqual([BUILDER_CODE]);
expect(dependencies.prepare).toHaveBeenCalledOnce();
expect(dependencies.verify).not.toHaveBeenCalled();
} finally { await client.close(); }
});

it.each(["0", "-1", "0.0000001", "1e3", "9".repeat(80)])("rejects invalid amount %s before calling the existing API", async amount => {
const dependencies = handlers();
const client = await connect(dependencies);
try {
const result = await client.callTool({ name: "prepare_base_payment", arguments: { amount, recipient: "0x1111111111111111111111111111111111111111" } });
expect(result.isError).toBe(true);
expect(dependencies.prepare).not.toHaveBeenCalled();
} finally { await client.close(); }
});

it("preserves verification errors and passes the original proof inputs to the existing API", async () => {
const dependencies = handlers();
const client = await connect(dependencies);
try {
const input = { paymentId: `0x${"1".repeat(64)}`, orderToken: "signed-order" };
const result = await client.callTool({ name: "issue_base_receipt", arguments: input });
expect(result.isError).toBe(true);
expect(result.structuredContent).toMatchObject({ httpStatus: 409, error: "This payment was already used for another request" });
expect(await dependencies.verify.mock.calls[0][0].json()).toEqual(input);
} finally { await client.close(); }
});

it("returns a verified receipt only after the existing API accepts it", async () => {
const dependencies = handlers();
dependencies.verify.mockImplementation(async () => Response.json({ receipt: { status: "completed", orderId: "test-order" } }));
const client = await connect(dependencies);
try {
const result = await client.callTool({ name: "issue_base_receipt", arguments: { paymentId: `0x${"1".repeat(64)}`, orderToken: "signed-order" } });
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({ httpStatus: 200, receipt: { status: "completed" } });
} finally { await client.close(); }
});

it("rejects unsupported HTTP methods, foreign browser origins and oversized requests", async () => {
const dependencies = handlers();
expect((await handleReceiptMcpRequest(new Request("https://receipt.example/mcp"), dependencies)).status).toBe(405);
const foreign = new Request("https://receipt.example/mcp", { method: "POST", headers: { Origin: "https://other.example" } });
expect((await handleReceiptMcpRequest(foreign, dependencies)).status).toBe(403);
const large = new Request("https://receipt.example/mcp", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, body: "x".repeat(65537) });
expect((await handleReceiptMcpRequest(large, dependencies)).status).toBe(413);
expect(dependencies.prepare).not.toHaveBeenCalled();
expect(dependencies.verify).not.toHaveBeenCalled();
});
});
Loading
Loading