diff --git a/manifest.json b/manifest.json index 63a4288..faab2d3 100644 --- a/manifest.json +++ b/manifest.json @@ -3,7 +3,7 @@ "manifest_version": "0.4", "name": "web-intel-mcp", "display_name": "Web Intel", - "version": "0.2.0", + "version": "0.2.1", "description": "Páginas web a Markdown limpio, metadatos, enlaces, stack técnico y auditorías SEO. Pago por uso con créditos KeyFlint.", "long_description": "Lee cualquier URL y devuelve Markdown limpio, metadatos (Open Graph, JSON-LD), enlaces, stack tecnológico y una auditoría SEO puntuada. Cada llamada descuenta créditos de tu licencia KeyFlint; las herramientas pricing y credits_balance son gratis.", "author": { diff --git a/pyproject.toml b/pyproject.toml index 7c6ff57..4b6ab8a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "web-intel-mcp" -version = "0.2.0" +version = "0.2.1" description = "Metered MCP server: web pages to clean Markdown, metadata, links, SEO audits and tech stack. Billed per call with KeyFlint credits." readme = "README.md" requires-python = ">=3.10" diff --git a/server.json b/server.json index 29fb8a1..51550f0 100644 --- a/server.json +++ b/server.json @@ -3,7 +3,7 @@ "name": "io.github.ArceeDev/web-intel-mcp", "title": "Web Intel", "description": "Web pages to clean Markdown, metadata, links, tech stack and scored SEO audits. Pay per call.", - "version": "0.2.0", + "version": "0.2.1", "websiteUrl": "https://mcp.keyflint.dev", "repository": { "url": "https://github.com/ArceeDev/web-intel-mcp", @@ -14,7 +14,7 @@ "registryType": "pypi", "registryBaseUrl": "https://pypi.org", "identifier": "web-intel-mcp", - "version": "0.2.0", + "version": "0.2.1", "transport": { "type": "stdio" }, diff --git a/src/web_intel_mcp/__init__.py b/src/web_intel_mcp/__init__.py index 018e44d..89d0b95 100644 --- a/src/web_intel_mcp/__init__.py +++ b/src/web_intel_mcp/__init__.py @@ -1,3 +1,3 @@ """Web Intel: a pay-per-call MCP server for web content, SEO and tech-stack intelligence.""" -__version__ = "0.2.0" +__version__ = "0.2.1" diff --git a/src/web_intel_mcp/billing.py b/src/web_intel_mcp/billing.py index 5d96f36..74f5fe2 100644 --- a/src/web_intel_mcp/billing.py +++ b/src/web_intel_mcp/billing.py @@ -3,14 +3,22 @@ stdio: the license comes from KEYFLINT_LICENSE (one buyer per process). HTTP: the license comes from each request (``Authorization: Bearer LIC-...`` or ``X-KeyFlint-License``), so one hosted server bills many buyers. + +Retries: a call repeated with the same license, tool, credits and inputs within ``DEDUP_TTL`` seconds +reuses the first call's idempotency key, so the gateway replays the debit instead of charging twice +(e.g. the client timed out and retried). A refunded call frees its key, so a retry after a failure is +billed normally. """ from __future__ import annotations import asyncio +import hashlib +import json import os import pathlib import threading +import time import uuid from collections import OrderedDict from contextlib import asynccontextmanager @@ -20,6 +28,8 @@ LICENSE_HEADERS = ("x-license-key", "authorization") _MAX_CLIENTS = 1024 +DEDUP_TTL = 300.0 +_MAX_DEDUP = 4096 DEFAULT_GATEWAY = "https://licenses.keyflint.dev" DEFAULT_CHECKOUT = "https://mcp.keyflint.dev/precios/" @@ -100,6 +110,7 @@ def __init__(self, *, hosted: bool = False, **kf_kwargs: Any) -> None: self._env_kf = KeyFlint(**kf_kwargs) self._clients: "OrderedDict[str, KeyFlint]" = OrderedDict() self._lock = threading.Lock() + self._recent: "OrderedDict[str, tuple[str, float]]" = OrderedDict() @property def checkout_url(self) -> Optional[str]: @@ -129,18 +140,54 @@ def client(self, headers: Optional[Mapping[str, str]] = None) -> KeyFlint: self._clients.move_to_end(key) return kf + def _idem_key(self, fp: Optional[str]) -> str: + """Same fingerprint within DEDUP_TTL -> same key; otherwise a fresh one.""" + fresh = f"wi-{uuid.uuid4().hex}" + if fp is None: + return fresh + now = time.monotonic() + with self._lock: + hit = self._recent.get(fp) + if hit is not None and now - hit[1] < DEDUP_TTL: + return hit[0] + self._recent[fp] = (fresh, now) + self._recent.move_to_end(fp) + while len(self._recent) > _MAX_DEDUP: + self._recent.popitem(last=False) + return fresh + + def _forget(self, fp: Optional[str], idem: str) -> None: + with self._lock: + if fp is not None and self._recent.get(fp, ("",))[0] == idem: + del self._recent[fp] + @asynccontextmanager async def charge(self, credits: int, tool: str, headers: Optional[Mapping[str, str]] = None, - features: Optional[list[str]] = None) -> AsyncIterator[dict[str, Any]]: - """Offline license check, debit, run body; refund if the body raises.""" + features: Optional[list[str]] = None, + inputs: Optional[Mapping[str, Any]] = None) -> AsyncIterator[dict[str, Any]]: + """Offline license check, debit, run body; refund if the body raises. + + ``inputs`` (the tool arguments, e.g. ``locals()``) makes retries idempotent: see module doc. + """ kf = self.client(headers) kf.check(features) - idem = f"wi-{uuid.uuid4().hex}" - receipt = await asyncio.to_thread(kf.deduct, credits, idempotency_key=idem, event_type=f"mcp:{tool}") + fp = _fingerprint(getattr(kf, "license_key", ""), tool, credits, inputs) + idem = self._idem_key(fp) + try: + receipt = await asyncio.to_thread(kf.deduct, credits, idempotency_key=idem, event_type=f"mcp:{tool}") + except LicenseError as exc: + if getattr(exc, "reason", None) != "IDEMPOTENCY_CONFLICT": + raise + self._forget(fp, idem) # key was refunded meanwhile: bill this call on its own key + idem = self._idem_key(fp) + receipt = await asyncio.to_thread(kf.deduct, credits, idempotency_key=idem, event_type=f"mcp:{tool}") + replay = bool(receipt.get("is_cached")) try: yield receipt except BaseException: - await asyncio.to_thread(kf.refund, idem, "tool_error") + if not replay: # a replay is the first call's paid result; that call refunds its own failure + self._forget(fp, idem) + await asyncio.to_thread(kf.refund, idem, "tool_error") raise async def balance(self, headers: Optional[Mapping[str, str]] = None) -> dict[str, Any]: @@ -163,5 +210,33 @@ def _get() -> dict[str, Any]: return await asyncio.to_thread(_get) +def _plain(v: Any) -> Any: + """JSON-safe copy of tool arguments; drops anything that is not plain data (Context, objects).""" + if v is None or isinstance(v, (str, int, float, bool)): + return v + if isinstance(v, (list, tuple)): + return [_plain(x) for x in v] + if isinstance(v, Mapping): + return {str(k): _plain(x) for k, x in v.items() if not str(k).startswith("_") and _is_plain(x)} + return None + + +def _is_plain(v: Any) -> bool: + if v is None or isinstance(v, (str, int, float, bool)): + return True + if isinstance(v, (list, tuple)): + return all(_is_plain(x) for x in v) + if isinstance(v, Mapping): + return all(_is_plain(x) for x in v.values()) + return False + + +def _fingerprint(license_key: str, tool: str, credits: int, inputs: Optional[Mapping[str, Any]]) -> Optional[str]: + if inputs is None: + return None + blob = json.dumps([license_key, tool, int(credits), _plain(inputs)], sort_keys=True, separators=(",", ":")) + return hashlib.sha256(blob.encode("utf-8")).hexdigest() + + def from_env() -> Billing: return Billing(hosted=os.environ.get("WEB_INTEL_TRANSPORT", "stdio") != "stdio") diff --git a/src/web_intel_mcp/server.py b/src/web_intel_mcp/server.py index dce8aa1..06de5ce 100644 --- a/src/web_intel_mcp/server.py +++ b/src/web_intel_mcp/server.py @@ -74,8 +74,9 @@ def _run(fn: Any, *args: Any) -> Any: async def _paid(ctx: Context, tool: str, url: str, fn: Any, *args: Any) -> tuple[dict, dict]: + inputs = {"url": url, "args": list(args)} url = validate_url(url) # bad input is rejected before any debit - async with billing.charge(PRICES[tool], tool, _headers(ctx)) as receipt: + async with billing.charge(PRICES[tool], tool, _headers(ctx), inputs=inputs) as receipt: out = _run(fn, _ok(await fetch(url)), *args) return out, receipt @@ -148,7 +149,8 @@ async def compare_seo(urls: list[str], ctx: Context) -> dict[str, Any]: failed.append({"url": u, "error": str(exc)}) if not pages: raise FetchError("None of the URLs could be fetched; nothing was charged.") - async with billing.charge(unit * len(pages), "compare_seo", _headers(ctx)) as receipt: + async with billing.charge(unit * len(pages), "compare_seo", _headers(ctx), + inputs={"urls": [p.final_url for p in pages]}) as receipt: for p in pages: a = _run(analyze.seo_audit, p) results.append({"url": a["url"], "score": a["score"], "grade": a["grade"], "top_fixes": a["top_fixes"]}) diff --git a/tests/conftest.py b/tests/conftest.py index 2064d47..45ffbe7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -80,6 +80,7 @@ class FakeGateway: def __init__(self) -> None: self.balances: dict[str, int] = {} self.debits: dict[tuple[str, str], int] = {} + self.refunded: set[tuple[str, str]] = set() self.lock = threading.Lock() gw = self @@ -108,9 +109,14 @@ def do_POST(self) -> None: # noqa: N802 if key not in gw.balances: return self._unknown() left = gw.balances[key] + cached = False if self.path.endswith("/deduct"): need = int(body["credits"]) - if (key, idem) not in gw.debits: + if (key, idem) in gw.refunded: # like the real ledger: a refunded key is spent + return self._send(409, {"error": {"code": "IDEMPOTENCY_CONFLICT", + "message": "Key already refunded."}}) + cached = (key, idem) in gw.debits + if not cached: if need > left: return self._send(402, {"error": { "code": "QUOTA_EXHAUSTED", "message": "No credits.", @@ -119,9 +125,10 @@ def do_POST(self) -> None: # noqa: N802 gw.debits[(key, idem)] = need elif self.path.endswith("/refund"): gw.balances[key] += gw.debits.pop((key, idem), 0) + gw.refunded.add((key, idem)) else: return self._send(404, {"error": {"code": "NOT_FOUND", "message": self.path}}) - self._send(200, {"data": {"remaining_balance": gw.balances[key]}}) + self._send(200, {"data": {"remaining_balance": gw.balances[key], "is_cached": cached}}) def log_message(self, *a: object) -> None: pass diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 7dfebba..ccb95ed 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -137,3 +137,48 @@ async def test_hosted_mode_requires_header(gateway, license_, monkeypatch): assert receipt["remaining_balance"] >= 0 with pytest.raises(LicenseError): b.client({"X-License-Key": "LIC-forged"}).check() + + + +async def test_duplicate_call_same_inputs_charges_once(server, site): + """A client retry (same tool, same inputs) inside the dedupe window replays the debit.""" + price = server.PRICES["read_url"] + before = await balance(server) + args = dict(url=f"{site}/") + err1, first, t1 = await call(server, "read_url", **args) + err2, second, t2 = await call(server, "read_url", **args) + assert not err1 and not err2, (t1, t2) + assert await balance(server) == before - price + err3, _, t3 = await call(server, "read_url", **{**args, **{"url": f"{site}/bad"}}) + assert not err3, t3 + assert await balance(server) == before - 2 * price # different inputs are a different call + + +async def test_duplicate_call_after_window_is_charged(server, site, monkeypatch): + monkeypatch.setattr(importlib.import_module("web_intel_mcp.billing"), "DEDUP_TTL", 0.0) + price = server.PRICES["read_url"] + before = await balance(server) + args = dict(url=f"{site}/") + for _ in range(2): + err, _, text = await call(server, "read_url", **args) + assert not err, text + assert await balance(server) == before - 2 * price + + +async def test_retry_after_refunded_failure_is_billed_once(server): + b = server.billing + before = await balance(server) + inputs = {"content": "x"} + with pytest.raises(RuntimeError): + async with b.charge(3, "read_url", inputs=inputs): + raise RuntimeError("tool body failed") + assert await balance(server) == before # refunded + async with b.charge(3, "read_url", inputs=inputs) as receipt: + assert not receipt.get("is_cached") + assert await balance(server) == before - 3 + # A failing replay of a paid call does not refund the paid one. + with pytest.raises(RuntimeError): + async with b.charge(3, "read_url", inputs=inputs) as receipt: + assert receipt.get("is_cached") + raise RuntimeError("retry failed") + assert await balance(server) == before - 3 diff --git a/tests/test_limits.py b/tests/test_limits.py index c7a8945..7c4ce4f 100644 --- a/tests/test_limits.py +++ b/tests/test_limits.py @@ -128,6 +128,7 @@ async def test_concurrent_calls_never_overdraw(gateway, monkeypatch): monkeypatch.setenv("WEB_INTEL_ALLOW_PRIVATE", "1") import web_intel_mcp.server as srv srv = importlib.reload(srv) + monkeypatch.setattr(importlib.import_module("web_intel_mcp.billing"), "DEDUP_TTL", 0.0) # distinct calls from conftest import _Site site = _serve(_Site); url = f"http://127.0.0.1:{site.server_address[1]}/" async def one():