@absol-labs/agent 0.9.1 → 0.11.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.
Files changed (293) hide show
  1. package/README.md +184 -26
  2. package/dist/capability/invocation-capability.d.ts +18 -6
  3. package/dist/capability/invocation-capability.d.ts.map +1 -1
  4. package/dist/capability/invocation-capability.js.map +1 -1
  5. package/dist/cli/amounts.d.ts +26 -0
  6. package/dist/cli/amounts.d.ts.map +1 -0
  7. package/dist/cli/amounts.js +71 -0
  8. package/dist/cli/amounts.js.map +1 -0
  9. package/dist/cli/args.d.ts +32 -0
  10. package/dist/cli/args.d.ts.map +1 -0
  11. package/dist/cli/args.js +119 -0
  12. package/dist/cli/args.js.map +1 -0
  13. package/dist/cli/attesters.d.ts +51 -0
  14. package/dist/cli/attesters.d.ts.map +1 -0
  15. package/dist/cli/attesters.js +58 -0
  16. package/dist/cli/attesters.js.map +1 -0
  17. package/dist/cli/bin.d.ts +3 -0
  18. package/dist/cli/bin.d.ts.map +1 -0
  19. package/dist/cli/bin.js +5 -0
  20. package/dist/cli/bin.js.map +1 -0
  21. package/dist/cli/commands/claim.d.ts +13 -0
  22. package/dist/cli/commands/claim.d.ts.map +1 -0
  23. package/dist/cli/commands/claim.js +102 -0
  24. package/dist/cli/commands/claim.js.map +1 -0
  25. package/dist/cli/commands/close.d.ts +3 -0
  26. package/dist/cli/commands/close.d.ts.map +1 -0
  27. package/dist/cli/commands/close.js +55 -0
  28. package/dist/cli/commands/close.js.map +1 -0
  29. package/dist/cli/commands/discover.d.ts +3 -0
  30. package/dist/cli/commands/discover.d.ts.map +1 -0
  31. package/dist/cli/commands/discover.js +183 -0
  32. package/dist/cli/commands/discover.js.map +1 -0
  33. package/dist/cli/commands/invoke.d.ts +3 -0
  34. package/dist/cli/commands/invoke.d.ts.map +1 -0
  35. package/dist/cli/commands/invoke.js +142 -0
  36. package/dist/cli/commands/invoke.js.map +1 -0
  37. package/dist/cli/commands/mcp.d.ts +3 -0
  38. package/dist/cli/commands/mcp.d.ts.map +1 -0
  39. package/dist/cli/commands/mcp.js +113 -0
  40. package/dist/cli/commands/mcp.js.map +1 -0
  41. package/dist/cli/commands/open.d.ts +3 -0
  42. package/dist/cli/commands/open.d.ts.map +1 -0
  43. package/dist/cli/commands/open.js +331 -0
  44. package/dist/cli/commands/open.js.map +1 -0
  45. package/dist/cli/commands/reclaim-unverified.d.ts +3 -0
  46. package/dist/cli/commands/reclaim-unverified.d.ts.map +1 -0
  47. package/dist/cli/commands/reclaim-unverified.js +172 -0
  48. package/dist/cli/commands/reclaim-unverified.js.map +1 -0
  49. package/dist/cli/commands/reclaim.d.ts +33 -0
  50. package/dist/cli/commands/reclaim.d.ts.map +1 -0
  51. package/dist/cli/commands/reclaim.js +308 -0
  52. package/dist/cli/commands/reclaim.js.map +1 -0
  53. package/dist/cli/commands/status.d.ts +3 -0
  54. package/dist/cli/commands/status.d.ts.map +1 -0
  55. package/dist/cli/commands/status.js +43 -0
  56. package/dist/cli/commands/status.js.map +1 -0
  57. package/dist/cli/commands/streams.d.ts +3 -0
  58. package/dist/cli/commands/streams.d.ts.map +1 -0
  59. package/dist/cli/commands/streams.js +257 -0
  60. package/dist/cli/commands/streams.js.map +1 -0
  61. package/dist/cli/commands/watch.d.ts +3 -0
  62. package/dist/cli/commands/watch.d.ts.map +1 -0
  63. package/dist/cli/commands/watch.js +55 -0
  64. package/dist/cli/commands/watch.js.map +1 -0
  65. package/dist/cli/config.d.ts +61 -0
  66. package/dist/cli/config.d.ts.map +1 -0
  67. package/dist/cli/config.js +140 -0
  68. package/dist/cli/config.js.map +1 -0
  69. package/dist/cli/context.d.ts +29 -0
  70. package/dist/cli/context.d.ts.map +1 -0
  71. package/dist/cli/context.js +2 -0
  72. package/dist/cli/context.js.map +1 -0
  73. package/dist/cli/deps.d.ts +191 -0
  74. package/dist/cli/deps.d.ts.map +1 -0
  75. package/dist/cli/deps.js +277 -0
  76. package/dist/cli/deps.js.map +1 -0
  77. package/dist/cli/descriptor.d.ts +61 -0
  78. package/dist/cli/descriptor.d.ts.map +1 -0
  79. package/dist/cli/descriptor.js +78 -0
  80. package/dist/cli/descriptor.js.map +1 -0
  81. package/dist/cli/errors.d.ts +48 -0
  82. package/dist/cli/errors.d.ts.map +1 -0
  83. package/dist/cli/errors.js +129 -0
  84. package/dist/cli/errors.js.map +1 -0
  85. package/dist/cli/escape-hatch.d.ts +50 -0
  86. package/dist/cli/escape-hatch.d.ts.map +1 -0
  87. package/dist/cli/escape-hatch.js +45 -0
  88. package/dist/cli/escape-hatch.js.map +1 -0
  89. package/dist/cli/index.d.ts +8 -0
  90. package/dist/cli/index.d.ts.map +1 -0
  91. package/dist/cli/index.js +7 -0
  92. package/dist/cli/index.js.map +1 -0
  93. package/dist/cli/listings.d.ts +15 -0
  94. package/dist/cli/listings.d.ts.map +1 -0
  95. package/dist/cli/listings.js +56 -0
  96. package/dist/cli/listings.js.map +1 -0
  97. package/dist/cli/mandate.d.ts +66 -0
  98. package/dist/cli/mandate.d.ts.map +1 -0
  99. package/dist/cli/mandate.js +61 -0
  100. package/dist/cli/mandate.js.map +1 -0
  101. package/dist/cli/output.d.ts +33 -0
  102. package/dist/cli/output.d.ts.map +1 -0
  103. package/dist/cli/output.js +34 -0
  104. package/dist/cli/output.js.map +1 -0
  105. package/dist/cli/preflight.d.ts +38 -0
  106. package/dist/cli/preflight.d.ts.map +1 -0
  107. package/dist/cli/preflight.js +72 -0
  108. package/dist/cli/preflight.js.map +1 -0
  109. package/dist/cli/privy.d.ts +83 -0
  110. package/dist/cli/privy.d.ts.map +1 -0
  111. package/dist/cli/privy.js +230 -0
  112. package/dist/cli/privy.js.map +1 -0
  113. package/dist/cli/progress.d.ts +36 -0
  114. package/dist/cli/progress.d.ts.map +1 -0
  115. package/dist/cli/progress.js +40 -0
  116. package/dist/cli/progress.js.map +1 -0
  117. package/dist/cli/run.d.ts +25 -0
  118. package/dist/cli/run.d.ts.map +1 -0
  119. package/dist/cli/run.js +173 -0
  120. package/dist/cli/run.js.map +1 -0
  121. package/dist/cli/scan-range.d.ts +55 -0
  122. package/dist/cli/scan-range.d.ts.map +1 -0
  123. package/dist/cli/scan-range.js +57 -0
  124. package/dist/cli/scan-range.js.map +1 -0
  125. package/dist/cli/spend-policy.d.ts +60 -0
  126. package/dist/cli/spend-policy.d.ts.map +1 -0
  127. package/dist/cli/spend-policy.js +65 -0
  128. package/dist/cli/spend-policy.js.map +1 -0
  129. package/dist/cli/status.d.ts +90 -0
  130. package/dist/cli/status.d.ts.map +1 -0
  131. package/dist/cli/status.js +252 -0
  132. package/dist/cli/status.js.map +1 -0
  133. package/dist/cli/timeout.d.ts +30 -0
  134. package/dist/cli/timeout.d.ts.map +1 -0
  135. package/dist/cli/timeout.js +55 -0
  136. package/dist/cli/timeout.js.map +1 -0
  137. package/dist/cli/version.d.ts +12 -0
  138. package/dist/cli/version.d.ts.map +1 -0
  139. package/dist/cli/version.js +22 -0
  140. package/dist/cli/version.js.map +1 -0
  141. package/dist/cli/wallet.d.ts +164 -0
  142. package/dist/cli/wallet.d.ts.map +1 -0
  143. package/dist/cli/wallet.js +234 -0
  144. package/dist/cli/wallet.js.map +1 -0
  145. package/dist/frameworks/crewai.d.ts +10 -0
  146. package/dist/frameworks/crewai.d.ts.map +1 -1
  147. package/dist/frameworks/crewai.js +12 -2
  148. package/dist/frameworks/crewai.js.map +1 -1
  149. package/dist/gateway/caller-auth-gateway.d.ts +38 -3
  150. package/dist/gateway/caller-auth-gateway.d.ts.map +1 -1
  151. package/dist/gateway/caller-auth-gateway.js +25 -1
  152. package/dist/gateway/caller-auth-gateway.js.map +1 -1
  153. package/dist/gateway/http-server.d.ts +53 -0
  154. package/dist/gateway/http-server.d.ts.map +1 -1
  155. package/dist/gateway/http-server.js +189 -4
  156. package/dist/gateway/http-server.js.map +1 -1
  157. package/dist/gateway/server-entry.d.ts +1 -0
  158. package/dist/gateway/server-entry.js +1 -0
  159. package/dist/gateway/server-entry.js.map +1 -1
  160. package/dist/gateway/x402-mode.d.ts +123 -0
  161. package/dist/gateway/x402-mode.d.ts.map +1 -0
  162. package/dist/gateway/x402-mode.js +212 -0
  163. package/dist/gateway/x402-mode.js.map +1 -0
  164. package/dist/index.d.ts +6 -4
  165. package/dist/index.d.ts.map +1 -1
  166. package/dist/index.js +8 -3
  167. package/dist/index.js.map +1 -1
  168. package/dist/mandates/env.d.ts +3 -2
  169. package/dist/mandates/env.d.ts.map +1 -1
  170. package/dist/mandates/env.js +3 -2
  171. package/dist/mandates/env.js.map +1 -1
  172. package/dist/mcp/http-server.d.ts +1 -0
  173. package/dist/mcp/http-server.js +1 -0
  174. package/dist/mcp/http-server.js.map +1 -1
  175. package/dist/mcp/server.d.ts +49 -0
  176. package/dist/mcp/server.d.ts.map +1 -1
  177. package/dist/mcp/server.js +533 -25
  178. package/dist/mcp/server.js.map +1 -1
  179. package/dist/mcp/service-invoker.d.ts +97 -0
  180. package/dist/mcp/service-invoker.d.ts.map +1 -0
  181. package/dist/mcp/service-invoker.js +167 -0
  182. package/dist/mcp/service-invoker.js.map +1 -0
  183. package/dist/mcp/stdio.d.ts +1 -0
  184. package/dist/mcp/stdio.js +1 -0
  185. package/dist/mcp/stdio.js.map +1 -1
  186. package/dist/sdk/client.d.ts +25 -1
  187. package/dist/sdk/client.d.ts.map +1 -1
  188. package/dist/sdk/client.js +20 -1
  189. package/dist/sdk/client.js.map +1 -1
  190. package/dist/sdk/invoke.d.ts +19 -4
  191. package/dist/sdk/invoke.d.ts.map +1 -1
  192. package/dist/sdk/invoke.js +69 -5
  193. package/dist/sdk/invoke.js.map +1 -1
  194. package/dist/x402/delivery-oracle.d.ts +108 -0
  195. package/dist/x402/delivery-oracle.d.ts.map +1 -0
  196. package/dist/x402/delivery-oracle.js +174 -0
  197. package/dist/x402/delivery-oracle.js.map +1 -0
  198. package/dist/x402/facilitator-server-entry.d.ts +3 -0
  199. package/dist/x402/facilitator-server-entry.d.ts.map +1 -0
  200. package/dist/x402/facilitator-server-entry.js +27 -0
  201. package/dist/x402/facilitator-server-entry.js.map +1 -0
  202. package/dist/x402/facilitator-server.d.ts +73 -0
  203. package/dist/x402/facilitator-server.d.ts.map +1 -0
  204. package/dist/x402/facilitator-server.js +305 -0
  205. package/dist/x402/facilitator-server.js.map +1 -0
  206. package/dist/x402/facilitator.d.ts +69 -17
  207. package/dist/x402/facilitator.d.ts.map +1 -1
  208. package/dist/x402/facilitator.js +76 -33
  209. package/dist/x402/facilitator.js.map +1 -1
  210. package/dist/x402/payment-requirements.d.ts +106 -0
  211. package/dist/x402/payment-requirements.d.ts.map +1 -0
  212. package/dist/x402/payment-requirements.js +138 -0
  213. package/dist/x402/payment-requirements.js.map +1 -0
  214. package/dist/x402/relayer.d.ts +41 -0
  215. package/dist/x402/relayer.d.ts.map +1 -0
  216. package/dist/x402/relayer.js +64 -0
  217. package/dist/x402/relayer.js.map +1 -0
  218. package/dist/x402/resource-index.d.ts +75 -0
  219. package/dist/x402/resource-index.d.ts.map +1 -0
  220. package/dist/x402/resource-index.js +126 -0
  221. package/dist/x402/resource-index.js.map +1 -0
  222. package/dist/x402/verified-delivery-facilitator.d.ts +285 -0
  223. package/dist/x402/verified-delivery-facilitator.d.ts.map +1 -0
  224. package/dist/x402/verified-delivery-facilitator.js +423 -0
  225. package/dist/x402/verified-delivery-facilitator.js.map +1 -0
  226. package/dist/zktls/t2-delivery-proof.d.ts +6 -6
  227. package/docs/agent-layer.md +14 -9
  228. package/docs/cli.md +705 -0
  229. package/docs/crewai.md +6 -2
  230. package/docs/eliza.md +6 -1
  231. package/docs/mcp-hosted.md +7 -5
  232. package/docs/mcp-reference.md +175 -0
  233. package/docs/quickstart.md +36 -9
  234. package/docs/threat-model.md +4 -3
  235. package/docs/x402.md +648 -0
  236. package/package.json +33 -10
  237. package/src/capability/invocation-capability.ts +17 -1
  238. package/src/cli/amounts.ts +102 -0
  239. package/src/cli/args.ts +150 -0
  240. package/src/cli/attesters.ts +86 -0
  241. package/src/cli/bin.ts +5 -0
  242. package/src/cli/commands/claim.ts +126 -0
  243. package/src/cli/commands/close.ts +69 -0
  244. package/src/cli/commands/discover.ts +228 -0
  245. package/src/cli/commands/invoke.ts +178 -0
  246. package/src/cli/commands/mcp.ts +135 -0
  247. package/src/cli/commands/open.ts +397 -0
  248. package/src/cli/commands/reclaim-unverified.ts +218 -0
  249. package/src/cli/commands/reclaim.ts +377 -0
  250. package/src/cli/commands/status.ts +56 -0
  251. package/src/cli/commands/streams.ts +344 -0
  252. package/src/cli/commands/watch.ts +70 -0
  253. package/src/cli/config.ts +208 -0
  254. package/src/cli/context.ts +30 -0
  255. package/src/cli/deps.ts +528 -0
  256. package/src/cli/descriptor.ts +133 -0
  257. package/src/cli/errors.ts +162 -0
  258. package/src/cli/escape-hatch.ts +92 -0
  259. package/src/cli/index.ts +27 -0
  260. package/src/cli/listings.ts +77 -0
  261. package/src/cli/mandate.ts +126 -0
  262. package/src/cli/output.ts +63 -0
  263. package/src/cli/preflight.ts +88 -0
  264. package/src/cli/privy.ts +396 -0
  265. package/src/cli/progress.ts +75 -0
  266. package/src/cli/run.ts +209 -0
  267. package/src/cli/scan-range.ts +76 -0
  268. package/src/cli/spend-policy.ts +139 -0
  269. package/src/cli/status.ts +381 -0
  270. package/src/cli/timeout.ts +64 -0
  271. package/src/cli/version.ts +21 -0
  272. package/src/cli/wallet.ts +372 -0
  273. package/src/frameworks/crewai.ts +13 -2
  274. package/src/gateway/caller-auth-gateway.ts +77 -6
  275. package/src/gateway/http-server.ts +280 -6
  276. package/src/gateway/server-entry.ts +1 -0
  277. package/src/gateway/x402-mode.ts +350 -0
  278. package/src/index.ts +40 -5
  279. package/src/mandates/env.ts +3 -2
  280. package/src/mcp/http-server.ts +1 -0
  281. package/src/mcp/server.ts +706 -30
  282. package/src/mcp/service-invoker.ts +285 -0
  283. package/src/mcp/stdio.ts +1 -0
  284. package/src/sdk/client.ts +33 -1
  285. package/src/sdk/invoke.ts +90 -12
  286. package/src/x402/delivery-oracle.ts +285 -0
  287. package/src/x402/facilitator-server-entry.ts +35 -0
  288. package/src/x402/facilitator-server.ts +445 -0
  289. package/src/x402/facilitator.ts +125 -46
  290. package/src/x402/payment-requirements.ts +231 -0
  291. package/src/x402/relayer.ts +122 -0
  292. package/src/x402/resource-index.ts +228 -0
  293. package/src/x402/verified-delivery-facilitator.ts +744 -0
@@ -1,5 +1,6 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
+ import { BASE_SEPOLIA_ESCROW_V2 } from "@absol-labs/sdk";
3
4
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
6
  import { http, isAddress, isHex } from "viem";
@@ -11,6 +12,9 @@ import { parseServerMandateCapsEnv, signServerMandate, ServerMandateConfigError,
11
12
  import { isCheckpointStream, } from "../sdk/client.js";
12
13
  import { createWalletBackedAgentClient, parseAgentWalletEnv, } from "../wallet/provider.js";
13
14
  import { createReclaimConsumerProofServiceFromEnv, } from "../zktls/reclaim.js";
15
+ import { CAPABILITY_HEADER_NAME, httpMethodSchema, } from "../capability/invocation-capability.js";
16
+ import { createSdkInvokeStreamReader, InvokeAccessUrlError, InvokeBuyerMismatchError, InvokePathError, InvokeServiceRefMismatchError, InvokeStreamExpiredError, InvokeStreamNotActiveError, } from "../sdk/invoke.js";
17
+ import { createServiceInvoker, RegistryUnavailableError, ServiceListingNotFoundError, } from "./service-invoker.js";
14
18
  /**
15
19
  * MCP server for the agent lane.
16
20
  *
@@ -42,6 +46,41 @@ const hireVerifiedServiceSchema = {
42
46
  .optional()
43
47
  .describe("Optional max stream lifetime in seconds. Defaults to the server mandate's max duration."),
44
48
  };
49
+ /**
50
+ * Ceiling on a capability's lifetime.
51
+ *
52
+ * A signed capability is a bearer credential for one method+path on one stream:
53
+ * anything holding it can make that call until it expires. The signer's own
54
+ * default is 60s; this bounds what an LLM may ask for so a single tool argument
55
+ * cannot mint a long-lived credential. It is a cap, not the default.
56
+ */
57
+ const MAX_CAPABILITY_TTL_SECONDS = 300;
58
+ const invokeServiceSchema = {
59
+ streamId: bytes32Schema.describe("Stream id of an ACTIVE stream whose buyer is this server's wallet (from hire_verified_service or list_streams)."),
60
+ path: z
61
+ .string()
62
+ .min(1)
63
+ .optional()
64
+ .describe('Origin-relative request path, query string included, e.g. "/price?symbol=BTC". Defaults to "/". The ORIGIN is not a parameter: it is read from the operator-signed listing for this stream\'s serviceRef.'),
65
+ method: httpMethodSchema
66
+ .optional()
67
+ .describe('HTTP method. Defaults to "GET". The capability authorizes exactly this method and this path — nothing else.'),
68
+ headers: z
69
+ .record(z.string())
70
+ .optional()
71
+ .describe("Extra request headers. The capability header is attached by the server and cannot be supplied here."),
72
+ body: z
73
+ .string()
74
+ .optional()
75
+ .describe("Request body, sent verbatim. Defaults to a JSON content-type when a body is present and none is given."),
76
+ ttlSeconds: z
77
+ .number()
78
+ .int()
79
+ .positive()
80
+ .max(MAX_CAPABILITY_TTL_SECONDS)
81
+ .optional()
82
+ .describe(`Capability lifetime in seconds (default 60, max ${MAX_CAPABILITY_TTL_SECONDS}). Shorter is safer; it only has to outlive one request.`),
83
+ };
45
84
  const getStreamStatusSchema = {
46
85
  streamId: bytes32Schema.describe("Stream id returned by hire_verified_service."),
47
86
  };
@@ -89,36 +128,73 @@ const metrikAgentEnvSchema = z.object({
89
128
  METRIK_AGENT_CHAIN_ID: z.string().optional(),
90
129
  METRIK_AGENT_CHAIN_NAME: z.string().optional(),
91
130
  METRIK_AGENT_MCP_STATE_FILE: z.string().optional(),
131
+ METRIK_AGENT_ESCROW_GENERATION: z.string().optional(),
132
+ METRIK_AGENT_REGISTRY_URL: z.string().url().optional(),
133
+ METRIK_AGENT_REGISTRY_APIKEY: z.string().optional(),
134
+ METRIK_AGENT_ALLOW_UNVERIFIED_OPERATOR: z.string().optional(),
92
135
  });
136
+ /**
137
+ * The retired V1 metered escrow.
138
+ *
139
+ * Refused by NAME rather than left to fail at read time, because it does not
140
+ * fail at read time: V1 and V2 `getStream` return different tuples that diverge
141
+ * from index 5 onward, so a V2 decoder pointed at V1 does not revert — it
142
+ * decodes other fields into correctly-named ones and reports a confident wrong
143
+ * answer about someone's money. This repository's own shipped docs pointed
144
+ * `METRIK_AGENT_ESCROW` here as recently as 0.10.0.
145
+ */
146
+ const RETIRED_V1_ESCROW = "0x21948a5e6ae8d9a3d1050791ab6138657fb54286";
147
+ /**
148
+ * Opt out of the operator/serviceRef cross-check on hire. Operator-set input
149
+ * only — an MCP caller can neither read nor set it.
150
+ */
151
+ export const ALLOW_UNVERIFIED_OPERATOR_ENV = "METRIK_AGENT_ALLOW_UNVERIFIED_OPERATOR";
152
+ /** An unset escrow slot decodes as an all-zero struct rather than reverting. */
153
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
154
+ /**
155
+ * The one sentence every stream-opening surface has to carry.
156
+ *
157
+ * A reviewer made ONE call against a stream and was billed for 302 seconds. The
158
+ * escrow behaved exactly as designed — and nothing in the tool surface had told
159
+ * them what they were buying. An LLM picks a tool from its description alone, so
160
+ * the meter is stated in the description of every tool that opens, reads, or
161
+ * ends a stream, not only in the docs it will never read.
162
+ */
163
+ export const METERING_MODEL = "METERING: this is TIME-metered rental of an endpoint that keeps proving it is live, NOT per-call billing. Cost = ratePerSecondUsdc x seconds the oracle VERIFIED, capped at the escrowed budget. One call and a thousand calls cost the same second, and the clock runs while you call nothing. Only closing the stream (reclaim_unspent) stops it; nothing refunds automatically.";
93
164
  export const METRIK_MCP_TOOLS = [
94
165
  {
95
166
  name: "discover_services",
96
- description: "Discover verified third-party services on the Metrik marketplace. Returns operator + serviceRef + endpoint for listings whose operator signature is cryptographically verified, so an agent can go from discovery to hire without pre-known addresses.",
167
+ description: "Discover verified third-party services on the Metrik marketplace. Returns operator + serviceRef + endpoint for listings whose operator signature is cryptographically verified, so an agent can go from discovery to hire without pre-known addresses. Listings are priced per second, not per call.",
97
168
  movesFunds: false,
98
169
  },
99
170
  {
100
171
  name: "hire_verified_service",
101
- description: "Open a verified payment stream for a third-party service. Pays only for oracle-verified delivered time. Subject to the agent's spend mandate.",
172
+ description: `Open a verified payment stream for a third-party service, then call it with invoke_service. Pays only for oracle-verified delivered time. Subject to the agent's spend mandate. ${METERING_MODEL}`,
102
173
  movesFunds: true,
103
174
  },
175
+ {
176
+ name: "invoke_service",
177
+ description: "Call the service a stream is already paying for. Signs a single-use EIP-712 capability as the stream's buyer and calls the origin the operator cryptographically signed (resolved from the verified listing — never a caller-supplied URL). This is how an agent USES what it hired. It moves no funds and adds no cost: billing is by verified elapsed time, so invoking more often is free and invoking never still costs.",
178
+ movesFunds: false,
179
+ },
104
180
  {
105
181
  name: "check_stream_status",
106
- description: "Read a stream's live status, accrued amount, and claimable/reclaimable balances. In V2, failed or unproven intervals do not advance cumulative entitlement; the stream remains active until buyer close or expiry.",
182
+ description: `Read a stream's live status, settled amount, and claimable/reclaimable balances. In V2, failed or unproven intervals do not advance cumulative entitlement; the stream remains active until buyer close or expiry. ${METERING_MODEL}`,
107
183
  movesFunds: false,
108
184
  },
109
185
  {
110
186
  name: "reclaim_unspent",
111
- description: "Close a stream and reclaim unspent funds to the buyer. V2 reclaim follows checkpoint finalization or escape-window rules.",
187
+ description: "Close a stream and reclaim unspent funds to the buyer. Closing is what STOPS the per-second meter — nothing else does, and no refund is ever pushed back on its own. V2 reclaim follows checkpoint finalization or escape-window rules.",
112
188
  movesFunds: true,
113
189
  },
114
190
  {
115
191
  name: "list_streams",
116
- description: "List the agent's streams and their current state.",
192
+ description: "List the streams this server opened and their current state. Every active stream is still accruing cost per verified second whether or not it is being invoked.",
117
193
  movesFunds: false,
118
194
  },
119
195
  {
120
196
  name: "prove_https_response",
121
- description: "Generate a zkTLS proof of the exact HTTPS response consumed for a tracked stream. This is an L2 delivery signal (consumer zkTLS) and must be cross-checked with oracle/L1 evidence.",
197
+ description: "Generate a buyer-side zkTLS proof of an HTTPS response from a stream's verified service origin. PUBLIC listings only: the proof is fetched by a third-party Reclaim attestor, which cannot present this stream's caller-auth capability, so a GATED listing answers the attestor with a 403 and the tool fails closed rather than proving a rejection. This is an L2 delivery signal (consumer zkTLS) and must be cross-checked with oracle/L1 evidence; it is not a substitute for it.",
122
198
  movesFunds: false,
123
199
  },
124
200
  ];
@@ -212,12 +288,26 @@ function warnOnce(key, message) {
212
288
  // stderr, never stdout: stdout is the MCP stdio transport channel.
213
289
  console.error(message);
214
290
  }
215
- const DISCOVER_TOOL_SPEC = METRIK_MCP_TOOLS[0];
216
- const HIRE_TOOL_SPEC = METRIK_MCP_TOOLS[1];
217
- const STATUS_TOOL_SPEC = METRIK_MCP_TOOLS[2];
218
- const RECLAIM_TOOL_SPEC = METRIK_MCP_TOOLS[3];
219
- const LIST_TOOL_SPEC = METRIK_MCP_TOOLS[4];
220
- const PROVE_TOOL_SPEC = METRIK_MCP_TOOLS[5];
291
+ /**
292
+ * Looks a tool spec up by NAME. This used to index into METRIK_MCP_TOOLS by
293
+ * position, which silently rebinds every description the moment a tool is
294
+ * inserted anywhere but the end — a tool whose advertised description belongs
295
+ * to a different tool is worse than a missing one, because an agent acts on it.
296
+ */
297
+ function toolSpec(name) {
298
+ const spec = METRIK_MCP_TOOLS.find((entry) => entry.name === name);
299
+ if (spec === undefined) {
300
+ throw new Error(`unknown MCP tool spec: ${name}`);
301
+ }
302
+ return spec;
303
+ }
304
+ const DISCOVER_TOOL_SPEC = toolSpec("discover_services");
305
+ const HIRE_TOOL_SPEC = toolSpec("hire_verified_service");
306
+ const INVOKE_TOOL_SPEC = toolSpec("invoke_service");
307
+ const STATUS_TOOL_SPEC = toolSpec("check_stream_status");
308
+ const RECLAIM_TOOL_SPEC = toolSpec("reclaim_unspent");
309
+ const LIST_TOOL_SPEC = toolSpec("list_streams");
310
+ const PROVE_TOOL_SPEC = toolSpec("prove_https_response");
221
311
  const discoverServicesSchema = {
222
312
  category: z
223
313
  .string()
@@ -273,6 +363,10 @@ export function createVerifiedStreamMcpServer(options) {
273
363
  };
274
364
  const now = options.now ?? (() => Math.floor(Date.now() / 1000));
275
365
  const discover = options.discoverServices ?? defaultDiscoverServices;
366
+ const allowUnverifiedOperator = options.allowUnverifiedOperatorPairing ?? false;
367
+ if (allowUnverifiedOperator) {
368
+ warnOnce("mcp-unverified-operator", `[metrik] ${ALLOW_UNVERIFIED_OPERATOR_ENV} is set: hires whose operator/serviceRef pairing CANNOT be verified will proceed. The operator address is the wallet that gets paid; an unverifiable pairing can escrow to a wallet that does not own the service. A contradicted pairing is still refused.`);
369
+ }
276
370
  const mcpServer = new McpServer(options.serverInfo ?? {
277
371
  name: "metrik-agent-mcp",
278
372
  version: "0.1.0",
@@ -292,9 +386,14 @@ export function createVerifiedStreamMcpServer(options) {
292
386
  ...(category === undefined ? {} : { category }),
293
387
  ...(limit === undefined ? {} : { limit }),
294
388
  });
295
- return successResult(`discovered ${listings.length} verified service${listings.length === 1 ? "" : "s"}`, { services: listings.map(serializeServiceListing) });
389
+ return successResult(`discovered ${listings.length} verified service${listings.length === 1 ? "" : "s"}, priced per verified second`, { services: listings.map(serializeServiceListing) });
296
390
  }
297
391
  catch (error) {
392
+ if (error instanceof RegistryUnavailableError) {
393
+ // Loud, not silent: discovery never degrades to stale local data, so
394
+ // "the registry is down" must not read as "there are no services".
395
+ return errorResult("the service registry is unreachable, so no listing could be verified. This is NOT the same as zero services — do not conclude the marketplace is empty. Retry shortly.");
396
+ }
298
397
  return safeToolError(error);
299
398
  }
300
399
  });
@@ -319,6 +418,33 @@ export function createVerifiedStreamMcpServer(options) {
319
418
  ratePerSecondUsdc: BigInt(args.ratePerSecondUsdc),
320
419
  maxDurationSeconds: args.durationSeconds ?? signedMandate.mandate.maxDurationSeconds,
321
420
  };
421
+ // Does this operator actually own this serviceRef?
422
+ //
423
+ // The two arrive as independent tool arguments, and `operator` is the
424
+ // wallet that gets paid. An LLM that pairs a real serviceRef with an
425
+ // attacker's payout address escrows the buyer's USDC to a stranger, and
426
+ // nothing downstream catches it: the escrow does not know who owns a
427
+ // serviceRef, and the oracle would happily verify the real endpoint
428
+ // while the money accrued elsewhere. Discovery DOES know — it recovers
429
+ // the operator's signature over the record the serviceRef is derived
430
+ // from — so the pairing is checked against it here.
431
+ //
432
+ // A serviceRef that is not listed at all is allowed with a warning
433
+ // (the registry is not the authority on what exists, and refusing would
434
+ // block private or freshly-listed services); a serviceRef that IS
435
+ // listed under a DIFFERENT operator is refused outright.
436
+ const pairing = await checkOperatorPairing(discover, args.serviceRef, request.operator);
437
+ if (pairing.verdict !== "verified") {
438
+ // FAIL CLOSED. Anything short of a positive match is a refusal: a
439
+ // registry outage is not evidence that the pairing is sound, and the
440
+ // money moves before any note attached to a success result could be
441
+ // read. The only override is an operator-set environment variable
442
+ // (never a tool argument), and even that never overrides a positive
443
+ // contradiction.
444
+ if (pairing.verdict === "mismatch" || !allowUnverifiedOperator) {
445
+ return errorResult(explainPairingRefusal(pairing, args.serviceRef, request.operator));
446
+ }
447
+ }
322
448
  // Serialize per owner: the spent-so-far read, cap check, open, and
323
449
  // registry write must be atomic, or concurrent hires could both pass
324
450
  // the cumulative-cap check on stale spend and overshoot maxTotalUsdc.
@@ -354,7 +480,15 @@ export function createVerifiedStreamMcpServer(options) {
354
480
  openedAtSeconds: nowSeconds,
355
481
  mandateId: signedMandate.mandateId,
356
482
  });
357
- return successResult(`opened verified stream ${result.streamId} on chain ${result.handle.chainId}`, {
483
+ // The meter starts HERE, not on the first invoke_service call. Say
484
+ // so in the result as well as the tool description: a reviewer who
485
+ // opened a stream, made one call and was billed for 302 seconds read
486
+ // the result, not the docs.
487
+ const maxSpendUsdc = request.budgetUsdc <
488
+ request.ratePerSecondUsdc * BigInt(request.maxDurationSeconds)
489
+ ? request.budgetUsdc
490
+ : request.ratePerSecondUsdc * BigInt(request.maxDurationSeconds);
491
+ return successResult(`opened verified stream ${result.streamId} on chain ${result.handle.chainId}.${pairing.verdict === "verified" ? "" : ` WARNING: the operator/serviceRef pairing was NOT verified (${pairing.verdict}) and this server is configured to escrow anyway via ${ALLOW_UNVERIFIED_OPERATOR_ENV}. The operator is the wallet that gets paid and nothing proved it owns this service.`} The meter is running from now at ${request.ratePerSecondUsdc} USDC base units per VERIFIED second, whether or not you call the service. Call it with invoke_service; stop the meter with reclaim_unspent.`, {
358
492
  streamId: result.streamId,
359
493
  txHash: result.txHash,
360
494
  approveTxHash: result.approveTxHash,
@@ -363,6 +497,15 @@ export function createVerifiedStreamMcpServer(options) {
363
497
  escrow: result.handle.escrow,
364
498
  chainId: result.handle.chainId,
365
499
  },
500
+ operatorPairing: pairing.verdict,
501
+ metering: {
502
+ model: "time-metered",
503
+ ratePerSecondUsdc: request.ratePerSecondUsdc.toString(),
504
+ budgetUsdc: request.budgetUsdc.toString(),
505
+ maxDurationSeconds: request.maxDurationSeconds,
506
+ maxSpendUsdc: maxSpendUsdc.toString(),
507
+ note: METERING_MODEL,
508
+ },
366
509
  });
367
510
  });
368
511
  }
@@ -370,6 +513,64 @@ export function createVerifiedStreamMcpServer(options) {
370
513
  return safeToolError(error);
371
514
  }
372
515
  });
516
+ if (options.serviceInvoker !== undefined) {
517
+ const serviceInvoker = options.serviceInvoker;
518
+ mcpServer.registerTool("invoke_service", {
519
+ description: INVOKE_TOOL_SPEC.description,
520
+ inputSchema: invokeServiceSchema,
521
+ annotations: {
522
+ // Not idempotent and not read-only: the call reaches a third party's
523
+ // endpoint, which may do anything. It is NOT destructive in Metrik's
524
+ // own terms — it signs no transaction and moves no USDC.
525
+ destructiveHint: false,
526
+ idempotentHint: false,
527
+ openWorldHint: true,
528
+ readOnlyHint: false,
529
+ title: "Invoke Paid Service",
530
+ },
531
+ }, async ({ streamId, path, method, headers, body, ttlSeconds }) => {
532
+ const requestPath = path ?? "/";
533
+ // Defence in depth. `resolveInvocationUrl` is the authority — it
534
+ // resolves the path and proves the result did not leave the signed
535
+ // origin — but a tool argument that cannot possibly be a safe path is
536
+ // refused here, with a message the caller can act on, before anything
537
+ // reads the chain. A prefix check ALONE was the bug: the URL parser
538
+ // treats a backslash as a host separator for http(s), so a path
539
+ // beginning `/\\` resolved against a signed origin points somewhere
540
+ // else entirely while passing a `//` test.
541
+ if (!requestPath.startsWith("/") || requestPath.startsWith("//")) {
542
+ return errorResult(`path must be origin-relative and start with a single slash (got ${JSON.stringify(requestPath)}). The host is not yours to choose: it comes from the operator-signed listing.`);
543
+ }
544
+ if (hasForbiddenPathCharacter(requestPath)) {
545
+ return errorResult(`path must not contain a backslash or a control character (got ${JSON.stringify(requestPath)}). A backslash is a host separator to the URL parser, so it would redirect this call off the operator-signed origin.`);
546
+ }
547
+ const requestHeaders = normalizeHeaders(headers);
548
+ if (CAPABILITY_HEADER_NAME in requestHeaders) {
549
+ return errorResult(`do not set the ${CAPABILITY_HEADER_NAME} header: this server signs the capability itself, as the stream's buyer. Supplying one would be silently overwritten.`);
550
+ }
551
+ if (body !== undefined &&
552
+ requestHeaders["content-type"] === undefined) {
553
+ requestHeaders["content-type"] = "application/json";
554
+ }
555
+ try {
556
+ const result = await serviceInvoker.invokeService({
557
+ streamId: streamId,
558
+ method: method ?? "GET",
559
+ path: requestPath,
560
+ headers: requestHeaders,
561
+ ...(body === undefined ? {} : { body }),
562
+ ...(ttlSeconds === undefined ? {} : { ttlSeconds }),
563
+ });
564
+ return serializeInvocation(result);
565
+ }
566
+ catch (error) {
567
+ const explained = explainInvokeFailure(error, streamId);
568
+ return explained === null
569
+ ? safeToolError(error)
570
+ : errorResult(explained);
571
+ }
572
+ });
573
+ }
373
574
  mcpServer.registerTool("check_stream_status", {
374
575
  description: STATUS_TOOL_SPEC.description,
375
576
  inputSchema: getStreamStatusSchema,
@@ -382,7 +583,15 @@ export function createVerifiedStreamMcpServer(options) {
382
583
  }, async ({ streamId }) => {
383
584
  try {
384
585
  const status = await options.agentClient.getStreamStatus(streamId);
385
- return successResult(`stream ${streamId} is ${status.stream.status}`, serializeStreamStatus(status, streamId));
586
+ if (status.stream.buyer === ZERO_ADDRESS) {
587
+ // An unset slot decodes as an all-zero struct rather than reverting,
588
+ // which otherwise surfaces as a confident "the stream is closed" for
589
+ // a stream that never existed. A real stream always has a buyer.
590
+ return errorResult(`no stream with id ${streamId} exists on the configured escrow. Check the id, and check that this server is pointed at the escrow the stream was opened on.`);
591
+ }
592
+ return successResult(status.stream.status === "active"
593
+ ? `stream ${streamId} is active and still metering at ${status.stream.ratePerSecond} USDC base units per verified second; reclaim_unspent closes it and stops the meter`
594
+ : `stream ${streamId} is ${status.stream.status}`, serializeStreamStatus(status, streamId));
386
595
  }
387
596
  catch (error) {
388
597
  return safeToolError(error);
@@ -400,10 +609,14 @@ export function createVerifiedStreamMcpServer(options) {
400
609
  },
401
610
  }, async ({ streamId, closeFirst }) => {
402
611
  try {
612
+ // The local registry is a CONVENIENCE, not an authority. It used to be
613
+ // required here, which meant a restarted server with in-memory state
614
+ // could no longer return the buyer's own money through this tool — a
615
+ // local bookkeeping gap standing between a buyer and their funds. The
616
+ // escrow itself enforces that only the buyer may close and reclaim, so
617
+ // proceeding without a record is safe and strictly buyer-favouring; an
618
+ // id that is not this wallet's stream simply reverts on chain.
403
619
  const record = await registry.get(streamId);
404
- if (record === null) {
405
- return errorResult(`unknown stream: ${streamId}`);
406
- }
407
620
  const signedMandate = await resolveMandate();
408
621
  // Reclaim/close only RETURN unspent funds to the buyer or stop payment.
409
622
  // They are authorized on mandate-owner signature ALONE (see the SDK
@@ -416,9 +629,10 @@ export function createVerifiedStreamMcpServer(options) {
416
629
  nowSeconds: now(),
417
630
  ...(closeFirst === undefined ? {} : { closeFirst }),
418
631
  });
419
- return successResult(`reclaimed stream ${streamId}`, {
632
+ return successResult(`reclaimed stream ${streamId}; the per-second meter on it has stopped${record === null ? " (this server had no local record of it — the escrow authorized the recovery on the buyer wallet alone)" : ""}`, {
420
633
  closeTxHash: result.closeResult?.txHash ?? null,
421
634
  reclaimTxHash: result.reclaimResult.txHash,
635
+ tracked: record !== null,
422
636
  });
423
637
  }
424
638
  catch (error) {
@@ -480,6 +694,34 @@ export function createVerifiedStreamMcpServer(options) {
480
694
  if (record === null) {
481
695
  return errorResult(`unknown stream: ${streamId}`);
482
696
  }
697
+ // Bind the PROOF TARGET to the stream's verified listing.
698
+ //
699
+ // Without this the tool would zkTLS-prove any URL an LLM named and
700
+ // stamp it with this stream's delivery binding (owner, streamId,
701
+ // operator, serviceRef) — a proof of someone else's endpoint,
702
+ // labelled as this stream's delivery. The origin has to come from the
703
+ // operator's signed record for the same reason invoke_service's does.
704
+ const listings = await discover().catch((error) => {
705
+ throw new ProveTargetError(error instanceof RegistryUnavailableError
706
+ ? "the service registry is unreachable, so this stream's signed service origin could not be verified. No proof was attempted."
707
+ : `the service registry could not be read: ${asErrorMessage(error)}`);
708
+ });
709
+ const listing = listings.find((entry) => entry.serviceRef.toLowerCase() ===
710
+ record.serviceRef.toLowerCase());
711
+ if (listing === undefined) {
712
+ return errorResult(`no verified listing matches this stream's serviceRef (${record.serviceRef}), so there is no signed origin to prove against. Run discover_services.`);
713
+ }
714
+ if (listing.access === "gated") {
715
+ // Not a degradation we can paper over. The Reclaim attestor fetches
716
+ // the URL itself, from its own network position, and cannot present
717
+ // this stream's single-use caller-auth capability — so the only
718
+ // thing it could prove about a gated origin is its own 403.
719
+ return errorResult(`this stream's service is GATED behind caller-auth (${safeOrigin(listing.accessUrl)}), and a consumer zkTLS proof cannot authenticate to it: the Reclaim attestor fetches the URL itself and cannot carry this stream's single-use capability, so it would only ever prove a 403. Use invoke_service to call it — that delivery is covered by the oracle's own L1/L4 verification. prove_https_response works for PUBLIC listings only.`);
720
+ }
721
+ const signedOrigin = safeOrigin(listing.accessUrl);
722
+ if (safeOrigin(url) !== signedOrigin) {
723
+ return errorResult(`refusing to prove ${safeOrigin(url)} for this stream: its operator signed ${signedOrigin}. A proof of an origin the stream did not pay for is not evidence of its delivery.`);
724
+ }
483
725
  const result = await deliveryProofService.proveConsumedHttpsResponse({
484
726
  url,
485
727
  ...(method === undefined ? {} : { method }),
@@ -501,6 +743,9 @@ export function createVerifiedStreamMcpServer(options) {
501
743
  return successResult(`generated zkTLS response proof for stream ${streamId}`, serializeConsumedResponseProof(record.streamId, result));
502
744
  }
503
745
  catch (error) {
746
+ if (error instanceof ProveTargetError) {
747
+ return errorResult(error.message);
748
+ }
504
749
  return safeToolError(error);
505
750
  }
506
751
  });
@@ -516,8 +761,27 @@ export function createVerifiedStreamMcpServer(options) {
516
761
  },
517
762
  };
518
763
  }
764
+ /** One readable line per invalid or missing environment variable. */
765
+ function describeEnvIssues(error) {
766
+ const seen = new Set();
767
+ for (const issue of error.issues) {
768
+ const name = issue.path.join(".");
769
+ seen.add(issue.code === "invalid_type" && issue.received === "undefined"
770
+ ? `${name} is not set`
771
+ : `${name} is invalid (${issue.message})`);
772
+ }
773
+ return [...seen].join("; ");
774
+ }
519
775
  export function parseMetrikAgentEnv(env = process.env) {
520
- const parsed = metrikAgentEnvSchema.parse(env);
776
+ const result = metrikAgentEnvSchema.safeParse(env);
777
+ if (!result.success) {
778
+ // `.parse()` threw a ZodError whose message is a JSON array of issue
779
+ // objects. `metrik-mcp` is started by an MCP host and fails closed on stdio,
780
+ // so that array was the ONLY thing an operator ever saw — a correct failure
781
+ // rendered as noise. Name the variables instead.
782
+ throw new Error(`metrik-mcp is not configured: ${describeEnvIssues(result.error)}. Set METRIK_AGENT_RPC_URL (an http(s) URL), METRIK_AGENT_ESCROW and METRIK_AGENT_USDC (EVM addresses), plus a wallet (METRIK_AGENT_PRIVATE_KEY, or the CDP/Privy variables). METRIK_AGENT_CHAIN_ID defaults to Base Sepolia (${baseSepolia.id}).`);
783
+ }
784
+ const parsed = result.data;
521
785
  const chainId = Number(parsed.METRIK_AGENT_CHAIN_ID ?? baseSepolia.id);
522
786
  if (!Number.isInteger(chainId) || chainId <= 0) {
523
787
  throw new Error("METRIK_AGENT_CHAIN_ID must be a positive integer");
@@ -525,9 +789,28 @@ export function parseMetrikAgentEnv(env = process.env) {
525
789
  if (chainId !== baseSepolia.id) {
526
790
  throw new Error(`unsupported METRIK_AGENT_CHAIN_ID ${chainId}; phase 2 is Base Sepolia only`);
527
791
  }
792
+ // Generation is CONFIGURED. `v2` is the only generation the checkpoint escrow
793
+ // semantics this server implements apply to, so anything else is refused up
794
+ // front instead of silently mis-decoded (see RETIRED_V1_ESCROW).
795
+ const generation = (parsed.METRIK_AGENT_ESCROW_GENERATION ?? "v2").toLowerCase();
796
+ if (generation !== "v2") {
797
+ throw new Error(`unsupported METRIK_AGENT_ESCROW_GENERATION "${parsed.METRIK_AGENT_ESCROW_GENERATION}": this server reads checkpoint-settled StreamEscrowV2 only. Leave it unset (or set it to "v2") and point METRIK_AGENT_ESCROW at the V2 escrow.`);
798
+ }
799
+ if (parsed.METRIK_AGENT_ESCROW.toLowerCase() === RETIRED_V1_ESCROW) {
800
+ throw new Error(`METRIK_AGENT_ESCROW is the RETIRED V1 metered escrow (${parsed.METRIK_AGENT_ESCROW}). It is no longer settled by the oracle, and its stream tuple is incompatible with the checkpoint decoder this server uses — reads would not revert, they would return confident nonsense. Point it at the live StreamEscrowV2 (${BASE_SEPOLIA_ESCROW_V2}).`);
801
+ }
528
802
  return {
529
803
  rpcUrl: parsed.METRIK_AGENT_RPC_URL,
530
804
  escrow: parsed.METRIK_AGENT_ESCROW,
805
+ escrowGeneration: "v2",
806
+ // Opt-IN only: any value but the exact string "true" leaves the check on.
807
+ allowUnverifiedOperatorPairing: parsed.METRIK_AGENT_ALLOW_UNVERIFIED_OPERATOR === "true",
808
+ ...(parsed.METRIK_AGENT_REGISTRY_URL === undefined
809
+ ? {}
810
+ : { registryUrl: parsed.METRIK_AGENT_REGISTRY_URL }),
811
+ ...(parsed.METRIK_AGENT_REGISTRY_APIKEY === undefined
812
+ ? {}
813
+ : { registryApiKey: parsed.METRIK_AGENT_REGISTRY_APIKEY }),
531
814
  usdc: parsed.METRIK_AGENT_USDC,
532
815
  chain: {
533
816
  ...baseSepolia,
@@ -566,11 +849,13 @@ export async function createVerifiedStreamMcpServerOptionsFromEnv(env = process.
566
849
  chain: parsed.chain,
567
850
  transport: http(parsed.rpcUrl),
568
851
  escrow: parsed.escrow,
569
- // Declare the escrow as V2 as well. Without this the SDK treats the
570
- // client as V1 and routes claimable()/reclaimable() to the legacy ABI,
571
- // which reverts against StreamEscrowV2 the checkpoint escrow replaced
572
- // those one-argument views with proof-carrying ones.
573
- escrowV2: parsed.escrow,
852
+ // Select the checkpoint decoder, on the strength of the DECLARED
853
+ // generation (`parsed.escrowGeneration`, validated in parseMetrikAgentEnv
854
+ // which also refuses the retired V1 address outright). Without this the
855
+ // SDK treats the client as V1 and routes claimable()/reclaimable() to the
856
+ // legacy ABI, which reverts against StreamEscrowV2: the checkpoint escrow
857
+ // replaced those one-argument views with proof-carrying ones.
858
+ ...(parsed.escrowGeneration === "v2" ? { escrowV2: parsed.escrow } : {}),
574
859
  usdc: parsed.usdc,
575
860
  settlementTarget: {
576
861
  chainId: parsed.chain.id,
@@ -594,6 +879,29 @@ export async function createVerifiedStreamMcpServerOptionsFromEnv(env = process.
594
879
  }
595
880
  return cachedMandate;
596
881
  };
882
+ // The "use" half. `invoke()` needs a signer that can produce an EIP-712
883
+ // signature; every wallet this package resolves can, but only a raw key is a
884
+ // viem LocalAccount by type — hence the structural check rather than a cast.
885
+ const serviceInvoker = createServiceInvoker({
886
+ streamReader: createSdkInvokeStreamReader({
887
+ escrowAddress: parsed.escrow,
888
+ rpcUrl: parsed.rpcUrl,
889
+ }),
890
+ buyer: requireCapabilitySigner(wallet.account),
891
+ domain: { chainId, verifyingContract: parsed.escrow },
892
+ discoverServices: defaultDiscoverServices,
893
+ discoverOptions: {
894
+ ...(parsed.registryUrl === undefined
895
+ ? {}
896
+ : { registryUrl: parsed.registryUrl }),
897
+ ...(parsed.registryApiKey === undefined
898
+ ? {}
899
+ : { apiKey: parsed.registryApiKey }),
900
+ // stderr, never stdout: stdout is the MCP stdio transport channel, and
901
+ // discovery warns about every listing it DROPS for a bad signature.
902
+ logger: { warn: (...parts) => console.error(...parts) },
903
+ },
904
+ });
597
905
  return {
598
906
  agentClient,
599
907
  signedMandate,
@@ -601,9 +909,23 @@ export async function createVerifiedStreamMcpServerOptionsFromEnv(env = process.
601
909
  registry: parsed.stateFile === undefined
602
910
  ? new InMemoryStreamRegistry()
603
911
  : new FileStreamRegistry(parsed.stateFile),
912
+ allowUnverifiedOperatorPairing: parsed.allowUnverifiedOperatorPairing,
913
+ serviceInvoker,
604
914
  ...(deliveryProofService === null ? {} : { deliveryProofService }),
605
915
  };
606
916
  }
917
+ /**
918
+ * Narrows a resolved wallet account to something that can sign a capability.
919
+ *
920
+ * Fails closed at STARTUP with a named cause rather than at the first
921
+ * `invoke_service` call with a `TypeError`.
922
+ */
923
+ function requireCapabilitySigner(account) {
924
+ if (typeof account.signTypedData !== "function") {
925
+ throw new Error(`the configured wallet (${account.address}) cannot sign EIP-712 typed data, so it cannot authorize a service invocation. Use a wallet whose account exposes signTypedData (a raw key, a CDP server account, or a Privy embedded wallet).`);
926
+ }
927
+ return account;
928
+ }
607
929
  export async function createVerifiedStreamMcpServerFromEnv(env = process.env) {
608
930
  return createVerifiedStreamMcpServer(await createVerifiedStreamMcpServerOptionsFromEnv(env));
609
931
  }
@@ -659,6 +981,11 @@ function serializeStreamStatus(status, streamId) {
659
981
  },
660
982
  claimable: status.claimable.toString(),
661
983
  reclaimable: status.reclaimable.toString(),
984
+ metering: {
985
+ model: "time-metered",
986
+ ratePerSecondUsdc: status.stream.ratePerSecond.toString(),
987
+ note: METERING_MODEL,
988
+ },
662
989
  };
663
990
  }
664
991
  function serializeConsumedResponseProof(streamId, proof) {
@@ -673,6 +1000,187 @@ function serializeConsumedResponseProof(streamId, proof) {
673
1000
  verification: proof.verification,
674
1001
  };
675
1002
  }
1003
+ /**
1004
+ * True when a path carries a character that must never appear in one.
1005
+ *
1006
+ * Mirrors `assertOriginRelativePath` in `../sdk/invoke.ts`. The backslash is the
1007
+ * one that matters: the URL parser reads it as a host separator for http(s), so
1008
+ * it turns an apparently origin-relative path into a different host. C0
1009
+ * controls and DEL go with it — a header- or log-splitting character has no
1010
+ * business in a path either.
1011
+ */
1012
+ function hasForbiddenPathCharacter(value) {
1013
+ for (const character of value) {
1014
+ const code = character.codePointAt(0) ?? 0;
1015
+ if (character === "\\" || code < 0x20 || code === 0x7f) {
1016
+ return true;
1017
+ }
1018
+ }
1019
+ return false;
1020
+ }
1021
+ /**
1022
+ * Checks that `operator` — the wallet that gets paid — is the one the
1023
+ * registry's operator-signed record for `serviceRef` names.
1024
+ *
1025
+ * This reports; it does not decide. Every outcome other than `verified` is
1026
+ * treated as a refusal by the hire path (see ALLOW_UNVERIFIED_OPERATOR_ENV).
1027
+ * An earlier version failed OPEN on anything but a positive contradiction,
1028
+ * which meant that during any registry read failure the exact bug this check
1029
+ * exists to stop was fully live: an attacker's `operator` paired with a genuine
1030
+ * `serviceRef`, the oracle verifying the real endpoint, and accrual settling to
1031
+ * the attacker. Settlement does not depend on this HTTP endpoint being
1032
+ * reachable from the MCP host, so a read failure is no evidence of safety.
1033
+ *
1034
+ * A hostile registry cannot forge a match — the operator's signature over the
1035
+ * record the serviceRef is derived from is recovered client-side — but it CAN
1036
+ * suppress a row, which is exactly why `unlisted` must not be a soft verdict.
1037
+ *
1038
+ * An outage is reported distinctly from a malformed/failed read: "retry in a
1039
+ * moment" and "something is wrong with this registry" are different next steps.
1040
+ */
1041
+ async function checkOperatorPairing(discover, serviceRef, operator) {
1042
+ let listings;
1043
+ try {
1044
+ listings = await discover();
1045
+ }
1046
+ catch (error) {
1047
+ return error instanceof RegistryUnavailableError
1048
+ ? { verdict: "registry-unavailable", detail: asErrorMessage(error) }
1049
+ : { verdict: "registry-error", detail: asErrorMessage(error) };
1050
+ }
1051
+ const listing = listings.find((entry) => entry.serviceRef.toLowerCase() === serviceRef.toLowerCase());
1052
+ if (listing === undefined) {
1053
+ return { verdict: "unlisted" };
1054
+ }
1055
+ if (listing.operator.toLowerCase() !== operator.toLowerCase()) {
1056
+ return { verdict: "mismatch", listedOperator: listing.operator };
1057
+ }
1058
+ return { verdict: "verified" };
1059
+ }
1060
+ /**
1061
+ * Why a hire was refused, in words the caller can act on.
1062
+ *
1063
+ * Refusing strands nothing: no USDC has moved, and the same call succeeds once
1064
+ * the registry answers again.
1065
+ */
1066
+ function explainPairingRefusal(pairing, serviceRef, operator) {
1067
+ switch (pairing.verdict) {
1068
+ case "mismatch":
1069
+ return `refusing to hire: serviceRef ${serviceRef} is listed under operator ${pairing.listedOperator}, not ${operator}. The operator address is the wallet that gets paid — escrowing to a different one would pay a stranger for someone else's service. Take the operator/serviceRef pair from discover_services.`;
1070
+ case "unlisted":
1071
+ return `refusing to hire: serviceRef ${serviceRef} is not in the verified registry, so there is no operator-signed record proving that ${operator} is the wallet this service pays. Run discover_services and hire a listed service. (A row that fails signature verification is dropped, so a revoked or malformed listing looks the same as an absent one.)`;
1072
+ case "registry-unavailable":
1073
+ return `refusing to hire: the service registry is unreachable (${pairing.detail}), so this hire's operator/serviceRef pairing cannot be verified and the escrow could be paid to the wrong wallet. Nothing was spent — retry when the registry answers.`;
1074
+ case "registry-error":
1075
+ return `refusing to hire: the service registry could not be read (${pairing.detail}), so this hire's operator/serviceRef pairing cannot be verified and the escrow could be paid to the wrong wallet. Nothing was spent.`;
1076
+ }
1077
+ }
1078
+ /** A prove-target precondition that failed with a caller-actionable reason. */
1079
+ class ProveTargetError extends Error {
1080
+ constructor(message) {
1081
+ super(message);
1082
+ this.name = "ProveTargetError";
1083
+ }
1084
+ }
1085
+ /** Origin of a URL, or the raw value when it will not parse. */
1086
+ function safeOrigin(value) {
1087
+ try {
1088
+ return new URL(value).origin;
1089
+ }
1090
+ catch {
1091
+ return value;
1092
+ }
1093
+ }
1094
+ function normalizeHeaders(headers) {
1095
+ const normalized = {};
1096
+ for (const [name, value] of Object.entries(headers ?? {})) {
1097
+ normalized[name.toLowerCase()] = value;
1098
+ }
1099
+ return normalized;
1100
+ }
1101
+ /**
1102
+ * Renders an invocation as an MCP result.
1103
+ *
1104
+ * A non-2xx answer is returned as `isError` WITH the full structured content:
1105
+ * the call really happened and its body may be the thing the agent needs, but a
1106
+ * buyer who paid and got a 403 should not have to infer that from a status
1107
+ * field. Gateway denials carry their machine-readable reason, because
1108
+ * `stream-expired` and `nonce-replayed` call for opposite responses.
1109
+ */
1110
+ function serializeInvocation(result) {
1111
+ const summary = `${result.method} ${result.path} -> ${result.status}`;
1112
+ if (result.ok) {
1113
+ return {
1114
+ content: [{ type: "text", text: summary }],
1115
+ structuredContent: { ...result },
1116
+ };
1117
+ }
1118
+ const because = result.gatewayDenialReason === null
1119
+ ? `the service itself answered ${result.status}; the capability was accepted`
1120
+ : `the seller's caller-auth gateway REFUSED the call: ${result.gatewayDenialReason}${gatewayDenialHint(result.gatewayDenialReason)}`;
1121
+ return {
1122
+ content: [{ type: "text", text: `${summary} — ${because}` }],
1123
+ structuredContent: { ...result },
1124
+ isError: true,
1125
+ };
1126
+ }
1127
+ /** One actionable next step per gateway denial reason. */
1128
+ function gatewayDenialHint(reason) {
1129
+ switch (reason) {
1130
+ case "stream-not-funded":
1131
+ return " — the stream's remaining budget is exhausted; open a new one with hire_verified_service.";
1132
+ case "stream-expired":
1133
+ return " — the stream is past its expiry; reclaim_unspent returns the unspent budget.";
1134
+ case "stream-not-active":
1135
+ return " — the stream is closed; open a new one with hire_verified_service.";
1136
+ case "capability-expired":
1137
+ return " — the signed capability outlived its TTL before the gateway saw it; retry (optionally with a larger ttlSeconds).";
1138
+ case "nonce-replayed":
1139
+ return " — each capability is single-use; retry to mint a fresh one.";
1140
+ case "stream-state-stale":
1141
+ return " — the gateway's view of the chain is too stale to authorize; retry shortly.";
1142
+ case "buyer-mismatch":
1143
+ return " — the stream does not belong to this server's wallet.";
1144
+ default:
1145
+ return "";
1146
+ }
1147
+ }
1148
+ /**
1149
+ * Turns an invocation failure into something an LLM can act on, or `null` when
1150
+ * it is not a failure this layer understands (those fall through to the generic
1151
+ * handler, which logs the detail server-side and says nothing more).
1152
+ *
1153
+ * The generic "the tool call failed" is correct for an unexpected RPC/viem
1154
+ * error — it can carry internal detail — but it is useless for the three things
1155
+ * that actually go wrong here: wrong wallet, dead stream, unlisted service.
1156
+ */
1157
+ function explainInvokeFailure(error, streamId) {
1158
+ if (error instanceof InvokeBuyerMismatchError) {
1159
+ return `stream ${streamId} does not belong to this server's wallet, so this server cannot sign a capability for it. Only the stream's buyer can invoke it — use a stream from hire_verified_service or list_streams.`;
1160
+ }
1161
+ if (error instanceof InvokeStreamNotActiveError) {
1162
+ return `stream ${streamId} is closed, so it authorizes nothing. Open a new one with hire_verified_service.`;
1163
+ }
1164
+ if (error instanceof InvokeStreamExpiredError) {
1165
+ return `stream ${streamId} has expired, so it authorizes nothing. reclaim_unspent returns the unspent budget; hire_verified_service opens a replacement.`;
1166
+ }
1167
+ if (error instanceof ServiceListingNotFoundError) {
1168
+ return `no verified listing matches this stream's serviceRef (${error.serviceRef}). Run discover_services: a listing whose operator signature fails verification is dropped, so an unlisted or revoked service cannot be invoked.`;
1169
+ }
1170
+ if (error instanceof InvokeServiceRefMismatchError) {
1171
+ return `the registry's listing does not match this stream's serviceRef. The call was refused rather than sent to an origin this stream did not pay for.`;
1172
+ }
1173
+ if (error instanceof InvokeAccessUrlError) {
1174
+ return `this stream's listing carries no usable signed invocation origin (${error.message}). This server refuses to call an origin the operator did not sign.`;
1175
+ }
1176
+ if (error instanceof InvokePathError) {
1177
+ return `invalid request path: ${error.message}`;
1178
+ }
1179
+ if (error instanceof RegistryUnavailableError) {
1180
+ return `the service registry is unreachable, so the operator-signed origin for this stream could not be verified. The call was not attempted — an unverified origin is never guessed. Retry when the registry is back.`;
1181
+ }
1182
+ return null;
1183
+ }
676
1184
  function successResult(text, structuredContent) {
677
1185
  return {
678
1186
  content: [{ type: "text", text }],