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 typecheck
- run: npm test
- run: npm run build
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
RUN npm ci
COPY tsconfig.json tsconfig.build.json ./
COPY src ./src
RUN npm run build
Expand All @@ -10,7 +10,7 @@ FROM node:22-alpine AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
EXPOSE 4021
CMD ["npm", "start"]
30 changes: 21 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,18 @@ For POST resources:
npm run check -- https://api.example.com/paid-resource --method POST --body '{"query":"value"}'
```

The CLI prints JSON. `FAIL` exits with code 1 and invalid input exits with code 2. `PASS` and `WARN` exit successfully so teams can choose their warning policy. The same workflow is available through `POST /api/check`. Public DNS resolution is checked and private, loopback, link-local, and carrier-grade NAT targets are rejected.
The CLI prints JSON. `FAIL` exits with code 1 and invalid input exits with code 2. `PASS` and `WARN` exit successfully so teams can choose their warning policy. The same workflow is available through `POST /api/check`. The checker rejects non-public IP addresses, connects only to the DNS addresses it validated, does not follow redirects, and caps response bodies at 128 KiB. Explicit POST checks can have effects on the target service; the MCP tool supports GET only.

## Agent interface (MCP)

Base Agent Meter exposes a remote MCP Streamable HTTP endpoint at `/mcp`. It publishes two read-only tools that agents can discover through the MCP protocol:

| Tool | Purpose |
| --- | --- |
| `check_x402_endpoint` | Inspect a public seller endpoint's x402 v2 challenge, Base USDC terms, Bazaar metadata, Builder Code declaration, and optional pinned expectations. |
| `check_x402_endpoint` | Send an unpaid GET to inspect a public seller endpoint's x402 v2 challenge, Base USDC terms, Bazaar metadata, Builder Code declaration, and optional pinned expectations. |
| `verify_base_settlement` | Verify an existing Base transaction's successful receipt and USDC transfer, with optional payer and Builder Code checks. |

Neither tool can create a payment, sign a transaction, or access payer credentials. The endpoint uses stateless Streamable HTTP; there is no MCP session state. Requests to `/mcp` are limited to 30 per minute per client IP. The older JSON endpoints remain available for scripts and CI. Once deployed, connect an MCP client to `https://<your-deployment-host>/mcp`.
Neither tool can create a payment, sign a transaction, or access payer credentials. The endpoint uses stateless Streamable HTTP; there is no MCP session state. HTTP POST is the MCP transport method; GET and DELETE on `/mcp` return 405. Requests to `/mcp` are limited to 30 per minute per observed connection IP. Behind a reverse proxy this can be a shared limit; forwarded IP headers are not trusted. The older JSON endpoints remain available for scripts and CI. Once deployed, connect an MCP client to `https://<your-deployment-host>/mcp`.

Example tool inputs:

Expand All @@ -42,10 +42,18 @@ Example tool inputs:
```

```json
{"transactionHash":"0x...","expectedPayTo":"0xYourExpectedRecipient","expectedAmount":"1000","expectedPayer":"0xOptionalExpectedPayer"}
{"transactionHash":"0x...","expectedPayTo":"0xYourExpectedRecipient","expectedAmount":"1000","expectedPayer":"0xOptionalExpectedPayer","declaredBuilderCode":"seller_code"}
```

`expectedAmount` is the integer amount in USDC's 6-decimal atomic units. A challenge can declare a Builder Code, but the tool only reports attribution as verified when it observes the configured code in the completed transaction.
`expectedAmount` is the integer amount in USDC's 6-decimal atomic units. `expectedPayer` and `declaredBuilderCode` are optional. Addresses and transaction hashes above are placeholders. The proof tool always reports observed attribution, and marks it verified only when it matches the explicitly supplied `declaredBuilderCode`. Omitting that field does not silently use this project's Builder Code.

A runnable SDK example is provided for agent developers:

```bash
node examples/agent-client.mjs https://<your-deployment-host>/mcp https://<seller-host>/paid-resource
```

The automated MCP integration test uses the official SDK client against a real local HTTP listener to exercise discovery, tool calls, input validation, and unsupported transport methods. It does not establish public deployment availability.

## 2. Live paid canary

Expand Down Expand Up @@ -85,9 +93,13 @@ After a completed canary, Base Agent Meter verifies transaction inclusion and st

The canary writes a JSON artifact under `artifacts/` containing endpoint, timestamp, payment terms, payer, transaction hash, response status, latency, response body hash, USDC evidence, and builder-attribution evidence. Existing transactions can be checked through `POST /api/proof/verify`.

## Existing deployed seller fixture
## Deployment status and optional seller fixture

The previously configured Railway host returned **HTTP 404, Application not found**, on 2026-10-01. Public availability of `/health` and `/mcp` is not verified. A passing build or a merged commit is not evidence of a live service.

`railway.json` selects the Dockerfile, sets `/health` as the deployment health check, and configures up to three on-failure restarts. The Docker build and CI use the committed dependency lockfile. This configuration applies when an authorized Railway service deploys the repository; it does not create or reconnect that service. See [Railway's configuration reference](https://docs.railway.com/config-as-code/reference).

The repository preserves the original paid Base snapshot as an optional self-test fixture. The deployment predates the Production Assurance pivot.
The repository preserves the original paid Base snapshot as an optional self-test fixture. Its historical deployment predates the Production Assurance pivot.

- Service: `https://base-agent-meter-production.up.railway.app`
- Resource: `GET /api/base-snapshot`
Expand Down Expand Up @@ -116,7 +128,7 @@ This evidence verifies the seller fixture's payment and attribution path. It doe
## Local server

```bash
npm install
npm ci
npm run typecheck
npm test
npm run build
Expand All @@ -136,7 +148,7 @@ BUILDER_CODE=bc_h2oqnbbh

## Safety boundaries

- Checks are read-only and never submit payment headers.
- The MCP checker sends unpaid GET requests and never submits payment headers. Explicit CLI/API POST checks may have effects on the target service.
- Canary dry-runs do not load or require a private key.
- Real payment requires pinned expectations and a confirmation token.
- Secrets remain environment-only and are excluded from git.
Expand Down
23 changes: 23 additions & 0 deletions examples/agent-client.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

// Run from this repository after its dependencies are available.
// Usage: node examples/agent-client.mjs <MCP URL> <public seller URL>
const [mcpUrl, sellerUrl] = process.argv.slice(2);
if (!mcpUrl || !sellerUrl) {
console.error("Usage: node examples/agent-client.mjs <MCP URL> <public seller URL>");
process.exit(2);
}

const client = new Client({ name: "base-agent-meter-example", version: "1.0.0" });
try {
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));
const result = await client.callTool({ name: "check_x402_endpoint", arguments: { url: sellerUrl } });
console.log(JSON.stringify(result, null, 2));
if (result.isError) process.exitCode = 1;
} catch (error) {
console.error(error instanceof Error ? error.message : "MCP request failed");
process.exitCode = 1;
} finally {
await client.close();
}
13 changes: 13 additions & 0 deletions railway.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"$schema": "https://railway.com/railway.schema.json",
"build": {
"builder": "DOCKERFILE",
"dockerfilePath": "Dockerfile"
},
"deploy": {
"healthcheckPath": "/health",
"healthcheckTimeout": 60,
"restartPolicyType": "ON_FAILURE",
"restartPolicyMaxRetries": 3
}
}
56 changes: 9 additions & 47 deletions src/assurance.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
import { CheckInputError, requestPublicTarget, resolvePublicTarget } from "./public-http.js";
export { CheckInputError } from "./public-http.js";
import { decodePaymentRequiredHeader } from "@x402/core/http";
import { parsePaymentRequired } from "@x402/core/schemas";
import { getAddress, isAddress } from "viem";
Expand Down Expand Up @@ -58,52 +58,12 @@ export interface AssuranceReport {
findings: AssuranceFinding[];
}

export class CheckInputError extends Error {}

interface CheckDependencies {
fetchImpl?: typeof fetch;
resolveHost?: (hostname: string) => Promise<string[]>;
now?: () => Date;
}

function isPrivateAddress(address: string): boolean {
const normalized = address.toLowerCase();
if (normalized === "::1" || normalized === "::" || normalized.startsWith("fe80:") || normalized.startsWith("fc") || normalized.startsWith("fd")) return true;
if (!isIP(address)) return true;
const parts = address.split(".").map(Number);
if (parts.length !== 4) return false;
return parts[0] === 10
|| parts[0] === 127
|| parts[0] === 0
|| (parts[0] === 169 && parts[1] === 254)
|| (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31)
|| (parts[0] === 192 && parts[1] === 168)
|| (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127);
}

async function defaultResolveHost(hostname: string): Promise<string[]> {
const records = await lookup(hostname, { all: true, verbatim: true });
return records.map(record => record.address);
}

async function validatePublicUrl(rawUrl: string, resolveHost: (hostname: string) => Promise<string[]>): Promise<URL> {
let url: URL;
try {
url = new URL(rawUrl);
} catch {
throw new CheckInputError("url must be a valid absolute URL");
}
if (url.protocol !== "https:" && url.protocol !== "http:") {
throw new CheckInputError("url must use http or https");
}
if (url.username || url.password) throw new CheckInputError("url credentials are not allowed");
const addresses = await resolveHost(url.hostname);
if (addresses.length === 0 || addresses.some(isPrivateAddress)) {
throw new CheckInputError("url must resolve only to public IP addresses");
}
return url;
}

function decodeChallenge(response: Response, body: unknown): unknown {
const header = response.headers.get("payment-required");
if (header) return decodePaymentRequiredHeader(header);
Expand Down Expand Up @@ -135,11 +95,10 @@ export async function checkX402Endpoint(input: CheckRequest, dependencies: Check
if (!input || typeof input !== "object" || typeof input.url !== "string") {
throw new CheckInputError("url must be a valid absolute URL");
}
const fetchImpl = dependencies.fetchImpl ?? fetch;
const resolveHost = dependencies.resolveHost ?? defaultResolveHost;
const now = dependencies.now ?? (() => new Date());
const startedAt = performance.now();
const url = await validatePublicUrl(input.url, resolveHost);
const target = await resolvePublicTarget(input.url, dependencies.resolveHost);
const url = target.url;
const method = input.method ?? "GET";
if (method !== "GET" && method !== "POST") throw new CheckInputError("method must be GET or POST");
const expectations = input.expectations ?? {};
Expand All @@ -153,13 +112,16 @@ export async function checkX402Endpoint(input: CheckRequest, dependencies: Check
let response: Response;
let responseBody: unknown;
try {
response = await fetchImpl(url, {
const request: RequestInit = {
method,
redirect: "manual",
signal: AbortSignal.timeout(12_000),
headers: method === "POST" ? { "content-type": "application/json", accept: "application/json" } : { accept: "application/json" },
body: method === "POST" ? JSON.stringify(input.body ?? {}) : undefined,
});
};
response = dependencies.fetchImpl
? await dependencies.fetchImpl(url, request)
: await requestPublicTarget(target, request);
const text = await response.text();
try { responseBody = text ? JSON.parse(text) : undefined; } catch { responseBody = text; }
} catch (error) {
Expand Down
21 changes: 13 additions & 8 deletions src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ interface McpDependencies {
checkEndpoint?: typeof checkX402Endpoint;
verifySettlement?: typeof verifyBaseSettlement;
rpcUrl: string;
builderCode: string;
}

function jsonResult(value: unknown) {
Expand All @@ -36,11 +35,10 @@ export function createMeterMcpServer(dependencies: McpDependencies) {
"check_x402_endpoint",
{
title: "Check an x402 endpoint",
description: "Read a public HTTP endpoint and report whether its x402 v2 challenge advertises Base Mainnet USDC, stable payment details, Bazaar metadata, and Builder Code attribution. No payment is made. Private, loopback, link-local, and carrier-grade NAT destinations are rejected.",
description: "Send an unpaid GET to a public endpoint and report its x402 v2 Base Mainnet USDC challenge, payment details, Bazaar metadata, and declared Builder Code. Only GET is supported by this read-only tool; use the CLI or HTTP API for an explicitly requested POST check.",
inputSchema: {
url: z.string().url(),
method: z.enum(["GET", "POST"]).optional(),
body: z.unknown().optional(),
method: z.literal("GET").optional(),
expectations: z.object({
network: z.string().optional(),
asset: z.string().optional(),
Expand All @@ -63,12 +61,13 @@ export function createMeterMcpServer(dependencies: McpDependencies) {
"verify_base_settlement",
{
title: "Verify a Base settlement",
description: "Read a Base Mainnet transaction and verify its successful receipt and exact USDC transfer to the expected recipient, amount, and optional payer. Also reports whether the configured Builder Code appears in the transaction calldata. This does not submit or modify transactions.",
description: "Read a Base Mainnet transaction and verify its successful receipt and exact USDC transfer to the expected recipient, amount, and optional payer. Reports observed attribution and compares it with declaredBuilderCode only when supplied. This does not submit or modify transactions.",
inputSchema: {
transactionHash: z.string().refine(isHash, "must be a 32-byte transaction hash"),
expectedPayTo: z.string().refine(isAddress, "must be a valid EVM address"),
expectedAmount: z.string().regex(/^[1-9]\d*$/, "must be a positive atomic-unit amount"),
expectedPayer: z.string().refine(isAddress, "must be a valid EVM address").optional(),
declaredBuilderCode: z.string().regex(/^[a-z0-9_]{1,32}$/).optional(),
},
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
},
Expand All @@ -78,7 +77,6 @@ export function createMeterMcpServer(dependencies: McpDependencies) {
verifiedAt: new Date().toISOString(),
proof: await verifySettlement(dependencies.rpcUrl, {
...input,
declaredBuilderCode: dependencies.builderCode,
}),
});
} catch (error) {
Expand All @@ -95,15 +93,22 @@ export async function handleMeterMcpRequest(
res: ServerResponse,
dependencies: McpDependencies,
) {
if (req.method !== "POST") {
res.writeHead(405, { Allow: "POST", "Content-Type": "application/json" });
res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32000, message: "Method not allowed" } }));
return;
}
const server = createMeterMcpServer(dependencies);
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
try {
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
} catch (error) {
console.error("mcp_request_failed", error);
if (!res.headersSent) res.statusCode = 500;
if (!res.writableEnded) res.end(JSON.stringify({ error: "mcp_request_failed" }));
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "MCP request failed" } }));
} else if (!res.writableEnded) res.end();
} finally {
await transport.close().catch(() => undefined);
await server.close().catch(() => undefined);
Expand Down
Loading
Loading