Fabric Documentation
The trust layer for the agent economy. Fabric is a production-ready gateway that gives AI agents the ability to discover services via ERC-8004 smart contracts on Base, verify reputation with a live scoring engine, and pay autonomously via x402 with managed USDC wallets.
Production-ready — 111 files, 9 test suites (116 cases), 2 Solidity contracts (40 tests), TypeScript & Python SDKs, Stripe billing, Prometheus monitoring, CI/CD pipeline. Get your API key.
Quickstart
Get Fabric running with your agent in under 5 minutes.
1. Install the SDK
npm install @usefabric/mcp
2. Configure your server
import { FabricServer } from '@usefabric/mcp' const fabric = new FabricServer({ apiKey: process.env.FABRIC_KEY, budget: '$5/day', // Daily spend limit trustThreshold: 0.8, // Min trust score (0-1) chain: 'base', // Payment chain fallbackEnabled: true, // Auto-retry on failure })
3. Add to your MCP config
{
"mcpServers": {
"fabric": {
"command": "npx",
"args": ["@usefabric/mcp"],
"env": {
"FABRIC_KEY": "your-api-key"
}
}
}
}4. Use from your agent
Your agent now has access to six tools: discover, route, evaluate, budget, feedback, and favorites.
// Your agent can now say things like: "Use Fabric to find an image generation service and generate a logo" "Check my remaining budget on Fabric" "Evaluate the trust score of provider 0x1234..."
Architecture
Fabric sits between your AI agent and the broader agent economy. It reads on-chain data from ERC-8004 smart contracts on Base, computes trust scores using a live scoring engine with time-decay, handles x402 payments via managed wallets, and enforces budget controls with Stripe billing for subscriptions.
Your Agent (Claude, Cursor, LangChain, custom) │ ├── MCP protocol (6 tools: discover, route, evaluate, budget, feedback, favorites) ├── REST API (22 endpoints, /v1/*) └── SDKs (TypeScript + Python) │ ▼ Fabric Gateway (Elysia + Bun) ├── Auth → API key validation + plan enforcement ├── Rate Limiter → sliding window (Redis sorted sets) ├── Usage Tracker → per-request metering + overage ├── Trust Scorer → live scoring + time-decay + circuit breaker ├── Provider Selector → composite ranking + fallback ├── Route Executor → x402 → direct → mock (3-tier) ├── Budget Engine → per-agent/task limits + daily/weekly/monthly reset └── Billing → Stripe subscriptions + overage + invoices │ ▼ Base L2 ├── FabricRegistry.sol → ERC-8004 agent/provider registry ├── FabricIdentity.sol → ERC-721 identity NFTs └── USDC transfers → x402 payment settlement
No crypto knowledge required. Fabric handles wallet creation, funding, and transaction signing. Your agent just calls route() and gets results.
Tool: discover
Find services by capability. Queries the ERC-8004 Identity Registry and returns a ranked list of providers with trust scores and pricing.
{
"providers": [
{
"agentId": "0x1a2b...3c4d",
"name": "PixelForge",
"capability": "image-generation",
"trustScore": 0.94,
"price": "$0.02",
"uptime": 0.998,
"totalReviews": 1247,
"endpoint": "https://pixelforge.ai/v1"
},
// ...
],
"totalFound": 12,
"filtered": 4 // below trust threshold
}Tool: route
End-to-end: discover → score → pay → return result. The primary tool most agents will use. Handles everything in a single call.
// Agent calls route with a task fabric.route({ capability: "image-generation", input: { prompt: "A blue octopus reading a newspaper" }, priority: "quality" }) // Returns { "result": { url: "https://...", format: "png" }, "provider": "PixelForge", "cost": "$0.02", "latency": "240ms", "txHash": "0xabc...", "trustScore": 0.94, "fallbackUsed": false }
Tool: evaluate
Get a detailed trust profile for a specific agent. Reads the full reputation history from the ERC-8004 Reputation Registry and computes a breakdown.
{
"agentId": "0x1a2b...3c4d",
"name": "PixelForge",
"overallTrust": 0.94,
"breakdown": {
"uptime": 0.998,
"quality": 0.92,
"responseTime": 0.88,
"reviewerCredibility": 0.96,
"priceEfficiency": 0.91
},
"totalFeedback": 1247,
"registeredSince": "2026-01-30",
"capabilities": ["image-generation", "image-editing"],
"x402Enabled": true
}Tool: budget
Check remaining budget, view spend history, and update limits.
| Action | Description | Returns |
|---|---|---|
| check | Current balance and remaining daily limit | Balance, spent today, daily limit |
| history | Transaction log with provider, cost, timestamp | Array of recent transactions |
| update | Change daily/per-task limits | Updated configuration |
Tool: feedback
Post reputation feedback to the ERC-8004 Reputation Registry after a completed interaction. Called automatically by route, but can also be invoked manually.
Tool: favorites
Manage a list of preferred providers. When a favorite is available for a capability, Fabric will try it first before discovering alternatives.
Trust Scoring
Fabric's scoring engine reads raw reputation data from the ERC-8004 Reputation Registry and computes a composite trust score using a proprietary weighted algorithm.
Scoring factors
| Factor | Weight | Source |
|---|---|---|
| Uptime | 25% | Success rate from on-chain feedback |
| Quality | 30% | Average quality scores from reviews |
| Response time | 15% | Latency measurements from feedback metadata |
| Reviewer credibility | 20% | Weighted by reviewer's own reputation (Sybil resistance) |
| Price efficiency | 10% | Quality-adjusted cost relative to peers |
Sybil resistance. The ERC-8004 spec stores feedback with the reviewer's address. Fabric weights reviews by the reviewer's own on-chain reputation — a brand-new address with no history has near-zero influence on scores.
Priority modes
When using route, the priority parameter adjusts these weights:
- quality (default) — Maximizes quality and reviewer credibility scores
- speed — Boosts response time weight to 40%
- cost — Boosts price efficiency weight to 40%
Payments & x402
Fabric uses the x402 protocol for agent-to-agent payments. When a service provider returns HTTP 402 Payment Required, Fabric automatically constructs and signs the payment, then retries the request.
How it works
- Agent calls a provider's x402-enabled endpoint via Fabric
- Provider returns 402 with payment requirements in headers
- Fabric checks budget limits — rejects if over budget
- Fabric signs USDC payment from the managed wallet
- Payment settles on Base via Coinbase CDP facilitator
- Fabric retries the request with payment proof
- Provider returns the result
Supported chains & tokens
| Chain | Token | Avg. tx cost |
|---|---|---|
| Base | USDC | ~$0.00025 |
| Ethereum (planned) | USDC | ~$0.50–2.00 |
| Solana (planned) | USDC | ~$0.001 |
Budget Controls
Fabric enforces spending limits at multiple levels to prevent runaway agent costs.
| Level | Description | Default |
|---|---|---|
| Per-request | Max spend on a single service call | $0.50 |
| Per-task | Max spend for a multi-step task | $2.00 |
| Daily | Total spend across all agents per day | $5.00 |
| Monthly | Hard cap for billing period | $50.00 |
When a limit is hit, Fabric returns an error to the agent with a clear message about which budget was exceeded. Limits are configurable via the budget tool or the developer dashboard.
Agent Identity
Fabric is built on two smart contracts deployed to Base L2, implementing the ERC-8004 standard for on-chain agent identity and reputation.
On-chain data model
- FabricRegistry (ERC-8004): Stores provider ID (bytes32), owner address, endpoint URL, category, name, reputation score (×1000), total interactions, registration timestamp, active status
- FabricIdentity (ERC-721): NFT per agent linking to registry ID. One token per registryId (deduped). Full ERC-721 Enumerable support.
- Reputation updates: Batched by the Fabric operator to amortise gas. Scores are aggregated off-chain from feedback, then committed periodically.
Smart Contracts
Two Solidity contracts deployed on Base L2 using Foundry. 40 test cases. Optimised for cheap reads and batched operator writes.
FabricRegistry.sol — ERC-8004
On-chain registry for AI agent/provider identities. Stores endpoint, category, name, and reputation scores.
// Anyone can register registry.registerAgent( keccak256("prov_flux_001"), // bytes32 agentId "https://flux.ai/v1/generate", // endpoint "image-generation", // category "Flux Pro" // name ); // Operator batches reputation updates registry.batchUpdateReputation( agentIds, // bytes32[] scores, // uint256[] (×1000, e.g. 4500 = 4.5) interactions // uint256[] (accumulates) ); // Read providers by category (paginated) Agent[] memory agents = registry.getAgentsByCategory("image-generation", 0, 10);
| Function | Access | Description |
|---|---|---|
| registerAgent | Anyone | Register a new provider with endpoint, category, name |
| updateAgent | Agent owner | Update endpoint or active status |
| deactivateAgent | Agent owner | Set agent inactive |
| batchUpdateReputation | Operator | Batch update scores + interactions |
| getAgent | View | Get agent by bytes32 ID |
| getAgentsByCategory | View | Paginated category query |
| getReputation | View | Score + interaction count |
| totalAgents | View | Total registered count |
FabricIdentity.sol — ERC-721
Non-fungible identity tokens for agents. Each token links to a registry entry. One NFT per registryId (deduped). Full ERC-721 + Enumerable.
// Operator mints identity NFT uint256 tokenId = identity.mint( agentWallet, // address to "Flux Pro", // agentName keccak256("prov_flux_001") // registryId (must match registry) ); // Read agent data from NFT (string name, bytes32 regId, uint256 createdAt) = identity.getAgentData(tokenId);
# Deploy both contracts forge script script/Deploy.s.sol:DeployFabric \ --rpc-url $BASE_SEPOLIA_RPC_URL \ --private-key $PRIVATE_KEY \ --broadcast --verify # Seed 5 test providers forge script script/Deploy.s.sol:SeedProviders --rpc-url $BASE_SEPOLIA_RPC_URL --broadcast # Mint identity NFTs forge script script/Deploy.s.sol:MintIdentities --rpc-url $BASE_SEPOLIA_RPC_URL --broadcast
WebMCP Integration
Fabric integrates with the W3C WebMCP spec — the new browser-native API (navigator.modelContext) co-authored by Google and Microsoft that lets websites expose structured tools to AI agents. Fabric adds the missing pieces: trust verification, autonomous payments, and cross-origin discovery.
WebMCP + Fabric = Complete Agent Stack
WebMCP provides the tool contract (what actions exist). Fabric provides the trust contract (should the agent use this tool?) and the payment contract (how does the agent pay?). Together they replace screenshot-based browser agents with structured, verified, paid tool calls.
Architecture
Browser (site) Fabric Gateway Base L2 ────────────── ────────────── ──────── registerTool() ───────► Index tool contract Compute trust score Agent calls tool ──────► Verify trust ≥ threshold Settle x402 payment ──────► USDC transfer Proxy to origin ◄────── Confirmation ◄─────── Return result + receipt
Browser SDK
npm install @usefabric/webmcp
import { FabricWebMCP } from '@usefabric/webmcp' const fabric = new FabricWebMCP({ apiKey: process.env.FABRIC_KEY, gateway: 'https://fabric-gateway.fly.dev', }) // Register a tool — bridges navigator.modelContext with Fabric trust+payment fabric.registerTool({ name: 'searchProducts', description: 'Search the product catalog', inputSchema: { type: 'object', properties: { query: { type: 'string' }, maxResults: { type: 'number' }, }, required: ['query'], }, category: 'ecommerce', pricePerCall: 0.01, // $0.01 per call — settled via x402 async execute(params) { return await productSearch(params.query) }, }) // Tools auto-sync to Fabric on registration
Execution Modes
Server-proxied — Fabric calls the origin, handles payment, returns result:
const result = await fabric.execute( 'searchProducts', { query: 'running shoes' }, agentId ) // result.payment.settled === true // result.trust.score === 0.92
Client-delegated — Fabric authorises payment, browser executes locally:
const result = await fabric.executeLocal( 'searchProducts', { query: 'running shoes' }, agentId ) // result.local === true — executed in-browser
REST API
| Method | Endpoint | Description |
|---|---|---|
| POST | /v1/webmcp/register | Register tools from an origin |
| POST | /v1/webmcp/manifest | Register from manifest URL |
| GET | /v1/webmcp/discover | Discover tools across origins |
| GET | /v1/webmcp/tools/:id | Get tool details |
| POST | /v1/webmcp/execute | Execute through trust+payment |
| POST | /v1/webmcp/authorise | Get auth for client execution |
| DELETE | /v1/webmcp/origin | Deactivate origin tools |
MCP Tools
WebMCP tools are also accessible through Fabric's MCP interface:
| Tool | Description |
|---|---|
| fabric_webmcp_discover | Find WebMCP tools by category, origin, trust score |
| fabric_webmcp_execute | Execute a WebMCP tool through Fabric trust+payment |
| fabric_webmcp_register | Register tool contracts from an origin |
WebMCP vs MCP vs Fabric
| Feature | MCP (Anthropic) | WebMCP (W3C) | Fabric |
|---|---|---|---|
| Runtime | Server-side | Browser-native | Both |
| Protocol | JSON-RPC | navigator.modelContext | REST + MCP |
| Trust | None built-in | None built-in | 7-signal scoring |
| Payments | None built-in | None built-in | x402 / USDC on Base |
| Discovery | Per-server | Per-page | Cross-origin registry |
| User consent | Optional | Required (elicitation) | Configurable |
REST API
22 endpoints across 7 route groups. All endpoints require x-api-key header (except health checks).
| Group | Endpoints | Description |
|---|---|---|
| Discovery | GET /v1/discover | Find providers by category with trust scores |
| Routing | POST /v1/route | End-to-end: discover → score → pay → return |
| Evaluation | POST /v1/evaluate | Evaluate a specific provider's trust score |
| Budgets | GET/POST /v1/budget | View/set spending limits (per-agent, per-task, daily) |
| Feedback | POST /v1/feedback | Submit provider feedback (1-5 score) |
| Favorites | GET/POST/DELETE /v1/favorites | Manage preferred providers |
| Wallets | GET/POST /v1/wallets | Create and manage USDC wallets |
| Chain | GET /v1/chain/* | On-chain data: balance, tx status, gas |
| Billing | GET/POST /v1/billing/* | Subscription, checkout, invoices, overage |
| Health | GET /healthz /ready /health | Shallow, readiness, deep health checks |
| Metrics | GET /metrics | Prometheus OpenMetrics format |
| MCP | POST /mcp | MCP JSON-RPC handler (6 tools) |
SDKs
First-class TypeScript and Python SDKs with full type safety.
import { FabricClient } from '@fabric/sdk' const fabric = new FabricClient({ apiKey: 'fab_...', baseUrl: 'https://api.usefabric.ai' }) // Discover providers const providers = await fabric.discover({ category: 'image-generation', minTrust: 0.8 }) // Route (discover → score → pay → return) const result = await fabric.route({ capability: 'image-generation', input: { prompt: 'A sunset over the ocean' }, priority: 'quality' }) // Check budget const budget = await fabric.getBudget()
from fabric_sdk import FabricClient fabric = FabricClient(api_key="fab_...") # Async discover providers = await fabric.discover(category="translation", min_trust=0.7) # Sync route result = fabric.route_sync( capability="translation", input={"text": "Hello world", "target": "es"} )
Billing
Stripe-powered subscriptions with metered overage. 10 billing endpoints.
| Endpoint | Description |
|---|---|
| GET /v1/billing/subscription | Current plan + subscription info |
| POST /v1/billing/checkout | Create Stripe Checkout session |
| POST /v1/billing/portal | Open Stripe billing portal |
| POST /v1/billing/plan | Change plan (proration preview) |
| POST /v1/billing/cancel | Cancel at period end |
| POST /v1/billing/reactivate | Reactivate cancelled subscription |
| GET /v1/billing/invoices | List invoices (limit 12) |
| GET /v1/billing/upcoming | Upcoming invoice estimate + projection |
| GET /v1/billing/overage | Daily and period overage summary |
Webhook handler at POST /webhooks/stripe processes 6 event types: checkout completed, subscription created/updated/deleted, invoice paid, payment failed.
Rate Limits
Sliding window algorithm using Redis sorted sets. No boundary-burst issues.
| Context | Limit | Window |
|---|---|---|
| Per API key (authenticated) | 100 requests | 1 minute |
| Per IP (unauthenticated) | 20 requests | 1 minute |
Response headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After. Health and metrics endpoints are exempt.
Configuration
new FabricServer({ // Required apiKey: "fab_...", // Trust trustThreshold: 0.8, // 0-1, min trust score priority: "quality", // quality | speed | cost fallbackEnabled: true, // auto-retry next provider maxFallbacks: 3, // max retry attempts // Payments chain: "base", // payment chain token: "USDC", // payment token // Budgets budget: "$5/day", // daily limit maxPerRequest: "$0.50", // per-call limit maxPerTask: "$2.00", // per-task limit // Feedback autoFeedback: true, // post feedback after route feedbackDelay: 5000, // ms delay before posting })
Pricing
Fabric charges a flat monthly subscription plus a percentage routing fee on x402 transactions. No markup on Base gas fees — those come directly from your managed wallet.
| Plan | Price | Requests/day | Routing fee | Wallets | Features |
|---|---|---|---|---|---|
| Free | $0 | 50 | — | 0 | Discovery + evaluate only. No routing or payments. |
| Builder | $9/mo | 5,000 | 0.5% | 3 | Full routing + payments, budget controls, feedback |
| Pro | $39/mo | 15,000 | 0.4% | 10 | Custom trust weights, analytics dashboard, overage billing |
| Team | $149/mo | 50,000 | 0.3% | 50 | Multi-agent management, audit logs, SLA guarantees, dedicated support |
Overage
Requests beyond your daily limit are billed at $0.001 per request, charged monthly in arrears. You can set a hard cap in your dashboard to prevent overage entirely.
What counts as a request?
Each call to discover, route, evaluate, budget, feedback, or favorites counts as one request. On the Free plan, only discover and evaluate are available.
Free users can explore the registry and evaluate providers before committing. When you're ready to route and pay, upgrade to Builder — no credit card required for the first 7 days.
Protocol Stack
| Protocol | Role in Fabric | Maintainers |
|---|---|---|
| ERC-8004 | Agent identity + reputation registries | Ethereum Foundation, Coinbase, Google, MetaMask |
| x402 | HTTP-native agent payments | Coinbase, Cloudflare, x402 Foundation |
| MCP | Agent ↔ tool interface standard (server-side) | Anthropic, OpenAI, Google, Microsoft |
| WebMCP | Browser-native agent ↔ tool API (client-side) | Google, Microsoft, W3C WebML CG |
| Base L2 | Payment settlement layer | Coinbase |
| ERC-721 | Agent identity NFTs | Ethereum |
| USDC | Payment token | Circle |
Deployment
Production-ready with Docker, monitoring, and CI/CD.
# Start the full stack docker compose -f docker-compose.prod.yml up -d # Services: gateway, postgres, redis, prometheus, grafana # Gateway: 512M memory, non-root user, health check every 15s # Grafana dashboard: 8 panels (request rate, error rate, p99 latency, memory)
| Component | Details |
|---|---|
| Runtime | Bun + Elysia in multi-stage Docker (non-root user 1001) |
| Database | PostgreSQL with Prisma ORM (9 models) |
| Cache | Redis (trust scores, rate limits, overage tracking) |
| Monitoring | Prometheus scraping /metrics + 8-panel Grafana dashboard |
| Error tracking | Sentry integration (onError hook) |
| CI/CD | GitHub Actions: lint → test → build → Docker push → deploy |
| Load testing | Custom script: 5 weighted scenarios, p99 < 2000ms pass criteria |
| Security | HSTS, CSP, request IDs, 10MB payload limit, KMS key encryption |
GET /healthz → shallow (for load balancers) GET /ready → readiness (DB healthy, Redis optional) — 503 if not ready GET /health → deep (postgres latency, redis latency, memory, uptime)