@paystage/mcp 0.3.5 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -107,7 +107,7 @@ this tool.
107
107
 
108
108
  | Package | Version | Purpose |
109
109
  | --- | --- | --- |
110
- | `@paystage/mcp` | Umbrella server (5 tools) |
110
+ | `@paystage/mcp` | Umbrella server (9 tools) |
111
111
  | `@paystage/preflight` | x402 payment preflight |
112
112
  | `@paystage/auth-watch` | Outstanding-auth tools |
113
113
  | `@paystage/trade-preflight` | HIP-3 / trade.xyz trade preflight |
@@ -170,3 +170,29 @@ Full table: [SECURITY.md](../../SECURITY.md).
170
170
  ## License
171
171
 
172
172
  MIT
173
+
174
+ ## Tools
175
+
176
+ Every one is read-only. None of them signs, holds a key, or moves money — the agent stays the only
177
+ signer, which is the entire product.
178
+
179
+ | tool | what it answers |
180
+ |---|---|
181
+ | `evaluate_mcp_payment` | should this x402 payment be signed? → `pay` · `review` · `do_not_pay` |
182
+ | `evaluate_batch` | the same question for several payments at once, one verdict each |
183
+ | `list_outstanding_auths` | which ERC-20 / Permit2 / EIP-3009 authorisations are still outstanding |
184
+ | `evaluate_outstanding_auths` | which of those need attention before the next payment |
185
+ | `evaluate_hip3_trade` | should this HIP-3 / trade.xyz order be placed? → `allow` · `review` · `do_not_trade` |
186
+ | `evaluate_velocity` | is this spend a burst, a spike, or a runaway cadence |
187
+ | `verify_receipt` | is this receipt really ours, checked against the published key |
188
+ | `decode_payment_required` | what does this base64 402 header actually say |
189
+ | `validate_policy` | is this policy document valid, and if not why |
190
+
191
+ ## Check a policy file before you run anything
192
+
193
+ ```bash
194
+ npx -y -p @paystage/mcp paystage-policy check policy.json
195
+ ```
196
+
197
+ Exit `0` valid, `1` invalid (one line per offending field), `2` unreadable. Offline, no key, no signup —
198
+ the same schema the evaluator enforces, so a file that passes here is a file that will load there.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=policy-cli.d.ts.map
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `paystage-policy check <file>` — does this policy parse?
4
+ *
5
+ * The most common support question is not "what verdict" but "why does my policy file not load". The
6
+ * answer today requires installing a package, writing a script and reading a stack trace. This answers
7
+ * it in one command, offline, with the exact message the evaluator would have produced.
8
+ *
9
+ * paystage-policy check policy.json # exit 0 valid · 1 invalid · 2 unreadable
10
+ * paystage-policy check --json policy.json
11
+ */
12
+ import { readFileSync } from "node:fs";
13
+ import { parsePolicy } from "@paystage/policy";
14
+ const args = process.argv.slice(2);
15
+ const asJson = args.includes("--json");
16
+ const positional = args.filter((a) => !a.startsWith("-"));
17
+ const verb = positional[0] === "check" ? "check" : null;
18
+ const file = verb ? positional[1] : positional[0];
19
+ if (!file) {
20
+ console.error("usage: paystage-policy check <policy.json> [--json]");
21
+ process.exit(2);
22
+ }
23
+ let raw;
24
+ try {
25
+ raw = readFileSync(file, "utf8");
26
+ }
27
+ catch (err) {
28
+ const message = err instanceof Error ? err.message : String(err);
29
+ if (asJson)
30
+ console.log(JSON.stringify({ ok: false, stage: "read", error: message }, null, 2));
31
+ else
32
+ console.error(`cannot read ${file}: ${message}`);
33
+ process.exit(2);
34
+ }
35
+ let parsed;
36
+ try {
37
+ parsed = JSON.parse(raw);
38
+ }
39
+ catch (err) {
40
+ const message = err instanceof Error ? err.message : String(err);
41
+ if (asJson)
42
+ console.log(JSON.stringify({ ok: false, stage: "json", error: message }, null, 2));
43
+ else
44
+ console.error(`${file} is not valid JSON: ${message}`);
45
+ process.exit(1);
46
+ }
47
+ try {
48
+ const policy = parsePolicy(parsed);
49
+ if (asJson) {
50
+ console.log(JSON.stringify({ ok: true, file, policy }, null, 2));
51
+ }
52
+ else {
53
+ const caps = [
54
+ policy.max_amount ? `max_amount ${policy.max_amount.value}` : "no max_amount",
55
+ Array.isArray(policy.allowed_networks) && policy.allowed_networks.length
56
+ ? `networks ${policy.allowed_networks.join(", ")}`
57
+ : "no allowed_networks",
58
+ policy.unknown_payee ? `unknown_payee ${policy.unknown_payee}` : "unknown_payee unset",
59
+ ];
60
+ console.log(`${file}: valid`);
61
+ console.log(` ${caps.join(" · ")}`);
62
+ }
63
+ process.exit(0);
64
+ }
65
+ catch (err) {
66
+ // The Zod message is the point: it names the field and the problem, which is what a stack trace
67
+ // buries. Print it verbatim rather than wrapping it.
68
+ const message = err instanceof Error ? err.message : String(err);
69
+ if (asJson) {
70
+ console.log(JSON.stringify({ ok: false, stage: "policy", error: message }, null, 2));
71
+ process.exit(1);
72
+ }
73
+ console.error(`${file}: invalid`);
74
+ try {
75
+ const issues = JSON.parse(message);
76
+ if (Array.isArray(issues)) {
77
+ // One line per field, because that is the question: which field, and what is wrong with it.
78
+ for (const issue of issues) {
79
+ const where = Array.isArray(issue.path) && issue.path.length ? issue.path.join(".") : "(root)";
80
+ console.error(` ${where}: ${issue.message ?? "invalid"}`);
81
+ }
82
+ process.exit(1);
83
+ }
84
+ }
85
+ catch {
86
+ // Not the structured form; fall through to the raw message.
87
+ }
88
+ console.error(message.split("\n").map((l) => ` ${l}`).join("\n"));
89
+ process.exit(1);
90
+ }
91
+ //# sourceMappingURL=policy-cli.js.map
package/dist/server.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/server";
2
- export declare const TOOL_NAMES: readonly ["evaluate_mcp_payment", "list_outstanding_auths", "evaluate_outstanding_auths", "evaluate_hip3_trade", "evaluate_velocity"];
3
- export type ToolName = (typeof TOOL_NAMES)[number];
2
+ import { TOOL_NAMES, type ToolName } from "./tools.js";
3
+ export { TOOL_NAMES };
4
+ export type { ToolName };
4
5
  export declare function createServer(): McpServer;
5
6
  export declare function getToolNames(): string[];
6
7
  export declare function startServer(): Promise<void>;
package/dist/server.js CHANGED
@@ -1,212 +1,24 @@
1
1
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
2
2
  import { createRequire } from "node:module";
3
+ import { McpServer } from "@modelcontextprotocol/server";
4
+ import { loadPolicy, parsePolicy } from "@paystage/policy";
5
+ import { registerAllTools, SERVER_CAPABILITIES, TOOL_NAMES } from "./tools.js";
3
6
  /**
4
- * Report the real package version. This was hardcoded as "0.3.0" and stayed there two
5
- * releases, so every client logging serverInfo was told the wrong version.
7
+ * Report the real package version. This was hardcoded as "0.3.0" and stayed there two releases,
8
+ * so every client logging serverInfo was told the wrong version.
6
9
  */
7
10
  const SERVER_VERSION = createRequire(import.meta.url)("../package.json").version;
8
- import { McpServer } from "@modelcontextprotocol/server";
9
- import { z } from "zod";
10
- import { loadPolicy, parsePolicy } from "@paystage/policy";
11
- import { evaluatePayment, normalizePaymentRequired } from "@paystage/preflight";
12
- import { listOutstandingAuths, evaluateOutstandingAuths, createRpcClient, resolveRpcUrl, } from "@paystage/auth-watch";
13
- import { evaluateTrade, parseTradePolicy, fetchMetaAndAssetCtxs, } from "@paystage/trade-preflight";
14
- import { evaluateVelocity, serializeVelocityResult, EvaluateVelocityInputSchema, } from "@paystage/velocity";
15
- export const TOOL_NAMES = [
16
- "evaluate_mcp_payment",
17
- "list_outstanding_auths",
18
- "evaluate_outstanding_auths",
19
- "evaluate_hip3_trade",
20
- "evaluate_velocity",
21
- ];
22
- const DEFAULT_NETWORK = "base";
11
+ export { TOOL_NAMES };
12
+ /** The stdio transport resolves a policy from a path; the Worker never can. */
23
13
  async function resolvePolicy(input) {
24
- if (input.policy !== undefined) {
14
+ if (input.policy !== undefined)
25
15
  return parsePolicy(input.policy);
26
- }
27
16
  const path = input.policy_path ?? process.env.PAYSTAGE_POLICY_PATH ?? "./policy.json";
28
17
  return await loadPolicy(path);
29
18
  }
30
- function tokensForNetwork(policy, network) {
31
- const tokens = policy.tokens;
32
- return tokens?.[network] ?? [];
33
- }
34
- function spendersForPolicy(policy) {
35
- const spenders = policy.spenders;
36
- return spenders ?? [];
37
- }
38
- const authWatchShape = {
39
- wallet: z.string(),
40
- network: z.string().optional(),
41
- tokens: z.array(z.string()).optional(),
42
- spenders: z.array(z.string()).optional(),
43
- policy_path: z.string().optional(),
44
- policy: z.unknown().optional(),
45
- eip3009_nonces: z.array(z.string()).optional(),
46
- rpc_url: z.string().optional(),
47
- };
48
- const tradeProposalShape = z.object({
49
- dex: z.string(),
50
- asset: z.string(),
51
- side: z.enum(["buy", "sell"]),
52
- size: z.string(),
53
- leverage: z.number().optional(),
54
- order_type: z.enum(["limit", "market"]).optional(),
55
- limit_px: z.string().optional(),
56
- });
57
- function registerAllTools(server) {
58
- server.registerTool("evaluate_mcp_payment", {
59
- description: "Evaluate an x402 PaymentRequired payload against a PayStage spending policy before paying",
60
- inputSchema: z.object({
61
- payment_required: z.unknown(),
62
- policy_path: z.string().optional(),
63
- policy: z.unknown().optional(),
64
- }),
65
- }, async (input) => {
66
- try {
67
- const policy = await resolvePolicy(input);
68
- const pr = normalizePaymentRequired(input.payment_required);
69
- const result = evaluatePayment(pr, policy);
70
- return {
71
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
72
- };
73
- }
74
- catch (error) {
75
- const message = error instanceof Error ? error.message : String(error);
76
- return {
77
- isError: true,
78
- content: [{ type: "text", text: `Error: ${message}` }],
79
- };
80
- }
81
- });
82
- server.registerTool("list_outstanding_auths", {
83
- description: "List outstanding token authorizations for a wallet",
84
- inputSchema: z.object(authWatchShape),
85
- }, async (args) => {
86
- const policy = await resolvePolicy(args);
87
- const network = args.network ?? DEFAULT_NETWORK;
88
- const tokens = args.tokens ?? tokensForNetwork(policy, network);
89
- const spenders = args.spenders ?? spendersForPolicy(policy);
90
- const rpcUrl = args.rpc_url ?? resolveRpcUrl(network);
91
- const rpc = createRpcClient(rpcUrl);
92
- const items = await listOutstandingAuths({
93
- wallet: args.wallet,
94
- network,
95
- tokens,
96
- spenders,
97
- rpc,
98
- eip3009Nonces: args.eip3009_nonces,
99
- });
100
- const serialized = items.map((i) => ({
101
- ...i,
102
- amount: i.amount.toString(),
103
- }));
104
- return {
105
- content: [
106
- {
107
- type: "text",
108
- text: JSON.stringify({ items: serialized }, null, 2),
109
- },
110
- ],
111
- };
112
- });
113
- server.registerTool("evaluate_outstanding_auths", {
114
- description: "List and evaluate outstanding token authorizations against a policy",
115
- inputSchema: z.object(authWatchShape),
116
- }, async (args) => {
117
- const policy = await resolvePolicy(args);
118
- const network = args.network ?? DEFAULT_NETWORK;
119
- const tokens = args.tokens ?? tokensForNetwork(policy, network);
120
- const spenders = args.spenders ?? spendersForPolicy(policy);
121
- const rpcUrl = args.rpc_url ?? resolveRpcUrl(network);
122
- const rpc = createRpcClient(rpcUrl);
123
- const items = await listOutstandingAuths({
124
- wallet: args.wallet,
125
- network,
126
- tokens,
127
- spenders,
128
- rpc,
129
- eip3009Nonces: args.eip3009_nonces,
130
- });
131
- const results = evaluateOutstandingAuths(items, policy);
132
- const serialized = results.map((r) => ({
133
- item: { ...r.item, amount: r.item.amount.toString() },
134
- flags: r.flags,
135
- summary: r.summary,
136
- }));
137
- return {
138
- content: [
139
- {
140
- type: "text",
141
- text: JSON.stringify({ results: serialized }, null, 2),
142
- },
143
- ],
144
- };
145
- });
146
- server.registerTool("evaluate_hip3_trade", {
147
- description: "Evaluate a Hyperliquid HIP-3 (trade.xyz) order against a TradePolicy before an agent trades. Returns decision allow | review | do_not_trade.",
148
- inputSchema: z.object({
149
- proposal: tradeProposalShape,
150
- policy: z.unknown().optional(),
151
- policy_path: z.string().optional(),
152
- snapshot: z.unknown().optional(),
153
- }),
154
- }, async (args) => {
155
- try {
156
- const policy = parseTradePolicy(args.policy);
157
- const snapshot = args.snapshot !== undefined
158
- ? args.snapshot
159
- : await fetchMetaAndAssetCtxs(args.proposal.dex || "xyz");
160
- const result = evaluateTrade(args.proposal, snapshot, policy);
161
- return {
162
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
163
- };
164
- }
165
- catch (error) {
166
- const message = error instanceof Error ? error.message : String(error);
167
- return {
168
- isError: true,
169
- content: [{ type: "text", text: `Error: ${message}` }],
170
- };
171
- }
172
- });
173
- server.registerTool("evaluate_velocity", {
174
- description: "Rolling-window rate and spend-pattern check for a proposed payment against recent action history and a policy.velocity config",
175
- inputSchema: z.object({
176
- history: EvaluateVelocityInputSchema.shape.history,
177
- proposed: EvaluateVelocityInputSchema.shape.proposed,
178
- policy: z.unknown().optional(),
179
- policy_path: z.string().optional(),
180
- now_ms: z.number().int().nonnegative().optional(),
181
- }),
182
- }, async (input) => {
183
- try {
184
- const parsed = EvaluateVelocityInputSchema.parse(input);
185
- const result = await evaluateVelocity(parsed);
186
- return {
187
- content: [
188
- {
189
- type: "text",
190
- text: JSON.stringify(serializeVelocityResult(result), null, 2),
191
- },
192
- ],
193
- };
194
- }
195
- catch (error) {
196
- const message = error instanceof Error ? error.message : String(error);
197
- return {
198
- isError: true,
199
- content: [{ type: "text", text: `Error: ${message}` }],
200
- };
201
- }
202
- });
203
- }
204
19
  export function createServer() {
205
- const server = new McpServer({
206
- name: "paystage",
207
- version: SERVER_VERSION,
208
- });
209
- registerAllTools(server);
20
+ const server = new McpServer({ name: "paystage", version: SERVER_VERSION }, { capabilities: SERVER_CAPABILITIES });
21
+ registerAllTools(server, { resolvePolicy, version: SERVER_VERSION });
210
22
  return server;
211
23
  }
212
24
  export function getToolNames() {
@@ -0,0 +1,37 @@
1
+ import { McpServer, type ServerCapabilities } from "@modelcontextprotocol/server";
2
+ import type { Policy } from "@paystage/policy";
3
+ export declare const TOOL_NAMES: readonly ["evaluate_mcp_payment", "list_outstanding_auths", "evaluate_outstanding_auths", "evaluate_hip3_trade", "evaluate_velocity", "verify_receipt", "decode_payment_required", "validate_policy", "evaluate_batch"];
4
+ export type ToolName = (typeof TOOL_NAMES)[number];
5
+ /**
6
+ * The server exposes tools only, but it must answer `resources/list` and `prompts/list` with an
7
+ * empty result rather than `-32601 Method not found`: Anthropic's and Cursor's MCP checks treat a
8
+ * declared-but-unimplemented capability as a bug, and a client that probes either list gets a hard
9
+ * error instead of "none". Declaring the capabilities is what makes the SDK serve the empty lists
10
+ * (see `ServerOptions.capabilities`); no resource or prompt is registered.
11
+ *
12
+ * Shared by the stdio server and the hosted Worker so both surfaces answer the same way.
13
+ */
14
+ export declare const SERVER_CAPABILITIES: ServerCapabilities;
15
+ export interface ToolDeps {
16
+ /**
17
+ * Resolve a policy from a tool call. The stdio server reads a file; the hosted Worker has no
18
+ * filesystem, so it refuses `policy_path` and requires an inline policy.
19
+ */
20
+ resolvePolicy: (input: {
21
+ policy?: unknown;
22
+ policy_path?: string;
23
+ }) => Promise<Policy>;
24
+ /** Reported in `serverInfo`; the Worker and the package version them separately. */
25
+ version: string;
26
+ /**
27
+ * The published key, when the host already holds it.
28
+ *
29
+ * A Worker that serves `verify_receipt` cannot fetch its own `/v1/public/receipt-key.json`: the
30
+ * subrequest to its own origin came back 522/523, so a genuine signed receipt reported
31
+ * `unverifiable` on the live endpoint while the same check passed locally. Passing the key in
32
+ * removes the network from the one path that is supposed to be an independent check.
33
+ */
34
+ resolveReceiptKey?: () => Promise<Record<string, unknown> | null>;
35
+ }
36
+ export declare function registerAllTools(server: McpServer, deps: ToolDeps): void;
37
+ //# sourceMappingURL=tools.d.ts.map
package/dist/tools.js ADDED
@@ -0,0 +1,352 @@
1
+ import { z } from "zod";
2
+ import { parsePolicy } from "@paystage/policy";
3
+ import { evaluatePayment, normalizePaymentRequired } from "@paystage/preflight";
4
+ import { verifyReceipt } from "./verify.js";
5
+ import { listOutstandingAuths, evaluateOutstandingAuths, createRpcClient, resolveRpcUrl, } from "@paystage/auth-watch";
6
+ import { evaluateTrade, parseTradePolicy, fetchMetaAndAssetCtxs, } from "@paystage/trade-preflight";
7
+ import { evaluateVelocity, serializeVelocityResult, EvaluateVelocityInputSchema, } from "@paystage/velocity";
8
+ export const TOOL_NAMES = [
9
+ "evaluate_mcp_payment",
10
+ "list_outstanding_auths",
11
+ "evaluate_outstanding_auths",
12
+ "evaluate_hip3_trade",
13
+ "evaluate_velocity",
14
+ "verify_receipt",
15
+ "decode_payment_required",
16
+ "validate_policy",
17
+ "evaluate_batch",
18
+ ];
19
+ const DEFAULT_NETWORK = "base";
20
+ /**
21
+ * The server exposes tools only, but it must answer `resources/list` and `prompts/list` with an
22
+ * empty result rather than `-32601 Method not found`: Anthropic's and Cursor's MCP checks treat a
23
+ * declared-but-unimplemented capability as a bug, and a client that probes either list gets a hard
24
+ * error instead of "none". Declaring the capabilities is what makes the SDK serve the empty lists
25
+ * (see `ServerOptions.capabilities`); no resource or prompt is registered.
26
+ *
27
+ * Shared by the stdio server and the hosted Worker so both surfaces answer the same way.
28
+ */
29
+ export const SERVER_CAPABILITIES = { resources: {}, prompts: {} };
30
+ function tokensForNetwork(policy, network) {
31
+ const tokens = policy.tokens;
32
+ return tokens?.[network] ?? [];
33
+ }
34
+ function spendersForPolicy(policy) {
35
+ const spenders = policy.spenders;
36
+ return spenders ?? [];
37
+ }
38
+ const authWatchShape = {
39
+ wallet: z.string(),
40
+ network: z.string().optional(),
41
+ tokens: z.array(z.string()).optional(),
42
+ spenders: z.array(z.string()).optional(),
43
+ policy_path: z.string().optional(),
44
+ policy: z.unknown().optional(),
45
+ eip3009_nonces: z.array(z.string()).optional(),
46
+ rpc_url: z.string().optional(),
47
+ };
48
+ const tradeProposalShape = z.object({
49
+ dex: z.string(),
50
+ asset: z.string(),
51
+ side: z.enum(["buy", "sell"]),
52
+ size: z.string(),
53
+ leverage: z.number().optional(),
54
+ order_type: z.enum(["limit", "market"]).optional(),
55
+ limit_px: z.string().optional(),
56
+ });
57
+ export function registerAllTools(server, deps) {
58
+ server.registerTool("evaluate_mcp_payment", {
59
+ description: "Evaluate an x402 PaymentRequired payload against a PayStage spending policy before paying",
60
+ annotations: {
61
+ title: "Evaluate an x402 payment (read-only, never signs)",
62
+ readOnlyHint: true,
63
+ destructiveHint: false,
64
+ openWorldHint: false,
65
+ },
66
+ inputSchema: z.object({
67
+ payment_required: z.unknown(),
68
+ policy_path: z.string().optional(),
69
+ policy: z.unknown().optional(),
70
+ agent_id: z
71
+ .string()
72
+ .optional()
73
+ .describe("Which agent is asking. Required to reach per-agent budgets in policy.agents."),
74
+ }),
75
+ }, async (input) => {
76
+ try {
77
+ const policy = await deps.resolvePolicy(input);
78
+ const pr = normalizePaymentRequired(input.payment_required);
79
+ const result = evaluatePayment(pr, policy, input.agent_id !== undefined ? { agentId: input.agent_id } : {});
80
+ return {
81
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
82
+ };
83
+ }
84
+ catch (error) {
85
+ const message = error instanceof Error ? error.message : String(error);
86
+ return {
87
+ isError: true,
88
+ content: [{ type: "text", text: `Error: ${message}` }],
89
+ };
90
+ }
91
+ });
92
+ server.registerTool("list_outstanding_auths", {
93
+ description: "List outstanding token authorizations for a wallet",
94
+ annotations: {
95
+ title: "List outstanding token authorizations (read-only, never signs)",
96
+ readOnlyHint: true,
97
+ destructiveHint: false,
98
+ openWorldHint: true,
99
+ },
100
+ inputSchema: z.object(authWatchShape),
101
+ }, async (args) => {
102
+ const policy = await deps.resolvePolicy(args);
103
+ const network = args.network ?? DEFAULT_NETWORK;
104
+ const tokens = args.tokens ?? tokensForNetwork(policy, network);
105
+ const spenders = args.spenders ?? spendersForPolicy(policy);
106
+ const rpcUrl = args.rpc_url ?? resolveRpcUrl(network);
107
+ const rpc = createRpcClient(rpcUrl);
108
+ const items = await listOutstandingAuths({
109
+ wallet: args.wallet,
110
+ network,
111
+ tokens,
112
+ spenders,
113
+ rpc,
114
+ eip3009Nonces: args.eip3009_nonces,
115
+ });
116
+ const serialized = items.map((i) => ({
117
+ ...i,
118
+ amount: i.amount.toString(),
119
+ }));
120
+ return {
121
+ content: [
122
+ {
123
+ type: "text",
124
+ text: JSON.stringify({ items: serialized }, null, 2),
125
+ },
126
+ ],
127
+ };
128
+ });
129
+ server.registerTool("evaluate_outstanding_auths", {
130
+ description: "List and evaluate outstanding token authorizations against a policy",
131
+ annotations: {
132
+ title: "Evaluate outstanding token authorizations (read-only, never signs)",
133
+ readOnlyHint: true,
134
+ destructiveHint: false,
135
+ openWorldHint: true,
136
+ },
137
+ inputSchema: z.object(authWatchShape),
138
+ }, async (args) => {
139
+ const policy = await deps.resolvePolicy(args);
140
+ const network = args.network ?? DEFAULT_NETWORK;
141
+ const tokens = args.tokens ?? tokensForNetwork(policy, network);
142
+ const spenders = args.spenders ?? spendersForPolicy(policy);
143
+ const rpcUrl = args.rpc_url ?? resolveRpcUrl(network);
144
+ const rpc = createRpcClient(rpcUrl);
145
+ const items = await listOutstandingAuths({
146
+ wallet: args.wallet,
147
+ network,
148
+ tokens,
149
+ spenders,
150
+ rpc,
151
+ eip3009Nonces: args.eip3009_nonces,
152
+ });
153
+ const results = evaluateOutstandingAuths(items, policy);
154
+ const serialized = results.map((r) => ({
155
+ item: { ...r.item, amount: r.item.amount.toString() },
156
+ flags: r.flags,
157
+ summary: r.summary,
158
+ }));
159
+ return {
160
+ content: [
161
+ {
162
+ type: "text",
163
+ text: JSON.stringify({ results: serialized }, null, 2),
164
+ },
165
+ ],
166
+ };
167
+ });
168
+ server.registerTool("evaluate_hip3_trade", {
169
+ description: "Evaluate a Hyperliquid HIP-3 (trade.xyz) order against a TradePolicy before an agent trades. Returns decision allow | review | do_not_trade.",
170
+ annotations: {
171
+ title: "Evaluate a HIP-3 trade (read-only, never signs)",
172
+ readOnlyHint: true,
173
+ destructiveHint: false,
174
+ openWorldHint: true,
175
+ },
176
+ inputSchema: z.object({
177
+ proposal: tradeProposalShape,
178
+ policy: z.unknown().optional(),
179
+ policy_path: z.string().optional(),
180
+ snapshot: z.unknown().optional(),
181
+ }),
182
+ }, async (args) => {
183
+ try {
184
+ const policy = parseTradePolicy(args.policy);
185
+ const snapshot = args.snapshot !== undefined
186
+ ? args.snapshot
187
+ : await fetchMetaAndAssetCtxs(args.proposal.dex || "xyz");
188
+ const result = evaluateTrade(args.proposal, snapshot, policy);
189
+ return {
190
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
191
+ };
192
+ }
193
+ catch (error) {
194
+ const message = error instanceof Error ? error.message : String(error);
195
+ return {
196
+ isError: true,
197
+ content: [{ type: "text", text: `Error: ${message}` }],
198
+ };
199
+ }
200
+ });
201
+ server.registerTool("evaluate_velocity", {
202
+ description: "Rolling-window rate and spend-pattern check for a proposed payment against recent action history and a policy.velocity config",
203
+ annotations: {
204
+ title: "Evaluate payment velocity (read-only, never signs)",
205
+ readOnlyHint: true,
206
+ destructiveHint: false,
207
+ openWorldHint: false,
208
+ },
209
+ inputSchema: z.object({
210
+ history: EvaluateVelocityInputSchema.shape.history,
211
+ proposed: EvaluateVelocityInputSchema.shape.proposed,
212
+ policy: z.unknown().optional(),
213
+ policy_path: z.string().optional(),
214
+ now_ms: z.number().int().nonnegative().optional(),
215
+ }),
216
+ }, async (input) => {
217
+ try {
218
+ const parsed = EvaluateVelocityInputSchema.parse(input);
219
+ const result = await evaluateVelocity(parsed);
220
+ return {
221
+ content: [
222
+ {
223
+ type: "text",
224
+ text: JSON.stringify(serializeVelocityResult(result), null, 2),
225
+ },
226
+ ],
227
+ };
228
+ }
229
+ catch (error) {
230
+ const message = error instanceof Error ? error.message : String(error);
231
+ return {
232
+ isError: true,
233
+ content: [{ type: "text", text: `Error: ${message}` }],
234
+ };
235
+ }
236
+ });
237
+ // ---------------------------------------------------------------------------------------------
238
+ // Four more tools, added 2026-11-14. Each one reuses code that already shipped as a library or a
239
+ // CLI call: nothing here is new logic, it is the same evaluation reachable from an agent.
240
+ // ---------------------------------------------------------------------------------------------
241
+ server.registerTool("verify_receipt", {
242
+ description: "Verify a PayStage receipt against the published signing key. Returns the verdict it attests to, or why it cannot be trusted.",
243
+ annotations: {
244
+ title: "Verify a receipt against the published key (read-only, never signs)",
245
+ readOnlyHint: true,
246
+ destructiveHint: false,
247
+ openWorldHint: true,
248
+ },
249
+ inputSchema: z.object({
250
+ receipt: z.unknown().describe("The receipt object as issued"),
251
+ key_url: z.string().url().optional().describe("Override the published key location"),
252
+ }),
253
+ }, async ({ receipt, key_url }) => {
254
+ try {
255
+ // Prefer a key the host already holds; an explicit key_url still wins, so a caller can check
256
+ // a receipt from a different deployment against that deployment's published key.
257
+ const injected = key_url === undefined && deps.resolveReceiptKey
258
+ ? await deps.resolveReceiptKey()
259
+ : null;
260
+ const verdict = await verifyReceipt(receipt, key_url ? { keyUrl: key_url } : injected ? { jwk: injected } : {});
261
+ return { content: [{ type: "text", text: JSON.stringify(verdict, null, 2) }] };
262
+ }
263
+ catch (error) {
264
+ return {
265
+ isError: true,
266
+ content: [{ type: "text", text: `Error: ${error instanceof Error ? error.message : String(error)}` }],
267
+ };
268
+ }
269
+ });
270
+ server.registerTool("decode_payment_required", {
271
+ description: "Decode a base64 `payment-required` header from a 402 response into the JSON challenge, so an agent can inspect it before deciding anything.",
272
+ annotations: {
273
+ title: "Decode a payment-required header (read-only, never signs)",
274
+ readOnlyHint: true,
275
+ destructiveHint: false,
276
+ openWorldHint: false,
277
+ },
278
+ inputSchema: z.object({
279
+ header: z.string().min(1).describe("The raw base64 value of the payment-required header"),
280
+ }),
281
+ }, async ({ header }) => {
282
+ // Inline rather than importing @paystage/x402-guard: this is four lines and a dependency for
283
+ // four lines is a supply-chain cost paid by every user of the umbrella.
284
+ let decoded;
285
+ try {
286
+ decoded = typeof atob === "function" ? atob(header) : Buffer.from(header, "base64").toString("utf8");
287
+ }
288
+ catch {
289
+ return { isError: true, content: [{ type: "text", text: "Error: header is not valid base64" }] };
290
+ }
291
+ let parsed;
292
+ try {
293
+ parsed = JSON.parse(decoded);
294
+ }
295
+ catch {
296
+ return { isError: true, content: [{ type: "text", text: "Error: decoded header is not JSON" }] };
297
+ }
298
+ return { content: [{ type: "text", text: JSON.stringify(parsed, null, 2) }] };
299
+ });
300
+ server.registerTool("validate_policy", {
301
+ description: "Check a policy document without evaluating a payment. Returns the exact validation error when it is wrong, which is the question behind most support requests.",
302
+ annotations: {
303
+ title: "Validate a spending policy (read-only, never signs)",
304
+ readOnlyHint: true,
305
+ destructiveHint: false,
306
+ openWorldHint: false,
307
+ },
308
+ inputSchema: z.object({ policy: z.unknown() }),
309
+ }, async ({ policy }) => {
310
+ try {
311
+ const parsed = parsePolicy(policy);
312
+ return {
313
+ content: [{ type: "text", text: JSON.stringify({ valid: true, version: parsed.version ?? null }, null, 2) }],
314
+ };
315
+ }
316
+ catch (error) {
317
+ const message = error instanceof Error ? error.message : String(error);
318
+ return {
319
+ content: [{ type: "text", text: JSON.stringify({ valid: false, error: message }, null, 2) }],
320
+ };
321
+ }
322
+ });
323
+ server.registerTool("evaluate_batch", {
324
+ description: "Evaluate several payment challenges against one policy in a single call. Returns one verdict per input, in order, so an agent settling a batch decides once per payment and can stop at the first refusal.",
325
+ annotations: {
326
+ title: "Evaluate a batch of x402 payments (read-only, never signs)",
327
+ readOnlyHint: true,
328
+ destructiveHint: false,
329
+ openWorldHint: false,
330
+ },
331
+ inputSchema: z.object({
332
+ payments: z.array(z.unknown()).min(1).max(50),
333
+ policy: z.unknown(),
334
+ }),
335
+ }, async ({ payments, policy }) => {
336
+ const parsedPolicy = parsePolicy(policy);
337
+ const results = payments.map((payment) => {
338
+ try {
339
+ const normalised = normalizePaymentRequired(payment);
340
+ return evaluatePayment(normalised, parsedPolicy);
341
+ }
342
+ catch (error) {
343
+ return {
344
+ decision: "do_not_pay",
345
+ reasons: [`could not evaluate: ${error instanceof Error ? error.message : String(error)}`],
346
+ };
347
+ }
348
+ });
349
+ return { content: [{ type: "text", text: JSON.stringify({ results }, null, 2) }] };
350
+ });
351
+ }
352
+ //# sourceMappingURL=tools.js.map
package/dist/verify.js CHANGED
@@ -14,7 +14,9 @@
14
14
  * is DER. Getting this wrong produces the same failure mode, so it is pinned to
15
15
  * `ieee-p1363` explicitly.
16
16
  */
17
- import { createPublicKey, verify as nodeVerify, webcrypto } from "node:crypto";
17
+ // globalThis.crypto exists in Workers and in Node 18+. Importing `webcrypto` from node:crypto
18
+ // works in Node and breaks the Worker bundle, which is the difference that matters here.
19
+ const webcrypto = globalThis.crypto;
18
20
  /** The receipt format version this verifier understands. Kept local on purpose: a verifier
19
21
  * must not silently follow the issuer's constant upward — it validates what it knows. */
20
22
  const RECEIPT_VERSION = 1;
@@ -154,11 +156,15 @@ export async function verifyReceipt(receipt, options = {}) {
154
156
  };
155
157
  }
156
158
  }
157
- const data = Buffer.from(canonicalize(receiptPayload(receipt)), "utf8");
158
- const signature = base64UrlToBuffer(receipt.signature);
159
+ const data = new TextEncoder().encode(canonicalize(receiptPayload(receipt)));
160
+ const signatureBuffer = base64UrlToBuffer(receipt.signature);
161
+ const signature = new Uint8Array(signatureBuffer.buffer, signatureBuffer.byteOffset, signatureBuffer.byteLength);
159
162
  try {
160
- const publicKey = createPublicKey({ key: jwk, format: "jwk" });
161
- const valid = nodeVerify("sha256", data, { key: publicKey, dsaEncoding: "ieee-p1363" }, signature);
163
+ // Web Crypto rather than node:crypto: identical verification, but it also runs in a Worker,
164
+ // which is what lets the hosted endpoint expose `verify_receipt` at all. The JWK already names
165
+ // the curve and hash, so the import is the whole setup.
166
+ const publicKey = await webcrypto.subtle.importKey("jwk", jwk, { name: "ECDSA", namedCurve: String(jwk.crv ?? "P-256") }, false, ["verify"]);
167
+ const valid = await webcrypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, publicKey, signature, data);
162
168
  if (!valid) {
163
169
  return {
164
170
  ok: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paystage/mcp",
3
- "version": "0.3.5",
3
+ "version": "0.5.0",
4
4
  "description": "PayStage umbrella MCP: payment preflight, auth watch, HIP-3 trade preflight, and velocity rate/spend-pattern checks",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -11,11 +11,16 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.js"
13
13
  },
14
- "./package.json": "./package.json"
14
+ "./package.json": "./package.json",
15
+ "./tools": {
16
+ "types": "./dist/tools.d.ts",
17
+ "import": "./dist/tools.js"
18
+ }
15
19
  },
16
20
  "bin": {
17
21
  "paystage-mcp": "dist/cli.js",
18
- "paystage-verify": "dist/verify-cli.js"
22
+ "paystage-verify": "dist/verify-cli.js",
23
+ "paystage-policy": "dist/policy-cli.js"
19
24
  },
20
25
  "files": [
21
26
  "dist",
@@ -52,7 +57,7 @@
52
57
  "@modelcontextprotocol/server": "^2.4.0",
53
58
  "@paystage/auth-watch": "0.2.0",
54
59
  "@paystage/policy": "0.2.1",
55
- "@paystage/preflight": "0.2.3",
60
+ "@paystage/preflight": "0.3.0",
56
61
  "@paystage/trade-preflight": "0.2.0",
57
62
  "@paystage/velocity": "0.2.0",
58
63
  "zod": "^4.6.7"
@@ -63,7 +68,7 @@
63
68
  "vitest": "^4.1.12"
64
69
  },
65
70
  "scripts": {
66
- "build": "tsc && chmod +x dist/cli.js dist/verify-cli.js",
71
+ "build": "tsc && chmod +x dist/cli.js dist/verify-cli.js dist/policy-cli.js",
67
72
  "test": "vitest run",
68
73
  "typecheck": "tsc --noEmit",
69
74
  "prepublishOnly": "npm run build"