agentsla 2.0.3 → 2.1.0
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.
- package/README.md +149 -41
- package/index.js +187 -76
- package/package.json +9 -3
package/README.md
CHANGED
|
@@ -1,19 +1,11 @@
|
|
|
1
|
-
# AgentSLA (`agentsla` v2.0
|
|
1
|
+
# AgentSLA (`agentsla` v2.1.0)
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
**Check an API before your agent pays it.** AgentSLA checks whether an API or MCP server answers within your
|
|
4
|
+
latency limit (HTTP 2xx/3xx), signs the result with its oracle (EIP-712), and offers refundable USDC escrow on Base.
|
|
5
5
|
|
|
6
|
-
- **Site:** [https://agentsla.io](https://agentsla.io)
|
|
7
|
-
- **MCP server (
|
|
8
|
-
- **
|
|
9
|
-
- **OpenAPI:** [https://agentsla.io/openapi.json](https://agentsla.io/openapi.json)
|
|
10
|
-
- **llms.txt:** [https://agentsla.io/llms.txt](https://agentsla.io/llms.txt)
|
|
11
|
-
- **Escrow contract (Base):** `0x5c8D11AB570D7384d01226bC80123D0dD103Fb57`
|
|
12
|
-
- **USDC (Base):** `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`
|
|
13
|
-
|
|
14
|
-
> **Upgrade from 2.0.2 or earlier.** Those versions pointed at a retired escrow contract
|
|
15
|
-
> (`0x6ca6cDDd…99Ba79CD`) and sent `jobId: 1` with every `verifyEndpoint` call. 2.0.3 uses the current contract
|
|
16
|
-
> and only sends `jobId` when you pass one.
|
|
6
|
+
- **Site:** [agentsla.io](https://agentsla.io) · **Docs:** [agentsla.io/docs](https://agentsla.io/docs)
|
|
7
|
+
- **MCP server (Streamable HTTP):** `https://agentsla.io/mcp` · **OpenAPI:** `https://agentsla.io/openapi.json`
|
|
8
|
+
- **Contract security:** [agentsla.io/docs#security](https://agentsla.io/docs#security)
|
|
17
9
|
|
|
18
10
|
## Install
|
|
19
11
|
|
|
@@ -21,55 +13,171 @@ EIP-712 signed SLA checks, and use refundable USDC escrow on **Base Mainnet (cha
|
|
|
21
13
|
npm install agentsla ethers
|
|
22
14
|
```
|
|
23
15
|
|
|
24
|
-
##
|
|
16
|
+
## Check before paying (free)
|
|
25
17
|
|
|
26
18
|
```javascript
|
|
27
19
|
import { AgentSLA } from "agentsla";
|
|
28
20
|
|
|
29
21
|
const sla = new AgentSLA();
|
|
30
|
-
const
|
|
31
|
-
|
|
22
|
+
const { ok, reason } = await sla.checkBeforePaying("https://api.example.com/v1/quote", { maxLatencyMs: 1500 });
|
|
23
|
+
if (!ok) throw new Error("Not paying: " + reason);
|
|
32
24
|
```
|
|
33
25
|
|
|
34
|
-
|
|
26
|
+
10 free checks per month per IP. With a 7-day pass on the agent's wallet they are unlimited.
|
|
27
|
+
|
|
28
|
+
## Signed checks, paid automatically
|
|
35
29
|
|
|
36
|
-
|
|
30
|
+
Give the SDK the agent's own Base wallet. A signed check uses the wallet's pass if it has one, otherwise it pays
|
|
31
|
+
**0.05 USDC per check with x402**: one USDC signature, no gas, no approval.
|
|
37
32
|
|
|
38
33
|
```javascript
|
|
39
|
-
const
|
|
40
|
-
|
|
34
|
+
const sla = new AgentSLA({ privateKey: process.env.AGENT_PRIVATE_KEY }); // or { signer } (any ethers v6 Signer)
|
|
35
|
+
|
|
36
|
+
const signed = await sla.verifyEndpoint({ endpointUrl: "https://api.example.com/health" });
|
|
37
|
+
console.log(signed.slaMet, signed.httpStatus, signed.latencyMs, signed.eip712Signature, signed.oracleSigner);
|
|
41
38
|
```
|
|
42
39
|
|
|
43
|
-
|
|
40
|
+
Many checks? Buy a **7-day pass** (5 USDC, also one signature, no gas):
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
43
|
+
if (!(await sla.isSubscribed())) await sla.buyPass();
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`pay: "pass" | "x402" | "none"` (constructor or per call) forces one payment method. Verify any signature yourself
|
|
47
|
+
with `ethers.verifyTypedData`, using the domain and types from `GET https://agentsla.io/v1/attestations?url=...`.
|
|
48
|
+
|
|
49
|
+
> **Pass access needs a wallet signature (since 2.1).** Pass purchases are public on-chain, so a bare `walletAddress`
|
|
50
|
+
> no longer unlocks a pass. The SDK signs a short message with the pass wallet automatically. Calling the API
|
|
51
|
+
> directly? See [Pass access without the SDK](#pass-access-without-the-sdk).
|
|
52
|
+
|
|
53
|
+
## Use it in your agent framework
|
|
54
|
+
|
|
55
|
+
The MCP server gives any framework the free tools (directory search, live checks, pass status, escrow quotes). For
|
|
56
|
+
signed checks paid from the agent's wallet, add the SDK tools.
|
|
44
57
|
|
|
45
|
-
|
|
46
|
-
|
|
58
|
+
### Any framework: `agentslaTools()`
|
|
59
|
+
|
|
60
|
+
Three tools with JSON Schema parameters and an `execute` function: `check_before_paying` (free), `signed_check`
|
|
61
|
+
(pass or 0.05 USDC) and `find_apis`.
|
|
47
62
|
|
|
48
63
|
```javascript
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
64
|
+
import { AgentSLA, agentslaTools } from "agentsla";
|
|
65
|
+
const tools = agentslaTools(new AgentSLA({ privateKey: process.env.AGENT_PRIVATE_KEY }));
|
|
66
|
+
// each: { name, description, parameters (JSON Schema), execute(args) }
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### OpenAI Agents SDK (TypeScript)
|
|
70
|
+
|
|
71
|
+
```javascript
|
|
72
|
+
import { Agent, run, tool, MCPServerStreamableHttp } from "@openai/agents";
|
|
73
|
+
import { AgentSLA, agentslaTools } from "agentsla";
|
|
74
|
+
|
|
75
|
+
const mcp = new MCPServerStreamableHttp({ name: "agentsla", url: "https://agentsla.io/mcp" });
|
|
76
|
+
await mcp.connect();
|
|
77
|
+
const sla = new AgentSLA({ privateKey: process.env.AGENT_PRIVATE_KEY });
|
|
78
|
+
const paid = agentslaTools(sla).map((t) => tool({ name: t.name, description: t.description, parameters: t.parameters, strict: false, execute: t.execute }));
|
|
79
|
+
|
|
80
|
+
const agent = new Agent({
|
|
81
|
+
name: "Buyer",
|
|
82
|
+
instructions: "Before paying or relying on any external API, call check_before_paying and stop if ok is false.",
|
|
83
|
+
mcpServers: [mcp],
|
|
84
|
+
tools: paid
|
|
85
|
+
});
|
|
86
|
+
console.log((await run(agent, "Is https://api.example.com/v1/quote safe to pay right now?")).finalOutput);
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### OpenAI Agents SDK (Python)
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from agents import Agent, Runner
|
|
93
|
+
from agents.mcp import MCPServerStreamableHttp
|
|
94
|
+
|
|
95
|
+
async with MCPServerStreamableHttp(name="agentsla", params={"url": "https://agentsla.io/mcp"}) as agentsla:
|
|
96
|
+
agent = Agent(name="Buyer", mcp_servers=[agentsla],
|
|
97
|
+
instructions="Before paying or relying on any external API, call check_endpoint and stop if meetsSla is false.")
|
|
98
|
+
print((await Runner.run(agent, "Check https://api.example.com/v1/quote before I pay it.")).final_output)
|
|
53
99
|
```
|
|
54
100
|
|
|
55
|
-
|
|
56
|
-
`ethers.verifyTypedData` using the domain and types from `GET https://agentsla.io/v1/attestations?url=...`.
|
|
101
|
+
### LangChain / LangGraph (Python)
|
|
57
102
|
|
|
58
|
-
|
|
103
|
+
```python
|
|
104
|
+
from langchain_mcp_adapters.client import MultiServerMCPClient
|
|
105
|
+
from langgraph.prebuilt import create_react_agent
|
|
106
|
+
|
|
107
|
+
client = MultiServerMCPClient({"agentsla": {"url": "https://agentsla.io/mcp", "transport": "streamable_http"}})
|
|
108
|
+
tools = await client.get_tools()
|
|
109
|
+
agent = create_react_agent("openai:gpt-4.1", tools)
|
|
110
|
+
await agent.ainvoke({"messages": "Find a weather API on AgentSLA and check it before I pay it."})
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### CrewAI (Python)
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from crewai import Agent
|
|
117
|
+
from crewai_tools import MCPServerAdapter
|
|
118
|
+
|
|
119
|
+
with MCPServerAdapter({"url": "https://agentsla.io/mcp", "transport": "streamable-http"}) as tools:
|
|
120
|
+
buyer = Agent(role="API buyer", goal="Only pay APIs that pass a live AgentSLA check",
|
|
121
|
+
backstory="Careful with money.", tools=tools)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Vercel AI SDK
|
|
59
125
|
|
|
60
126
|
```javascript
|
|
61
|
-
|
|
127
|
+
import { generateText, tool, jsonSchema, stepCountIs } from "ai";
|
|
128
|
+
import { openai } from "@ai-sdk/openai";
|
|
129
|
+
import { AgentSLA, agentslaTools } from "agentsla";
|
|
130
|
+
|
|
131
|
+
const sla = new AgentSLA({ privateKey: process.env.AGENT_PRIVATE_KEY });
|
|
132
|
+
const tools = Object.fromEntries(agentslaTools(sla).map((t) => [t.name, tool({ description: t.description, inputSchema: jsonSchema(t.parameters), execute: t.execute })]));
|
|
133
|
+
|
|
134
|
+
const { text } = await generateText({ model: openai("gpt-4.1"), tools, stopWhen: stepCountIs(5),
|
|
135
|
+
prompt: "Check https://api.example.com/v1/quote before paying it." });
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Framework APIs move quickly: if a snippet doesn't match your version, the parts that stay the same are the MCP URL
|
|
139
|
+
(`https://agentsla.io/mcp`, Streamable HTTP) and `agentslaTools()` (JSON Schema + `execute`).
|
|
140
|
+
|
|
141
|
+
## Pass access without the SDK
|
|
142
|
+
|
|
143
|
+
Sign this message with the pass wallet (EIP-191 `personal_sign`, no gas), within 5 minutes of the request:
|
|
144
|
+
|
|
145
|
+
```
|
|
146
|
+
AgentSLA pass access
|
|
147
|
+
Wallet: <checksummed wallet address>
|
|
148
|
+
Signed at: <unix seconds>
|
|
62
149
|
```
|
|
63
150
|
|
|
64
|
-
|
|
65
|
-
`
|
|
151
|
+
Then send `walletAddress`, `walletSignedAt` and `walletSignature` in the JSON body of `POST /v1/verify` (or as MCP
|
|
152
|
+
arguments to `verify_endpoint_sla`), or the header `X-AgentSLA-Wallet-Auth: <signedAt>.<signature>`.
|
|
66
153
|
|
|
67
|
-
|
|
154
|
+
Python (`eth-account`):
|
|
68
155
|
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
156
|
+
```python
|
|
157
|
+
import os, time, requests
|
|
158
|
+
from eth_account import Account
|
|
159
|
+
from eth_account.messages import encode_defunct
|
|
160
|
+
|
|
161
|
+
acct = Account.from_key(os.environ["AGENT_PRIVATE_KEY"])
|
|
162
|
+
ts = int(time.time())
|
|
163
|
+
sig = acct.sign_message(encode_defunct(text=f"AgentSLA pass access\nWallet: {acct.address}\nSigned at: {ts}")).signature.hex()
|
|
164
|
+
r = requests.post("https://agentsla.io/v1/verify", json={
|
|
165
|
+
"targetApiUrl": "https://api.example.com/health",
|
|
166
|
+
"walletAddress": acct.address, "walletSignedAt": ts, "walletSignature": sig if sig.startswith("0x") else "0x" + sig,
|
|
167
|
+
})
|
|
168
|
+
print(r.json())
|
|
75
169
|
```
|
|
170
|
+
|
|
171
|
+
## Escrow (beta)
|
|
172
|
+
|
|
173
|
+
`escrowTransactions({ apiId, providerAddress, priceUsdc })` returns the unsigned Base transactions that lock USDC for a
|
|
174
|
+
listing; the oracle pays the provider if the SLA is met and refunds you otherwise. See
|
|
175
|
+
[agentsla.io/docs#escrow](https://agentsla.io/docs#escrow).
|
|
176
|
+
|
|
177
|
+
## Changes in 2.1.0
|
|
178
|
+
|
|
179
|
+
- `verifyEndpoint()` pays automatically: the wallet's pass (with a wallet signature), else 0.05 USDC by x402.
|
|
180
|
+
- New: `checkBeforePaying()`, `buyPass()` (x402, no gas), `passStatus()`, `passAuth()`, `x402Post()`, `agentslaTools()`,
|
|
181
|
+
`escrowTransactions()`.
|
|
182
|
+
- `subscribeSevenDays()` now buys the pass with `buyPass()` (no approval). `isSubscribed()` counts passes bought either way.
|
|
183
|
+
- `discoverApis()` and every call use `https://agentsla.io`.
|
package/index.js
CHANGED
|
@@ -2,132 +2,243 @@
|
|
|
2
2
|
|
|
3
3
|
export const AGENTSLA_CONFIG = {
|
|
4
4
|
API_URL: "https://agentsla.io",
|
|
5
|
-
ORACLE_URL: "https://agentsla-oracle.agentsla-dev.workers.dev",
|
|
6
5
|
MCP_URL: "https://agentsla.io/mcp",
|
|
7
6
|
CHAIN_ID: 8453,
|
|
7
|
+
NETWORK: "eip155:8453",
|
|
8
8
|
RPC_URL: "https://mainnet.base.org",
|
|
9
|
-
// Current escrow contract (the one the oracle settles). 2.0.2 and earlier pointed at the retired 0x6ca6cDDd... contract.
|
|
10
9
|
ESCROW_CONTRACT: "0x5c8D11AB570D7384d01226bC80123D0dD103Fb57",
|
|
11
10
|
USDC_TOKEN: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
12
11
|
TREASURY_WALLET: "0x9A0d2dD2402991eC8095fE2Be0d96A59d9DCF13C"
|
|
13
12
|
};
|
|
14
13
|
|
|
15
|
-
const ESCROW_ABI = [
|
|
16
|
-
"function createJob(address _agent, uint256 _apiId, uint256 _lockedAmount) external returns (uint256)",
|
|
17
|
-
"function paySubscription() external"
|
|
18
|
-
];
|
|
19
|
-
|
|
20
14
|
const USDC_ABI = [
|
|
21
15
|
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
22
16
|
"function allowance(address owner, address spender) view returns (uint256)",
|
|
23
|
-
"function balanceOf(address account) view returns (uint256)"
|
|
24
|
-
"function transfer(address to, uint256 amount) external returns (bool)"
|
|
17
|
+
"function balanceOf(address account) view returns (uint256)"
|
|
25
18
|
];
|
|
19
|
+
const TRANSFER_WITH_AUTHORIZATION_TYPES = {
|
|
20
|
+
TransferWithAuthorization: [
|
|
21
|
+
{ name: "from", type: "address" }, { name: "to", type: "address" }, { name: "value", type: "uint256" },
|
|
22
|
+
{ name: "validAfter", type: "uint256" }, { name: "validBefore", type: "uint256" }, { name: "nonce", type: "bytes32" }
|
|
23
|
+
]
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const b64 = (s) => Buffer.from(s, "utf8").toString("base64");
|
|
27
|
+
const unb64 = (s) => Buffer.from(String(s), "base64").toString("utf8");
|
|
28
|
+
|
|
29
|
+
/** The message a pass wallet signs (personal_sign) to prove it is the caller. Valid for 5 minutes. */
|
|
30
|
+
export function passAuthMessage(wallet, signedAt) {
|
|
31
|
+
return "AgentSLA pass access\nWallet: " + ethers.getAddress(wallet) + "\nSigned at: " + Math.floor(Number(signedAt));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class AgentSLAError extends Error {
|
|
35
|
+
constructor(message, status, body) { super(message); this.name = "AgentSLAError"; this.status = status; this.body = body; }
|
|
36
|
+
}
|
|
26
37
|
|
|
27
38
|
export class AgentSLA {
|
|
39
|
+
/**
|
|
40
|
+
* @param {object} [options]
|
|
41
|
+
* @param {string} [options.privateKey] the agent's own Base wallet key (needed only to pay or use a pass)
|
|
42
|
+
* @param {import("ethers").Signer} [options.signer] or any ethers v6 Signer (wallet, KMS, smart account adapter)
|
|
43
|
+
* @param {"auto"|"pass"|"x402"|"none"} [options.pay="auto"] how signed checks are paid: an active pass first, else 0.05 USDC by x402
|
|
44
|
+
*/
|
|
28
45
|
constructor(options = {}) {
|
|
29
46
|
this.apiUrl = (options.apiUrl || AGENTSLA_CONFIG.API_URL).replace(/\/+$/, "");
|
|
30
|
-
this.oracleUrl = options.oracleUrl || AGENTSLA_CONFIG.ORACLE_URL;
|
|
31
47
|
this.mcpUrl = options.mcpUrl || AGENTSLA_CONFIG.MCP_URL;
|
|
32
|
-
this.
|
|
33
|
-
this.
|
|
34
|
-
this.
|
|
48
|
+
this.provider = new ethers.JsonRpcProvider(options.rpcUrl || AGENTSLA_CONFIG.RPC_URL, AGENTSLA_CONFIG.CHAIN_ID, { staticNetwork: true });
|
|
49
|
+
this.signer = options.signer || (options.privateKey ? new ethers.Wallet(options.privateKey, this.provider) : null);
|
|
50
|
+
this.pay = options.pay || "auto";
|
|
35
51
|
}
|
|
36
52
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
53
|
+
async address() { return this.signer ? await this.signer.getAddress() : null; }
|
|
54
|
+
#needSigner() { if (!this.signer) throw new AgentSLAError("This needs the agent's wallet: construct AgentSLA with { privateKey } or { signer }.", 0); }
|
|
55
|
+
|
|
56
|
+
async #json(path, init = {}) {
|
|
57
|
+
const res = await fetch(this.apiUrl + path, init);
|
|
58
|
+
const text = await res.text();
|
|
59
|
+
let body; try { body = JSON.parse(text); } catch { body = { raw: text.slice(0, 500) }; }
|
|
60
|
+
return { res, body };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---------------- free ----------------
|
|
64
|
+
|
|
65
|
+
/** Search the directory of APIs and MCP servers (indexed and probed, not audited). */
|
|
41
66
|
async discoverApis(filter = {}) {
|
|
42
67
|
const params = new URLSearchParams();
|
|
43
|
-
if (typeof filter === "string") {
|
|
44
|
-
|
|
45
|
-
} else if (filter && typeof filter === "object") {
|
|
68
|
+
if (typeof filter === "string") { if (filter && filter !== "all") params.set("category", filter); }
|
|
69
|
+
else {
|
|
46
70
|
if (filter.category && filter.category !== "all") params.set("category", filter.category);
|
|
47
|
-
if (filter.search) params.set("
|
|
71
|
+
if (filter.search || filter.q) params.set("q", filter.search || filter.q);
|
|
48
72
|
if (filter.limit) params.set("limit", String(filter.limit));
|
|
49
73
|
if (filter.offset) params.set("offset", String(filter.offset));
|
|
50
74
|
}
|
|
51
75
|
const qs = params.toString();
|
|
52
|
-
|
|
53
|
-
return await res.json();
|
|
76
|
+
return (await this.#json("/v1/directory" + (qs ? "?" + qs : ""))).body;
|
|
54
77
|
}
|
|
55
78
|
|
|
56
|
-
/**
|
|
57
|
-
* Call the remote Streamable HTTP MCP server at https://agentsla.io/mcp
|
|
58
|
-
*/
|
|
79
|
+
/** Call a tool on the MCP server (https://agentsla.io/mcp). Returns the parsed tool result. */
|
|
59
80
|
async callMcpTool(name, args = {}) {
|
|
60
81
|
const res = await fetch(this.mcpUrl, {
|
|
61
82
|
method: "POST",
|
|
62
83
|
headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
|
|
63
|
-
body: JSON.stringify({
|
|
64
|
-
jsonrpc: "2.0",
|
|
65
|
-
id: Date.now(),
|
|
66
|
-
method: "tools/call",
|
|
67
|
-
params: { name, arguments: args }
|
|
68
|
-
})
|
|
84
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: Date.now(), method: "tools/call", params: { name, arguments: args } })
|
|
69
85
|
});
|
|
70
|
-
|
|
86
|
+
const j = await res.json();
|
|
87
|
+
const text = j && j.result && j.result.content && j.result.content[0] && j.result.content[0].text;
|
|
88
|
+
let data = text; try { data = JSON.parse(text); } catch {}
|
|
89
|
+
return { isError: !!(j.result && j.result.isError), data, raw: j };
|
|
71
90
|
}
|
|
72
91
|
|
|
73
92
|
/**
|
|
74
|
-
*
|
|
93
|
+
* Unsigned live check: HTTP status, latency and the SLA rule (2xx/3xx within maxLatencyMs).
|
|
94
|
+
* 10 free per month per IP; with an active pass on the agent's wallet it is unlimited (signed automatically).
|
|
75
95
|
*/
|
|
76
|
-
async checkEndpoint({ endpointUrl, maxLatencyMs = 1000 }) {
|
|
96
|
+
async checkEndpoint({ endpointUrl, maxLatencyMs = 1000 } = {}) {
|
|
77
97
|
const qs = new URLSearchParams({ url: endpointUrl, max_latency_ms: String(maxLatencyMs) });
|
|
78
|
-
const
|
|
79
|
-
|
|
98
|
+
const headers = {};
|
|
99
|
+
if (this.signer && this.pay !== "none" && (await this.#hasPass())) {
|
|
100
|
+
const a = await this.passAuth();
|
|
101
|
+
qs.set("wallet", a.walletAddress);
|
|
102
|
+
headers["X-AgentSLA-Wallet-Auth"] = a.walletSignedAt + "." + a.walletSignature;
|
|
103
|
+
}
|
|
104
|
+
const { res, body } = await this.#json("/v1/verify?" + qs, { headers });
|
|
105
|
+
if (res.status === 402) body.paymentRequired = true;
|
|
106
|
+
return body;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Pass status for a wallet (default: the agent's wallet). Counts passes bought on-chain or at /v1/pass. */
|
|
110
|
+
async passStatus(address) {
|
|
111
|
+
const who = address || (await this.address());
|
|
112
|
+
if (!who) throw new AgentSLAError("Pass an address or construct AgentSLA with a wallet.", 0);
|
|
113
|
+
return (await this.#json("/v1/pass?wallet=" + encodeURIComponent(who))).body;
|
|
114
|
+
}
|
|
115
|
+
async isSubscribed(address) { return !!(await this.passStatus(address)).active; }
|
|
116
|
+
|
|
117
|
+
// ---------------- wallet proof ----------------
|
|
118
|
+
|
|
119
|
+
/** Fresh proof that the agent controls its pass wallet: { walletAddress, walletSignedAt, walletSignature }. */
|
|
120
|
+
async passAuth() {
|
|
121
|
+
this.#needSigner();
|
|
122
|
+
const walletAddress = ethers.getAddress(await this.signer.getAddress());
|
|
123
|
+
const walletSignedAt = Math.floor(Date.now() / 1000);
|
|
124
|
+
const walletSignature = await this.signer.signMessage(passAuthMessage(walletAddress, walletSignedAt));
|
|
125
|
+
return { walletAddress, walletSignedAt, walletSignature };
|
|
80
126
|
}
|
|
127
|
+
async #hasPass() { try { return await this.isSubscribed(); } catch { return false; } }
|
|
128
|
+
|
|
129
|
+
// ---------------- paid ----------------
|
|
81
130
|
|
|
82
131
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* (that probes the job's registered endpoint and settles the job). Without either, the response is HTTP 402 and
|
|
86
|
-
* explains how to pay (pass, escrow job, or x402 at 0.05 USDC per check).
|
|
87
|
-
* 2.0.2 and earlier sent jobId 1 by default, which tried to settle escrow job #1 instead of checking endpointUrl.
|
|
132
|
+
* x402 v2 payment on Base: POST path, read the 402 offer, sign a USDC transferWithAuthorization (no gas, no approval),
|
|
133
|
+
* retry with PAYMENT-SIGNATURE. Returns { body, receipt } (receipt = the settlement from PAYMENT-RESPONSE).
|
|
88
134
|
*/
|
|
89
|
-
async
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
if (
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
const
|
|
101
|
-
if (
|
|
102
|
-
|
|
135
|
+
async x402Post(path, body = {}, { maxAmountUsdc } = {}) {
|
|
136
|
+
this.#needSigner();
|
|
137
|
+
const init = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
|
|
138
|
+
const first = await this.#json(path, init);
|
|
139
|
+
if (first.res.status !== 402) {
|
|
140
|
+
if (first.res.ok) return { body: first.body, receipt: null };
|
|
141
|
+
throw new AgentSLAError(first.body.error || "HTTP " + first.res.status, first.res.status, first.body);
|
|
142
|
+
}
|
|
143
|
+
const hdr = first.res.headers.get("payment-required");
|
|
144
|
+
if (!hdr) throw new AgentSLAError("402 without a PAYMENT-REQUIRED header", 402, first.body);
|
|
145
|
+
const pr = JSON.parse(unb64(hdr));
|
|
146
|
+
const acc = (pr.accepts || []).find((a) => a.network === AGENTSLA_CONFIG.NETWORK && a.scheme === "exact");
|
|
147
|
+
if (!acc) throw new AgentSLAError("No Base payment option offered", 402, pr);
|
|
148
|
+
if (maxAmountUsdc != null && BigInt(acc.amount) > ethers.parseUnits(String(maxAmountUsdc), 6)) {
|
|
149
|
+
throw new AgentSLAError("Price " + ethers.formatUnits(acc.amount, 6) + " USDC is above maxAmountUsdc " + maxAmountUsdc, 402, pr);
|
|
150
|
+
}
|
|
151
|
+
const from = ethers.getAddress(await this.signer.getAddress());
|
|
152
|
+
const now = Math.floor(Date.now() / 1000);
|
|
153
|
+
const authorization = { from, to: ethers.getAddress(acc.payTo), value: String(acc.amount), validAfter: String(now - 600), validBefore: String(now + Number(acc.maxTimeoutSeconds || 300)), nonce: ethers.hexlify(ethers.randomBytes(32)) };
|
|
154
|
+
const signature = await this.signer.signTypedData(
|
|
155
|
+
{ name: acc.extra && acc.extra.name ? acc.extra.name : "USD Coin", version: acc.extra && acc.extra.version ? acc.extra.version : "2", chainId: AGENTSLA_CONFIG.CHAIN_ID, verifyingContract: acc.asset },
|
|
156
|
+
TRANSFER_WITH_AUTHORIZATION_TYPES, authorization
|
|
157
|
+
);
|
|
158
|
+
const payment = b64(JSON.stringify({ x402Version: 2, resource: pr.resource, accepted: acc, payload: { signature, authorization } }));
|
|
159
|
+
const second = await this.#json(path, { ...init, headers: { ...init.headers, "PAYMENT-SIGNATURE": payment } });
|
|
160
|
+
const rh = second.res.headers.get("payment-response");
|
|
161
|
+
const receipt = rh ? JSON.parse(unb64(rh)) : null;
|
|
162
|
+
if (!second.res.ok) throw new AgentSLAError(second.body.error || "Payment not accepted (HTTP " + second.res.status + ")", second.res.status, second.body);
|
|
163
|
+
return { body: second.body, receipt };
|
|
103
164
|
}
|
|
104
165
|
|
|
105
|
-
/**
|
|
106
|
-
async
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
const escrow = new ethers.Contract(AGENTSLA_CONFIG.ESCROW_CONTRACT, ["function isSubscribed(address) view returns (bool)"], this.provider);
|
|
110
|
-
return await escrow.isSubscribed(who);
|
|
166
|
+
/** Buy a 7-day pass: 5 USDC on Base with one signature (x402 at /v1/pass), no gas, no approval. */
|
|
167
|
+
async buyPass() {
|
|
168
|
+
const { body, receipt } = await this.x402Post("/v1/pass", {});
|
|
169
|
+
return { ...body, receipt };
|
|
111
170
|
}
|
|
171
|
+
/** @deprecated since 2.1: use buyPass() (no approval, no gas). Kept so existing code keeps working. */
|
|
172
|
+
async subscribeSevenDays() { return this.buyPass(); }
|
|
112
173
|
|
|
113
174
|
/**
|
|
114
|
-
*
|
|
175
|
+
* Signed check: probes the endpoint and returns an EIP-712 SLA attestation from the oracle.
|
|
176
|
+
* Payment (pay option): "auto" uses the wallet's pass if active (with a fresh wallet signature), else pays 0.05 USDC by x402;
|
|
177
|
+
* "pass" only uses the pass; "x402" always pays per check. jobId settles that escrow job instead (no payment).
|
|
115
178
|
*/
|
|
116
|
-
async
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
if (allowance < fee) {
|
|
125
|
-
const approveTx = await usdc.approve(AGENTSLA_CONFIG.ESCROW_CONTRACT, fee);
|
|
126
|
-
await approveTx.wait(1);
|
|
179
|
+
async verifyEndpoint({ endpointUrl, maxLatencyMs, payload, jobId, pay } = {}) {
|
|
180
|
+
const mode = pay || this.pay;
|
|
181
|
+
const body = { targetApiUrl: endpointUrl };
|
|
182
|
+
if (maxLatencyMs) body.maxLatencyMs = maxLatencyMs;
|
|
183
|
+
if (payload && Object.keys(payload).length) body.targetApiPayload = payload;
|
|
184
|
+
if (jobId) {
|
|
185
|
+
body.jobId = jobId;
|
|
186
|
+
return (await this.#json("/v1/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })).body;
|
|
127
187
|
}
|
|
128
|
-
|
|
129
|
-
|
|
188
|
+
if (mode !== "x402" && this.signer && (mode === "pass" || (await this.#hasPass()))) {
|
|
189
|
+
Object.assign(body, await this.passAuth());
|
|
190
|
+
const { res, body: out } = await this.#json("/v1/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
191
|
+
if (res.ok || mode === "pass") { if (res.status === 402 || res.status === 401) out.paymentRequired = true; return out; }
|
|
192
|
+
}
|
|
193
|
+
if (mode === "none" || mode === "pass" || !this.signer) {
|
|
194
|
+
const { res, body: out } = await this.#json("/v1/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
195
|
+
if (res.status === 402) out.paymentRequired = true;
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
const { body: out, receipt } = await this.x402Post("/v1/verify", body, { maxAmountUsdc: "0.05" });
|
|
199
|
+
return { ...out, payment: out.payment || receipt };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* One call before your agent pays or depends on an API: live check against the SLA rule.
|
|
204
|
+
* Returns { ok, reason, check }. signed: true returns the oracle-signed result (pass or 0.05 USDC).
|
|
205
|
+
*/
|
|
206
|
+
async checkBeforePaying(endpointUrl, { maxLatencyMs = 1000, signed = false } = {}) {
|
|
207
|
+
const check = signed ? await this.verifyEndpoint({ endpointUrl, maxLatencyMs }) : await this.checkEndpoint({ endpointUrl, maxLatencyMs });
|
|
208
|
+
if (check.paymentRequired || check.error) return { ok: false, reason: check.error || "payment required", check };
|
|
209
|
+
const met = signed ? check.slaMet === true : check.meetsSla === true;
|
|
210
|
+
const status = check.httpStatus, ms = signed ? check.latencyMs : check.edgeLatencyMs;
|
|
211
|
+
return { ok: met, reason: met ? "HTTP " + status + " in " + ms + " ms (limit " + maxLatencyMs + ")" : "SLA not met: HTTP " + status + " in " + ms + " ms (limit " + maxLatencyMs + ")", check };
|
|
130
212
|
}
|
|
213
|
+
|
|
214
|
+
// ---------------- escrow ----------------
|
|
215
|
+
|
|
216
|
+
/** The unsigned Base transactions that lock USDC in escrow for a listing (via the MCP tool create_escrow_job). */
|
|
217
|
+
async escrowTransactions({ apiId, providerAddress, priceUsdc }) {
|
|
218
|
+
const walletAddress = await this.address();
|
|
219
|
+
if (!walletAddress) this.#needSigner();
|
|
220
|
+
return (await this.callMcpTool("create_escrow_job", { walletAddress, apiId, providerAddress, priceUsdc })).data;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Framework-neutral tool definitions (JSON Schema + execute) for agent frameworks: OpenAI function calling, Vercel AI SDK,
|
|
226
|
+
* LangChain JS tool(), Mastra, etc. check_before_paying is free; signed_check pays with the wallet's pass or 0.05 USDC.
|
|
227
|
+
*/
|
|
228
|
+
export function agentslaTools(client = new AgentSLA()) {
|
|
229
|
+
const url = { type: "string", description: "Full http(s) URL of the API or MCP endpoint" };
|
|
230
|
+
const max = { type: "integer", minimum: 50, maximum: 30000, description: "Maximum response time in ms (default 1000)" };
|
|
231
|
+
return [
|
|
232
|
+
{ name: "check_before_paying", description: "Check an API or MCP endpoint right now before paying or relying on it: returns ok (HTTP 2xx/3xx within the latency limit), the status and latency.",
|
|
233
|
+
parameters: { type: "object", properties: { endpointUrl: url, maxLatencyMs: max }, required: ["endpointUrl"], additionalProperties: false },
|
|
234
|
+
execute: ({ endpointUrl, maxLatencyMs }) => client.checkBeforePaying(endpointUrl, { maxLatencyMs }) },
|
|
235
|
+
{ name: "signed_check", description: "Oracle-signed (EIP-712) check of an endpoint, as verifiable proof of its status and latency. Paid with the agent wallet's 7-day pass, else 0.05 USDC on Base.",
|
|
236
|
+
parameters: { type: "object", properties: { endpointUrl: url, maxLatencyMs: max }, required: ["endpointUrl"], additionalProperties: false },
|
|
237
|
+
execute: ({ endpointUrl, maxLatencyMs }) => client.verifyEndpoint({ endpointUrl, maxLatencyMs }) },
|
|
238
|
+
{ name: "find_apis", description: "Search the AgentSLA directory of APIs and MCP servers by keyword or category (indexed, not audited).",
|
|
239
|
+
parameters: { type: "object", properties: { search: { type: "string" }, category: { type: "string" }, limit: { type: "integer", minimum: 1, maximum: 50 } }, additionalProperties: false },
|
|
240
|
+
execute: (args) => client.discoverApis({ limit: 10, ...args }) }
|
|
241
|
+
];
|
|
131
242
|
}
|
|
132
243
|
|
|
133
244
|
export default AgentSLA;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentsla",
|
|
3
|
-
"version": "2.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "Check an API before your agent pays it: live and oracle-signed (EIP-712) endpoint checks, paid automatically with x402 or a 7-day pass, plus refundable USDC escrow on Base. MCP server and framework tools included.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"scripts": {
|
|
@@ -18,7 +18,13 @@
|
|
|
18
18
|
"x402",
|
|
19
19
|
"eip-712",
|
|
20
20
|
"llmstxt",
|
|
21
|
-
"glama"
|
|
21
|
+
"glama",
|
|
22
|
+
"agent-payments",
|
|
23
|
+
"openai-agents",
|
|
24
|
+
"langchain",
|
|
25
|
+
"crewai",
|
|
26
|
+
"vercel-ai-sdk",
|
|
27
|
+
"check-before-paying"
|
|
22
28
|
],
|
|
23
29
|
"author": "AgentSLA (https://agentsla.io)",
|
|
24
30
|
"license": "MIT",
|