-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
330 lines (264 loc) · 14.8 KB
/
Copy pathserver.py
File metadata and controls
330 lines (264 loc) · 14.8 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
"""fact-check-mcp — fact verification for autonomous agents.
Part of the FoundryNet Data Network. Verifies a claim by classifying its domain and
cross-referencing the relevant network data source (brand-intel, financial-signals,
patent-intel, compliance) plus a general web search, returning a verdict
(supported | disputed | unverifiable) with confidence + cited sources. On-demand
with 24h caching. 6 tools + free mint_info. Free tier 10/day, then x402 (USDC on
Solana). Transport: Streamable HTTP at /mcp (+ /sse).
"""
from __future__ import annotations
import asyncio
import contextlib
import inspect
import logging
from fastmcp import FastMCP
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
import event_log
import config
import core
import daily_curator
import fact_sources as src
import identity
import payment_gate
import x402_standard
import supa
import tools
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("fact.mcp")
if not supa.configured():
logger.warning("SUPABASE_SERVICE_KEY not set — cache + free-tier ledger disabled until configured.")
mcp = FastMCP("fact-check")
if payment_gate.is_active():
logger.info(f"pay-per-query ARMED → {config.PAYMENT_RECIPIENT} after {config.FREE_TIER_DAILY}/day free")
else:
logger.info("pay-per-query INERT — all tools free")
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="fact-check"))
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("fact-check"))
@mcp.custom_route("/health", methods=["GET"])
async def health(request: Request) -> JSONResponse:
return JSONResponse({
"status": "ok", "service": "fact-check-mcp", "transport": "streamable-http",
"network": "FoundryNet Data Network",
"tools": ["verify_claim", "batch_verify", "source_check", "daily_brief", "brief_summary", "mint_info"],
"cache": "supabase:fact_checks" if supa.configured() else "unconfigured",
"sources": "web_search + foundrynet-data-network siblings",
"web_search": "set" if src.web_search_configured() else "unset",
"x402_enabled": config.X402_ENABLED,
"query_payment": "armed" if payment_gate.is_active() else "free",
"free_tier_daily": config.FREE_TIER_DAILY,
"payment_recipient": config.PAYMENT_RECIPIENT,
})
@mcp.custom_route("/ping", methods=["GET"])
async def ping(request: Request) -> JSONResponse:
return JSONResponse({"status": "ok"})
# ── REST surface ─────────────────────────────────────────────────────────────
_ERR = {"bad_request": 400, "not_configured": 503, "not_found": 404, "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 "")
code = _ERR.get(err, 502 if err in ("network", "non_json_response", "unreachable") else 400)
if err.startswith("http_") and err[5:].isdigit():
code = int(err[5:])
return JSONResponse(d, status_code=code)
async def _body(request: Request) -> dict:
try:
b = await request.json()
return b if isinstance(b, dict) else {}
except Exception:
return {}
def _akey(request: Request, body: dict) -> str:
return identity.resolve_agent_key(body.get("agent_id"), request=request)
@mcp.custom_route("/v1/verify", methods=["POST"])
async def rest_verify(request: Request) -> JSONResponse:
b = await _body(request)
return _resp(await core.do_verify_claim(b.get("claim", ""), b.get("context"),
agent_key=_akey(request, b),
payment_tx=b.get("payment_tx"),
api_key=identity.bearer(request)))
@mcp.custom_route("/v1/batch-verify", methods=["POST"])
async def rest_batch(request: Request) -> JSONResponse:
b = await _body(request)
return _resp(await core.do_batch_verify(b.get("claims") or [],
agent_key=_akey(request, b),
payment_tx=b.get("payment_tx"),
api_key=identity.bearer(request)))
@mcp.custom_route("/v1/source-check", methods=["POST"])
async def rest_source(request: Request) -> JSONResponse:
b = await _body(request)
return _resp(await core.do_source_check(b.get("url", ""), agent_key=_akey(request, b),
payment_tx=b.get("payment_tx"),
api_key=identity.bearer(request)))
@mcp.custom_route("/v1/daily-brief", methods=["POST"])
async def rest_brief(request: Request) -> JSONResponse:
b = await _body(request)
return _resp(await core.do_daily_brief(b.get("date"), agent_key=_akey(request, b),
payment_tx=b.get("payment_tx"),
api_key=identity.bearer(request)))
@mcp.custom_route("/v1/mint-info", methods=["GET", "POST"])
async def rest_mint(request: Request) -> JSONResponse:
return JSONResponse(core.mint_info())
@mcp.custom_route("/admin/curate", methods=["POST"])
async def admin_curate(request: Request) -> JSONResponse:
import os
tok = os.environ.get("ADMIN_TOKEN", "")
if not tok or request.headers.get("x-admin-token") != tok:
return JSONResponse({"error": "forbidden"}, status_code=403)
qp = request.query_params
date = qp.get("date") or None
if qp.get("wait") == "1":
return JSONResponse(await daily_curator.run_curation(date))
asyncio.create_task(daily_curator.run_curation(date))
return JSONResponse({"started": True, "date": date})
# ── Discovery ────────────────────────────────────────────────────────────────
_TAGLINE = "Fact verification for agents — verdict, confidence, and cited sources for any claim."
_DESC = ("Fact verification for agents: verify a claim against the FoundryNet Data Network "
"(brand-intel, financial-signals, patent-intel, compliance) plus a general web search, "
"returning a verdict (supported/disputed/unverifiable) with confidence and cited "
"sources. Includes batch verification, source-credibility checks, and a daily brief. "
"Part of the FoundryNet Data Network.")
_KEYWORDS = ["fact checking", "fact verification", "claim verification", "misinformation",
"source credibility", "citation checking", "verification"]
_AGENT_CARD = {
"name": "Fact Verification MCP",
"description": ("Verify factual claims with a verdict, confidence score, and cited "
"sources — cross-referencing web search and the FoundryNet data "
"network; supports batch verification and source-trust checks."),
"url": config.PUBLIC_MCP_URL,
"version": "1.0.0",
"capabilities": {"tools": ["verify_claim", "batch_verify", "source_check",
"daily_brief", "brief_summary", "mint_info"]},
"provider": {"name": "FoundryNet", "url": "https://foundrynet.io"},
"network": "FoundryNet Data Network",
"attestation": {"type": "verifiable provenance", "verified_outputs": True},
"protocols": {"mcp": {"endpoint": config.PUBLIC_MCP_URL, "transport": "streamable-http", "tools_count": 6},
"x402": {"supported": True}},
"see_also": config.SISTER_SERVERS,
"contact": "forge@foundrynet.io",
}
@mcp.custom_route("/.well-known/agent-card.json", methods=["GET"])
async def agent_card(request: Request) -> JSONResponse:
return JSONResponse(_AGENT_CARD, headers={"Cache-Control": "public, max-age=300"})
@mcp.custom_route("/.well-known/mcp", methods=["GET"])
async def mcp_endpoints(request: Request) -> JSONResponse:
return JSONResponse({"endpoints": [{"url": config.PUBLIC_MCP_URL, "transport": "streamable-http",
"name": "Fact Verification MCP"}]},
headers={"Cache-Control": "public, max-age=300"})
async def _live_tools() -> list:
res = mcp.list_tools()
if inspect.iscoroutine(res):
res = await res
return [{"name": t.name, "description": (getattr(t, "description", "") or "").strip(),
"inputSchema": getattr(t, "parameters", None) or {"type": "object"}} for t in res]
@mcp.custom_route("/.well-known/mcp/server-card.json", methods=["GET"])
async def server_card(request: Request) -> JSONResponse:
live = await _live_tools()
return JSONResponse({
"serverInfo": {"name": "Fact Verification MCP", "version": "1.0.0"},
"authentication": {"type": "http", "scheme": "bearer",
"description": ("mint_info is free; other tools give 10 free "
"verifications/day then take an fnet_ Bearer key or a per-query payment.")},
"tools": live, "version": "1.0", "name": "Fact Verification MCP",
"tagline": _TAGLINE, "description": _DESC,
"serverUrl": config.PUBLIC_MCP_URL, "transport": "streamable-http",
"tools_count": len(live),
"categories": ["research", "fact-checking", "data", "verification", "trust"],
"keywords": _KEYWORDS, "network": "FoundryNet Data Network",
"see_also": config.SISTER_SERVERS,
"pricing": {"model": "metered",
"free_tier": f"{config.FREE_TIER_DAILY} verifications/day + free mint_info",
"paid_from": f"${config.PRICE_SOURCE_CHECK} per query"},
}, headers={"Cache-Control": "public, max-age=300"})
_FREE_TOOL_NAMES = {"mint_info", "macro_dashboard", "cve_detail", "detail",
"domain_age", "convert", "rates", "market_overview", "price",
"quote", "batch_quote", "sector_performance"}
@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": _AGENT_CARD["name"],
"description": _AGENT_CARD["description"],
"url": config.PUBLIC_MCP_URL,
"transport": ["streamable-http"],
"tools": names,
"pricing": {"model": "per-query", "free_tier": True,
"paid_tools": [n for n in names if n not in _FREE_TOOL_NAMES]},
"attestation": {"enabled": True, "type": "verifiable provenance"},
"network": {"name": "FoundryNet Data Network", "servers": 17,
"homepage": "https://foundrynet.io"},
}, headers={"Cache-Control": "public, max-age=300"})
# ── Standard x402 compliance (discoverable on x402scan / 402 Index / CDP Bazaar) ──
@mcp.custom_route("/x402", methods=["GET"])
async def x402_index(request: Request) -> JSONResponse:
return JSONResponse(x402_standard.index(),
headers={"Cache-Control": "public, max-age=300",
"Access-Control-Allow-Origin": "*"})
@mcp.custom_route("/.well-known/x402", methods=["GET"])
async def x402_wellknown(request: Request) -> JSONResponse:
return JSONResponse(x402_standard.index(),
headers={"Cache-Control": "public, max-age=300",
"Access-Control-Allow-Origin": "*"})
@mcp.custom_route("/x402/{tool}", methods=["GET", "POST"])
async def x402_resource(request: Request) -> JSONResponse:
tool = request.path_params["tool"]
if tool not in x402_standard.PAID_TOOLS:
return JSONResponse({"error": "unknown_resource", "tool": tool,
"available": list(x402_standard.PAID_TOOLS)}, status_code=404)
challenge = x402_standard.payment_required_header(tool)
return JSONResponse(x402_standard.payment_required(tool), status_code=402,
headers={"Cache-Control": "public, max-age=300",
"Access-Control-Allow-Origin": "*",
"PAYMENT-REQUIRED": challenge,
"X-PAYMENT": challenge,
"Link": '</openapi.json>; rel="describedby"',
"WWW-Authenticate": 'x402 version="2"'})
@mcp.custom_route("/openapi.json", methods=["GET"])
async def openapi_doc(request: Request) -> JSONResponse:
"""OpenAPI 3.1 discovery doc — x402scan requires a spec at a discoverable URL."""
return JSONResponse(x402_standard.openapi(),
headers={"Cache-Control": "public, max-age=300",
"Access-Control-Allow-Origin": "*",
"Link": '</openapi.json>; rel="describedby"'})
def build_dual_app():
main_app = mcp.http_app(transport="http", path="/mcp")
sse_app = mcp.http_app(transport="sse", path="/sse")
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):
# On-demand server: only the daily curator loop runs in-process
# (no cron aggregator).
brief_task = asyncio.create_task(daily_curator.curator_loop())
try:
yield
finally:
brief_task.cancel()
with contextlib.suppress(Exception):
await brief_task
main_app.router.lifespan_context = _dual_lifespan
# Per-call telemetry middleware (fire-and-forget to agents ingest).
main_app.add_middleware(BaseHTTPMiddleware, dispatch=event_log.middleware)
return main_app
if __name__ == "__main__":
import uvicorn
logger.info(f"fact-check-mcp starting on 0.0.0.0:{config.PORT} "
f"(cache={'supabase' if supa.configured() else 'off'}, x402={config.X402_ENABLED})")
uvicorn.run(build_dual_app(), host="0.0.0.0", port=config.PORT, log_level="warning")