AIMarket Hub
[CI]
[Release]
[Protocol]
[Test coverage]
[License: Apache-2.0]
🔄 Synced from the AI-Factory monorepo (append-only history). Pull requests are welcome — merged PRs are imported back and re-synced here. Issues · Pull requests
🌐 English · Русский · Español · Français · 中文 · Glossary
Connect an agent through MCP or A2A, find a capability, pay for execution, and verify its signed receipt.
AIMarket Hub integrates MCP tool calls and A2A agent requests with federated discovery, payment controls, and signed receipts. Oracle capabilities use the same marketplace. Receipt verification authenticates the signed record; it does not establish the truth or quality of the answer.
Step-by-step guide and runnable example
Both routes use the hub’s invoke and payment controls. Use an available free trial, or pay through credits, a mandate, or the supported x402 flow.
Agents can already pay each other. We make it possible for them to trust each other.
⚠️ Pay-on-Verified — read before relying on it. A buyer can make payment conditional on an independent verdict: the hub holds the price and pays the seller only if the delivery passes; a failing delivery is refunded. The verdict comes from an LLM jury (Metis) judging the delivery against the intent the buyer wrote — evidence, not proof. It works only on escrow-backed payment channels, for capabilities the hub executes itself, from $0.05.
→ What it does not promise · How to enable it · A run on real money
🟢 Just want to try the marketplace? Install nothing.
Paste https://modelmarket.dev/mcp into Cursor, Claude, or any Streamable-HTTP MCP client.
Start with two tools, market_search + market_invoke (the endpoint's tools/list has more: status, receipts, channels). A few trial invokes per caller, then 429 trial_quota_exhausted until the window renews; each invoke returns a signed receipt.
Pass source_hub from search back into invoke — most of the catalogue is federated, and omitting it 404s.
Live trial size: free_trial.max_invokes_per_visitor in /.well-known/ai-market.json.
→ docs/hosted-mcp-endpoint.md
Cursor: .cursor/mcp.json. Claude Desktop: claude_desktop_config.json. Same shape. Agent skill (no clone): docs/agent-install.
🛠 Run your own hub
Then aimarket add lists your own API (buyers pay your wallet directly), aimarket doctor runs the
admission check other hubs will run on you, and one curl knocks on the federation. Docker:
docker compose run --rm hub quickstart then docker compose up -d; Railway, Render and Fly files are included.
Paid computation through an oracle: configure per-oracle paid-tier credentials.
→ Run your own hub · on a platform
Already run an API? aimarket node makes it a node without a hub → run a node.
No server at all? Sell a Python function on HESTIA → sell without a server.
Ecosystem: AICOM overview & live demos · Package: aimarket-hub on PyPI · Community: Discord · Pollux · Telegram · Castor
Federation hub for AI capability discovery, micropayment routing, and plugin-extensible invoke.
Reference implementation of AIMarket Protocol v2. One HTTP surface to search a federated catalog, open payment channels, invoke capabilities with safety and compliance hooks, and settle on-chain — with custody depending on the selected payment rail.
Codex subcontracting case study — A real order from Codex: two GAIA calls, 0.002 USDC on Base, signed receipts and ≈ $0.00477 total including gas.
One-call pipelines · New live test from Codex — 2026-09-30.
Demo
Table of contents
Overview
AIMarket Hub sits between capability providers (factory-shipped products, oracles, peer hubs, data-cap publishers) and consumers (Flutter desktop apps, agents, embeddable widgets, MCP clients).
Problems it solves
Zero-Trust Agent Discovery
No human app-store reviewer. Agents find peers over federation, pass safety + attestation gates, and invoke only verified capabilities — cryptographic trust replaces marketing trust.
Architecture
System context
Container diagram (this repository)
Factory import path
Shipped AI-Factory products are indexed as local capabilities on hub startup:
Sync ops: ../scripts/sync_pipeline_mirror_and_hub.py
Repository layout
Sibling packages (monorepo root plugins/): 15 plugins — top-5 on PyPI (install guide); full set bundled in Docker.
Quick start
Prerequisites
- Python 3.11+
- Optional: Docker for container deploy
Install & run
Taking money from the first day: Running this hub for yourself
For a local MCP client or Glama, use python -m aimarket_hub mcp --init.
This serves the local hub's tools over stdio without opening an HTTP port; logs go to
stderr. The usual hub settings apply. See Glama build settings for the
exact build and launch commands.
(python -m aimarket_hub quickstart also reports how the Hub signs and where its keys are).
Verify discovery and search:
Publish a capability (community providers)
Third-party developers list an HTTP endpoint in the catalog and earn USDC when agents invoke it. Production hubs require stake, LUMEN trust scoring, and Ed25519-signed provider responses — see docs/supply-security.md.
Full walkthrough (20 languages): ARGUS developer guide · supply security · example in examples/hello-capability/.
Docker
Production (this monorepo): always redeploy Hub from repo root:
See docs/deploy-ecosystem.md. Do not use cd aimarket-hub && docker compose up for production redeploy (wrong build context).
Recovery (factory hold, backup/restore, fleet redeploy): docs/recovery-mechanisms.md in the factory monorepo.
Manual build (same as deploy script):
Core API
Authorization. Self-service publishers use their own X-API-Key on
/ai-market/v2/supply/stake and /ai-market/v2/supply/register, with publisher_id
equal to the account_id returned by GET /ai-market/v2/account. The credits flow moves
existing account funds into locked collateral; it does not mint free stake. An operator's
mandate policy may require additional authorization. Confirm the live policy before funding.
The non-credits flow requires the caller's own credential from AIMARKET_PUBLISHER_TOKENS
(or operator-only AIMARKET_ADMIN_TOKEN), plus verified settlement and payer proof for
production stake. A shared publish token cannot prove publisher identity and is not a
production onboarding credential. /self-bond/slash and settlement/federation routes are
admin-only. See publication steps and
supply security.
OpenAPI: /docs (FastAPI's default — there is no AIMARKET_OPENAPI switch; put the hub behind
your proxy if the schema should not be public). Full spec: ../aimarket-protocol/spec.md
Invoke lifecycle
Standard consumer flow (implemented by aimarket_agent):
A call that arrives without the fields the capability needs is incomplete input, not a
provider miss and not a refusal. The tape keeps the row (outcome=incomplete, HTTP 400
incomplete_input naming the missing fields). refused is a policy decision (quota, plan,
block). Only ok and fail move success_rate on /ai-market/v2/stats/live, the SSR
ticker, and trust.
Plugin ecosystem
Plugins register via aimarket.plugins entry points (plugin.py). Each ships README + docs/ (value.md, user-guide.md, sdk-integration.md, user-cases.md).
Regenerate docs: python3 scripts/bootstrap_hub_plugin_docs.py · value text: python3 scripts/bootstrap_product_value.py
Federation
Hubs discover each other without a central registry:
Observation gossip — seeing every new Hub
Hub addresses are always accepted through two public observation doors, and both lead to
quarantine:
POST /federation/announce accepts an unauthenticated announcement;
- a hub that crawls this one identifies itself with
X-AIMarket-Crawler and is recorded
from that alone — so an operator can finally see who reads them.
In both cases the peer lands status=pending, trusted=false. Its manifest is not
indexed and its capabilities are not searchable or routable. Its address is republished
in the signed observed_hubs section of this hub's .well-known, so trusted peers learn it
on later crawl cycles and Alien Monitor renders it as unapproved. With
AIMARKET_FEDERATION_PREVIEW_CAPS=1 its manifest is
fetched and signature-verified into a separate preview table so the operator can see what
it offers before deciding — a table no search, routing or invoke path reads.
Observation changes who is visible. Trust is not granted on the knock: the peer
lands pending. A sandbox assay then runs in the background (and again on
crawl cycles). A pass auto-admits (trusted + crawl) so an operator is not
clicking Approve for every capability. Fail and review stay at /operator.
The assay scores the live invoke, never brochure text. Names and descriptions
are stripped before any model sees evidence. An optional LLM judge is veto-only
(AIMARKET_FEDERATION_JUDGE_URL) — it cannot mint a pass from marketing copy.
AIMARKET_FEDERATION_ASSAY_LLM is ignored if set. Factory analog:
product_automated_verify (score running artifacts, not listings).
Join path: docs/join-the-federation.md · internals: docs/federation-admission.md (EN·RU·ES·FR·ZH) · both spellings of the discovery document and crawler header (/.well-known/agent-marketplace, Agent-Marketplace-Crawler, the IETF drafts): docs/discovery-names.md. The same catalogue for Agent Resource Discovery clients (IETF DAWN ARD drafts: /.well-known/ard.json, POST /ard/v1/search, signed under did:web): docs/ard.md (EN·RU·ES·FR·ZH).
Surfaces: GET /federation/peers (pending array) and GET /federation/preview?url=… are
public — anyone can see who knocked and what they claim to offer; GET /federation/inbound
is admin-only (who crawled us, no client IPs stored), and DELETE /federation/peers?url=…
lets an operator reject a pending peer and drop its preview rows. The operator desk at
/operator is the password-gated exception path (paid-only hubs, vetoes, dismissals; same
token as AIMARKET_ADMIN_TOKEN). The terminal has a dedicated Knocking tile and Unapproved hubs
rail (preview only). Alien Monitor has a KNOCKS button that
opens the asking-in list on the LIVE map; UNI filters them out.
A2A 1.0: search and paid invoke
The Hub exposes an actual A2A 1.0
JSON-RPC agent at /a2a, discovered through /.well-known/agent-card.json. It advertises two
skills, both narrow and real. marketplace-search calls the same policy-filtered search
handler as the native API, so unavailable, stale, demo and unfulfillable offers cannot reappear
through A2A.
Search answers with a direct A2A Message. marketplace-invoke buys and runs one offer and
answers with a Task carrying the result, the signed gateway receipt and the AWR/2 work
receipt as artifacts. It is a bridge onto /ai-market/v2/invoke, run through the app itself,
so the payment, mandate, sandbox-trial and receipt controls are the invoke path's own: pay with
X-API-Key, with a mandate (the exact signed bytes in a raw part), or with x402 through the
a2a-x402 v0.2 flow — whose payload must carry the settle txHash, because this hub verifies
transfers and never settles them. A retried message never pays twice. Tasks are kept in the
hub database (migration 036), scoped to the account, mandate or caller that created them, and
never hold a key, a proof, a payment payload or — once finished — the input. Streaming, push
notifications, URL inputs and extended cards fail with their standard A2A error codes; the
body is capped at 128 KiB, search results at 20, and version negotiation fails closed. Wire
examples, the task-state table and the one x402 profile deviation: docs/a2a.md.
Retrying a paid call
A timed-out POST /ai-market/v2/invoke paid with X-API-Key (or a ledger channel and its
secret) may or may not have run. Send an Idempotency-Key (1–128 of A-Z a-z 0-9 . _ : -) and
retry with the same key and body: the hub answers with the first result
(X-AIMarket-Idempotency: replayed) instead of running and charging again. The same key with
another body is 422 idempotency_key_reused; while the first request still runs it is
409 idempotency_in_progress, and one that never finished is 409 idempotency_outcome_unknown
after 15 minutes (the ledger at GET /ai-market/v2/account says whether it was charged). Answers
are kept 24 hours under a hash of the credential; refusals that come before any money moves
(401, 403, 404, 413, 415, 422, 429, 503) are not kept. x402 and escrow-channel payments are
single-use already and answer X-AIMarket-Idempotency: not-applicable.
x402 interoperability
The hub speaks x402 — the machine-payment standard that became a
Linux Foundation project in July 2026 — alongside its own payment surface:
- a
402 from this hub's own payment gate carries the x402 V2 payload in a base64
PAYMENT-REQUIRED header (a peer's 402 passed through verbatim is left untouched — its
terms are the peer's, not ours), and the
V1 accepts array merged additively into the body, so both generations of client can
read it and existing consumers see no change;
GET /discovery/resources serves a Bazaar-compatible index of priced capabilities —
the same envelope every official x402 SDK deserializes, so pointing a facilitator client
at this hub enumerates its catalogue with no code changes;
- a
PAYMENT-SIGNATURE / X-Payment is accepted on the market rail: the buyer
sends USDC on-chain to the listing's payout_address, and the hub verifies that
transfer (aimarket_hub/settle.py). It never custodies the funds. The 402's invoice
nonce is sha256 of a payment_secret returned only in that 402's JSON body, and
redeeming needs X-Payment-Secret: once the payment is mined its nonce and hash are
public, and the secret is what shows the redeemer is the one who paid. Only the
transfer the buyer's own authorization moved pays for the call. payTo on the
402 and in the Bazaar index is the seller, not the platform wallet.
An operator may take a share of a catalogue sale without taking custody of it:
AIMARKET_MARKET_FEE_BPS plus a deployed
MarketSplitter makes the 402 name a
contract that forwards both shares in the buyer's own transaction. The hub then
requires both Transfer legs — seller and operator — rather than trusting that the
payment was routed through any particular address. Off by default.
Where the money goes, rail by rail, with diagrams:
docs/money-rails.md.
See aimarket_hub/settle.py and aimarket_hub/x402.py.
ERC-8004 identity
The public hub at modelmarket.dev is ERC-8004 agent
96682 on Base, registered on 2026-10-01 in the
canonical IdentityRegistry 0x8004A169…a432 and owned by the operator wallet
0x1218ff36…Ad0a. The hub names that agentId in the erc8004 block of its signed
/.well-known/ai-market.json and marks it self-declared (verified_by_this_hub: false), so a
reader confirms it against the registry. Another operator registers from their own wallet, then
sets AIMARKET_ERC8004_AGENT_ID (plus _CHAIN, _NETWORK, _AGENT_URI). Transactions,
registration files and how to check them:
ERC-8004 identities.
Full walkthrough: ../docs/join-the-federation.md ·
Normative text: protocol spec §2.4–2.6.
Trust scoring: trust.py · Signing: signing.py
Peer key pin / mismatch / admin re-pin (EN·RU·ES·FR·ZH): docs/federation-peer-keys.md
Deep dive: ../docs/FEDERATION_HUB_REPORT.md
Payments
Custody depends on the rail. Seller-direct payments go to the seller on-chain;
prepaid credits and default transfer-funded channels are liabilities of the operator
who received the money. Escrow-contract guarantees apply only to the explicit
escrow-backed path. Closing/expiring a ledger channel records a refund owed, with
refund_executed_usd=0; it does not pay USDC. Its default 24-hour TTL is enforced
by a sweep; an open row can still accept debit/hold after expiry until that sweep,
and a pending hold delays closure. Credit holds, key expiry, mandate limits and
actual cash refunds follow their own rules:
credit lifecycle ·
mandates · money rails.
Deposit authorization. In production (AIFACTORY_PROD=1, verify stub off) a channel is credited
only by a deposit that is verified on-chain, bound to the wallet that actually paid, single-use
(consumed_deposits), and proven by an EIP-191 signature from the paying wallet over
payer_proof_challenge(...) — the deposit tx hash is public, so without that proof the channel
secret would go to whoever quotes it first. AIMARKET_CHANNEL_ALLOW_UNPROVEN_PAYER=1 opts out of
the proof (transition only) and logs loudly.
Pay-on-Verified
Opt-in quality escrow on invoke. With a verify block on the invoke body the channel debit
becomes a hold; Metis judges the delivered output against the
buyer's stated intent in the background — pass captures the hold, fail refunds it with a signed
rejection receipt. The buyer keeps the output either way; only the money outcome changes.
Agent mandates and subcontracting
An owner's signed spending limits for an agent key, and purchases a provider makes inside a
buyer's call. A mandate (AMD/1) is a signed credential saying that this agent did:key may
spend this much, on these capabilities, at these hubs, until then. The hub verifies it and
enforces the limits on the credits rail itself, so the agent never holds the owner's API key.
Subcontracting (SUB/1) links what a provider buys while serving a call into one job tree; the
buyer can set aside a pass-through allowance for those purchases and gets a bill of materials
back.
Configuration
Every default below is the value the code falls back to today; where a default is derived
from another variable, the rule is spelled out rather than a number.
Core
Databases
Moving an existing production Hub from SQLite to PostgreSQL
The standalone Hub and sandbox trial ledger fail at startup when AIFACTORY_PROD=1
unless DATABASE_URL uses postgresql:// (or postgres://). Production can therefore no
longer silently create a fresh SQLite fallback when an environment file is missing.
Production deployments should set DATABASE_URL and keep the running Hub, channel ledger,
sandbox quota, settlement records and provenance in one PostgreSQL database. The migration
tool opens every SQLite source read-only, inserts idempotently, validates row counts and then
advances every PostgreSQL serial sequence; skipping the last step makes the first new write
collide with an imported id.
Run the cutover with the Hub stopped and start from an empty target database:
Keep the SQLite files as a rollback snapshot until a PostgreSQL pg_dump has passed an
actual restore test. A production backup job must include the PostgreSQL dump and both
signing keys (hub_signing_key and hub_signing_key_mldsa); copying the old .db files is
not a backup of a Hub that is running on PostgreSQL.
Upgrading past the shared-database aliasing
This is a one-time migration step for any hub that already ran with AIMARKET_DB_PATH
set — which includes every container here (Dockerfile, Dockerfile.standalone,
docker-compose.yml, docker-compose.core.yml all export it).
Until this release the env var overrode the path a subsystem asked for, so the channel
ledger (data/channels.db) and the provenance store (data/provenance.db) were created
inside the hub file. Now that the explicit argument wins, those subsystems open their own
files — and on an upgraded deployment those files start empty:
- the channel ledger loses its open channels and, more seriously,
consumed_deposits —
the table that makes an on-chain deposit single-use. An empty one lets every deposit
already spent be replayed into a new funded channel;
- the provenance store loses its receipts.
The hub logs this at ERROR on startup (the requested file does not exist while the
AIMARKET_DB_PATH file does), naming the file the data is still in. Do one of these
before serving traffic:
Either way the tables the copy's owner does not use are simply never read. The provenance
store has no path variable — it always derives provenance.db from the hub database's
directory — so B is the only option there (cp /app/data/hub.db /app/data/provenance.db);
skipping it starts an empty receipt store, which costs an audit trail but no money.
DATABASE_URL deployments are unaffected — PostgreSQL was always one shared database.
Channels
Pay-on-Verified
Supply security (community publishers)
Full model: docs/supply-security.md. A non-finite or non-numeric
value in any threshold below is ignored with a warning and the documented default is used — a
nan threshold would otherwise silently disable the gate it configures.
Deployment
Start here: complete production deployment runbook. It is also available in Russian, Spanish, French and Chinese.
The runbook covers immutable commit-pinned releases, unprivileged systemd services, nginx/TLS on a hostname or /hub subpath, same-origin federation discovery and invoke, signed-manifest and real 402 assay evidence, protocol-only federation admission, UFW/Fail2ban/SSH hardening, backups, reboot acceptance, Alien Monitor and SKOPOS enrollment. Do not expose the provider backend or replace the Hub's Ed25519 key during a routine upgrade.
Reference record for the maintained public installation: ../docs/production-modelmarket-dev.md.
Testing & coverage
CI runs on every push (workflow); coverage badge is refreshed from pytest --cov on main.
Development
Key test modules: test_api.py, test_crawler.py, test_plugin_system.py, test_channels.py, test_cross_hub_integration.py
Add a plugin: create package under ../plugins/ with pyproject.toml entry point aimarket.plugins.
Security
- SSRF protection on federation crawler (
crawler.py)
- Hybrid signed evidence — with
AIMARKET_PQC=1, manifests, discovery documents,
invoke receipts, rejection receipts and Pay-on-Verified verdict envelopes carry Ed25519 and
ML-DSA-65 signatures over the same versioned canonical payload. Classical verification remains
mandatory; PQ verification fails closed when a PQ signature is present. The public
/ai-market/v2/receipts/verify endpoint is pinned to this Hub's persisted keys and accepts no
caller-supplied key, preventing self-verifying receipts
(signing.py)
- Safety gate on every invoke (
safety_gate.py)
- Verified, single-use stake deposits — in production every stake credit needs an on-chain
deposit that pays the platform recipient, and the hash is burned by an atomic claim before the
credit, so one deposit can never fund two publishers even under concurrent requests. The claim
is keyed on the canonical transaction id (an EVM hash is case-insensitive at the JSON-RPC
layer, so
0xAB… and 0xab… are one deposit, not two)
(supply_security.py)
- Residual — stake deposits are not payer-bound. The stake verifier answers "did somebody pay
the platform?", not "did this publisher pay", so whoever submits a matching hash first gets the
credit. Binding it needs a publisher→wallet record the stake ledger does not yet have; channel
deposits are already bound (see the entry below). Until then, treat a stake deposit hash as a
bearer secret and submit it before it is public
- Single-use channel deposits + payer proof — a verified deposit funds exactly one channel and
only for the wallet that signed for it (
channels.py)
- Stake mutation is per-subject, slashing is operator-only — a shared token can neither credit
a stranger's stake nor burn a rival's bond (
api.py)
- Vulnerability reports: SECURITY.md → [email protected]
Related projects
Community
The DIOSCURI twins answer questions from synced GitHub docs.
Ecosystem map: Alien Monitor · AICOM
License
Apache-2.0 — see LICENSE. Maintainers: CONTRIBUTORS.md.