@sluzen/mcp 0.0.0-stage → 0.1.2

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
@@ -1,3 +1,138 @@
1
- # Temporary Holding Version
1
+ # @sluzen/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MCP (stdio) surface for **HTTP 402 schemes on XRPL (Payment | PayChan | allowlisted RLUSD)**.
4
+
5
+ Wraps live Sluzen APIs and `@sluzen/sdk`. Does **not** invent rails. Private keys / seeds stay on the MCP host only. Never paste a seed into sluzen.network.
6
+
7
+ Rail contract: [`.ops/TERMS_RAIL.md`](../.ops/TERMS_RAIL.md) **§2.3** (PayChan) · **§2.4** (RLUSD). Specs: [`.ops/SPEC_PAYCHAN.md`](../.ops/SPEC_PAYCHAN.md), [`.ops/SPEC_RLUSD.md`](../.ops/SPEC_RLUSD.md).
8
+
9
+ Machine contract (OpenAPI): [`docs/openapi.yaml`](../docs/openapi.yaml) · [sluzen.network/openapi.yaml](https://sluzen.network/openapi.yaml). Human evaluate: [sluzen.network/developers](https://sluzen.network/developers#agent-loop).
10
+
11
+ ## Cold orchestrator loop (Find → Trust → Pay → Prove)
12
+
13
+ Use shipped surfaces only. No consumer social graph, no ranking marketplace, no `/.well-known` agent-card (not mandated; Find is `GET /api/v1/discovery`).
14
+
15
+ 1. **Discover (Find)** — `list_announced_routes` → `GET /api/v1/discovery` (SDK `listAnnouncedRoutes`). Optional density + `railFacts` (facts, not scores). Empty `routes` is valid. Sticker ≠ binding price.
16
+ 2. **Policy (Trust)** — prefer `SLUZEN_PRINCIPAL_MANDATE` + JWKS (signed principal TTL mandate) or legacy `SLUZEN_MACHINE_POLICY` JSON. Fail-closed before sign.
17
+ 3. **Pay** — `challenge` → `sign_payment_xrp` | `sign_payment_rlusd` | `sign_paychan_claim` → `proxy_pay` or facilitator `settle` / `authorize`. Seed stays on this host.
18
+ 4. **Verify receipt (Prove)** — `get_call_receipt` with `SLUZEN-CALL-ID` / `callId` → `GET /api/v1/receipt`. Then `bind_task_call` to map local `taskId`/`goalId` → `callId` (process memory only). Facilitator: `delivery.recorded=false` (issuer holds body).
19
+
20
+ Hosts: API `https://api.sluzen.network`; marketing docs `https://sluzen.network`. Land `/` stays issuer-first (no endpoint catalog).
21
+
22
+ ## Schemes
23
+
24
+ | Loop | Challenge | Sign (local) | Deliver to Sluzen | Latency (honest) |
25
+ |------|-----------|--------------|-------------------|------------------|
26
+ | A Payment XRP | `scheme: exact`, `asset: XRP` | `sign_payment_xrp` | `proxy_pay` or `facilitator_settle` | Ledger `submitAndWait` |
27
+ | B PayChan | `scheme: paychan`, `asset: XRP` | `sign_paychan_claim` | `proxy_pay` (JSON) or `facilitator_authorize` | Claim verify / authorize: sub-second possible |
28
+ | C Payment RLUSD | `scheme: exact`, `asset: RLUSD` + allowlisted `iou` | `sign_payment_rlusd` | same as A | Ledger `submitAndWait` |
29
+
30
+ Open `PaymentChannelCreate` and on-chain `PaymentChannelClaim` stay on the agent or issuer host. Sluzen verifies claims and debits prepaid take; it does not hold session keys or custody funds.
31
+
32
+ `GET /facilitator/supported` lists exact + paychan (XRP). RLUSD appears only on per-route challenges.
33
+
34
+ ## Custody ban
35
+
36
+ - Seeds: `CLIENT_WALLET_SEED` (or tool override) on the **local** MCP host.
37
+ - No MoR, refund, dispute, or Operator-held session keys.
38
+ - Prepaid / 0.8% take: already enforced by the proxy; this package does not reimplement fees.
39
+
40
+ ## Tools
41
+
42
+ | Tool | Role |
43
+ |------|------|
44
+ | `health` | `GET /health` |
45
+ | `list_announced_routes` | Find: `GET /api/v1/discovery` (density + railFacts; no seed; empty list valid) |
46
+ | `get_call_receipt` | Prove: `GET /api/v1/receipt?callId=` (settle→delivery join; facilitator has no Sluzen delivery) |
47
+ | `bind_task_call` | Local taskId/goalId ↔ callId (process memory; not a Sluzen store) |
48
+ | `lookup_task_call` | Lookup a prior local binding |
49
+ | `facilitator_supported` | `GET /facilitator/supported` |
50
+ | `challenge` | Proxy unpaid path or `POST /facilitator/challenge` |
51
+ | `sign_payment_xrp` | Local exact XRP Payment blob |
52
+ | `sign_payment_rlusd` | Local allowlisted RLUSD IOU Payment blob (fail-closed) |
53
+ | `sign_paychan_claim` | Local off-chain claim + JSON `PAYMENT-SIGNATURE` |
54
+ | `proxy_pay` | Retry with `PAYMENT-SIGNATURE` |
55
+ | `facilitator_verify` | Read-only verify (exact or PayChan triad) |
56
+ | `facilitator_settle` | Exact only (`use_authorize` if PayChan JSON) |
57
+ | `facilitator_authorize` | PayChan debit + cursor |
58
+
59
+ Fail-closed when currency is not allowlisted, PayChan params are invalid, local seed is missing, or `SLUZEN_MACHINE_POLICY` rejects the spend (per-call caps, PayChan cumulative, session `maxCalls` / `maxSessionDrops`).
60
+
61
+ ## Env
62
+
63
+ | Variable | Required | Notes |
64
+ |----------|----------|--------|
65
+ | `CLIENT_WALLET_SEED` | For sign tools | Local host only |
66
+ | `XRPL_NODE` | For exact Payment sign (autofill) | WebSocket rippled |
67
+ | `SLUZEN_API_BASE` | No | Default `https://api.sluzen.network` |
68
+ | `SLUZEN_MACHINE_POLICY` | No | JSON `MachinePolicy` (same shape as SDK). Unset = uncapped legacy. PayChan needs `maxCumulativeDrops` and/or `maxPriceDrops` (+ optional `challenge` / `deltaDrops`). Session counters live in the MCP process. |
69
+ | `SLUZEN_PRINCIPAL_MANDATE` | No | Compact JWS from the principal (prefers over JSON policy). Requires JWKS/public key. |
70
+ | `SLUZEN_MANDATE_JWKS` | With JWS | JWKS or JWK JSON for verify. |
71
+ | `SLUZEN_MANDATE_PUBLIC_KEY` | Alt | SPKI PEM or JWK JSON when JWKS unset. |
72
+ | `SLUZEN_MANDATE_REVOKED_JTIS` | No | Comma-separated `jti` denylist (orchestrator-owned revocation). |
73
+
74
+ Example mandate (host-local JSON legacy):
75
+
76
+ ```json
77
+ {
78
+ "maxPriceDrops": 50000,
79
+ "maxCumulativeDrops": 1000000,
80
+ "maxSessionDrops": 500000,
81
+ "maxCalls": 100,
82
+ "requireDiscoveryListed": true
83
+ }
84
+ ```
85
+
86
+ PayChan remains XRP-only. Channel Amount on ledger is the deposit envelope; `maxCumulativeDrops` is the agent claim ceiling. See [`docs/PRICE_AND_CAPS.md`](../docs/PRICE_AND_CAPS.md).
87
+
88
+ ## Claude Desktop (stdio)
89
+
90
+ ```json
91
+ {
92
+ "mcpServers": {
93
+ "sluzen": {
94
+ "command": "node",
95
+ "args": ["C:/Pons/sluzen-mcp/dist/bin/sluzen-mcp.js"],
96
+ "env": {
97
+ "CLIENT_WALLET_SEED": "(local seed)",
98
+ "XRPL_NODE": "wss://s.altnet.rippletest.net:51233",
99
+ "SLUZEN_API_BASE": "https://api.sluzen.network"
100
+ }
101
+ }
102
+ }
103
+ }
104
+ ```
105
+
106
+ Build first: `npm --prefix sluzen-mcp install && npm --prefix sluzen-mcp run build` (and `npm --prefix sluzen-sdk run build`).
107
+
108
+ Published package: `npx @sluzen/mcp` after npm publish of this version (see `.ops/NPM.md`).
109
+
110
+ ## AgentKit-style example
111
+
112
+ [`examples/paid-tool.ts`](examples/paid-tool.ts) cold path: Find (`list_announced_routes` + `railFacts`) → Trust (mandate/policy via `createRuntimeAsync`) → Pay → Prove (`get_call_receipt` + `bind_task_call`). No EVM / multi-rail co-branding.
113
+
114
+ ## Registries / default path
115
+
116
+ | Channel | Status |
117
+ |---------|--------|
118
+ | npm `@sluzen/mcp` | Publish = **HUMAN** WebAuthn (`.ops/NPM.md`). Tree version `0.1.2` (complete nerve). Prior registry may still be `0.1.0` / `0.1.1` until published. |
119
+ | npm `@sluzen/sdk` | Tree `2.1.0` (mandate + task bind + density types). Publish = HUMAN sync to public client repo. |
120
+ | MCP client config | Claude Desktop / Cursor stdio snippet above (`npx @sluzen/mcp` or local `dist/bin`). |
121
+ | HTTP Find | `GET https://api.sluzen.network/api/v1/discovery` |
122
+ | OpenAPI | `https://sluzen.network/openapi.yaml` |
123
+ | `/.well-known` agent-card | **CLOSED** (not mandated; AGENT_LOOP Phase 10). |
124
+
125
+ Third-party MCP directory listings (where an account is required) = HUMAN submission after npm publish.
126
+
127
+ ## Develop
128
+
129
+ ```bash
130
+ npm --prefix sluzen-sdk run build
131
+ npm --prefix sluzen-mcp install
132
+ npm --prefix sluzen-mcp run build
133
+ npm --prefix sluzen-mcp test
134
+ ```
135
+
136
+ ## License
137
+
138
+ ISC
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { createRuntimeAsync } from "../config.js";
4
+ import { createSluzenMcpServer } from "../server.js";
5
+ async function main() {
6
+ const runtime = await createRuntimeAsync();
7
+ const server = createSluzenMcpServer(runtime);
8
+ const transport = new StdioServerTransport();
9
+ await server.connect(transport);
10
+ }
11
+ main().catch((err) => {
12
+ console.error(err instanceof Error ? err.message : String(err));
13
+ process.exit(1);
14
+ });
@@ -0,0 +1,47 @@
1
+ import { TaskCallBindingStore, type MachinePolicy, type SpendSessionState } from "@sluzen/sdk";
2
+ export declare const DEFAULT_API_BASE = "https://api.sluzen.network";
3
+ export type McpRuntimeConfig = {
4
+ apiBase: string;
5
+ walletSeed: string;
6
+ xrplNode: string | undefined;
7
+ fetchFn: typeof fetch;
8
+ /** Optional Trust/Pay mandate. Absent = uncapped signing (legacy). */
9
+ machinePolicy: MachinePolicy | undefined;
10
+ /** Session counters for maxSessionDrops / maxCalls; always present. */
11
+ spendSession: SpendSessionState;
12
+ /** Local taskId/goalId ↔ callId store (process memory only). */
13
+ taskBindings: TaskCallBindingStore;
14
+ };
15
+ export declare function resolveApiBase(override?: string): string;
16
+ export declare function resolveWalletSeed(override?: string): string;
17
+ export declare function resolveXrplNode(override?: string): string | undefined;
18
+ /**
19
+ * Prefer signed principal mandate (`SLUZEN_PRINCIPAL_MANDATE` + key material).
20
+ * Falls back to legacy `SLUZEN_MACHINE_POLICY` JSON. Unset both → uncapped.
21
+ */
22
+ export declare function resolveMachinePolicyFromEnv(env?: NodeJS.ProcessEnv): Promise<MachinePolicy | undefined>;
23
+ /**
24
+ * Parse optional `SLUZEN_MACHINE_POLICY` JSON into a MachinePolicy.
25
+ * Empty / unset → undefined (uncapped). Invalid JSON or fields → throw.
26
+ */
27
+ export declare function parseMachinePolicyEnv(raw?: string | undefined): MachinePolicy | undefined;
28
+ export declare function createRuntime(options?: {
29
+ apiBase?: string;
30
+ walletSeed?: string;
31
+ xrplNode?: string;
32
+ fetchFn?: typeof fetch;
33
+ machinePolicy?: MachinePolicy;
34
+ spendSession?: SpendSessionState;
35
+ taskBindings?: TaskCallBindingStore;
36
+ }): McpRuntimeConfig;
37
+ /** Async entry for signed principal mandate env (Phase 7). */
38
+ export declare function createRuntimeAsync(options?: {
39
+ apiBase?: string;
40
+ walletSeed?: string;
41
+ xrplNode?: string;
42
+ fetchFn?: typeof fetch;
43
+ machinePolicy?: MachinePolicy;
44
+ spendSession?: SpendSessionState;
45
+ taskBindings?: TaskCallBindingStore;
46
+ }): Promise<McpRuntimeConfig>;
47
+ export declare function requireSeed(seed: string): string;
package/dist/config.js ADDED
@@ -0,0 +1,174 @@
1
+ import { createSpendSession, TaskCallBindingStore, verifyPrincipalMandate, } from "@sluzen/sdk";
2
+ export const DEFAULT_API_BASE = "https://api.sluzen.network";
3
+ export function resolveApiBase(override) {
4
+ const raw = override?.trim() ||
5
+ process.env.SLUZEN_API_BASE?.trim() ||
6
+ DEFAULT_API_BASE;
7
+ return raw.replace(/\/$/, "");
8
+ }
9
+ export function resolveWalletSeed(override) {
10
+ return (override?.trim() ||
11
+ process.env.CLIENT_WALLET_SEED?.trim() ||
12
+ "");
13
+ }
14
+ export function resolveXrplNode(override) {
15
+ const node = override?.trim() || process.env.XRPL_NODE?.trim();
16
+ return node && node.length > 0 ? node : undefined;
17
+ }
18
+ function asFiniteNonNegInt(value, label) {
19
+ if (value == null) {
20
+ return undefined;
21
+ }
22
+ const n = typeof value === "number" ? value : Number(value);
23
+ if (!Number.isSafeInteger(n) || n < 0) {
24
+ throw new Error(`SLUZEN_MACHINE_POLICY: ${label} must be a safe non-negative integer`);
25
+ }
26
+ return n;
27
+ }
28
+ /** MCP schemes are XRPL Payment | PayChan | allowlisted RLUSD only. */
29
+ function asCurrencyList(value) {
30
+ if (value == null) {
31
+ return undefined;
32
+ }
33
+ if (!Array.isArray(value)) {
34
+ throw new Error("SLUZEN_MACHINE_POLICY: allowedCurrencies must be an array");
35
+ }
36
+ const out = [];
37
+ for (const raw of value) {
38
+ const c = String(raw).trim().toUpperCase();
39
+ if (c !== "XRP" && c !== "RLUSD") {
40
+ throw new Error(`SLUZEN_MACHINE_POLICY: unsupported currency ${raw} (MCP: XRP|RLUSD only)`);
41
+ }
42
+ if (!out.includes(c)) {
43
+ out.push(c);
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ /**
49
+ * Prefer signed principal mandate (`SLUZEN_PRINCIPAL_MANDATE` + key material).
50
+ * Falls back to legacy `SLUZEN_MACHINE_POLICY` JSON. Unset both → uncapped.
51
+ */
52
+ export async function resolveMachinePolicyFromEnv(env = process.env) {
53
+ const jws = env.SLUZEN_PRINCIPAL_MANDATE?.trim() ?? "";
54
+ if (jws.length > 0) {
55
+ const jwks = env.SLUZEN_MANDATE_JWKS?.trim() ||
56
+ env.SLUZEN_MANDATE_PUBLIC_KEY?.trim() ||
57
+ "";
58
+ if (!jwks) {
59
+ throw new Error("SLUZEN_PRINCIPAL_MANDATE requires SLUZEN_MANDATE_JWKS or SLUZEN_MANDATE_PUBLIC_KEY");
60
+ }
61
+ const revokedRaw = env.SLUZEN_MANDATE_REVOKED_JTIS?.trim() ?? "";
62
+ const revokedJtis = revokedRaw.length > 0
63
+ ? revokedRaw.split(",").map((x) => x.trim()).filter(Boolean)
64
+ : undefined;
65
+ const verified = await verifyPrincipalMandate(jws, {
66
+ publicKey: jwks,
67
+ revokedJtis,
68
+ });
69
+ return verified.machinePolicy;
70
+ }
71
+ return parseMachinePolicyEnv(env.SLUZEN_MACHINE_POLICY);
72
+ }
73
+ /**
74
+ * Parse optional `SLUZEN_MACHINE_POLICY` JSON into a MachinePolicy.
75
+ * Empty / unset → undefined (uncapped). Invalid JSON or fields → throw.
76
+ */
77
+ export function parseMachinePolicyEnv(raw = process.env.SLUZEN_MACHINE_POLICY) {
78
+ const text = raw?.trim() ?? "";
79
+ if (text.length === 0) {
80
+ return undefined;
81
+ }
82
+ let parsed;
83
+ try {
84
+ parsed = JSON.parse(text);
85
+ }
86
+ catch {
87
+ throw new Error("SLUZEN_MACHINE_POLICY must be valid JSON");
88
+ }
89
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
90
+ throw new Error("SLUZEN_MACHINE_POLICY must be a JSON object");
91
+ }
92
+ const o = parsed;
93
+ const policy = {};
94
+ const maxPriceDrops = asFiniteNonNegInt(o.maxPriceDrops, "maxPriceDrops");
95
+ if (maxPriceDrops != null) {
96
+ policy.maxPriceDrops = maxPriceDrops;
97
+ }
98
+ if (o.maxPriceDropsByHost != null) {
99
+ if (typeof o.maxPriceDropsByHost !== "object" ||
100
+ Array.isArray(o.maxPriceDropsByHost)) {
101
+ throw new Error("SLUZEN_MACHINE_POLICY: maxPriceDropsByHost must be an object");
102
+ }
103
+ const map = {};
104
+ for (const [host, val] of Object.entries(o.maxPriceDropsByHost)) {
105
+ const n = asFiniteNonNegInt(val, `maxPriceDropsByHost.${host}`);
106
+ if (n != null) {
107
+ map[host.trim().toLowerCase()] = n;
108
+ }
109
+ }
110
+ policy.maxPriceDropsByHost = map;
111
+ }
112
+ if (typeof o.maxIouValue === "string" && o.maxIouValue.trim().length > 0) {
113
+ policy.maxIouValue = o.maxIouValue.trim();
114
+ }
115
+ const allowedCurrencies = asCurrencyList(o.allowedCurrencies);
116
+ if (allowedCurrencies != null) {
117
+ policy.allowedCurrencies = allowedCurrencies;
118
+ }
119
+ if (Array.isArray(o.allowedNetworks)) {
120
+ policy.allowedNetworks = o.allowedNetworks.map((x) => String(x));
121
+ }
122
+ if (Array.isArray(o.allowedDestinations)) {
123
+ policy.allowedDestinations = o.allowedDestinations.map((x) => String(x));
124
+ }
125
+ if (o.requireDiscoveryListed === true) {
126
+ policy.requireDiscoveryListed = true;
127
+ }
128
+ if (typeof o.discoveryBaseUrl === "string" && o.discoveryBaseUrl.trim()) {
129
+ policy.discoveryBaseUrl = o.discoveryBaseUrl.trim().replace(/\/$/, "");
130
+ }
131
+ const maxCumulativeDrops = asFiniteNonNegInt(o.maxCumulativeDrops, "maxCumulativeDrops");
132
+ if (maxCumulativeDrops != null) {
133
+ policy.maxCumulativeDrops = maxCumulativeDrops;
134
+ }
135
+ const maxSessionDrops = asFiniteNonNegInt(o.maxSessionDrops, "maxSessionDrops");
136
+ if (maxSessionDrops != null) {
137
+ policy.maxSessionDrops = maxSessionDrops;
138
+ }
139
+ const maxCalls = asFiniteNonNegInt(o.maxCalls, "maxCalls");
140
+ if (maxCalls != null) {
141
+ policy.maxCalls = maxCalls;
142
+ }
143
+ return policy;
144
+ }
145
+ export function createRuntime(options) {
146
+ if (options?.machinePolicy === undefined &&
147
+ (process.env.SLUZEN_PRINCIPAL_MANDATE?.trim() ?? "").length > 0) {
148
+ throw new Error("SLUZEN_PRINCIPAL_MANDATE is set: use createRuntimeAsync() (or pass machinePolicy)");
149
+ }
150
+ return {
151
+ apiBase: resolveApiBase(options?.apiBase),
152
+ walletSeed: resolveWalletSeed(options?.walletSeed),
153
+ xrplNode: resolveXrplNode(options?.xrplNode),
154
+ fetchFn: options?.fetchFn ?? fetch,
155
+ machinePolicy: options?.machinePolicy !== undefined
156
+ ? options.machinePolicy
157
+ : parseMachinePolicyEnv(),
158
+ spendSession: options?.spendSession ?? createSpendSession(),
159
+ taskBindings: options?.taskBindings ?? new TaskCallBindingStore(),
160
+ };
161
+ }
162
+ /** Async entry for signed principal mandate env (Phase 7). */
163
+ export async function createRuntimeAsync(options) {
164
+ const machinePolicy = options && Object.prototype.hasOwnProperty.call(options, "machinePolicy")
165
+ ? options.machinePolicy
166
+ : await resolveMachinePolicyFromEnv();
167
+ return createRuntime({ ...options, machinePolicy });
168
+ }
169
+ export function requireSeed(seed) {
170
+ if (!seed || seed.length === 0) {
171
+ throw new Error("CLIENT_WALLET_SEED is required on the MCP host (local only; never send seed to Sluzen)");
172
+ }
173
+ return seed;
174
+ }
@@ -0,0 +1,3 @@
1
+ export { createRuntime, createRuntimeAsync, resolveApiBase, resolveMachinePolicyFromEnv, DEFAULT_API_BASE, } from "./config.js";
2
+ export { createSluzenMcpServer } from "./server.js";
3
+ export * from "./tools.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { createRuntime, createRuntimeAsync, resolveApiBase, resolveMachinePolicyFromEnv, DEFAULT_API_BASE, } from "./config.js";
2
+ export { createSluzenMcpServer } from "./server.js";
3
+ export * from "./tools.js";
@@ -0,0 +1,8 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { type McpRuntimeConfig } from "./config.js";
3
+ /**
4
+ * Build the Sluzen MCP server (stdio transport attached by the bin).
5
+ * HTTP 402 schemes on XRPL (Payment | PayChan | allowlisted RLUSD).
6
+ * Private keys stay on the MCP host only.
7
+ */
8
+ export declare function createSluzenMcpServer(runtime?: McpRuntimeConfig): McpServer;
package/dist/server.js ADDED
@@ -0,0 +1,174 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { createRuntime } from "./config.js";
4
+ import { toolChallenge, toolFacilitatorAuthorize, toolFacilitatorSettle, toolFacilitatorSupported, toolFacilitatorVerify, toolBindTaskCall, toolGetCallReceipt, toolHealth, toolListAnnouncedRoutes, toolLookupTaskCall, toolProxyPay, toolSignPaychanClaim, toolSignPaymentRlusd, toolSignPaymentXrp, } from "./tools.js";
5
+ function textResult(result) {
6
+ const payload = JSON.stringify(result, null, 2);
7
+ if (!result.ok) {
8
+ return {
9
+ content: [{ type: "text", text: payload }],
10
+ isError: true,
11
+ };
12
+ }
13
+ return {
14
+ content: [{ type: "text", text: payload }],
15
+ };
16
+ }
17
+ const challengeInput = z.union([z.string(), z.record(z.unknown())]);
18
+ /**
19
+ * Build the Sluzen MCP server (stdio transport attached by the bin).
20
+ * HTTP 402 schemes on XRPL (Payment | PayChan | allowlisted RLUSD).
21
+ * Private keys stay on the MCP host only.
22
+ */
23
+ export function createSluzenMcpServer(runtime = createRuntime()) {
24
+ const server = new McpServer({
25
+ name: "sluzen",
26
+ version: "0.1.2",
27
+ });
28
+ server.registerTool("health", {
29
+ description: "GET /health on the Sluzen API (rail open, network, supportsPayChan).",
30
+ inputSchema: {},
31
+ }, async () => textResult(await toolHealth(runtime)));
32
+ server.registerTool("list_announced_routes", {
33
+ description: "Find: GET /api/v1/discovery (SDK listAnnouncedRoutes). Public announced sellable proxy capabilities (url, sourceRoute, currency/network, price sticker, label, optional category). No seed. Empty routes is valid. Not a marketplace, rank, or volume claim. Binding price is still the 402 challenge.",
34
+ inputSchema: {},
35
+ }, async () => textResult(await toolListAnnouncedRoutes(runtime)));
36
+ server.registerTool("get_call_receipt", {
37
+ description: "Prove: GET /api/v1/receipt?callId= (joined settle→delivery). No admin Bearer. Facilitator: delivery.recorded=false (issuer holds body). Not a browseable index.",
38
+ inputSchema: {
39
+ callId: z
40
+ .string()
41
+ .describe("Attempt id from SLUZEN-CALL-ID / challenge.callId"),
42
+ },
43
+ }, async (args) => textResult(await toolGetCallReceipt(args, runtime)));
44
+ server.registerTool("bind_task_call", {
45
+ description: "Prove bridge: bind local taskId/goalId to callId in MCP process memory only. Does not upload to Sluzen; no durable body store. Optional resultRef stays local.",
46
+ inputSchema: {
47
+ callId: z.string().describe("Attempt id (SLUZEN-CALL-ID)"),
48
+ taskId: z.string().optional(),
49
+ goalId: z.string().optional(),
50
+ resultRef: z
51
+ .string()
52
+ .optional()
53
+ .describe("Optional local/issuer result hash or opaque ref"),
54
+ },
55
+ }, async (args) => textResult(toolBindTaskCall(args, runtime)));
56
+ server.registerTool("lookup_task_call", {
57
+ description: "Lookup a local task↔call binding previously stored with bind_task_call (process memory only).",
58
+ inputSchema: {
59
+ callId: z.string().optional(),
60
+ taskId: z.string().optional(),
61
+ goalId: z.string().optional(),
62
+ },
63
+ }, async (args) => textResult(toolLookupTaskCall(args, runtime)));
64
+ server.registerTool("facilitator_supported", {
65
+ description: "GET /facilitator/supported. Global kinds: exact XRP + paychan XRP. RLUSD is per-route only (v2 challenge/settle supported; not listed here).",
66
+ inputSchema: {},
67
+ }, async () => textResult(await toolFacilitatorSupported(runtime)));
68
+ server.registerTool("challenge", {
69
+ description: "Issue an HTTP 402 PAYMENT-REQUIRED challenge (proxy path or facilitator resource). Returns decoded challenge + selectAccept scheme.",
70
+ inputSchema: {
71
+ surface: z.enum(["proxy", "facilitator"]),
72
+ path: z
73
+ .string()
74
+ .optional()
75
+ .describe("Proxy path starting with / (surface=proxy)"),
76
+ resource: z
77
+ .string()
78
+ .optional()
79
+ .describe("https facilitator resource URL (surface=facilitator)"),
80
+ channelId: z
81
+ .string()
82
+ .optional()
83
+ .describe("Optional PayChan channel id for facilitator challenge"),
84
+ method: z.string().optional().describe("HTTP method for proxy unpaid call"),
85
+ },
86
+ }, async (args) => textResult(await toolChallenge(args, runtime)));
87
+ server.registerTool("sign_payment_xrp", {
88
+ description: "Sign exact XRP Payment locally (CLIENT_WALLET_SEED on MCP host). Optional SLUZEN_MACHINE_POLICY fail-closed before sign. Requires XRPL_NODE for autofill.",
89
+ inputSchema: {
90
+ challenge: challengeInput.describe("Decoded challenge object or PAYMENT-REQUIRED base64"),
91
+ walletSeed: z
92
+ .string()
93
+ .optional()
94
+ .describe("Override seed; prefer CLIENT_WALLET_SEED env on host"),
95
+ requestUrl: z
96
+ .string()
97
+ .optional()
98
+ .describe("URL for host caps / discovery listing proof"),
99
+ },
100
+ }, async (args) => textResult(await toolSignPaymentXrp({
101
+ challenge: args.challenge,
102
+ walletSeed: args.walletSeed,
103
+ requestUrl: args.requestUrl,
104
+ }, runtime)));
105
+ server.registerTool("sign_payment_rlusd", {
106
+ description: "Sign allowlisted RLUSD IOU Payment locally. Fail-closed if currency/issuer not allowlisted. Honors SLUZEN_MACHINE_POLICY when set.",
107
+ inputSchema: {
108
+ challenge: challengeInput,
109
+ walletSeed: z.string().optional(),
110
+ requestUrl: z.string().optional(),
111
+ },
112
+ }, async (args) => textResult(await toolSignPaymentRlusd({
113
+ challenge: args.challenge,
114
+ walletSeed: args.walletSeed,
115
+ requestUrl: args.requestUrl,
116
+ }, runtime)));
117
+ server.registerTool("sign_paychan_claim", {
118
+ description: "Sign off-chain PayChan claim locally (XRP-only). With SLUZEN_MACHINE_POLICY: need maxCumulativeDrops and/or maxPriceDrops (+ challenge/deltaDrops). Channel Amount is the on-ledger deposit envelope.",
119
+ inputSchema: {
120
+ channelId: z.string(),
121
+ cumulativeDrops: z.string(),
122
+ walletSeed: z.string().optional(),
123
+ challenge: challengeInput.optional(),
124
+ deltaDrops: z
125
+ .string()
126
+ .optional()
127
+ .describe("Per-call delta drops when no challenge.amount"),
128
+ requestUrl: z.string().optional(),
129
+ },
130
+ }, async (args) => textResult(await toolSignPaychanClaim({
131
+ channelId: args.channelId,
132
+ cumulativeDrops: args.cumulativeDrops,
133
+ walletSeed: args.walletSeed,
134
+ challenge: args.challenge,
135
+ deltaDrops: args.deltaDrops,
136
+ requestUrl: args.requestUrl,
137
+ }, runtime)));
138
+ server.registerTool("proxy_pay", {
139
+ description: "Retry a proxy path with PAYMENT-SIGNATURE (exact tx blob or PayChan JSON). Exact settle uses submitAndWait server-side; PayChan authorize path is off-chain claim verify.",
140
+ inputSchema: {
141
+ path: z.string(),
142
+ paymentSignature: z.string(),
143
+ method: z.string().optional(),
144
+ body: z.string().optional(),
145
+ },
146
+ }, async (args) => textResult(await toolProxyPay(args, runtime)));
147
+ server.registerTool("facilitator_verify", {
148
+ description: "POST /facilitator/verify (read-only). Exact: paymentSignature. PayChan: channelId + claimSignature + cumulativeDrops.",
149
+ inputSchema: {
150
+ resource: z.string(),
151
+ paymentSignature: z.string().optional(),
152
+ channelId: z.string().optional(),
153
+ claimSignature: z.string().optional(),
154
+ cumulativeDrops: z.string().optional(),
155
+ },
156
+ }, async (args) => textResult(await toolFacilitatorVerify(args, runtime)));
157
+ server.registerTool("facilitator_settle", {
158
+ description: "POST /facilitator/settle for exact Payment only (server submitAndWait). PayChan must use facilitator_authorize.",
159
+ inputSchema: {
160
+ resource: z.string(),
161
+ paymentSignature: z.string(),
162
+ },
163
+ }, async (args) => textResult(await toolFacilitatorSettle(args, runtime)));
164
+ server.registerTool("facilitator_authorize", {
165
+ description: "POST /facilitator/authorize for PayChan claim increment (debit take + advance cursor). Not for exact Payment.",
166
+ inputSchema: {
167
+ resource: z.string(),
168
+ channelId: z.string(),
169
+ claimSignature: z.string(),
170
+ cumulativeDrops: z.string(),
171
+ },
172
+ }, async (args) => textResult(await toolFacilitatorAuthorize(args, runtime)));
173
+ return server;
174
+ }