Home How it works Features Pricing Stack Overview Quickstart Architecture MCP: discover MCP: route MCP: evaluate Trust Scoring Payments & x402 Smart Contracts WebMCP Integration REST API SDKs Billing Get started

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

bash
npm install @usefabric/mcp

2. Configure your server

typescript
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

json
{
  "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.

agent prompt
// 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.

architecture
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.

capabilitystringrequired
What your agent needs, e.g. "image-generation", "data-lookup", "code-review"
maxResultsnumber
Maximum providers to return. Default: 10
minTrustnumber
Minimum trust score (0-1). Overrides server-level trustThreshold for this query.
maxPricestring
Maximum price per request, e.g. "$0.05"
response
{
  "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.

capabilitystringrequired
Service capability needed
inputobjectrequired
Payload to send to the service provider
priority"quality" | "speed" | "cost"
How to weight the scoring. Default: "quality"
preferredProviderstring
Agent ID to try first (from favorites list)
example
// 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.

agentIdstringrequired
The ERC-8004 agent ID (NFT token ID or address)
response
{
  "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"check" | "history" | "update"required
What to do with the budget
ActionDescriptionReturns
checkCurrent balance and remaining daily limitBalance, spent today, daily limit
historyTransaction log with provider, cost, timestampArray of recent transactions
updateChange daily/per-task limitsUpdated 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.

agentIdstringrequired
Provider agent ID to rate
scorenumberrequired
Quality score 0–100
tagsstring[]
Up to 2 tag labels, e.g. ["fast", "accurate"]

Tool: favorites

Manage a list of preferred providers. When a favorite is available for a capability, Fabric will try it first before discovering alternatives.

action"list" | "add" | "remove"required
Manage favorites list
agentIdstring
Required for add/remove actions

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

FactorWeightSource
Uptime25%Success rate from on-chain feedback
Quality30%Average quality scores from reviews
Response time15%Latency measurements from feedback metadata
Reviewer credibility20%Weighted by reviewer's own reputation (Sybil resistance)
Price efficiency10%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:

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

  1. Agent calls a provider's x402-enabled endpoint via Fabric
  2. Provider returns 402 with payment requirements in headers
  3. Fabric checks budget limits — rejects if over budget
  4. Fabric signs USDC payment from the managed wallet
  5. Payment settles on Base via Coinbase CDP facilitator
  6. Fabric retries the request with payment proof
  7. Provider returns the result

Supported chains & tokens

ChainTokenAvg. tx cost
BaseUSDC~$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.

LevelDescriptionDefault
Per-requestMax spend on a single service call$0.50
Per-taskMax spend for a multi-step task$2.00
DailyTotal spend across all agents per day$5.00
MonthlyHard 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

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.

solidity — register a provider
// 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);
FunctionAccessDescription
registerAgentAnyoneRegister a new provider with endpoint, category, name
updateAgentAgent ownerUpdate endpoint or active status
deactivateAgentAgent ownerSet agent inactive
batchUpdateReputationOperatorBatch update scores + interactions
getAgentViewGet agent by bytes32 ID
getAgentsByCategoryViewPaginated category query
getReputationViewScore + interaction count
totalAgentsViewTotal 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.

solidity — mint identity
// 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 with Foundry
# 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

flow
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

bash
npm install @usefabric/webmcp
typescript
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:

typescript
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:

typescript
const result = await fabric.executeLocal(
  'searchProducts',
  { query: 'running shoes' },
  agentId
)
// result.local === true — executed in-browser

REST API

MethodEndpointDescription
POST/v1/webmcp/registerRegister tools from an origin
POST/v1/webmcp/manifestRegister from manifest URL
GET/v1/webmcp/discoverDiscover tools across origins
GET/v1/webmcp/tools/:idGet tool details
POST/v1/webmcp/executeExecute through trust+payment
POST/v1/webmcp/authoriseGet auth for client execution
DELETE/v1/webmcp/originDeactivate origin tools

MCP Tools

WebMCP tools are also accessible through Fabric's MCP interface:

ToolDescription
fabric_webmcp_discoverFind WebMCP tools by category, origin, trust score
fabric_webmcp_executeExecute a WebMCP tool through Fabric trust+payment
fabric_webmcp_registerRegister tool contracts from an origin

WebMCP vs MCP vs Fabric

FeatureMCP (Anthropic)WebMCP (W3C)Fabric
RuntimeServer-sideBrowser-nativeBoth
ProtocolJSON-RPCnavigator.modelContextREST + MCP
TrustNone built-inNone built-in7-signal scoring
PaymentsNone built-inNone built-inx402 / USDC on Base
DiscoveryPer-serverPer-pageCross-origin registry
User consentOptionalRequired (elicitation)Configurable

REST API

22 endpoints across 7 route groups. All endpoints require x-api-key header (except health checks).

GroupEndpointsDescription
DiscoveryGET /v1/discoverFind providers by category with trust scores
RoutingPOST /v1/routeEnd-to-end: discover → score → pay → return
EvaluationPOST /v1/evaluateEvaluate a specific provider's trust score
BudgetsGET/POST /v1/budgetView/set spending limits (per-agent, per-task, daily)
FeedbackPOST /v1/feedbackSubmit provider feedback (1-5 score)
FavoritesGET/POST/DELETE /v1/favoritesManage preferred providers
WalletsGET/POST /v1/walletsCreate and manage USDC wallets
ChainGET /v1/chain/*On-chain data: balance, tx status, gas
BillingGET/POST /v1/billing/*Subscription, checkout, invoices, overage
HealthGET /healthz /ready /healthShallow, readiness, deep health checks
MetricsGET /metricsPrometheus OpenMetrics format
MCPPOST /mcpMCP JSON-RPC handler (6 tools)

SDKs

First-class TypeScript and Python SDKs with full type safety.

typescript
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()
python
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.

EndpointDescription
GET /v1/billing/subscriptionCurrent plan + subscription info
POST /v1/billing/checkoutCreate Stripe Checkout session
POST /v1/billing/portalOpen Stripe billing portal
POST /v1/billing/planChange plan (proration preview)
POST /v1/billing/cancelCancel at period end
POST /v1/billing/reactivateReactivate cancelled subscription
GET /v1/billing/invoicesList invoices (limit 12)
GET /v1/billing/upcomingUpcoming invoice estimate + projection
GET /v1/billing/overageDaily 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.

ContextLimitWindow
Per API key (authenticated)100 requests1 minute
Per IP (unauthenticated)20 requests1 minute

Response headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After. Health and metrics endpoints are exempt.

Configuration

full config
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.

PlanPriceRequests/dayRouting feeWalletsFeatures
Free$0500Discovery + evaluate only. No routing or payments.
Builder$9/mo5,0000.5%3Full routing + payments, budget controls, feedback
Pro$39/mo15,0000.4%10Custom trust weights, analytics dashboard, overage billing
Team$149/mo50,0000.3%50Multi-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 → Builder upgrade path

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

ProtocolRole in FabricMaintainers
ERC-8004Agent identity + reputation registriesEthereum Foundation, Coinbase, Google, MetaMask
x402HTTP-native agent paymentsCoinbase, Cloudflare, x402 Foundation
MCPAgent ↔ tool interface standard (server-side)Anthropic, OpenAI, Google, Microsoft
WebMCPBrowser-native agent ↔ tool API (client-side)Google, Microsoft, W3C WebML CG
Base L2Payment settlement layerCoinbase
ERC-721Agent identity NFTsEthereum
USDCPayment tokenCircle

Deployment

Production-ready with Docker, monitoring, and CI/CD.

docker compose — production
# 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)
ComponentDetails
RuntimeBun + Elysia in multi-stage Docker (non-root user 1001)
DatabasePostgreSQL with Prisma ORM (9 models)
CacheRedis (trust scores, rate limits, overage tracking)
MonitoringPrometheus scraping /metrics + 8-panel Grafana dashboard
Error trackingSentry integration (onError hook)
CI/CDGitHub Actions: lint → test → build → Docker push → deploy
Load testingCustom script: 5 weighted scenarios, p99 < 2000ms pass criteria
SecurityHSTS, CSP, request IDs, 10MB payload limit, KMS key encryption
health checks
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)