toolvouch 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
toolvouch/__init__.py ADDED
@@ -0,0 +1,133 @@
1
+ """ToolVouch: verified paid APIs for AI agents.
2
+
3
+ Free: ``find`` and ``report``. Paid: ``route`` picks a verified tool, pays it via x402, checks the
4
+ answer and fails over. It costs the provider's price + 30%, charged only on success.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import datetime as _dt
10
+ import os
11
+ from typing import Any
12
+
13
+ import httpx
14
+
15
+ __all__ = ["ToolVouch", "SpendLimitError", "DEFAULT_BASE_URL"]
16
+ __version__ = "0.1.0"
17
+
18
+ DEFAULT_BASE_URL = "https://toolvouch.tbyuh88.workers.dev"
19
+ _USDC_BASE = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"
20
+
21
+
22
+ class SpendLimitError(Exception):
23
+ """Raised when a payment would exceed your per-call or daily cap."""
24
+
25
+
26
+ class ToolVouch:
27
+ def __init__(
28
+ self,
29
+ private_key: str | None = None,
30
+ max_per_call_usd: float = 0.05,
31
+ max_per_day_usd: float = 1.0,
32
+ base_url: str = DEFAULT_BASE_URL,
33
+ timeout: float = 60.0,
34
+ ) -> None:
35
+ self.base = base_url.rstrip("/")
36
+ self.max_per_call = max_per_call_usd
37
+ self.max_per_day = max_per_day_usd
38
+ self.timeout = timeout
39
+ self._private_key = private_key
40
+ self._spent_day = ""
41
+ self._spent_usd = 0.0
42
+
43
+ # ---------- free ----------
44
+ def find(self, task: str, max_price_usd: float | None = None, limit: int = 5) -> list[dict[str, Any]]:
45
+ """Best currently-healthy paid tools for a task, ranked by live checks and real demand."""
46
+ params: dict[str, Any] = {"task": task, "limit": limit}
47
+ if max_price_usd:
48
+ params["max_price_usd"] = max_price_usd
49
+ r = httpx.get(f"{self.base}/api/search", params=params, timeout=self.timeout)
50
+ r.raise_for_status()
51
+ return r.json()["results"]
52
+
53
+ def report(self, resource: str) -> dict[str, Any]:
54
+ """Reliability report for one paid endpoint URL."""
55
+ r = httpx.get(f"{self.base}/api/tool", params={"resource": resource}, timeout=self.timeout)
56
+ r.raise_for_status()
57
+ return r.json()
58
+
59
+ @property
60
+ def spent_today_usd(self) -> float:
61
+ return self._spent_usd if self._spent_day == _today() else 0.0
62
+
63
+ # ---------- paid ----------
64
+ async def aroute(self, task: str, q: str, max_price_usd: float | None = None, params: dict[str, str] | None = None) -> dict[str, Any]:
65
+ """Route a data task to the best verified paid tool (async)."""
66
+ if not self._private_key:
67
+ raise ValueError("route needs private_key (a wallet with USDC on Base)")
68
+ from eth_account import Account
69
+ from x402 import x402Client
70
+ from x402.http.clients.httpx import x402AsyncTransport
71
+ from x402.mechanisms.evm.exact.register import register_exact_evm_client
72
+ from x402.mechanisms.evm.signers import EthAccountSigner
73
+ from x402.schemas.hooks import AbortResult
74
+
75
+ client = x402Client()
76
+ register_exact_evm_client(client, EthAccountSigner(Account.from_key(self._private_key)))
77
+
78
+ def guard(ctx: Any) -> AbortResult | None:
79
+ req = ctx.selected_requirements
80
+ if req.network != "eip155:8453" or str(req.asset).lower() != _USDC_BASE:
81
+ return AbortResult(reason="toolvouch: only USDC on Base is allowed")
82
+ usd = int(req.amount) / 1e6
83
+ if self._spent_day != _today():
84
+ self._spent_day, self._spent_usd = _today(), 0.0
85
+ if usd > self.max_per_call:
86
+ return AbortResult(reason=f"toolvouch: ${usd} exceeds max_per_call_usd ${self.max_per_call}")
87
+ if self._spent_usd + usd > self.max_per_day:
88
+ return AbortResult(reason=f"toolvouch: daily limit ${self.max_per_day} reached")
89
+ self._spent_usd += usd
90
+ return None
91
+
92
+ async def guard_async(ctx: Any) -> AbortResult | None:
93
+ return guard(ctx)
94
+
95
+ client.on_before_payment_creation(guard_async)
96
+
97
+ query: dict[str, Any] = {
98
+ "task": task,
99
+ "q": q,
100
+ "max_price_usd": min(max_price_usd or self.max_per_call, self.max_per_call),
101
+ }
102
+ for k, v in (params or {}).items():
103
+ query[f"p.{k}"] = v
104
+ try:
105
+ async with httpx.AsyncClient(transport=x402AsyncTransport(client, transport=_base_transport()), timeout=self.timeout) as http:
106
+ r = await http.get(f"{self.base}/api/route", params=query)
107
+ except Exception as e: # noqa: BLE001
108
+ msg = str(e)
109
+ if "toolvouch:" in msg:
110
+ raise SpendLimitError(msg[msg.index("toolvouch:"):]) from e
111
+ raise
112
+ try:
113
+ body = r.json()
114
+ except ValueError:
115
+ body = {"ok": False, "error": f"HTTP {r.status_code}"}
116
+ if r.status_code >= 400:
117
+ body["ok"] = False
118
+ return body
119
+
120
+ def route(self, task: str, q: str, max_price_usd: float | None = None, params: dict[str, str] | None = None) -> dict[str, Any]:
121
+ """Route a data task to the best verified paid tool (blocking)."""
122
+ return asyncio.run(self.aroute(task, q, max_price_usd, params))
123
+
124
+
125
+ def _base_transport() -> httpx.AsyncHTTPTransport:
126
+ """Honour HTTPS_PROXY and custom CA bundles, as httpx does by default for plain clients."""
127
+ proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or None
128
+ ca = os.environ.get("SSL_CERT_FILE") or os.environ.get("REQUESTS_CA_BUNDLE")
129
+ return httpx.AsyncHTTPTransport(proxy=proxy, verify=ca if ca else True)
130
+
131
+
132
+ def _today() -> str:
133
+ return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%d")
toolvouch/__main__.py ADDED
@@ -0,0 +1,48 @@
1
+ """ToolVouch CLI: python -m toolvouch (or the `toolvouch` command)."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+
9
+ from . import SpendLimitError, ToolVouch
10
+
11
+
12
+ def main() -> int:
13
+ ap = argparse.ArgumentParser(prog="toolvouch", description="Verified paid APIs for AI agents")
14
+ sub = ap.add_subparsers(dest="cmd", required=True)
15
+ f = sub.add_parser("find", help="FREE: best working tools for a task")
16
+ f.add_argument("task")
17
+ f.add_argument("--max", type=float)
18
+ f.add_argument("--limit", type=int, default=5)
19
+ rp = sub.add_parser("report", help="FREE: reliability of one tool")
20
+ rp.add_argument("resource")
21
+ r = sub.add_parser("route", help="PAID: pick, pay, check, fail over (needs TOOLVOUCH_PRIVATE_KEY)")
22
+ r.add_argument("task")
23
+ r.add_argument("q", nargs="?", default="")
24
+ r.add_argument("--max", type=float)
25
+ a = ap.parse_args()
26
+
27
+ tv = ToolVouch(
28
+ private_key=os.environ.get("TOOLVOUCH_PRIVATE_KEY"),
29
+ max_per_call_usd=float(os.environ.get("TOOLVOUCH_MAX_PER_CALL", 0.05)),
30
+ max_per_day_usd=float(os.environ.get("TOOLVOUCH_MAX_PER_DAY", 1)),
31
+ base_url=os.environ.get("TOOLVOUCH_URL", "https://toolvouch.tbyuh88.workers.dev"),
32
+ )
33
+ try:
34
+ if a.cmd == "find":
35
+ out = tv.find(a.task, a.max, a.limit)
36
+ elif a.cmd == "report":
37
+ out = tv.report(a.resource)
38
+ else:
39
+ out = tv.route(a.task, a.q, a.max)
40
+ except (SpendLimitError, ValueError) as e:
41
+ print(f"toolvouch: {e}" if not str(e).startswith("toolvouch:") else str(e), file=sys.stderr)
42
+ return 1
43
+ print(json.dumps(out, indent=2))
44
+ return 0 if a.cmd != "route" or out.get("ok") else 2
45
+
46
+
47
+ if __name__ == "__main__":
48
+ sys.exit(main())
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.5
2
+ Name: toolvouch
3
+ Version: 0.1.0
4
+ Summary: Verified paid APIs for AI agents: find working x402 tools free, or route any data task in one call with failover. Charged only on success.
5
+ Project-URL: Homepage, https://toolvouch.tbyuh88.workers.dev/developers
6
+ License-Expression: MIT
7
+ Keywords: agent-tools,ai-agents,api-router,mcp,payments,x402
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: eth-account>=0.13
10
+ Requires-Dist: httpx>=0.27
11
+ Requires-Dist: x402[evm,httpx]<3,>=2.29
12
+ Description-Content-Type: text/markdown
13
+
14
+ # toolvouch
15
+
16
+ Verified paid APIs for AI agents, in one line.
17
+
18
+ [ToolVouch](https://toolvouch.tbyuh88.workers.dev) checks 10,000+ x402 paid APIs every 6 hours.
19
+ It also pays for real calls to the top tools and grades the answers. Your agent can:
20
+
21
+ - **find** the best working tool for a task, for free; or
22
+ - **route** any data task in one paid call. ToolVouch picks a verified tool, pays it, checks the
23
+ answer, and fails over to the next tool if the answer is empty or broken. You pay the
24
+ provider's price + 30%, and **only when a good answer comes back**.
25
+
26
+ ```bash
27
+ pip install toolvouch
28
+ ```
29
+
30
+ ```python
31
+ import os
32
+ from toolvouch import ToolVouch
33
+
34
+ tv = ToolVouch(
35
+ private_key=os.environ.get("TOOLVOUCH_PRIVATE_KEY"), # wallet with USDC on Base (only for route)
36
+ max_per_call_usd=0.05, # the client refuses to sign anything above this
37
+ max_per_day_usd=1, # ...or above this per UTC day
38
+ )
39
+
40
+ tv.find("web search") # free, ranked by live reliability
41
+ r = tv.route("weather forecast", "Chicago") # paid, with automatic failover
42
+ print(r["provider"], r["charged_usd"], r["data"])
43
+ # async: await tv.aroute(...)
44
+ ```
45
+
46
+ ## CLI
47
+ ```bash
48
+ toolvouch find "scrape url to markdown"
49
+ TOOLVOUCH_PRIVATE_KEY=0x... toolvouch route "web search" "x402 news"
50
+ ```
51
+ Limits: `TOOLVOUCH_MAX_PER_CALL` (default 0.05) and `TOOLVOUCH_MAX_PER_DAY` (default 1).
52
+
53
+ ## MCP
54
+ Point any MCP client at `https://toolvouch.tbyuh88.workers.dev/mcp`. The free tools are
55
+ `find_tools`, `tool_report` and `index_stats`. Paid routing with x402 uses `route_basic`, `route`
56
+ and `route_premium`.
57
+
58
+ ## Safety
59
+ - The client only signs payments in USDC on Base, within your per-call and daily caps.
60
+ - ToolVouch never pays a provider more than its listed price, and only routes to read-only data
61
+ tools.
62
+ - A failed answer is never charged.
63
+
64
+ MIT licensed.
65
+
@@ -0,0 +1,6 @@
1
+ toolvouch/__init__.py,sha256=I2m_f_qWfxoa2Yt4sJ8jszIYTvUBdEs-k5Vh2HcVYw8,5533
2
+ toolvouch/__main__.py,sha256=jkknMC742hyalBcw7NvFqHoKlhZh8a2re6mzrPcYYng,1775
3
+ toolvouch-0.1.0.dist-info/METADATA,sha256=-f1Zs-tIMK-Zs6ZZoElQfbkIWudCbXRvwZHvmPZWWDY,2365
4
+ toolvouch-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ toolvouch-0.1.0.dist-info/entry_points.txt,sha256=xZx_f7CqgJPB03rbKenMMHoTpEmuweofhGX2rgysJ-o,54
6
+ toolvouch-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ toolvouch = toolvouch.__main__:main