agent-clinic-mcp 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +97 -2
- package/SKILL.md +47 -0
- package/package.json +35 -4
- package/retry.js +35 -0
- package/server.js +389 -0
- package/spend.js +40 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Muhammed Almohaish
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,98 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agent-clinic-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An MCP server that gives an AI agent [Agent Clinic](https://clinic.sosell.al)'s house call as tools. The agent pays once and gets the doctors' instructions for one visit, then examines its own run log on its own model and writes the report: the cause of each failure, the log line behind it, a fix and a corrected instruction file. The clinic runs no model and never sees the log; this server sends none. Payment is in USDC on Base over x402, from a wallet you give it, and only within the spending caps you set.
|
|
4
|
+
|
|
5
|
+
The clinic's free documents, for you and your agent: [llms.txt](https://clinic.sosell.al/llms.txt), [OpenAPI](https://clinic.sosell.al/openapi.json) and the [outline of a visit](https://clinic.sosell.al/house-call/outline).
|
|
6
|
+
|
|
7
|
+
## Tools
|
|
8
|
+
|
|
9
|
+
| Tool | Price | What it does |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| `clinic_info` | free | The clinic's price, protocol version and limits, the free outline (what a visit asks your agent to do and what it never asks), what a visit costs your own model in passes and tokens, and this server's network, wallet address, caps and today's spending |
|
|
12
|
+
| `clinic_house_call` | $1.00 | Pays for one visit. Returns the visit (its id, expiry, and a private link for you, the owner), the licence, and the stage instructions the agent runs on its own model |
|
|
13
|
+
| `clinic_checkin_stage` | free | Optional. Tells your link that a stage started, finished or failed, with the finished stage's findings as severity and code |
|
|
14
|
+
| `clinic_checkin_done` | free | Optional. Tells your link the visit is finished: the model, the mode, and each finding's severity and code. Returns a stamp the clinic signed |
|
|
15
|
+
| `clinic_outcome` | free | Tells the clinic whether the fix resolved the problem: the visit id and yes or no |
|
|
16
|
+
|
|
17
|
+
The price is the clinic's own: the server reads it from the clinic when it starts, so the tool description always matches what the clinic charges. The check-ins take fixed values only, from the lists the clinic publishes in its `/openapi.json` (read at start; the protocol 1.2 lists are built in for when the clinic cannot be read). An unknown value or any extra field is refused before anything is sent, so no text from the log can reach the clinic through them. `clinic_checkin_done` never sends the report itself.
|
|
18
|
+
|
|
19
|
+
The hosted tools of the clinic before 22 Nov 2026 (`clinic_scan`, `clinic_diagnose`, `clinic_checkup`, `clinic_treatment`) are gone: their routes answer 404.
|
|
20
|
+
|
|
21
|
+
## Paying, and never paying twice
|
|
22
|
+
|
|
23
|
+
- A payment is signed only for USDC's own contract on this server's network, and only after it fits both caps below. Anything else is refused before signing, and nothing is paid.
|
|
24
|
+
- The payment settles before the instructions are sent and is final: there are no refunds.
|
|
25
|
+
- Every house call carries a private `request_id`. The server keeps it in `~/.agent-clinic-mcp/pending-visit.json` from just before it signs until the visit has arrived. If an answer does not come back (a timeout, a lost connection, a crash), the next `clinic_house_call` sends the same `request_id`, and the clinic sends that visit again, free, instead of selling a second one. The file holds only that `request_id`, when it was made and `share_report`; it is deleted when the visit arrives, and dropped after 72 hours, when a visit expires.
|
|
26
|
+
- One house call at a time per server: a second call while one is under way is refused, and pays nothing.
|
|
27
|
+
- If the payment settled but the clinic could not complete the visit, the tool says so and asks the agent to tell you, rather than paying again.
|
|
28
|
+
|
|
29
|
+
## The licence
|
|
30
|
+
|
|
31
|
+
The instructions are licensed for one examination of one run: use them only for that, do not copy or keep them after the visit, and delete them when the report is written (the licence text comes with every visit). This server never writes them to disk or to its log. It keeps only each visit's check-in token, in memory, until it stops.
|
|
32
|
+
|
|
33
|
+
## Spending control
|
|
34
|
+
|
|
35
|
+
- `MAX_SPEND_USD_PER_CALL` (default `1.00`): a visit that costs more is refused before anything is signed.
|
|
36
|
+
- `MAX_SPEND_USD_PER_DAY` (default `5.00`): a visit that would take today's total (UTC) above this is refused. Today's total is kept in `~/.agent-clinic-mcp/spend.json` (change it with `SPEND_FILE`; the pending `request_id` is kept next to it), so restarting the server does not reset it.
|
|
37
|
+
- A payment counts once it was signed and may have settled. It is taken off again only when the clinic's answer shows it did not settle. A visit the clinic sends again for a kept `request_id` costs nothing and does not count.
|
|
38
|
+
|
|
39
|
+
## Configuration
|
|
40
|
+
|
|
41
|
+
| Variable | Required | Default | Meaning |
|
|
42
|
+
|---|---|---|---|
|
|
43
|
+
| `CLINIC_URL` | no | `https://clinic.sosell.al` | The clinic's address. https only (plain http only for localhost) |
|
|
44
|
+
| `AGENT_PRIVATE_KEY` | for `clinic_house_call` | none | The agent's wallet key (0x + 64 hex). Never printed or logged: on start the server prints only the wallet address |
|
|
45
|
+
| `NETWORK` | no | `eip155:8453` | `eip155:8453` is Base mainnet (real USDC). `eip155:84532` is Base Sepolia testnet (test USDC). The server refuses to pay a clinic on another network |
|
|
46
|
+
| `MAX_SPEND_USD_PER_CALL` | no | `1.00` | Per-call cap in US dollars |
|
|
47
|
+
| `MAX_SPEND_USD_PER_DAY` | no | `5.00` | Daily cap in US dollars |
|
|
48
|
+
| `SPEND_FILE` | no | `~/.agent-clinic-mcp/spend.json` | Where today's total is kept (the pending `request_id` goes in the same folder) |
|
|
49
|
+
|
|
50
|
+
Use a wallet that holds only what you are willing to spend on the clinic, not your main wallet. The wallet needs USDC on Base and no ETH: the clinic's facilitator pays the gas.
|
|
51
|
+
|
|
52
|
+
## Install
|
|
53
|
+
|
|
54
|
+
It needs Node.js 20 or later. Nothing to install by hand: your MCP client starts it with `npx`. The commands below name the exact version, so an update never changes what pays from your wallet unless you choose it: change the version yourself after reading what changed.
|
|
55
|
+
|
|
56
|
+
### Claude Code
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
claude mcp add agent-clinic --env AGENT_PRIVATE_KEY=0xYOUR_AGENT_KEY --env MAX_SPEND_USD_PER_DAY=5.00 -- npx -y agent-clinic-mcp@0.2.0
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Claude Desktop
|
|
63
|
+
|
|
64
|
+
Add this to `claude_desktop_config.json` (Settings → Developer → Edit Config), then restart Claude Desktop:
|
|
65
|
+
|
|
66
|
+
```json
|
|
67
|
+
{
|
|
68
|
+
"mcpServers": {
|
|
69
|
+
"agent-clinic": {
|
|
70
|
+
"command": "npx",
|
|
71
|
+
"args": ["-y", "agent-clinic-mcp@0.2.0"],
|
|
72
|
+
"env": {
|
|
73
|
+
"AGENT_PRIVATE_KEY": "0xYOUR_AGENT_KEY",
|
|
74
|
+
"MAX_SPEND_USD_PER_CALL": "1.00",
|
|
75
|
+
"MAX_SPEND_USD_PER_DAY": "5.00"
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Put the key only in your own local config file. Do not commit it or paste it into a chat.
|
|
83
|
+
|
|
84
|
+
## Data
|
|
85
|
+
|
|
86
|
+
Nothing from the log is sent: the house call takes no log, and the check-ins take fixed values only. The clinic keeps the payment (wallet, amount, transaction) and, if the agent sends the check-ins, stage names, counts, severities, diagnosis codes and the model's name. It keeps the full report only if the payer chose `share_report` and the agent sent it, which this server's tools never do. A visit's details are deleted after 72 hours. The examination runs on the agent's own model, so the log goes wherever that model runs.
|
|
87
|
+
|
|
88
|
+
## Tests
|
|
89
|
+
|
|
90
|
+
The tests are not part of this package: they run in the clinic's own repository before each release, against a throwaway clinic (Base Sepolia, its data in a temporary folder) with a stand-in facilitator and a fresh wallet key made for the run, never printed. No real payment is made, no model runs, and nothing reaches the public clinic. They check the tools and the price, the free information, a paid visit, that the instructions are written nowhere, the check-ins and their fixed values, the outcome, a lost answer followed by a retry that is sent the same visit without paying again, two calls at once, both caps, a missing wallet, the mainnet default refusing a testnet clinic, a clinic asking for another token, and that the key never appears in the output.
|
|
91
|
+
|
|
92
|
+
## Using it from an agent
|
|
93
|
+
|
|
94
|
+
[SKILL.md](SKILL.md) tells an agent when a house call is useful and how to run one. Load it with the server.
|
|
95
|
+
|
|
96
|
+
## Package licence
|
|
97
|
+
|
|
98
|
+
This package's code is under the MIT licence ([LICENSE](LICENSE)). The visit instructions it fetches are not part of the package: they come from the clinic with each paid visit, under that visit's own licence (see The licence, above).
|
package/SKILL.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: agent-clinic
|
|
3
|
+
description: When a task is stuck or failed and the cause is unclear, book an Agent Clinic house call with clinic_house_call and run its stages on your own model over your own run log. Paid once per visit, within the owner's spending caps.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Agent Clinic: house calls
|
|
7
|
+
|
|
8
|
+
A house call gets you the doctors' instructions for one visit: eleven stages (intake, seven departments, consolidation, verification, treatment) that you run on your own model over your own run log, and the format of one report. The clinic runs no model and never sees your log: `clinic_house_call` sends none.
|
|
9
|
+
|
|
10
|
+
## When it is useful
|
|
11
|
+
|
|
12
|
+
- The same tool call has failed several times in a row and retrying has not helped.
|
|
13
|
+
- A tool keeps returning errors and it is unclear what is wrong with the call.
|
|
14
|
+
- A task ended without reaching its goal, or with an answer you cannot back with a tool result, and you do not know why.
|
|
15
|
+
- Before running a similar task again, to get corrected instructions.
|
|
16
|
+
|
|
17
|
+
It is not needed when the cause is already clear, or when a task simply needs another attempt.
|
|
18
|
+
|
|
19
|
+
## Before paying
|
|
20
|
+
|
|
21
|
+
`clinic_info` (free) shows the price, the protocol version, the outline (what a visit asks you to do and what it never asks), what a visit costs your own model in passes and tokens, and the owner's caps and today's spending. Check it when unsure: the visit's tokens are spent on your model, at your owner's cost.
|
|
22
|
+
|
|
23
|
+
## The visit
|
|
24
|
+
|
|
25
|
+
1. Call `clinic_house_call`. It pays once ($1.00 in USDC) and returns the visit, a private link for your owner, the licence and the instructions.
|
|
26
|
+
2. Give your owner the link (`visit.owner_link`). Do not post it.
|
|
27
|
+
3. Run the stages as the instructions say, on your own model, over your own run log. Mask credentials in your working copy first, as the instructions ask.
|
|
28
|
+
4. Write the report in the format the instructions give, and the corrected instruction file.
|
|
29
|
+
5. Delete the instructions when the report is written: the licence allows one examination of one run, nothing more.
|
|
30
|
+
|
|
31
|
+
## Check-ins (optional, free)
|
|
32
|
+
|
|
33
|
+
They show your owner's link how the visit goes. They take fixed values only: stage ids, status, and each finding's severity and code. Never put text from the log anywhere.
|
|
34
|
+
|
|
35
|
+
- `clinic_checkin_stage`: a stage `started`, `done` (with its findings as `{severity, code}`) or `failed`.
|
|
36
|
+
- `clinic_checkin_done`: the model you used, `mode` (`separate` or `single`) and the report's findings as `{severity, code}`. It returns a stamp the clinic signed for the report.
|
|
37
|
+
|
|
38
|
+
## Spending
|
|
39
|
+
|
|
40
|
+
Each visit spends the owner's money. The server refuses a visit above the owner's per-call or daily cap and says so; do not try to get around a refusal. Tell the owner instead.
|
|
41
|
+
|
|
42
|
+
If a call does not come back, call `clinic_house_call` again: it sends the same private request_id, so if the visit was paid you get it again for free, not a second charge. If the answer says the payment settled but the visit could not be completed, payment is final: tell your owner instead of calling again.
|
|
43
|
+
|
|
44
|
+
## Afterwards
|
|
45
|
+
|
|
46
|
+
- Apply the fixes in the report, most severe first, and load the corrected instruction file at the start of the next run.
|
|
47
|
+
- Call `clinic_outcome` (free) with the visit id and whether the fix resolved the problem.
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-clinic-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "MCP server for Agent Clinic house calls: pay once in USDC over x402, within the owner's spending caps, and get the doctors' instructions for one visit, which the agent runs on its own model.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://clinic.sosell.al",
|
|
8
|
+
"keywords": ["mcp", "mcp-server", "ai-agents", "debugging", "diagnostics", "run-logs", "x402", "usdc", "base"],
|
|
9
|
+
"mcpName": "io.github.mohammedalmohaish-cyber/agent-clinic",
|
|
10
|
+
"bin": {
|
|
11
|
+
"agent-clinic-mcp": "server.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"server.js",
|
|
15
|
+
"spend.js",
|
|
16
|
+
"retry.js",
|
|
17
|
+
"README.md",
|
|
18
|
+
"SKILL.md"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=20"
|
|
22
|
+
},
|
|
23
|
+
"scripts": {
|
|
24
|
+
"start": "node server.js",
|
|
25
|
+
"test": "node test.js"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
29
|
+
"@x402/evm": "2.31.0",
|
|
30
|
+
"@x402/fetch": "2.31.0",
|
|
31
|
+
"viem": "2.58.1",
|
|
32
|
+
"zod": "4.6.7"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"dotenv": "16.6.1"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/retry.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// The request_id of a house call that has not come back yet, so a payment is never made twice for one visit.
|
|
2
|
+
// It is written before the payment is signed and removed once the visit has arrived. A retry after a timeout, a crash
|
|
3
|
+
// or a lost answer sends the same request_id, and the clinic sends the visit it already sold, free, instead of selling
|
|
4
|
+
// a second one. Only the request_id, when it was made and share_report are kept, never the instructions: the licence
|
|
5
|
+
// forbids keeping them. The file is readable by its owner only. A request_id older than a visit's life (72 hours)
|
|
6
|
+
// can no longer bring a visit back, so it is dropped.
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
|
|
11
|
+
export const REQUEST_ID = /^[A-Za-z0-9_-]{16,128}$/;
|
|
12
|
+
|
|
13
|
+
export function createRetryStore({ file, maxAgeMs = 72 * 3600 * 1000, now = () => Date.now() }) {
|
|
14
|
+
function read() {
|
|
15
|
+
try {
|
|
16
|
+
const data = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
17
|
+
const age = now() - Date.parse(data.created_at);
|
|
18
|
+
if (REQUEST_ID.test(data.request_id) && age >= 0 && age < maxAgeMs) return { request_id: data.request_id, created_at: data.created_at, share_report: data.share_report === true };
|
|
19
|
+
} catch {}
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
read,
|
|
24
|
+
/** A new private request_id for a new visit, kept until the visit arrives. */
|
|
25
|
+
create(shareReport) {
|
|
26
|
+
const data = { request_id: crypto.randomBytes(24).toString("base64url"), created_at: new Date(now()).toISOString(), share_report: shareReport === true };
|
|
27
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
28
|
+
fs.writeFileSync(file, JSON.stringify(data) + "\n", { mode: 0o600 });
|
|
29
|
+
return data;
|
|
30
|
+
},
|
|
31
|
+
clear() {
|
|
32
|
+
fs.rmSync(file, { force: true });
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
package/server.js
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Agent Clinic MCP server, for the house call (since 22 Nov 2026). An agent's owner installs it to give the agent the
|
|
3
|
+
// clinic as tools: clinic_info (free), clinic_house_call (pays for one visit), two optional check-ins (free, fixed
|
|
4
|
+
// values only) and clinic_outcome (free). The clinic runs no model: the agent runs the visit's stages on its own model.
|
|
5
|
+
// A payment is signed only for USDC on this server's network, and only within the owner's per-call and daily caps.
|
|
6
|
+
// Everything this server prints goes to stderr (stdout carries the MCP protocol). It never prints the private key,
|
|
7
|
+
// and never writes a visit's instructions to disk or to its log: they are licensed for one visit.
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
11
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
import { x402Client, wrapFetchWithPayment, decodePaymentResponseHeader } from "@x402/fetch";
|
|
14
|
+
import { ExactEvmScheme } from "@x402/evm";
|
|
15
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
16
|
+
import { createSpendLedger } from "./spend.js";
|
|
17
|
+
import { createRetryStore } from "./retry.js";
|
|
18
|
+
|
|
19
|
+
const VERSION = "0.2.0";
|
|
20
|
+
const log = (...a) => console.error("[agent-clinic-mcp]", ...a);
|
|
21
|
+
function stop(message) {
|
|
22
|
+
log(message);
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
function usdSetting(name, fallback) {
|
|
26
|
+
const v = process.env[name];
|
|
27
|
+
const n = v === undefined || v === "" ? fallback : Number(v);
|
|
28
|
+
if (!Number.isFinite(n) || n < 0) stop(`${name} must be an amount in US dollars, like 1.00.`);
|
|
29
|
+
return n;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const CLINIC_URL = (process.env.CLINIC_URL || "https://clinic.sosell.al").trim().replace(/\/+$/, "");
|
|
33
|
+
const NETWORK = (process.env.NETWORK || "eip155:8453").trim();
|
|
34
|
+
const NETWORKS = { "eip155:8453": "Base mainnet (real USDC)", "eip155:84532": "Base Sepolia testnet (test USDC)" };
|
|
35
|
+
// USDC's own contract on each network: this server signs a payment in nothing else.
|
|
36
|
+
const USDC = { "eip155:8453": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", "eip155:84532": "0x036cbd53842c5426634e7929541ec2318f3dcf7e" };
|
|
37
|
+
const MAX_PER_CALL = usdSetting("MAX_SPEND_USD_PER_CALL", 1.0);
|
|
38
|
+
const MAX_PER_DAY = usdSetting("MAX_SPEND_USD_PER_DAY", 5.0);
|
|
39
|
+
const SPEND_FILE = process.env.SPEND_FILE || path.join(os.homedir(), ".agent-clinic-mcp", "spend.json");
|
|
40
|
+
const RETRY_FILE = path.join(path.dirname(SPEND_FILE), "pending-visit.json");
|
|
41
|
+
const HOUSE_CALL = "/house-call";
|
|
42
|
+
const CALL_TIMEOUT_MS = 60000;
|
|
43
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
44
|
+
const MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,63}$/; // the clinic's own rule for the done check-in
|
|
45
|
+
const TOKEN = /^[A-Za-z0-9_-]{20,}$/;
|
|
46
|
+
|
|
47
|
+
try {
|
|
48
|
+
const u = new URL(CLINIC_URL);
|
|
49
|
+
const local = ["localhost", "127.0.0.1", "[::1]", "::1"].includes(u.hostname);
|
|
50
|
+
if (!(u.protocol === "https:" || (u.protocol === "http:" && local))) throw new Error("scheme");
|
|
51
|
+
} catch {
|
|
52
|
+
stop("CLINIC_URL must be the clinic's https address, like https://clinic.sosell.al (plain http only for localhost).");
|
|
53
|
+
}
|
|
54
|
+
if (!NETWORKS[NETWORK]) stop("NETWORK must be eip155:8453 (Base mainnet, the default) or eip155:84532 (Base Sepolia testnet).");
|
|
55
|
+
|
|
56
|
+
// The wallet. Only its address is ever shown.
|
|
57
|
+
let account = null;
|
|
58
|
+
const key = (process.env.AGENT_PRIVATE_KEY || "").trim();
|
|
59
|
+
if (key) {
|
|
60
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(key)) stop("AGENT_PRIVATE_KEY is not a valid private key (0x followed by 64 hex characters). It was not printed.");
|
|
61
|
+
account = privateKeyToAccount(key);
|
|
62
|
+
}
|
|
63
|
+
const spend = createSpendLedger({ file: SPEND_FILE, maxPerCall: MAX_PER_CALL, maxPerDay: MAX_PER_DAY });
|
|
64
|
+
const retry = createRetryStore({ file: RETRY_FILE });
|
|
65
|
+
|
|
66
|
+
const asUsd = (atomic) => Number(atomic) / 1e6; // USDC has 6 decimals
|
|
67
|
+
const money = (n) => `$${n.toFixed(2)}`;
|
|
68
|
+
const asText = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
|
|
69
|
+
const asError = (message, extra = {}) => ({ isError: true, content: [{ type: "text", text: JSON.stringify({ error: message, ...extra }, null, 2) }] });
|
|
70
|
+
const spending = () => ({ spent_today_usd: spend.spentToday(), daily_cap_usd: MAX_PER_DAY, per_call_cap_usd: MAX_PER_CALL });
|
|
71
|
+
const why = (err) => String(err?.cause?.code || err?.message || err).slice(0, 300);
|
|
72
|
+
|
|
73
|
+
async function readJson(res) {
|
|
74
|
+
try {
|
|
75
|
+
return await res.json();
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async function getJson(route, timeout = 10000) {
|
|
81
|
+
const res = await fetch(`${CLINIC_URL}${route}`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(timeout) });
|
|
82
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
83
|
+
return res.json();
|
|
84
|
+
}
|
|
85
|
+
async function postJson(route, body, headers = {}) {
|
|
86
|
+
const res = await fetch(`${CLINIC_URL}${route}`, {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: { "content-type": "application/json", accept: "application/json", ...headers },
|
|
89
|
+
body: JSON.stringify(body),
|
|
90
|
+
signal: AbortSignal.timeout(15000),
|
|
91
|
+
});
|
|
92
|
+
return { res, data: await readJson(res) };
|
|
93
|
+
}
|
|
94
|
+
const answer = ({ res, data }) => (res.ok ? asText(data) : asError(data?.error || `The clinic answered HTTP ${res.status}.`, { http_status: res.status }));
|
|
95
|
+
|
|
96
|
+
// The clinic's receipt (PAYMENT-RESPONSE header).
|
|
97
|
+
function receiptOf(res) {
|
|
98
|
+
try {
|
|
99
|
+
const h = res.headers.get("payment-response") || res.headers.get("x-payment-response");
|
|
100
|
+
return h ? decodePaymentResponseHeader(h) : null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const settledIn = (res) => receiptOf(res)?.success === true;
|
|
106
|
+
|
|
107
|
+
// What the clinic publishes, read once at start: the price and its network from its front page, and the check-ins'
|
|
108
|
+
// fixed lists from its OpenAPI document. The lists below are protocol 1.2's, used only when the clinic cannot be read.
|
|
109
|
+
const FALLBACK = {
|
|
110
|
+
stages: ["triage", "loop", "verity", "schema", "prompt", "context", "guard", "budget", "cmo", "verify", "treatment"],
|
|
111
|
+
statuses: ["started", "done", "failed"],
|
|
112
|
+
severities: ["critical", "high", "medium", "low"],
|
|
113
|
+
codes: ["LOOP.NO_STOP", "VERITY.UNGROUNDED", "SCHEMA.BAD_PARAM", "PROMPT.CONFLICT", "CONTEXT.GOAL_DRIFT", "GUARD.INJECTION", "GUARD.OVERREACH", "GUARD.SECRET_LEAK", "BUDGET.WASTE"],
|
|
114
|
+
modes: ["separate", "single"],
|
|
115
|
+
};
|
|
116
|
+
let front = null;
|
|
117
|
+
try {
|
|
118
|
+
front = await getJson("/", 8000);
|
|
119
|
+
} catch (err) {
|
|
120
|
+
log(`Could not read the clinic at ${CLINIC_URL} (${why(err)}). clinic_info tries again; the price is the clinic's own, asked when paying.`);
|
|
121
|
+
}
|
|
122
|
+
let lists = FALLBACK;
|
|
123
|
+
let listsFrom = "built in (protocol 1.2): the clinic's /openapi.json could not be read";
|
|
124
|
+
try {
|
|
125
|
+
const api = await getJson("/openapi.json", 8000);
|
|
126
|
+
const props = (p) => api.paths?.[p]?.post?.requestBody?.content?.["application/json"]?.schema?.properties || {};
|
|
127
|
+
const st = props("/visit/{id}/stage");
|
|
128
|
+
const dn = props("/visit/{id}/done");
|
|
129
|
+
const read = {
|
|
130
|
+
stages: st.stage?.enum,
|
|
131
|
+
statuses: st.status?.enum,
|
|
132
|
+
severities: st.findings?.items?.properties?.severity?.enum,
|
|
133
|
+
codes: st.findings?.items?.properties?.code?.enum,
|
|
134
|
+
modes: dn.mode?.enum,
|
|
135
|
+
};
|
|
136
|
+
if (Object.values(read).every((l) => Array.isArray(l) && l.length && l.every((x) => typeof x === "string" && x.length <= 64))) {
|
|
137
|
+
lists = read;
|
|
138
|
+
listsFrom = "the clinic's /openapi.json";
|
|
139
|
+
}
|
|
140
|
+
} catch {}
|
|
141
|
+
const service = front?.services?.find((s) => s.endpoint === `POST ${HOUSE_CALL}`);
|
|
142
|
+
const PRICE = service?.price || null;
|
|
143
|
+
const clinicNetwork = front?.payment?.network || null;
|
|
144
|
+
if (clinicNetwork && clinicNetwork !== NETWORK)
|
|
145
|
+
log(`The clinic takes payment on ${clinicNetwork}, and this server is set to ${NETWORK}: clinic_house_call refuses to pay until NETWORK matches.`);
|
|
146
|
+
|
|
147
|
+
// One payment for one visit, signed only for USDC on this server's network and only after it fits both caps.
|
|
148
|
+
// Returns {kind: "refused", why} (nothing signed), {kind: "unknown", why} (no answer: it may have settled), or
|
|
149
|
+
// {kind: "answer", res, data, reserved}. Every check is in the hook below, which runs before anything is signed; the
|
|
150
|
+
// x402 client's own spendControls is not used, as it refuses an unknown token with no reason this server can tell.
|
|
151
|
+
async function payForVisit(body) {
|
|
152
|
+
let reserved = 0;
|
|
153
|
+
const client = x402Client
|
|
154
|
+
.fromConfig({ schemes: [{ network: NETWORK, client: new ExactEvmScheme(account) }] })
|
|
155
|
+
.onBeforePaymentCreation(async ({ selectedRequirements: r }) => {
|
|
156
|
+
if (r.network !== NETWORK) return { abort: true, reason: `the clinic asked for a payment on ${r.network}, and this server pays only on ${NETWORK}` };
|
|
157
|
+
if (String(r.asset || "").toLowerCase() !== USDC[NETWORK]) return { abort: true, reason: `the clinic asked to be paid in ${r.asset}, which is not USDC on ${NETWORKS[NETWORK]}` };
|
|
158
|
+
const usd = asUsd(r.amount);
|
|
159
|
+
const refused = spend.reserve(usd);
|
|
160
|
+
if (refused) return { abort: true, reason: refused };
|
|
161
|
+
reserved = usd;
|
|
162
|
+
});
|
|
163
|
+
const pay = wrapFetchWithPayment(fetch, client);
|
|
164
|
+
let res;
|
|
165
|
+
try {
|
|
166
|
+
res = await pay(`${CLINIC_URL}${HOUSE_CALL}`, {
|
|
167
|
+
method: "POST",
|
|
168
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
169
|
+
body: JSON.stringify(body),
|
|
170
|
+
signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
|
|
171
|
+
});
|
|
172
|
+
} catch (err) {
|
|
173
|
+
const message = String(err?.message || err);
|
|
174
|
+
const aborted = message.match(/Payment creation aborted: (.*)$/);
|
|
175
|
+
if (aborted) {
|
|
176
|
+
if (reserved) spend.release(reserved);
|
|
177
|
+
return { kind: "refused", why: aborted[1] };
|
|
178
|
+
}
|
|
179
|
+
// `reserved` is set only when the hook approved a payment, just before it is signed. Without it, nothing was
|
|
180
|
+
// signed in this attempt, so nothing can have been paid: terms this server does not pay, or no answer at all.
|
|
181
|
+
if (!reserved)
|
|
182
|
+
return {
|
|
183
|
+
kind: "refused",
|
|
184
|
+
why: /Failed to create payment payload|rejected by/i.test(message)
|
|
185
|
+
? `the clinic's payment terms are not ones this server pays (USDC on ${NETWORKS[NETWORK]}): ${message.slice(0, 160)}`
|
|
186
|
+
: `the clinic could not be reached (${message.slice(0, 160)})`,
|
|
187
|
+
};
|
|
188
|
+
return { kind: "unknown", why: message.slice(0, 300), reserved };
|
|
189
|
+
}
|
|
190
|
+
return { kind: "answer", res, data: await readJson(res), reserved };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Check-in tokens of the visits this server delivered since it started: in memory only, never written anywhere.
|
|
194
|
+
const tokens = new Map();
|
|
195
|
+
let busy = false;
|
|
196
|
+
|
|
197
|
+
const server = new McpServer({ name: "agent-clinic", version: VERSION });
|
|
198
|
+
const priceText = PRICE ? `Costs ${PRICE} in USDC per visit` : "Costs the clinic's price (see clinic_info), in USDC, per visit";
|
|
199
|
+
|
|
200
|
+
server.registerTool(
|
|
201
|
+
"clinic_info",
|
|
202
|
+
{
|
|
203
|
+
title: "Agent Clinic: price, protocol and spending",
|
|
204
|
+
description:
|
|
205
|
+
"Free. Returns the clinic's price, protocol version and limits, the free outline (what a visit asks your agent to do and what it never asks), what a visit costs your own model in passes and tokens, and this server's network, wallet address, spending caps and what it has spent today. Makes no payment.",
|
|
206
|
+
inputSchema: {},
|
|
207
|
+
},
|
|
208
|
+
async () => {
|
|
209
|
+
const kept = retry.read();
|
|
210
|
+
const out = {
|
|
211
|
+
clinic_url: CLINIC_URL,
|
|
212
|
+
network: NETWORK,
|
|
213
|
+
network_name: NETWORKS[NETWORK],
|
|
214
|
+
wallet: account?.address || null,
|
|
215
|
+
spending: spending(),
|
|
216
|
+
unfinished_house_call: kept ? { started_at: kept.created_at, share_report: kept.share_report, note: "clinic_house_call will send the same request_id again, so a visit that was paid is sent again, not charged twice." } : null,
|
|
217
|
+
check_in_lists_from: listsFrom,
|
|
218
|
+
};
|
|
219
|
+
try {
|
|
220
|
+
const [f, o] = await Promise.all([getJson("/"), getJson(`${HOUSE_CALL}/outline`)]);
|
|
221
|
+
const s = f.services?.find((x) => x.endpoint === `POST ${HOUSE_CALL}`);
|
|
222
|
+
Object.assign(out, {
|
|
223
|
+
price: s?.price || null,
|
|
224
|
+
paid_in: s?.paid_in || null,
|
|
225
|
+
clinic_network: f.payment?.network || null,
|
|
226
|
+
protocol_version: o.protocol_version || null,
|
|
227
|
+
visit_lasts_hours: o.visit_lasts_hours || null,
|
|
228
|
+
paid_services: f.paid_services || null,
|
|
229
|
+
limits: f.limits || null,
|
|
230
|
+
cost_to_your_model: o.cost_to_your_model || f.cost_to_your_model || null,
|
|
231
|
+
outline: o,
|
|
232
|
+
});
|
|
233
|
+
if (f.payment?.network && f.payment.network !== NETWORK) out.warning = `The clinic takes payment on ${f.payment.network}; this server pays only on ${NETWORK}, so clinic_house_call would refuse. Set NETWORK to match.`;
|
|
234
|
+
return asText(out);
|
|
235
|
+
} catch (err) {
|
|
236
|
+
return asError(`Could not reach the clinic at ${CLINIC_URL}: ${why(err)}`, out);
|
|
237
|
+
}
|
|
238
|
+
},
|
|
239
|
+
);
|
|
240
|
+
|
|
241
|
+
server.registerTool(
|
|
242
|
+
"clinic_house_call",
|
|
243
|
+
{
|
|
244
|
+
title: "Agent Clinic: house call",
|
|
245
|
+
description:
|
|
246
|
+
"Useful when a task is stuck in a loop, a tool keeps failing, or it is unclear why a task failed. Pays for one house call and returns: the visit (its id, expiry, and a private link to give your owner, not to post), the licence, " +
|
|
247
|
+
"and the doctors' instructions: eleven stages you run on your own model over your own run log, then one report you write with the cause of each failure, the log line behind it, a fix and a corrected instruction file. " +
|
|
248
|
+
"The clinic never sees your log and runs no model; this call sends no log. " +
|
|
249
|
+
`${priceText}, paid over x402 from the configured wallet on ${NETWORKS[NETWORK]}. Refused before anything is signed if it would pass the owner's per-call or daily cap. The payment settles before the instructions are sent and is final. ` +
|
|
250
|
+
"If a call does not come back, call this tool again: it sends the same private request_id, so the clinic sends that visit again, free, instead of charging twice. " +
|
|
251
|
+
"The instructions are licensed for this one visit: read the licence that comes with them. This server does not write them to disk or to its log.",
|
|
252
|
+
inputSchema: {
|
|
253
|
+
share_report: z.boolean().optional().describe("Optional, default false. true lets your agent send its full report to your owner's link, as the instructions describe. This server's done check-in never sends a report."),
|
|
254
|
+
},
|
|
255
|
+
},
|
|
256
|
+
async ({ share_report }) => {
|
|
257
|
+
if (!account) return asError("No wallet is configured: set AGENT_PRIVATE_KEY to the agent's wallet key. Nothing was paid.");
|
|
258
|
+
if (clinicNetwork && clinicNetwork !== NETWORK) return asError(`Not called: the clinic takes payment on ${clinicNetwork} and this server pays only on ${NETWORK}. Nothing was paid.`, spending());
|
|
259
|
+
if (busy) return asError("A house call from this server is already under way. Wait for its answer; nothing more was paid.", spending());
|
|
260
|
+
busy = true;
|
|
261
|
+
try {
|
|
262
|
+
const want = share_report === true;
|
|
263
|
+
let kept = retry.read();
|
|
264
|
+
const repeating = Boolean(kept);
|
|
265
|
+
if (!kept) kept = retry.create(want); // kept before anything is signed
|
|
266
|
+
const notes = repeating
|
|
267
|
+
? [`This repeats a house call that did not come back (started ${kept.created_at}) with the same request_id: if it was paid, the clinic sends that visit again and does not charge twice.${kept.share_report !== want ? ` share_report stays ${kept.share_report}, as it was sent then.` : ""}`]
|
|
268
|
+
: [];
|
|
269
|
+
const r = await payForVisit({ share_report: kept.share_report, request_id: kept.request_id });
|
|
270
|
+
|
|
271
|
+
if (r.kind === "refused") {
|
|
272
|
+
if (!repeating) retry.clear();
|
|
273
|
+
return asError(`Not called, because ${r.why}. Nothing was paid.`, { ...spending(), ...(notes.length && { notes }) });
|
|
274
|
+
}
|
|
275
|
+
if (r.kind === "unknown")
|
|
276
|
+
return asError(
|
|
277
|
+
`The house call did not come back: ${r.why}. The payment may have settled. Call clinic_house_call again: it sends the same request_id, so if it was paid the clinic sends the visit and does not charge twice. It stays counted against today's cap.`,
|
|
278
|
+
spending(),
|
|
279
|
+
);
|
|
280
|
+
|
|
281
|
+
const { res, data, reserved } = r;
|
|
282
|
+
if (res.status === 200 && data?.visit?.id && data?.instructions) {
|
|
283
|
+
retry.clear();
|
|
284
|
+
const token = data.instructions.check_ins?.token;
|
|
285
|
+
if (typeof token === "string" && TOKEN.test(token)) tokens.set(data.visit.id, token);
|
|
286
|
+
const receipt = receiptOf(res);
|
|
287
|
+
return asText({
|
|
288
|
+
...data,
|
|
289
|
+
payment: {
|
|
290
|
+
paid_now_usd: reserved,
|
|
291
|
+
sent_again_free: data.visit.redelivered === true,
|
|
292
|
+
network: receipt?.network || NETWORK,
|
|
293
|
+
transaction: receipt?.transaction || null,
|
|
294
|
+
payer: receipt?.payer || account.address,
|
|
295
|
+
},
|
|
296
|
+
...(notes.length && { notes }),
|
|
297
|
+
spending: spending(),
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
if (settledIn(res)) {
|
|
301
|
+
// Paid, and the clinic could not complete the visit: payment is final. Calling again would pay again.
|
|
302
|
+
retry.clear();
|
|
303
|
+
return asError(`The payment settled but the clinic could not complete the visit (HTTP ${res.status}): ${data?.error || "no reason given"}. Payment is final. Tell your owner instead of calling again.`, { http_status: res.status, charged: true, ...spending() });
|
|
304
|
+
}
|
|
305
|
+
if (reserved) spend.release(reserved);
|
|
306
|
+
if (res.status === 409)
|
|
307
|
+
return asError(data?.error || "The clinic is still handling this request_id.", { http_status: 409, retry_after: data?.retry_after || 5, note: "Call clinic_house_call again in a few seconds: it sends the same request_id. You are not charged twice.", ...spending() });
|
|
308
|
+
if (!repeating) retry.clear();
|
|
309
|
+
const reason =
|
|
310
|
+
data?.error ||
|
|
311
|
+
(res.status === 402 && reserved ? "The payment was signed but did not settle (HTTP 402): nothing was taken and no visit was made. Try again later." : `The clinic answered HTTP ${res.status}.`);
|
|
312
|
+
return asError(reason, { http_status: res.status, charged: false, ...spending(), ...(notes.length && { notes }) });
|
|
313
|
+
} finally {
|
|
314
|
+
busy = false;
|
|
315
|
+
}
|
|
316
|
+
},
|
|
317
|
+
);
|
|
318
|
+
|
|
319
|
+
// The check-ins: optional and free. Fixed values only, from the clinic's own lists: no text from the log can be sent.
|
|
320
|
+
const finding = z.object({ severity: z.enum(lists.severities), code: z.enum(lists.codes) }).strict();
|
|
321
|
+
const checkInFields = {
|
|
322
|
+
visit_id: z.string().regex(UUID).describe("The visit id from clinic_house_call (visit.id)."),
|
|
323
|
+
checkin_token: z.string().regex(TOKEN).optional().describe("Only if this server did not deliver the visit since it started: the token in the instructions (check_ins.token)."),
|
|
324
|
+
};
|
|
325
|
+
async function checkIn(kind, visit_id, checkin_token, body) {
|
|
326
|
+
const token = checkin_token || tokens.get(visit_id);
|
|
327
|
+
if (!token) return asError("This server holds no check-in token for this visit (it was delivered before this server started). Pass checkin_token: it is in the visit's instructions, under check_ins.token. Nothing was sent.");
|
|
328
|
+
try {
|
|
329
|
+
return answer(await postJson(`/visit/${visit_id}/${kind}`, body, { authorization: `Bearer ${token}` }));
|
|
330
|
+
} catch (err) {
|
|
331
|
+
return asError(`Could not reach the clinic at ${CLINIC_URL}: ${why(err)}`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
server.registerTool(
|
|
336
|
+
"clinic_checkin_stage",
|
|
337
|
+
{
|
|
338
|
+
title: "Agent Clinic: stage check-in",
|
|
339
|
+
description: `Free and optional. Tells your owner's link that a stage of the visit started, finished or failed, with the finished stage's findings as severity and code only. Fixed values only: stage, status, and each finding's severity and code (lists from ${listsFrom}). No text is sent.`,
|
|
340
|
+
inputSchema: {
|
|
341
|
+
...checkInFields,
|
|
342
|
+
stage: z.enum(lists.stages).describe("The stage's id, as in the instructions."),
|
|
343
|
+
status: z.enum(lists.statuses),
|
|
344
|
+
findings: z.array(finding).max(200).optional().describe('With status "done" only: one {severity, code} per finding of this stage.'),
|
|
345
|
+
},
|
|
346
|
+
},
|
|
347
|
+
async ({ visit_id, checkin_token, stage, status, findings }) => checkIn("stage", visit_id, checkin_token, { stage, status, ...(findings && { findings }) }),
|
|
348
|
+
);
|
|
349
|
+
|
|
350
|
+
server.registerTool(
|
|
351
|
+
"clinic_checkin_done",
|
|
352
|
+
{
|
|
353
|
+
title: "Agent Clinic: visit done",
|
|
354
|
+
description:
|
|
355
|
+
"Free and optional. Tells your owner's link the visit is finished: the model that examined the run, the mode, and each finding's severity and code. Returns a stamp the clinic signed for the report. Fixed values only; this tool never sends the report itself.",
|
|
356
|
+
inputSchema: {
|
|
357
|
+
...checkInFields,
|
|
358
|
+
model: z.string().regex(MODEL_NAME).describe("The model that examined the run: letters, digits and . _ : / @ + - only, 64 characters at most."),
|
|
359
|
+
mode: z.enum(lists.modes).describe('"separate" if each stage ran as its own call, "single" if they ran in one.'),
|
|
360
|
+
findings: z.array(finding).max(200).optional().describe("One {severity, code} per finding in the report."),
|
|
361
|
+
},
|
|
362
|
+
},
|
|
363
|
+
async ({ visit_id, checkin_token, model, mode, findings }) => checkIn("done", visit_id, checkin_token, { model, mode, ...(findings && { findings }) }),
|
|
364
|
+
);
|
|
365
|
+
|
|
366
|
+
server.registerTool(
|
|
367
|
+
"clinic_outcome",
|
|
368
|
+
{
|
|
369
|
+
title: "Agent Clinic: report the outcome",
|
|
370
|
+
description: "Free. Tells the clinic whether the visit's fix resolved the problem. Sends only the visit id and yes or no, no text. The latest answer counts.",
|
|
371
|
+
inputSchema: {
|
|
372
|
+
visit_id: z.string().regex(UUID).describe("The visit id from clinic_house_call (visit.id, also given as session_id)."),
|
|
373
|
+
resolved: z.boolean().describe("true if the fix resolved the problem, false if not."),
|
|
374
|
+
},
|
|
375
|
+
},
|
|
376
|
+
async ({ visit_id, resolved }) => {
|
|
377
|
+
try {
|
|
378
|
+
return answer(await postJson("/outcome", { session_id: visit_id, resolved }));
|
|
379
|
+
} catch (err) {
|
|
380
|
+
return asError(`Could not reach the clinic at ${CLINIC_URL}: ${why(err)}`);
|
|
381
|
+
}
|
|
382
|
+
},
|
|
383
|
+
);
|
|
384
|
+
|
|
385
|
+
await server.connect(new StdioServerTransport());
|
|
386
|
+
log(
|
|
387
|
+
`Ready (${VERSION}). Clinic: ${CLINIC_URL}${PRICE ? `, ${PRICE} per visit` : ""}. Network: ${NETWORKS[NETWORK]}. Wallet: ${account ? account.address : "none (clinic_house_call disabled)"}. ` +
|
|
388
|
+
`Caps: ${money(MAX_PER_CALL)} per call, ${money(MAX_PER_DAY)} per day; spent today ${money(spend.spentToday())}. Check-in lists: ${listsFrom}.`,
|
|
389
|
+
);
|
package/spend.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Spending caps the agent's owner sets. A payment is reserved against today's total before it is signed, and
|
|
2
|
+
// released only when it did not settle (the clinic settles before it starts the examination, so a payment that
|
|
3
|
+
// settled is spent even if the clinic then fails; payment is final, no refunds).
|
|
4
|
+
// Today's total is kept in a small JSON file so that restarting the server does not reset the daily cap.
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
|
|
8
|
+
const today = () => new Date().toISOString().slice(0, 10); // UTC day
|
|
9
|
+
const round = (n) => Math.round(n * 1e6) / 1e6; // USDC has 6 decimals
|
|
10
|
+
|
|
11
|
+
export function createSpendLedger({ file, maxPerCall, maxPerDay }) {
|
|
12
|
+
function read() {
|
|
13
|
+
try {
|
|
14
|
+
const data = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
15
|
+
if (data.date === today() && Number.isFinite(data.spent_usd)) return data;
|
|
16
|
+
} catch {}
|
|
17
|
+
return { date: today(), spent_usd: 0 };
|
|
18
|
+
}
|
|
19
|
+
function write(data) {
|
|
20
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
21
|
+
fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
spentToday: () => read().spent_usd,
|
|
25
|
+
// Returns null when the payment fits both caps (and reserves it), or the reason it does not.
|
|
26
|
+
reserve(usd) {
|
|
27
|
+
if (!(usd >= 0)) return "the clinic asked for an amount this server cannot read";
|
|
28
|
+
if (usd > maxPerCall + 1e-9) return `it costs $${usd.toFixed(2)}, above the per-call cap of $${maxPerCall.toFixed(2)} (MAX_SPEND_USD_PER_CALL)`;
|
|
29
|
+
const data = read();
|
|
30
|
+
if (data.spent_usd + usd > maxPerDay + 1e-9)
|
|
31
|
+
return `it costs $${usd.toFixed(2)} and $${data.spent_usd.toFixed(2)} was already spent today, above the daily cap of $${maxPerDay.toFixed(2)} (MAX_SPEND_USD_PER_DAY)`;
|
|
32
|
+
write({ date: data.date, spent_usd: round(data.spent_usd + usd) });
|
|
33
|
+
return null;
|
|
34
|
+
},
|
|
35
|
+
release(usd) {
|
|
36
|
+
const data = read();
|
|
37
|
+
write({ date: data.date, spent_usd: round(Math.max(0, data.spent_usd - usd)) });
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|