-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
671 lines (578 loc) · 30.6 KB
/
Copy pathserver.py
File metadata and controls
671 lines (578 loc) · 30.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
"""MINT Protocol — Universal Work Attestation for Autonomous Agents.
A lean, standalone MCP server (FastAPI + SSE) exposing exactly three tools to any
autonomous agent, machine, or service:
mint_register — give an actor a persistent cryptographic identity (FREE)
mint_attest — anchor a tamper-evident record of completed work (FREE)
mint_verify — query an actor's trust score + verified work history (PAID)
It rebuilds nothing and holds no relay key: identity reuses Forge /v1/identify,
attestation reuses Forge /v1/attest (Forge is the single relay key-holder +
settlement engine). Agents are the users — no web UI, no dashboard. Free to
register and attest; the network grows on free identity + free attestation, and
revenue comes from the paid trust READ (verify / trust score). Signed ≠ verified.
Transport: Streamable HTTP at /mcp (remote Railway hosting + Smithery's hosted
gateway, which connects via Streamable HTTP — SSE 405s there). Health: GET /health.
Discovery: /.well-known/agent-card.json, /.well-known/mcp[/server-card.json].
"""
from __future__ import annotations
import inspect
import logging
import os
from fastmcp import FastMCP
from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse
import config
import core
import docs
import forge_client
import merkle_batch
import ml_scorer
import payment_gate
import read_gate
import supa
import tools
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("mint.mcp")
if not forge_client.configured():
logger.warning("FORGE_API_KEY not set — all three tools will return "
"not_configured until it's set in the Railway dashboard.")
mcp = FastMCP("mint-protocol")
# Pay-per-attest gating lives in core.do_attest (payment_gate.py) so the SAME
# policy backs both the MCP tool and the REST route — no middleware to drift, and
# no x402[svm] import that could crash-loop at boot. (The legacy facilitator
# middleware in x402_gate.py is superseded and no longer wired.)
if payment_gate.is_active():
logger.info(f"pay-per-attest ARMED: {config.ATTEST_PRICE_USDC} USDC → "
f"{config.PAYMENT_RECIPIENT} (rpc={config.PAYMENT_VERIFY_RPC})")
else:
logger.info("pay-per-attest INERT (X402_ENABLED off or PAYMENT_RECIPIENT unset) "
"— mint_attest is free")
# Merkle batch anchoring: attestations are recorded off-chain and anchored one
# merkle root per batch (one cheap Solana memo tx). The background anchorer is
# started/stopped in the app lifespan (below) so SIGTERM flushes the pending batch.
if config.MERKLE_ANCHOR_ENABLED:
logger.info(f"merkle batch anchoring ON: batch_size={config.BATCH_SIZE}, "
f"interval={config.BATCH_INTERVAL_SECONDS}s, "
f"signer={'set' if config.ANCHOR_WALLET_KEYPAIR else 'UNSET (inert until configured)'}")
else:
logger.info("merkle batch anchoring OFF (kill switch) — mint_attest settles "
"per-attestation on-chain via Forge")
# Attach the six tools (one module each under tools/).
tools.register_all(mcp)
# ── okf-reliability-v1: emit reliability metadata on every tool result (#2964) ──
try:
from okf_middleware import ReliabilityMiddleware
mcp.add_middleware(ReliabilityMiddleware(server_id="mint-protocol"))
except Exception as _okf_e: # noqa: BLE001
import logging as _okf_log; _okf_log.getLogger(__name__).warning(f"okf middleware not wired: {_okf_e}")
@mcp.custom_route("/v1/reliability", methods=["GET"])
async def _okf_reliability_route(request):
from starlette.responses import JSONResponse
import okf_endpoint
return JSONResponse(okf_endpoint.reliability_payload("mint-protocol"))
# ── Health ──────────────────────────────────────────────────────────────────
@mcp.custom_route("/health", methods=["GET"])
async def health(request: Request) -> JSONResponse:
"""Liveness for Railway + load balancers. Reports config presence only;
never leaks key values."""
return JSONResponse({
"status": "ok",
"service": "mint-protocol-mcp",
"transport": "streamable-http",
"tools": ["mint_register", "mint_attest", "mint_batch_attest",
"mint_feed", "mint_rate", "mint_recommend", "mint_discover",
"mint_verify", "mint_trust_score", "mint_trust_history",
"mint_trust_compare",
"mint_create_cell", "mint_join_cell", "mint_settle_cell",
"mint_create_policy", "mint_settle_policy"],
"pricing_model": "attest_free_verify_paid", # 2026-06-30 pivot
"read_gate": {
"enabled": read_gate.is_active(),
"prices_usdc": config.READ_PRICES,
"paid_tools": list(config.READ_PRICES),
"free_tools": ["mint_register", "mint_attest", "mint_batch_attest", "mint_feed",
"mint_rate", "mint_recommend", "mint_discover"],
},
"foundrynet_onchain": {
"program_id": config.FOUNDRY_PROGRAM_ID,
"cluster": config.FOUNDRY_CLUSTER,
"configured": bool((config.FOUNDRY_CELL_WALLET or "").strip())
and bool(config.FOUNDRY_STAKE_MINT),
},
"forge_api_url": config.FORGE_API_URL,
"forge_key_configured": forge_client.configured(),
"trust_store": "supabase" if supa.configured() else "unconfigured",
"trust_layer": "live" if supa.configured() else "identity_only",
"x402_enabled": config.X402_ENABLED,
"attest_payment": "armed" if payment_gate.is_active() else "free",
"attest_price_usdc": (config.ATTEST_PRICE_USDC if payment_gate.is_active() else 0.0),
"payment_recipient": config.PAYMENT_RECIPIENT,
"payment_ledger": "supabase" if supa.configured() else "in_memory",
"merkle_anchoring": ("on" if config.MERKLE_ANCHOR_ENABLED else "off"),
"anchor_signer": ("set" if config.ANCHOR_WALLET_KEYPAIR else "unset"),
"scoring": ml_scorer.model_info(),
"batch_size": config.BATCH_SIZE,
"batch_interval_s": config.BATCH_INTERVAL_SECONDS,
"docs_url": f"{docs.BASE_URL}/docs",
"openapi_url": f"{docs.BASE_URL}/openapi.json",
})
@mcp.custom_route("/ping", methods=["GET"])
async def ping(request: Request) -> JSONResponse:
"""Liveness for hosted runtimes that probe /ping (mcp-proxy etc.)."""
return JSONResponse({"status": "ok"})
# ── API reference (human + machine) ──────────────────────────────────────────
# Both generated from docs.ENDPOINTS so the prose and the spec never drift.
@mcp.custom_route("/docs", methods=["GET"])
async def api_docs(request: Request) -> HTMLResponse:
"""Styled HTML API reference — readable by a human in a browser AND fetchable
by an agent for endpoint discovery."""
return HTMLResponse(docs.render_docs(),
headers={"Cache-Control": "public, max-age=300"})
@mcp.custom_route("/openapi.json", methods=["GET"])
async def openapi_spec(request: Request) -> JSONResponse:
"""OpenAPI 3.0 spec — what Swagger/Postman/GPT Actions/agent frameworks import
to auto-discover the REST API."""
return JSONResponse(docs.build_openapi(),
headers={"Cache-Control": "public, max-age=300"})
# ── REST surface (for the mint-attest Python SDK + any HTTP client) ──────────
# The MCP tools speak SSE/JSON-RPC; these plain-HTTP routes expose the SAME three
# operations (via core.*, no logic drift) so a non-MCP client — the mint-attest
# PyPI SDK, curl, a webhook — can register/attest/verify with one POST. The
# developer's fnet_ key rides in `Authorization: Bearer` and is passed through to
# Forge so the actor + its attestations belong to THEIR account.
_ERR_STATUS = {"bad_request": 400, "not_configured": 503,
"not_found": 404, "attest_failed": 502,
"forbidden": 403, "conflict": 409,
"rate_failed": 502, "recommend_failed": 502,
"payment_required": 402}
def _resp(d: dict) -> JSONResponse:
if "error" not in d:
return JSONResponse(d, status_code=200)
err = str(d.get("error") or "")
if err in _ERR_STATUS:
code = _ERR_STATUS[err]
elif err.startswith("http_") and err[5:].isdigit():
code = int(err[5:]) # surface Forge's status (e.g. 401) verbatim
elif err in ("network", "non_json_response", "unreachable"):
code = 502
else:
code = 400
return JSONResponse(d, status_code=code)
def _bearer(request: Request):
a = request.headers.get("authorization", "")
return a[7:].strip() if a.lower().startswith("bearer ") else None
async def _json_body(request: Request) -> dict:
try:
b = await request.json()
return b if isinstance(b, dict) else {}
except Exception:
return {}
@mcp.custom_route("/v1/register", methods=["POST"])
async def rest_register(request: Request) -> JSONResponse:
b = await _json_body(request)
return _resp(await core.do_register(
b.get("actor_type", "ai_agent"), b.get("name", ""),
b.get("capabilities"), b.get("operator"), b.get("metadata"),
mcp_endpoint=b.get("mcp_endpoint"), description=b.get("description"),
api_key=_bearer(request)))
@mcp.custom_route("/v1/attest", methods=["POST"])
async def rest_attest(request: Request) -> JSONResponse:
# Pay-per-attest is enforced inside core.do_attest (payment_gate). When the
# caller hasn't paid, core returns the {"error":"payment_required", ...} body
# and _resp maps it to HTTP 402 — same policy as the MCP surface. An fnet_
# Bearer key (Stripe-billed) bypasses payment; otherwise pass payment_tx.
b = await _json_body(request)
d = await core.do_attest(
b.get("mint_id", ""), b.get("work_type", ""), b.get("duration_seconds", 0),
summary=b.get("summary", ""), input_hash=b.get("input_hash"),
output_hash=b.get("output_hash"), metadata=b.get("metadata"),
payment_tx=b.get("payment_tx"), api_key=_bearer(request))
return _resp(d)
async def _paid_read(request: Request, tool: str, args: dict, runner):
"""Shared paid-read wrapper for the REST surface: an fnet_ Bearer key bypasses,
else a keyless x402 payment_tx is verified on-chain, else 402 (read_gate). On
success runs `runner()` and folds in the billing note."""
decision = await read_gate.precheck(
tool, args, (await _json_body_cached(request)).get("payment_tx"),
api_key=_bearer(request))
if decision["gate"] == "blocked":
return JSONResponse(decision["body"], status_code=402)
result = await runner()
note = read_gate.billing_note(decision)
if note and isinstance(result, dict) and "error" not in result:
result["billing"] = note
return _resp(result)
async def _json_body_cached(request: Request) -> dict:
"""Parse the JSON body once and stash it on the request (a paid-read route reads
it for both payment_tx and the operation's args)."""
if not hasattr(request.state, "_json"):
request.state._json = await _json_body(request)
return request.state._json
@mcp.custom_route("/v1/verify", methods=["POST"])
async def rest_verify(request: Request) -> JSONResponse:
# PAID ($0.005) as of the 2026-06-30 pivot. An fnet_ Bearer key bypasses; else
# pass payment_tx (keyless x402). Without either, read_gate returns 402.
b = await _json_body_cached(request)
return await _paid_read(
request, "mint_verify",
{"mint_id": b.get("mint_id"), "actor_name": b.get("actor_name"),
"actor_type": b.get("actor_type"), "attestation_hash": b.get("attestation_hash")},
lambda: core.do_verify(b.get("mint_id"), b.get("actor_name"),
b.get("actor_type"), attestation_hash=b.get("attestation_hash")))
@mcp.custom_route("/v1/batch/attest", methods=["POST"])
async def rest_batch_attest(request: Request) -> JSONResponse:
# FREE — batch attestation (the distribution channel). An fnet_ key binds the
# attestations to the caller's Forge account; otherwise FORGE_API_KEY is used.
b = await _json_body(request)
return _resp(await core.do_batch_attest(
b.get("attestations") or [], api_key=_bearer(request)))
@mcp.custom_route("/v1/trust/score", methods=["POST"])
async def rest_trust_score(request: Request) -> JSONResponse:
# PAID ($0.01).
b = await _json_body_cached(request)
aid = b.get("agent_id") or b.get("mint_id") or ""
return await _paid_read(request, "mint_trust_score", {"agent_id": aid},
lambda: core.do_trust_score(aid))
@mcp.custom_route("/v1/trust/history", methods=["POST"])
async def rest_trust_history(request: Request) -> JSONResponse:
# PAID ($0.25).
b = await _json_body_cached(request)
aid = b.get("agent_id") or b.get("mint_id") or ""
days = b.get("days", 30)
return await _paid_read(request, "mint_trust_history",
{"agent_id": aid, "days": days},
lambda: core.do_trust_history(aid, days=days))
@mcp.custom_route("/v1/trust/compare", methods=["POST"])
async def rest_trust_compare(request: Request) -> JSONResponse:
# PAID ($0.05).
b = await _json_body_cached(request)
ids = b.get("agent_ids") or b.get("mint_ids") or []
return await _paid_read(request, "mint_trust_compare", {"agent_ids": ids},
lambda: core.do_trust_compare(ids))
@mcp.custom_route("/v1/batch/status", methods=["GET"])
async def batch_status(request: Request) -> JSONResponse:
"""Merkle anchoring telemetry: current batch size, time to next anchor, last
anchor tx, totals. Open (no auth) — it leaks no secrets."""
return JSONResponse(await merkle_batch.status())
@mcp.custom_route("/v1/feed", methods=["GET", "OPTIONS"])
async def feed(request: Request) -> JSONResponse:
"""Public live attestation feed: the newest attestations across the whole
network — originating server/agent, summary, trust score, ML confidence,
anchor status, merkle root + Solscan link — plus showcase stats. FREE,
CORS-open, short-cached. A public showcase, not a paid tool."""
cors = {"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Cache-Control": "public, max-age=15, s-maxage=15"}
if request.method == "OPTIONS":
return JSONResponse({}, status_code=204, headers=cors)
try:
limit = int(request.query_params.get("limit", "50"))
except (TypeError, ValueError):
limit = 50
items = await supa.recent_attestations(limit)
stats = await supa.feed_stats()
return JSONResponse({"attestations": items, "count": len(items), "stats": stats},
headers=cors)
@mcp.custom_route("/v1/stats", methods=["GET", "OPTIONS"])
async def stats(request: Request) -> JSONResponse:
"""Public lifetime showcase stats for the explorer header panels: registered
actors, total attestations, distinct work types, plus the protocol / settlement /
on-chain program constants. FREE, CORS-open, short-cached."""
cors = {"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Cache-Control": "public, max-age=60, s-maxage=60"}
if request.method == "OPTIONS":
return JSONResponse({}, status_code=204, headers=cors)
actors = await supa._count("mint_actors", {"select": "mint_id"})
attestations = await supa._count("mint_attestations", {})
rows = await supa._select("mint_attestations", {"select": "work_type", "limit": "2000"})
work_types = sorted({(r.get("work_type") or "").strip() for r in rows if r.get("work_type")})
return JSONResponse({
"registered_actors": actors,
"total_attestations": attestations,
"work_types": work_types,
"work_types_count": len(work_types),
"protocol": "MINT v1",
"settlement": "Solana",
"program_id": "4ZvTZ3skfeMF3ZGyABoazPa9tiudw2QSwuVKn45t2AKL",
"program_url": "https://solscan.io/account/4ZvTZ3skfeMF3ZGyABoazPa9tiudw2QSwuVKn45t2AKL",
}, headers=cors)
@mcp.custom_route("/v1/rate", methods=["POST"])
async def rest_rate(request: Request) -> JSONResponse:
# FREE; the Bearer fnet_ key identifies the rater (bound to an owned actor).
b = await _json_body(request)
return _resp(await core.do_rate(
b.get("attestation_id", ""), b.get("rated_mint_id", ""), b.get("score"),
rater_mint_id=b.get("rater_mint_id"), accuracy=b.get("accuracy", True),
would_use_again=b.get("would_use_again", True), tags=b.get("tags"),
comment=b.get("comment"), api_key=_bearer(request)))
@mcp.custom_route("/v1/recommend", methods=["POST"])
async def rest_recommend(request: Request) -> JSONResponse:
# FREE; the Bearer fnet_ key identifies the recommender.
b = await _json_body(request)
return _resp(await core.do_recommend(
b.get("recommended_mint_id", ""), b.get("context", ""), b.get("score"),
note=b.get("note"), recommender_mint_id=b.get("recommender_mint_id"),
attestation_id=b.get("attestation_id"), api_key=_bearer(request)))
@mcp.custom_route("/v1/discover", methods=["POST"])
async def rest_discover(request: Request) -> JSONResponse:
# FREE, no auth — discovery is open to any agent.
b = await _json_body(request)
return _resp(await core.do_discover(
capability=b.get("capability"), actor_type=b.get("actor_type"),
min_trust_score=b.get("min_trust_score", 0),
min_recommendations=b.get("min_recommendations", 0),
sort_by=b.get("sort_by", "trust_score"), limit=b.get("limit", 10)))
# ── Discovery: A2A agent card ────────────────────────────────────────────────
_AGENT_CARD = {
"name": "MINT Protocol",
"description": (
"Universal work attestation for autonomous agents. Register identity, "
"attest completed work, verify trust scores. The reputation layer for "
"the agent economy."
),
"url": "https://mint.foundrynet.io",
"live_feed": "https://mint.foundrynet.io/feed",
"feed_api": "https://mint-mcp-production.up.railway.app/v1/feed",
"capabilities": [
"agent_identity",
"work_attestation",
"trust_verification",
"reputation_scoring",
"peer_rating",
"peer_recommendation",
"trust_ranked_discovery",
],
"tagline": ("Attest free. Verify paid. The trust graph grows with every free "
"attestation — reading it is where the value lives."),
"tools": [
{"name": "mint_register",
"description": "Register any autonomous actor with persistent cryptographic identity",
"pricing": "free"},
{"name": "mint_attest",
"description": "Anchor a completed unit of work on Solana (tamper-evident record)",
"pricing": "free"},
{"name": "mint_batch_attest",
"description": "Anchor many work items in one call",
"pricing": "free"},
{"name": "mint_feed",
"description": "Live network attestation feed (discovery)",
"pricing": "free"},
{"name": "mint_rate",
"description": "Rate a completed attestation 1-5; updates the actor's trust score",
"pricing": "free"},
{"name": "mint_recommend",
"description": "Endorse an actor you've worked with in a named context",
"pricing": "free"},
{"name": "mint_discover",
"description": "Trust-ranked search of the actor directory by capability",
"pricing": "free"},
{"name": "mint_verify",
"description": "Verify an attestation / actor's trust profile against the chain",
"pricing": "$0.005"},
{"name": "mint_trust_score",
"description": "Agent reputation lookup from the trust graph",
"pricing": "$0.01"},
{"name": "mint_trust_history",
"description": "Full attestation audit trail for an agent",
"pricing": "$0.25"},
{"name": "mint_trust_compare",
"description": "Rank multiple agents by trust score",
"pricing": "$0.05"},
{"name": "mint_create_cell",
"description": "Open a stake-backed on-chain work cell (FoundryNet devnet)",
"pricing": "network fee"},
{"name": "mint_join_cell",
"description": "Join a work cell by staking; opens participant + trust accounts",
"pricing": "network fee"},
{"name": "mint_settle_cell",
"description": "Evaluate + settle a work cell; 96/2/2 split, stakes returned, trust updated",
"pricing": "network fee"},
{"name": "mint_create_policy",
"description": "Open a parametric insurance policy with funded coverage escrow",
"pricing": "network fee"},
{"name": "mint_settle_policy",
"description": "Settle a policy: pay beneficiary if triggered, else refund insurer",
"pricing": "network fee"},
],
"protocols": {
"mcp": {
"endpoint": config.PUBLIC_MCP_URL,
"transport": "streamable-http",
"tools_count": 16,
},
"x402": {
"supported": True,
"currency": "USDC",
"network": "solana",
"paid_tools": {k: f"{v} USDC" for k, v in config.READ_PRICES.items()},
},
"subscriptions": {
"pro": {"price": "$19/month", "checkout": config.STRIPE_LINK_PRO},
"intelligence": {"price": "$49/month", "checkout": config.STRIPE_LINK_INTEL},
},
},
"contact": "forge@foundrynet.io",
}
@mcp.custom_route("/.well-known/agent-card.json", methods=["GET"])
async def agent_card(request: Request) -> JSONResponse:
"""A2A agent card — how other agents discover MINT's identity + tools."""
return JSONResponse(_AGENT_CARD, headers={"Cache-Control": "public, max-age=300"})
# ── Discovery: well-known/mcp directory crawlers ─────────────────────────────
_FREE_TOOLS = ["mint_register", "mint_attest", "mint_batch_attest", "mint_feed",
"mint_rate", "mint_recommend", "mint_discover"]
def _mcp_directory() -> dict:
"""Discovery manifest for .well-known/mcp[.json] crawlers — endpoint + the
free/paid tool split + payment options, built from config so it never drifts."""
return {
"schema_version": "2024-11-05",
"name": "MINT Protocol",
"description": ("Universal work attestation + trust graph for autonomous agents. "
"Attest free, verify paid."),
"tagline": ("Attest free. Verify paid. The trust graph grows with every free "
"attestation — reading it is where the value lives."),
"pricing_model": "attest_free_verify_paid",
"endpoints": [{
"url": config.PUBLIC_MCP_URL, "transport": "streamable-http",
"name": "MINT Protocol MCP",
}],
"tools": {
"free": _FREE_TOOLS,
"paid": {k: f"{v} USDC" for k, v in config.READ_PRICES.items()},
},
"payment": {
"x402": {"supported": True, "currency": "USDC", "network": "solana"},
"subscriptions": {
"pro": {"price": "$19/month", "checkout": config.STRIPE_LINK_PRO},
"intelligence": {"price": "$49/month", "checkout": config.STRIPE_LINK_INTEL},
},
},
"contact": "forge@foundrynet.io",
}
@mcp.custom_route("/.well-known/mcp", methods=["GET"])
async def mcp_endpoints(request: Request) -> JSONResponse:
return JSONResponse(_mcp_directory(), headers={"Cache-Control": "public, max-age=300"})
@mcp.custom_route("/.well-known/mcp.json", methods=["GET"])
async def mcp_endpoints_json(request: Request) -> JSONResponse:
return JSONResponse(_mcp_directory(), headers={"Cache-Control": "public, max-age=300"})
async def _live_tools() -> list:
"""The registered tools in MCP-SDK shape ({name, description, inputSchema}),
built from FastMCP's live definitions so the card never drifts from the code."""
res = mcp.list_tools()
if inspect.iscoroutine(res):
res = await res
out = []
for t in res:
out.append({
"name": t.name,
"description": (getattr(t, "description", "") or "").strip(),
"inputSchema": getattr(t, "parameters", None) or {"type": "object"},
})
return out
@mcp.custom_route("/.well-known/mcp/server-card.json", methods=["GET"])
async def server_card(request: Request) -> JSONResponse:
"""MCP server card consumed by directories (Smithery, glama, pulsemcp).
Smithery's publish flow reads `serverInfo` + `tools` (MCP-SDK types) from this
card to SKIP its connection scan, so the listing populates its tools without a
live probe. The server itself speaks Streamable HTTP at /mcp (what Smithery's
hosted gateway connects with). Extra fields (tagline, pricing, categories) are
ignored by Smithery and used by other directories."""
tools = await _live_tools()
return JSONResponse(
{
# ── Smithery-required (and MCP-canonical) ──
"serverInfo": {"name": "MINT Protocol — Universal Work Attestation",
"version": "1.1.0"},
"authentication": {
"type": "http", "scheme": "bearer",
"description": ("mint_register and mint_verify are free and need no "
"auth; mint_attest takes an fnet_ Bearer key OR an "
"x402 USDC payment."),
},
"tools": tools,
# ── extra discovery metadata (other directories) ──
"version": "1.0",
"name": "MINT Protocol — Universal Work Attestation",
"tagline": "The reputation layer for the agent economy.",
"description": (
"Register, attest, and verify work for any autonomous agent — "
"AI agents, physical machines, IoT devices, services. Persistent "
"cryptographic identity, tamper-evident on-chain (Solana) work "
"records, and trust scores built from verified history. Free to "
"register and attest; verifying and reading trust scores is the "
"paid product. Signed ≠ verified."
),
"serverUrl": config.PUBLIC_MCP_URL,
"transport": "streamable-http",
"tools_count": len(tools),
"categories": ["agents", "identity", "reputation", "attestation", "blockchain"],
"pricing": {
"model": "attest_free_verify_paid",
"free_tier": "Unlimited register + attest, no card",
"paid_from": "0.005 USDC per verify (x402) or $19/mo Stripe",
},
# API reference (human HTML) + machine-readable spec — so any agent
# fetching the server card auto-discovers how to call the REST API.
"docs_url": f"{docs.BASE_URL}/docs",
"openapi_url": f"{docs.BASE_URL}/openapi.json",
},
headers={"Cache-Control": "public, max-age=300"},
)
@mcp.custom_route("/.well-known/mcp.json", methods=["GET"])
async def wellknown_mcp_json(request: Request) -> JSONResponse:
"""Machine-discovery card (emerging standard) for AI clients/crawlers."""
live = await _live_tools()
names = [t["name"] for t in live]
return JSONResponse({
"name": "MINT Protocol — Universal Work Attestation",
"description": ("Register, attest, and verify work for any autonomous agent — "
"the reputation layer for the agent economy."),
"url": config.PUBLIC_MCP_URL,
"transport": ["streamable-http"],
"tools": names,
"pricing": {"model": "per-query", "free_tier": True,
"paid_tools": ["mint_attest"]},
"attestation": {"enabled": True, "protocol": "MINT Protocol",
"feed": "https://mint.foundrynet.io/feed"},
"network": {"name": "FoundryNet Data Network", "servers": 17,
"homepage": "https://foundrynet.io"},
}, headers={"Cache-Control": "public, max-age=300"})
# ── Entrypoint ───────────────────────────────────────────────────────────────
def build_dual_app():
"""Serve BOTH transports from one app:
• Streamable HTTP at /mcp — modern clients + Smithery's hosted gateway
• legacy SSE at /sse (+ /messages) — existing mcp-remote configs keep working
The streamable-http app is primary (carries /mcp + every custom_route); we graft
only the two SSE transport routes onto it and chain both lifespans so each
transport's session manager starts. New users get /mcp; old users don't break."""
import contextlib
main_app = mcp.http_app(transport="http", path="/mcp") # /mcp + custom routes
sse_app = mcp.http_app(transport="sse", path="/sse") # /sse + /messages (+ dup customs)
for r in sse_app.routes:
if getattr(r, "path", None) in ("/sse", "/messages"):
main_app.router.routes.append(r)
main_life, sse_life = main_app.router.lifespan_context, sse_app.router.lifespan_context
@contextlib.asynccontextmanager
async def _dual_lifespan(app):
async with main_life(app):
async with sse_life(app):
# Start the merkle batch anchorer (no-op if MERKLE_ANCHOR_ENABLED is
# off). On shutdown — including uvicorn's SIGTERM-driven lifespan
# teardown — stop() flushes the pending batch before we exit.
await merkle_batch.start()
try:
yield
finally:
await merkle_batch.stop()
main_app.router.lifespan_context = _dual_lifespan
return main_app
if __name__ == "__main__":
import uvicorn
logger.info(
f"MINT Protocol MCP starting on 0.0.0.0:{config.PORT} "
f"(forge={config.FORGE_API_URL}, forge_key={forge_client.configured()}, "
f"x402={config.X402_ENABLED}) — dual transport: /mcp (streamable-http) + /sse (legacy)"
)
uvicorn.run(build_dual_app(), host="0.0.0.0", port=config.PORT, log_level="warning")