nirium-mcp 0.6.9 → 0.6.10

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 (2) hide show
  1. package/dist/index.js +334 -340
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -3,6 +3,8 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  // Copyright 2026 Nirium Protocol Contributors
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createNiriumMcpServer = createNiriumMcpServer;
7
+ exports.main = main;
6
8
  // ═══════════════════════════════════════════════════════════════
7
9
  // Nirium MCP Server — x402 + MPP + node tool suite
8
10
  // ═══════════════════════════════════════════════════════════════
@@ -46,370 +48,362 @@ const stellar_1 = require("@x402/stellar");
46
48
  const stellar_2 = require("@x402/stellar");
47
49
  const client_1 = require("mppx/client");
48
50
  const client_2 = require("@stellar/mpp/charge/client");
49
- // ─── Configuration ────────────────────────────────────────────
50
- const API_URL = process.env.AGENT_API_URL || 'http://127.0.0.1:3002';
51
- const STELLAR_KEY = process.env.STELLAR_SECRET_KEY || '';
52
- const NIRIUM_API_KEY = process.env.NIRIUM_API_KEY || '';
53
- const IS_MAINNET = process.env.STELLAR_NETWORK === 'mainnet';
54
- const STELLAR_NET = (IS_MAINNET
55
- ? 'stellar:pubnet'
56
- : stellar_2.STELLAR_TESTNET_CAIP2);
57
- // El default de RPC solo sirve para testnet: Stellar no publica un RPC de
58
- // mainnet abierto (el propio @x402/stellar lanza "mainnet requires a non-empty
59
- // rpcUrl"). Sin este guard, mainnet caía al RPC de testnet con el network id de
60
- // pubnet y el pago fallaba de forma confusa, con fondos reales. El RPC lo pone
61
- // quien corre el server — el endpoint dedicado de Nirium lleva token y vive
62
- // como secreto del backend, nunca dentro de un paquete publicado.
63
- const RPC_URL = process.env.SOROBAN_RPC_URL
64
- || (IS_MAINNET ? '' : stellar_2.DEFAULT_TESTNET_RPC_URL);
65
- // Sin RPC válido no se puede firmar un pago; las herramientas gratuitas siguen vivas.
66
- const PAYMENTS_ENABLED = !!STELLAR_KEY && !!RPC_URL;
67
- const PAYMENTS_DISABLED_REASON = PAYMENTS_ENABLED
68
- ? ''
69
- : !STELLAR_KEY
70
- ? 'STELLAR_SECRET_KEY is not set — paid tools need a funded Stellar wallet.'
71
- : 'STELLAR_NETWORK=mainnet requires SOROBAN_RPC_URL (Stellar publishes no open mainnet RPC). '
72
- + 'Pick a provider at https://developers.stellar.org/docs/data/apis/rpc/providers';
73
- // Derive public key from secret key if available, or use explicit env var
74
- const STELLAR_PUBLIC_KEY = (() => {
75
- if (process.env.STELLAR_PUBLIC_KEY)
76
- return process.env.STELLAR_PUBLIC_KEY;
77
- if (STELLAR_KEY) {
51
+ // La versión se lee de package.json: antes estaba escrita a mano en tres lugares
52
+ // y se quedaba atrás en cada release. dist/ queda un nivel debajo de package.json.
53
+ const PKG_VERSION = require('../package.json').version;
54
+ function createNiriumMcpServer(options = {}) {
55
+ // ─── Configuration ────────────────────────────────────────────
56
+ const API_URL = options.apiUrl ?? (process.env.AGENT_API_URL || 'http://127.0.0.1:3002');
57
+ const STELLAR_KEY = options.stellarKey ?? (process.env.STELLAR_SECRET_KEY || '');
58
+ const NIRIUM_API_KEY = options.niriumApiKey ?? (process.env.NIRIUM_API_KEY || '');
59
+ const IS_MAINNET = options.isMainnet ?? (process.env.STELLAR_NETWORK === 'mainnet');
60
+ const STELLAR_NET = (IS_MAINNET
61
+ ? 'stellar:pubnet'
62
+ : stellar_2.STELLAR_TESTNET_CAIP2);
63
+ // El default de RPC solo sirve para testnet: Stellar no publica un RPC de
64
+ // mainnet abierto (el propio @x402/stellar lanza "mainnet requires a non-empty
65
+ // rpcUrl"). Sin este guard, mainnet caía al RPC de testnet con el network id de
66
+ // pubnet y el pago fallaba de forma confusa, con fondos reales. El RPC lo pone
67
+ // quien corre el server — el endpoint dedicado de Nirium lleva token y vive
68
+ // como secreto del backend, nunca dentro de un paquete publicado.
69
+ const RPC_URL = options.rpcUrl ?? (process.env.SOROBAN_RPC_URL
70
+ || (IS_MAINNET ? '' : stellar_2.DEFAULT_TESTNET_RPC_URL));
71
+ // Sin RPC válido no se puede firmar un pago; las herramientas gratuitas siguen vivas.
72
+ let paymentsEnabled = options.paidFetch != null || (!!STELLAR_KEY && !!RPC_URL);
73
+ let paymentsDisabledReason = paymentsEnabled
74
+ ? ''
75
+ : !STELLAR_KEY
76
+ ? 'STELLAR_SECRET_KEY is not set — paid tools need a funded Stellar wallet.'
77
+ : 'STELLAR_NETWORK=mainnet requires SOROBAN_RPC_URL (Stellar publishes no open mainnet RPC). '
78
+ + 'Pick a provider at https://developers.stellar.org/docs/data/apis/rpc/providers';
79
+ // Derive public key from secret key if available, or use explicit env var
80
+ const STELLAR_PUBLIC_KEY = (() => {
81
+ if (options.stellarPublicKey)
82
+ return options.stellarPublicKey;
83
+ if (process.env.STELLAR_PUBLIC_KEY)
84
+ return process.env.STELLAR_PUBLIC_KEY;
85
+ if (STELLAR_KEY) {
86
+ try {
87
+ return (0, stellar_2.createEd25519Signer)(STELLAR_KEY, STELLAR_NET).address;
88
+ }
89
+ catch {
90
+ return '';
91
+ }
92
+ }
93
+ return '';
94
+ })();
95
+ // Auth headers for authenticated endpoints
96
+ const authHeaders = () => NIRIUM_API_KEY ? { 'x-api-key': NIRIUM_API_KEY } : {};
97
+ // Auth + legal consent headers (required by loop/start and execute endpoints)
98
+ const consentHeaders = () => ({
99
+ ...authHeaders(),
100
+ ...(STELLAR_PUBLIC_KEY ? { 'x-stellar-account': STELLAR_PUBLIC_KEY } : {}),
101
+ });
102
+ const fetchFn = options.fetchFn ?? fetch;
103
+ // ─── x402 Payment Client ──────────────────────────────────────
104
+ //
105
+ // Set up once; reused for all x402 premium tool calls.
106
+ // Requires STELLAR_SECRET_KEY env var with funded testnet wallet.
107
+ //
108
+ let paidFetch = options.paidFetch ?? fetchFn;
109
+ if (!options.paidFetch && paymentsEnabled) {
78
110
  try {
79
- return (0, stellar_2.createEd25519Signer)(STELLAR_KEY, STELLAR_NET).address;
111
+ const signer = (0, stellar_2.createEd25519Signer)(STELLAR_KEY, STELLAR_NET);
112
+ const client = new fetch_1.x402Client()
113
+ .register(STELLAR_NET, new stellar_1.ExactStellarScheme(signer, { url: RPC_URL }));
114
+ paidFetch = (0, fetch_1.wrapFetchWithPayment)(fetchFn, client);
115
+ console.error(`[Nirium MCP] x402 wallet: ${signer.address} | network: ${STELLAR_NET}`);
80
116
  }
81
- catch {
82
- return '';
117
+ catch (err) {
118
+ paymentsEnabled = false;
119
+ paymentsDisabledReason = `Failed to initialize x402 signer: ${err instanceof Error ? err.message : String(err)}`;
120
+ console.error(`[Nirium MCP] Paid tools disabled — ${paymentsDisabledReason}`);
83
121
  }
84
122
  }
85
- return '';
86
- })();
87
- // Auth headers for authenticated endpoints
88
- const authHeaders = () => NIRIUM_API_KEY ? { 'x-api-key': NIRIUM_API_KEY } : {};
89
- // Auth + legal consent headers (required by loop/start and execute endpoints)
90
- const consentHeaders = () => ({
91
- ...authHeaders(),
92
- ...(STELLAR_PUBLIC_KEY ? { 'x-stellar-account': STELLAR_PUBLIC_KEY } : {}),
93
- });
94
- // ─── x402 Payment Client ──────────────────────────────────────
95
- //
96
- // Set up once; reused for all x402 premium tool calls.
97
- // Requires STELLAR_SECRET_KEY env var with funded testnet wallet.
98
- //
99
- let paidFetch = fetch;
100
- if (PAYMENTS_ENABLED) {
101
- const signer = (0, stellar_2.createEd25519Signer)(STELLAR_KEY, STELLAR_NET);
102
- const client = new fetch_1.x402Client()
103
- .register(STELLAR_NET, new stellar_1.ExactStellarScheme(signer, { url: RPC_URL }));
104
- paidFetch = (0, fetch_1.wrapFetchWithPayment)(fetch, client);
105
- console.error(`[Nirium MCP] x402 wallet: ${signer.address} | network: ${STELLAR_NET}`);
106
- }
107
- else {
108
- console.error(`[Nirium MCP] Paid tools disabled — ${PAYMENTS_DISABLED_REASON}`);
109
- }
110
- // ─── MPP Payment Client ───────────────────────────────────────
111
- //
112
- // MPP Charge mode: per-request Soroban SAC transfer.
113
- // No external facilitator — server verifies directly.
114
- // Same STELLAR_SECRET_KEY funds both x402 and MPP payments.
115
- //
116
- let mppFetch = fetch;
117
- if (PAYMENTS_ENABLED) {
118
- const mppx = client_1.Mppx.create({
119
- methods: [
120
- client_2.stellar.charge({
121
- secretKey: STELLAR_KEY,
122
- rpcUrl: RPC_URL,
123
- }),
124
- ],
125
- });
126
- mppFetch = mppx.fetch;
127
- console.error(`[Nirium MCP] MPP Charge enabled | network: ${STELLAR_NET}`);
128
- }
129
- else {
130
- console.error(`[Nirium MCP] MPP tools disabled — ${PAYMENTS_DISABLED_REASON}`);
131
- }
132
- // ─── Server ───────────────────────────────────────────────────
133
- // La versión se lee de package.json: antes estaba escrita a mano en tres lugares
134
- // y se quedaba atrás en cada release. dist/ queda un nivel debajo de package.json.
135
- const PKG_VERSION = require('../package.json').version;
136
- const server = new mcp_js_1.McpServer({ name: 'nirium-mcp-server', version: PKG_VERSION }, { capabilities: { tools: {} } });
137
- const text = (body) => ({ content: [{ type: 'text', text: typeof body === 'string' ? body : JSON.stringify(body, null, 2) }] });
138
- const fail = (message) => ({ content: [{ type: 'text', text: message }], isError: true });
139
- // Un pago sin wallet o sin RPC de mainnet no puede firmarse: decirlo aquí evita
140
- // que el modelo reciba un 402 opaco y lo reporte como "el servidor falló".
141
- const paymentsUnavailable = () => PAYMENTS_ENABLED ? null : fail(`Payment tools unavailable: ${PAYMENTS_DISABLED_REASON}`);
142
- // Los nodos gratuitos comparten forma: GET/POST → JSON, error legible.
143
- async function callJson(url, init, doFetch = fetch) {
144
- try {
145
- const res = await doFetch(url, init);
146
- if (!res.ok)
147
- return fail(`Error ${res.status}: ${await res.text()}`);
148
- return text(await res.json());
123
+ else if (!paymentsEnabled && !options.paidFetch) {
124
+ console.error(`[Nirium MCP] Paid tools disabled — ${paymentsDisabledReason}`);
125
+ }
126
+ // ─── MPP Payment Client ───────────────────────────────────────
127
+ //
128
+ // MPP Charge mode: per-request Soroban SAC transfer.
129
+ // No external facilitator — server verifies directly.
130
+ // Same STELLAR_SECRET_KEY funds both x402 and MPP payments.
131
+ //
132
+ let mppFetch = options.mppFetch ?? fetchFn;
133
+ if (!options.mppFetch && paymentsEnabled) {
134
+ try {
135
+ const mppx = client_1.Mppx.create({
136
+ methods: [
137
+ client_2.stellar.charge({
138
+ secretKey: STELLAR_KEY,
139
+ rpcUrl: RPC_URL,
140
+ }),
141
+ ],
142
+ });
143
+ mppFetch = mppx.fetch;
144
+ console.error(`[Nirium MCP] MPP Charge enabled | network: ${STELLAR_NET}`);
145
+ }
146
+ catch (err) {
147
+ paymentsEnabled = false;
148
+ paymentsDisabledReason = `Failed to initialize MPP charge client: ${err instanceof Error ? err.message : String(err)}`;
149
+ console.error(`[Nirium MCP] MPP tools disabled — ${paymentsDisabledReason}`);
150
+ }
149
151
  }
150
- catch (err) {
151
- return fail(`Request failed: ${err instanceof Error ? err.message : String(err)}`);
152
+ else if (!paymentsEnabled && !options.mppFetch) {
153
+ console.error(`[Nirium MCP] MPP tools disabled — ${paymentsDisabledReason}`);
152
154
  }
153
- }
154
- // ─── FREE TOOLS ───────────────────────────────────────────────
155
- server.tool('get_market_state', 'Fetch real-time market data: XLM/USDC price (CoinGecko), SDEX spread, base fee, Blend supply/borrow rate, CETES rate. Free — no API key required.', {}, async () => {
156
- const res = await fetch(`${API_URL}/api/tickers`);
157
- const data = await res.json();
158
- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
159
- });
160
- server.tool('get_loop_status', 'Check the autonomous scanning loop: running/stopped, scan count, uptime, last AI decision. Free.', {}, async () => {
161
- const res = await fetch(`${API_URL}/api/loop/status`);
162
- const data = await res.json();
163
- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
164
- });
165
- server.tool('start_loop', 'Start the autonomous market scanning loop. Requires NIRIUM_API_KEY env var.', {
166
- minProfitPercentage: zod_1.z.number().optional().describe('Minimum profit % to trigger (default: 0.3)'),
167
- maxBaseFee: zod_1.z.number().optional().describe('Max Stellar base fee in stroops (default: 500)'),
168
- }, async (args) => {
169
- const res = await fetch(`${API_URL}/api/loop/start`, {
155
+ // ─── Server ───────────────────────────────────────────────────
156
+ const server = new mcp_js_1.McpServer({ name: 'nirium-mcp-server', version: PKG_VERSION }, { capabilities: { tools: {} } });
157
+ const text = (body) => ({ content: [{ type: 'text', text: typeof body === 'string' ? body : JSON.stringify(body, null, 2) }] });
158
+ const fail = (message) => ({ content: [{ type: 'text', text: message }], isError: true });
159
+ // Un pago sin wallet o sin RPC de mainnet no puede firmarse: decirlo aquí evita
160
+ // que el modelo reciba un 402 opaco y lo reporte como "el servidor falló".
161
+ const paymentsUnavailable = () => paymentsEnabled ? null : fail(`Payment tools unavailable: ${paymentsDisabledReason}`);
162
+ // Los nodos gratuitos comparten forma: GET/POST → JSON, error legible.
163
+ async function callJson(url, init, doFetch = fetchFn) {
164
+ try {
165
+ const res = await doFetch(url, init);
166
+ if (!res.ok)
167
+ return fail(`Error ${res.status}: ${await res.text()}`);
168
+ return text(await res.json());
169
+ }
170
+ catch (err) {
171
+ return fail(`Request failed: ${err instanceof Error ? err.message : String(err)}`);
172
+ }
173
+ }
174
+ // ─── FREE TOOLS ───────────────────────────────────────────────
175
+ server.tool('get_market_state', 'Fetch real-time market data: XLM/USDC price (CoinGecko), SDEX spread, base fee, Blend supply/borrow rate, CETES rate. Free — no API key required.', {}, async () => callJson(`${API_URL}/api/tickers`, undefined, fetchFn));
176
+ server.tool('get_loop_status', 'Check the autonomous scanning loop: running/stopped, scan count, uptime, last AI decision. Free.', {}, async () => callJson(`${API_URL}/api/loop/status`, undefined, fetchFn));
177
+ server.tool('start_loop', 'Start the autonomous market scanning loop. Requires NIRIUM_API_KEY env var.', {
178
+ minProfitPercentage: zod_1.z.number().optional().describe('Minimum profit % to trigger (default: 0.3)'),
179
+ maxBaseFee: zod_1.z.number().optional().describe('Max Stellar base fee in stroops (default: 500)'),
180
+ }, async (args) => callJson(`${API_URL}/api/loop/start`, {
170
181
  method: 'POST',
171
182
  headers: { 'Content-Type': 'application/json', ...consentHeaders() },
172
183
  body: JSON.stringify({ config: args }),
173
- });
174
- const data = await res.json();
175
- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
176
- });
177
- server.tool('stop_loop', 'Stop the autonomous scanning loop. Requires NIRIUM_API_KEY env var.', {}, async () => {
178
- const res = await fetch(`${API_URL}/api/loop/stop`, {
184
+ }, fetchFn));
185
+ server.tool('stop_loop', 'Stop the autonomous scanning loop. Requires NIRIUM_API_KEY env var.', {}, async () => callJson(`${API_URL}/api/loop/stop`, {
179
186
  method: 'POST',
180
187
  headers: authHeaders(),
181
- });
182
- const data = await res.json();
183
- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
184
- });
185
- server.tool('execute_demo', 'Dry-run a strategy via Soroban simulation — no real transaction. Free.', {
186
- strategy: zod_1.z.string().describe('Strategy name: flash-loan-arb, path-arbitrage, cross-dex, blend-yield, soroswap-swap'),
187
- asset: zod_1.z.string().describe('Trading pair, e.g. XLM-USDC'),
188
- }, async (args) => {
189
- const res = await fetch(`${API_URL}/api/execute-demo`, {
188
+ }, fetchFn));
189
+ server.tool('execute_demo', 'Dry-run a strategy via Soroban simulation — no real transaction. Free.', {
190
+ strategy: zod_1.z.string().describe('Strategy name: flash-loan-arb, path-arbitrage, cross-dex, blend-yield, soroswap-swap'),
191
+ asset: zod_1.z.string().describe('Trading pair, e.g. XLM-USDC'),
192
+ }, async (args) => callJson(`${API_URL}/api/execute-demo`, {
190
193
  method: 'POST',
191
194
  headers: { 'Content-Type': 'application/json' },
192
195
  body: JSON.stringify(args),
196
+ }, fetchFn));
197
+ // ─── PAID TOOLS (x402) ────────────────────────────────────────
198
+ server.tool('get_premium_signals', 'PAID ($0.02 USDC via x402) — TESTNET ONLY: signals are produced by the autonomous loop, which runs on testnet; the mainnet box has no loop and returns 501 without charging. Signals reference testnet tokens, which have no monetary value, and are not a recommendation to buy, sell or hold anything. Requires funded Stellar wallet.', {
199
+ count: zod_1.z.number().optional().describe('Number of signals to fetch (default: 20, max: 100)'),
200
+ }, async (args) => paymentsUnavailable()
201
+ ?? callJson(`${API_URL}/api/v1/premium/signals?count=${args.count || 20}`, undefined, paidFetch));
202
+ server.tool('get_premium_market', 'PAID ($0.05 USDC via x402) — Market state with reference rates attributed to their source, network fee pressure, and a description of current network conditions. Factual data only: no recommendation, no advice, no signal to act. Requires funded Stellar wallet.', {}, async () => paymentsUnavailable()
203
+ ?? callJson(`${API_URL}/api/v1/premium/market`, undefined, paidFetch));
204
+ server.tool('execute_paid_strategy', 'PAID ($0.25 USDC via x402) — Execute a DeFi strategy on Stellar via Soroban. No Nirium account required — pay per execution. Requires funded Stellar wallet.', {
205
+ strategy: zod_1.z.string().describe('Strategy: flash-loan-arb | path-arbitrage | cross-dex | blend-yield | soroswap-swap'),
206
+ asset: zod_1.z.string().describe('Trading pair, e.g. XLM-USDC'),
207
+ params: zod_1.z.record(zod_1.z.unknown()).optional().describe('Strategy-specific parameters'),
208
+ }, async (args) => paymentsUnavailable()
209
+ ?? callJson(`${API_URL}/api/v1/premium/execute`, {
210
+ method: 'POST',
211
+ headers: { 'Content-Type': 'application/json' },
212
+ body: JSON.stringify(args),
213
+ }, paidFetch));
214
+ server.tool('get_wallet_info', 'Show the x402 (MPP experimental) wallet address and payment configuration for this MCP session. Free.', {}, async () => text({
215
+ address: STELLAR_PUBLIC_KEY || null,
216
+ network: STELLAR_NET,
217
+ rpcUrl: RPC_URL || null,
218
+ agentApiUrl: API_URL,
219
+ niriumApiKeySet: !!NIRIUM_API_KEY,
220
+ x402Enabled: paymentsEnabled,
221
+ mppEnabled: paymentsEnabled,
222
+ ...(paymentsEnabled ? {} : { paymentsDisabledReason }),
223
+ freeTools: [
224
+ 'get_market_state', 'get_loop_status', 'execute_demo', 'get_nodes',
225
+ 'anchor_audit_record', 'get_reporting_summary',
226
+ 'get_treasury_info', 'get_treasury_vault', 'get_treasury_vaults', 'get_treasury_strategy_asset',
227
+ ],
228
+ authenticatedTools: [
229
+ 'start_loop', 'stop_loop',
230
+ 'deploy_treasury_vault', 'deposit_to_treasury_vault', 'withdraw_from_treasury_vault',
231
+ 'set_treasury_rebalance_manager', 'build_treasury_rebalance', 'execute_treasury_rebalance',
232
+ 'submit_treasury_tx',
233
+ ],
234
+ paidToolsX402: ['get_premium_signals', 'get_premium_market', 'execute_paid_strategy'],
235
+ paidToolsMpp: ['get_mpp_signals', 'get_mpp_market'],
236
+ }));
237
+ // ─── NODE CATALOG + AUDIT + REPORTING (free) ──────────────────
238
+ server.tool('get_nodes', 'List the Nirium execution nodes with their live status, custody model and network (testnet/mainnet). Free — reads the protocol registry.', {}, async () => callJson(`${API_URL}/api/nodes`, undefined, fetchFn));
239
+ server.tool('anchor_audit_record', 'Anchor evidence to IPFS and get back a CID. Tamper-evident, not tamper-proof: a changed document no longer matches its CID. Not notarization. '
240
+ + 'Pass `hash` (sha-256 hex of your own file/event) or `record` (small JSON object, max 8KB). '
241
+ + 'Anchor hashes rather than raw personal data — IPFS content cannot be deleted. Free during open beta.', {
242
+ hash: zod_1.z.string().optional().describe('sha-256 hex (64 chars), optionally prefixed "sha-256:"'),
243
+ record: zod_1.z.record(zod_1.z.unknown()).optional().describe('Small JSON object to anchor verbatim (max 8KB)'),
244
+ txHash: zod_1.z.string().optional().describe('Related Stellar transaction hash, if any'),
245
+ network: zod_1.z.string().optional().describe('Network label to store with the anchor, e.g. mainnet'),
246
+ tag: zod_1.z.string().optional().describe('Free-form label to group anchors'),
247
+ }, async (args) => {
248
+ if (!args.hash && !args.record)
249
+ return fail('Provide `hash` (sha-256 of your evidence) or `record` (small JSON object).');
250
+ return callJson(`${API_URL}/api/audit/log`, {
251
+ method: 'POST',
252
+ headers: { 'Content-Type': 'application/json', ...authHeaders() },
253
+ body: JSON.stringify(args),
254
+ }, fetchFn);
193
255
  });
194
- const data = await res.json();
195
- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
196
- });
197
- // ─── PAID TOOLS (x402) ────────────────────────────────────────
198
- //
199
- // Each call automatically:
200
- // 1. Hits the endpoint → receives HTTP 402 + payment requirements
201
- // 2. Signs a Soroban auth entry for the USDC amount
202
- // 3. Submits X-PAYMENT header → receives 200 + data
203
- //
204
- // Cost: $0.02 USDC per signals call, $0.05 per market call, $0.25 per execution.
205
- // Requires STELLAR_SECRET_KEY env var with funded testnet wallet.
206
- //
207
- server.tool('get_premium_signals', 'PAID ($0.02 USDC via x402) — TESTNET ONLY: signals are produced by the autonomous loop, which runs on testnet; the mainnet box has no loop and returns 501 without charging. Signals reference testnet tokens, which have no monetary value, and are not a recommendation to buy, sell or hold anything. Requires funded Stellar wallet.', {
208
- count: zod_1.z.number().optional().describe('Number of signals to fetch (default: 20, max: 100)'),
209
- }, async (args) => paymentsUnavailable()
210
- ?? callJson(`${API_URL}/api/v1/premium/signals?count=${args.count || 20}`, undefined, paidFetch));
211
- server.tool('get_premium_market', 'PAID ($0.05 USDC via x402) — Market state with reference rates attributed to their source, network fee pressure, and a description of current network conditions. Factual data only: no recommendation, no advice, no signal to act. Requires funded Stellar wallet.', {}, async () => paymentsUnavailable()
212
- ?? callJson(`${API_URL}/api/v1/premium/market`, undefined, paidFetch));
213
- server.tool('execute_paid_strategy', 'PAID ($0.25 USDC via x402) — Execute a DeFi strategy on Stellar via Soroban. No Nirium account required — pay per execution. Requires funded Stellar wallet.', {
214
- strategy: zod_1.z.string().describe('Strategy: flash-loan-arb | path-arbitrage | cross-dex | blend-yield | soroswap-swap'),
215
- asset: zod_1.z.string().describe('Trading pair, e.g. XLM-USDC'),
216
- params: zod_1.z.record(zod_1.z.unknown()).optional().describe('Strategy-specific parameters'),
217
- }, async (args) => paymentsUnavailable()
218
- ?? callJson(`${API_URL}/api/v1/premium/execute`, {
256
+ server.tool('get_reporting_summary', 'Institutional-format summary of settled payouts, x402 payment receipts and IPFS anchors for a period. '
257
+ + 'Not certified regulatory reporting — filings remain the client\'s responsibility. Free.', {
258
+ from: zod_1.z.string().optional().describe('ISO start date, e.g. 2026-07-01 (defaults to last 30 days)'),
259
+ to: zod_1.z.string().optional().describe('ISO end date'),
260
+ network: zod_1.z.enum(['testnet', 'mainnet']).optional().describe('Filter by network; omit for all'),
261
+ }, async (args) => {
262
+ const q = new URLSearchParams(Object.entries(args).filter(([, v]) => v !== undefined)).toString();
263
+ return callJson(`${API_URL}/api/reporting/summary${q ? `?${q}` : ''}`, { headers: authHeaders() }, fetchFn);
264
+ });
265
+ // ─── PAID TOOLS (MPP) ─────────────────────────────────────────
266
+ //
267
+ // MPP Charge mode: no external facilitator.
268
+ // The payment transaction is a direct Soroban SAC invocation
269
+ // signed by the agent's STELLAR_SECRET_KEY, verified by the server.
270
+ //
271
+ // Advantage over x402: no Coinbase facilitator dependency.
272
+ // Both x402 and MPP tools are available — client chooses.
273
+ //
274
+ server.tool('get_mpp_signals', 'PAID ($0.02 USDC via MPP Charge) — TESTNET ONLY, same data as get_premium_signals, settled via direct Soroban SAC transfer with no external facilitator. Testnet tokens have no monetary value; this is not a recommendation to buy, sell or hold anything. Requires funded Stellar wallet.', {
275
+ count: zod_1.z.number().optional().describe('Number of signals to fetch (default: 20, max: 100)'),
276
+ }, async (args) => paymentsUnavailable()
277
+ ?? callJson(`${API_URL}/api/v1/mpp/signals?count=${args.count || 20}`, undefined, mppFetch));
278
+ server.tool('get_mpp_market', 'PAID ($0.05 USDC via MPP Charge) — Market state settled via direct Soroban SAC transfer, no external facilitator. Reference rates with their source, fee pressure, and network conditions. Factual data only: no recommendation or advice. Requires funded Stellar wallet.', {}, async () => paymentsUnavailable()
279
+ ?? callJson(`${API_URL}/api/v1/mpp/market`, undefined, mppFetch));
280
+ // ─── TREASURY (DeFindex) ───────────────────────────────────────
281
+ //
282
+ // Nirium never holds these funds. It holds the RebalanceManager role of a
283
+ // DeFindex vault the client deploys and owns. The four read tools below hit
284
+ // public GET routes — free, no key required. The write tools hit routes
285
+ // behind the agent's own auth (NIRIUM_API_KEY) and every one of them returns
286
+ // an UNSIGNED XDR *except* execute_treasury_rebalance, which is the one
287
+ // route the agent signs itself, with its own server-side key — never the
288
+ // caller's. Even then it cannot withdraw: rebalance() takes no destination
289
+ // address, so the funds never leave the vault.
290
+ //
291
+ server.tool('get_treasury_info', 'Treasury node metadata: what role Nirium holds on DeFindex vaults, what it can and cannot do, fees, security notes. Free.', {}, async () => callJson(`${API_URL}/api/treasury/info`, undefined, fetchFn));
292
+ server.tool('get_treasury_vault', "Read a DeFindex vault's roles, assets and managed funds. Pass `holder` to also get that account's balance in the vault's asset. Free.", {
293
+ vaultId: zod_1.z.string().describe('Vault contract id (C...)'),
294
+ holder: zod_1.z.string().optional().describe('Stellar account (G...) to check the balance of'),
295
+ }, async (args) => {
296
+ const q = args.holder ? `?holder=${encodeURIComponent(args.holder)}` : '';
297
+ return callJson(`${API_URL}/api/treasury/vault/${args.vaultId}${q}`, undefined, fetchFn);
298
+ });
299
+ server.tool('get_treasury_vaults', 'List DeFindex vaults Nirium has deployed or read, on the current network. Free.', {
300
+ manager: zod_1.z.string().optional().describe('Filter by vault Manager (G...)'),
301
+ }, async (args) => {
302
+ const q = args.manager ? `?manager=${encodeURIComponent(args.manager)}` : '';
303
+ return callJson(`${API_URL}/api/treasury/vaults${q}`, undefined, fetchFn);
304
+ });
305
+ server.tool('get_treasury_strategy_asset', 'Read which asset a DeFindex strategy manages, as declared by the strategy itself — pairs it correctly before deploying a vault. Free.', {
306
+ strategyId: zod_1.z.string().describe('Strategy contract id (C...)'),
307
+ }, async (args) => callJson(`${API_URL}/api/treasury/strategy/${args.strategyId}`, undefined, fetchFn));
308
+ server.tool('deploy_treasury_vault', "Build an UNSIGNED XDR to deploy a DeFindex vault. `manager` keeps control (rescue, pause, revoke); Nirium only ever holds `rebalanceManager`, which cannot withdraw or change roles. Sign the returned XDR with `caller` and broadcast it with submit_treasury_tx. Requires NIRIUM_API_KEY env var. On mainnet this is invite-only (institutional key); a free key gets a 403. Open on testnet.", {
309
+ manager: zod_1.z.string().describe('Stellar account (G...) that owns and controls the vault'),
310
+ caller: zod_1.z.string().describe('Stellar account (G...) that pays to deploy and signs the returned XDR'),
311
+ assets: zod_1.z.array(zod_1.z.object({
312
+ address: zod_1.z.string().describe('Asset contract id (C...)'),
313
+ strategies: zod_1.z.array(zod_1.z.object({
314
+ address: zod_1.z.string().describe('Strategy contract id (C...)'),
315
+ name: zod_1.z.string(),
316
+ })).min(1),
317
+ })).min(1),
318
+ name: zod_1.z.string(),
319
+ symbol: zod_1.z.string(),
320
+ emergencyManager: zod_1.z.string().optional().describe('Defaults to `manager`'),
321
+ feeReceiver: zod_1.z.string().optional().describe('Defaults to `manager`'),
322
+ rebalanceManager: zod_1.z.string().optional().describe("Defaults to Nirium's configured role address; required as an explicit value on mainnet"),
323
+ }, async (args) => callJson(`${API_URL}/api/treasury/deploy`, {
219
324
  method: 'POST',
220
- headers: { 'Content-Type': 'application/json' },
325
+ headers: { 'Content-Type': 'application/json', ...authHeaders() },
221
326
  body: JSON.stringify(args),
222
- }, paidFetch));
223
- server.tool('get_wallet_info', 'Show the x402 (MPP experimental) wallet address and payment configuration for this MCP session. Free.', {}, async () => text({
224
- address: STELLAR_PUBLIC_KEY || null,
225
- network: STELLAR_NET,
226
- rpcUrl: RPC_URL || null,
227
- agentApiUrl: API_URL,
228
- niriumApiKeySet: !!NIRIUM_API_KEY,
229
- x402Enabled: PAYMENTS_ENABLED,
230
- mppEnabled: PAYMENTS_ENABLED,
231
- ...(PAYMENTS_ENABLED ? {} : { paymentsDisabledReason: PAYMENTS_DISABLED_REASON }),
232
- freeTools: [
233
- 'get_market_state', 'get_loop_status', 'execute_demo', 'get_nodes',
234
- 'anchor_audit_record', 'get_reporting_summary',
235
- 'get_treasury_info', 'get_treasury_vault', 'get_treasury_vaults', 'get_treasury_strategy_asset',
236
- ],
237
- authenticatedTools: [
238
- 'start_loop', 'stop_loop',
239
- 'deploy_treasury_vault', 'deposit_to_treasury_vault', 'withdraw_from_treasury_vault',
240
- 'set_treasury_rebalance_manager', 'build_treasury_rebalance', 'execute_treasury_rebalance',
241
- 'submit_treasury_tx',
242
- ],
243
- paidToolsX402: ['get_premium_signals', 'get_premium_market', 'execute_paid_strategy'],
244
- paidToolsMpp: ['get_mpp_signals', 'get_mpp_market'],
245
- }));
246
- // ─── NODE CATALOG + AUDIT + REPORTING (free) ──────────────────
247
- //
248
- // Los nodos non-custodial que ya corren en mainnet. Ninguno mueve fondos:
249
- // el catálogo es lectura, el anclaje sube un hash a IPFS y el reporting
250
- // agrega recibos existentes — por eso no llevan wallet ni pago.
251
- //
252
- server.tool('get_nodes', 'List the Nirium execution nodes with their live status, custody model and network (testnet/mainnet). Free — reads the protocol registry.', {}, async () => callJson(`${API_URL}/api/nodes`));
253
- server.tool('anchor_audit_record', 'Anchor evidence to IPFS and get back a CID. Tamper-evident, not tamper-proof: a changed document no longer matches its CID. Not notarization. '
254
- + 'Pass `hash` (sha-256 hex of your own file/event) or `record` (small JSON object, max 8KB). '
255
- + 'Anchor hashes rather than raw personal data — IPFS content cannot be deleted. Free during open beta.', {
256
- hash: zod_1.z.string().optional().describe('sha-256 hex (64 chars), optionally prefixed "sha-256:"'),
257
- record: zod_1.z.record(zod_1.z.unknown()).optional().describe('Small JSON object to anchor verbatim (max 8KB)'),
258
- txHash: zod_1.z.string().optional().describe('Related Stellar transaction hash, if any'),
259
- network: zod_1.z.string().optional().describe('Network label to store with the anchor, e.g. mainnet'),
260
- tag: zod_1.z.string().optional().describe('Free-form label to group anchors'),
261
- }, async (args) => {
262
- if (!args.hash && !args.record)
263
- return fail('Provide `hash` (sha-256 of your evidence) or `record` (small JSON object).');
264
- return callJson(`${API_URL}/api/audit/log`, {
327
+ }, fetchFn));
328
+ server.tool('deposit_to_treasury_vault', 'Build an UNSIGNED XDR to deposit into a DeFindex vault. Sign with `from` and broadcast it with submit_treasury_tx. Requires NIRIUM_API_KEY env var. On mainnet this is invite-only (institutional key); a free key gets a 403. Open on testnet.', {
329
+ vault: zod_1.z.string().describe('Vault contract id (C...)'),
330
+ from: zod_1.z.string().describe('Stellar account (G...) funding the deposit and signing the returned XDR'),
331
+ amounts: zod_1.z.array(zod_1.z.string()).min(1).describe('One amount per vault asset, in stroops, as strings — an i128 does not survive a JSON number'),
332
+ invest: zod_1.z.boolean().optional().describe('Invest the deposit into the strategy immediately. Default true.'),
333
+ maxSlippageBps: zod_1.z.number().optional(),
334
+ }, async (args) => callJson(`${API_URL}/api/treasury/deposit`, {
265
335
  method: 'POST',
266
336
  headers: { 'Content-Type': 'application/json', ...authHeaders() },
267
337
  body: JSON.stringify(args),
338
+ }, fetchFn));
339
+ server.tool('withdraw_from_treasury_vault', 'Build an UNSIGNED XDR to withdraw from a DeFindex vault. Omit `shares` to withdraw everything the account holds. Sign with `from` and broadcast it with submit_treasury_tx. Requires NIRIUM_API_KEY env var.', {
340
+ vault: zod_1.z.string().describe('Vault contract id (C...)'),
341
+ from: zod_1.z.string().describe('Stellar account (G...) holding the vault shares and signing the returned XDR'),
342
+ shares: zod_1.z.string().optional().describe('Vault shares to redeem, as an integer string. Omit to withdraw everything.'),
343
+ maxSlippageBps: zod_1.z.number().optional(),
344
+ }, async (args) => callJson(`${API_URL}/api/treasury/withdraw`, {
345
+ method: 'POST',
346
+ headers: { 'Content-Type': 'application/json', ...authHeaders() },
347
+ body: JSON.stringify(args),
348
+ }, fetchFn));
349
+ server.tool('set_treasury_rebalance_manager', "Build an UNSIGNED XDR handing the RebalanceManager role to a new address. Only the vault's current Manager can sign it — the same door that grants Nirium the role also revokes it. Requires NIRIUM_API_KEY env var. On mainnet this is invite-only (institutional key); a free key gets a 403. Open on testnet.", {
350
+ vault: zod_1.z.string().describe('Vault contract id (C...)'),
351
+ manager: zod_1.z.string().describe("The vault's current Manager (G...), who must sign the returned XDR"),
352
+ rebalanceManager: zod_1.z.string().describe('The new RebalanceManager address (G...)'),
353
+ }, async (args) => callJson(`${API_URL}/api/treasury/set-rebalance-manager`, {
354
+ method: 'POST',
355
+ headers: { 'Content-Type': 'application/json', ...authHeaders() },
356
+ body: JSON.stringify(args),
357
+ }, fetchFn));
358
+ const treasuryInstruction = zod_1.z.object({
359
+ kind: zod_1.z.enum(['Unwind', 'Invest']),
360
+ strategy: zod_1.z.string().describe('Strategy contract id (C...)'),
361
+ amount: zod_1.z.string().describe('Stroops, as a string — an i128 does not survive a JSON number'),
268
362
  });
269
- });
270
- server.tool('get_reporting_summary', 'Institutional-format summary of settled payouts, x402 payment receipts and IPFS anchors for a period. '
271
- + 'Not certified regulatory reporting — filings remain the client\'s responsibility. Free.', {
272
- from: zod_1.z.string().optional().describe('ISO start date, e.g. 2026-07-01 (defaults to last 30 days)'),
273
- to: zod_1.z.string().optional().describe('ISO end date'),
274
- network: zod_1.z.enum(['testnet', 'mainnet']).optional().describe('Filter by network; omit for all'),
275
- }, async (args) => {
276
- const q = new URLSearchParams(Object.entries(args).filter(([, v]) => v !== undefined)).toString();
277
- return callJson(`${API_URL}/api/reporting/summary${q ? `?${q}` : ''}`, { headers: authHeaders() });
278
- });
279
- // ─── PAID TOOLS (MPP) ─────────────────────────────────────────
280
- //
281
- // MPP Charge mode: no external facilitator.
282
- // The client signs a Soroban SAC transfer and sends it inline.
283
- // Server verifies the on-chain transfer and returns 200.
284
- //
285
- // Advantage over x402: no Coinbase facilitator dependency.
286
- // Both x402 and MPP tools are available — client chooses.
287
- //
288
- server.tool('get_mpp_signals', 'PAID ($0.02 USDC via MPP Charge) — TESTNET ONLY, same data as get_premium_signals, settled via direct Soroban SAC transfer with no external facilitator. Testnet tokens have no monetary value; this is not a recommendation to buy, sell or hold anything. Requires funded Stellar wallet.', {
289
- count: zod_1.z.number().optional().describe('Number of signals to fetch (default: 20, max: 100)'),
290
- }, async (args) => paymentsUnavailable()
291
- ?? callJson(`${API_URL}/api/v1/mpp/signals?count=${args.count || 20}`, undefined, mppFetch));
292
- server.tool('get_mpp_market', 'PAID ($0.05 USDC via MPP Charge) — Market state settled via direct Soroban SAC transfer, no external facilitator. Reference rates with their source, fee pressure, and network conditions. Factual data only: no recommendation or advice. Requires funded Stellar wallet.', {}, async () => paymentsUnavailable()
293
- ?? callJson(`${API_URL}/api/v1/mpp/market`, undefined, mppFetch));
294
- // ─── TREASURY (DeFindex) ───────────────────────────────────────
295
- //
296
- // Nirium never holds these funds. It holds the RebalanceManager role of a
297
- // DeFindex vault the client deploys and owns. The four read tools below hit
298
- // public GET routes — free, no key required. The write tools hit routes
299
- // behind the agent's own auth (NIRIUM_API_KEY) and every one of them returns
300
- // an UNSIGNED XDR *except* execute_treasury_rebalance, which is the one
301
- // route the agent signs itself, with its own server-side key — never the
302
- // caller's. Even then it cannot withdraw: rebalance() takes no destination
303
- // address, so the funds never leave the vault.
304
- //
305
- server.tool('get_treasury_info', 'Treasury node metadata: what role Nirium holds on DeFindex vaults, what it can and cannot do, fees, security notes. Free.', {}, async () => callJson(`${API_URL}/api/treasury/info`));
306
- server.tool('get_treasury_vault', "Read a DeFindex vault's roles, assets and managed funds. Pass `holder` to also get that account's balance in the vault's asset. Free.", {
307
- vaultId: zod_1.z.string().describe('Vault contract id (C...)'),
308
- holder: zod_1.z.string().optional().describe('Stellar account (G...) to check the balance of'),
309
- }, async (args) => {
310
- const q = args.holder ? `?holder=${encodeURIComponent(args.holder)}` : '';
311
- return callJson(`${API_URL}/api/treasury/vault/${args.vaultId}${q}`);
312
- });
313
- server.tool('get_treasury_vaults', 'List DeFindex vaults Nirium has deployed or read, on the current network. Free.', {
314
- manager: zod_1.z.string().optional().describe('Filter by vault Manager (G...)'),
315
- }, async (args) => {
316
- const q = args.manager ? `?manager=${encodeURIComponent(args.manager)}` : '';
317
- return callJson(`${API_URL}/api/treasury/vaults${q}`);
318
- });
319
- server.tool('get_treasury_strategy_asset', 'Read which asset a DeFindex strategy manages, as declared by the strategy itself — pairs it correctly before deploying a vault. Free.', {
320
- strategyId: zod_1.z.string().describe('Strategy contract id (C...)'),
321
- }, async (args) => callJson(`${API_URL}/api/treasury/strategy/${args.strategyId}`));
322
- server.tool('deploy_treasury_vault', "Build an UNSIGNED XDR to deploy a DeFindex vault. `manager` keeps control (rescue, pause, revoke); Nirium only ever holds `rebalanceManager`, which cannot withdraw or change roles. Sign the returned XDR with `caller` and broadcast it with submit_treasury_tx. Requires NIRIUM_API_KEY env var. On mainnet this is invite-only (institutional key); a free key gets a 403. Open on testnet.", {
323
- manager: zod_1.z.string().describe('Stellar account (G...) that owns and controls the vault'),
324
- caller: zod_1.z.string().describe('Stellar account (G...) that pays to deploy and signs the returned XDR'),
325
- assets: zod_1.z.array(zod_1.z.object({
326
- address: zod_1.z.string().describe('Asset contract id (C...)'),
327
- strategies: zod_1.z.array(zod_1.z.object({
328
- address: zod_1.z.string().describe('Strategy contract id (C...)'),
329
- name: zod_1.z.string(),
330
- })).min(1),
331
- })).min(1),
332
- name: zod_1.z.string(),
333
- symbol: zod_1.z.string(),
334
- emergencyManager: zod_1.z.string().optional().describe('Defaults to `manager`'),
335
- feeReceiver: zod_1.z.string().optional().describe('Defaults to `manager`'),
336
- rebalanceManager: zod_1.z.string().optional().describe("Defaults to Nirium's configured role address; required as an explicit value on mainnet"),
337
- }, async (args) => callJson(`${API_URL}/api/treasury/deploy`, {
338
- method: 'POST',
339
- headers: { 'Content-Type': 'application/json', ...authHeaders() },
340
- body: JSON.stringify(args),
341
- }));
342
- server.tool('deposit_to_treasury_vault', 'Build an UNSIGNED XDR to deposit into a DeFindex vault. Sign with `from` and broadcast it with submit_treasury_tx. Requires NIRIUM_API_KEY env var. On mainnet this is invite-only (institutional key); a free key gets a 403. Open on testnet.', {
343
- vault: zod_1.z.string().describe('Vault contract id (C...)'),
344
- from: zod_1.z.string().describe('Stellar account (G...) funding the deposit and signing the returned XDR'),
345
- amounts: zod_1.z.array(zod_1.z.string()).min(1).describe('One amount per vault asset, in stroops, as strings — an i128 does not survive a JSON number'),
346
- invest: zod_1.z.boolean().optional().describe('Invest the deposit into the strategy immediately. Default true.'),
347
- maxSlippageBps: zod_1.z.number().optional(),
348
- }, async (args) => callJson(`${API_URL}/api/treasury/deposit`, {
349
- method: 'POST',
350
- headers: { 'Content-Type': 'application/json', ...authHeaders() },
351
- body: JSON.stringify(args),
352
- }));
353
- server.tool('withdraw_from_treasury_vault', 'Build an UNSIGNED XDR to withdraw from a DeFindex vault. Omit `shares` to withdraw everything the account holds. Sign with `from` and broadcast it with submit_treasury_tx. Requires NIRIUM_API_KEY env var.', {
354
- vault: zod_1.z.string().describe('Vault contract id (C...)'),
355
- from: zod_1.z.string().describe('Stellar account (G...) holding the vault shares and signing the returned XDR'),
356
- shares: zod_1.z.string().optional().describe('Vault shares to redeem, as an integer string. Omit to withdraw everything.'),
357
- maxSlippageBps: zod_1.z.number().optional(),
358
- }, async (args) => callJson(`${API_URL}/api/treasury/withdraw`, {
359
- method: 'POST',
360
- headers: { 'Content-Type': 'application/json', ...authHeaders() },
361
- body: JSON.stringify(args),
362
- }));
363
- server.tool('set_treasury_rebalance_manager', "Build an UNSIGNED XDR handing the RebalanceManager role to a new address. Only the vault's current Manager can sign it — the same door that grants Nirium the role also revokes it. Requires NIRIUM_API_KEY env var. On mainnet this is invite-only (institutional key); a free key gets a 403. Open on testnet.", {
364
- vault: zod_1.z.string().describe('Vault contract id (C...)'),
365
- manager: zod_1.z.string().describe("The vault's current Manager (G...), who must sign the returned XDR"),
366
- rebalanceManager: zod_1.z.string().describe('The new RebalanceManager address (G...)'),
367
- }, async (args) => callJson(`${API_URL}/api/treasury/set-rebalance-manager`, {
368
- method: 'POST',
369
- headers: { 'Content-Type': 'application/json', ...authHeaders() },
370
- body: JSON.stringify(args),
371
- }));
372
- const treasuryInstruction = zod_1.z.object({
373
- kind: zod_1.z.enum(['Unwind', 'Invest']),
374
- strategy: zod_1.z.string().describe('Strategy contract id (C...)'),
375
- amount: zod_1.z.string().describe('Stroops, as a string — an i128 does not survive a JSON number'),
376
- });
377
- server.tool('build_treasury_rebalance', "Build an UNSIGNED rebalance XDR — Unwind/Invest between a vault's own strategies only; no other instruction is expressible, and none takes a destination address. Sign with the vault's RebalanceManager and broadcast it with submit_treasury_tx. Requires NIRIUM_API_KEY env var. On mainnet this is invite-only (institutional key); a free key gets a 403. Open on testnet.", {
378
- vault: zod_1.z.string().describe('Vault contract id (C...)'),
379
- instructions: zod_1.z.array(treasuryInstruction).min(1),
380
- caller: zod_1.z.string().optional().describe("Defaults to Nirium's configured rebalanceManager address"),
381
- }, async (args) => callJson(`${API_URL}/api/treasury/rebalance`, {
382
- method: 'POST',
383
- headers: { 'Content-Type': 'application/json', ...authHeaders() },
384
- body: JSON.stringify(args),
385
- }));
386
- server.tool('execute_treasury_rebalance', "Sign and submit a rebalance with Nirium's OWN RebalanceManager key, server-side, and wait for confirmation — the only treasury tool that signs anything itself, and it still cannot withdraw funds. Only available where that key actually lives; a receive-only mainnet box returns 501 by design, not a broken 500. Requires NIRIUM_API_KEY env var.", {
387
- vault: zod_1.z.string().describe('Vault contract id (C...)'),
388
- instructions: zod_1.z.array(treasuryInstruction).min(1),
389
- caller: zod_1.z.string().optional().describe("Defaults to Nirium's configured rebalanceManager address"),
390
- }, async (args) => callJson(`${API_URL}/api/treasury/rebalance/execute`, {
391
- method: 'POST',
392
- headers: { 'Content-Type': 'application/json', ...authHeaders() },
393
- body: JSON.stringify(args),
394
- }));
395
- server.tool('submit_treasury_tx', 'Broadcast a treasury XDR you already signed (deploy/deposit/withdraw/rebalance/set-rebalance-manager) and wait for confirmation. Requires NIRIUM_API_KEY env var.', {
396
- xdr: zod_1.z.string().describe('Signed transaction XDR'),
397
- }, async (args) => callJson(`${API_URL}/api/treasury/submit`, {
398
- method: 'POST',
399
- headers: { 'Content-Type': 'application/json', ...authHeaders() },
400
- body: JSON.stringify(args),
401
- }));
363
+ server.tool('build_treasury_rebalance', "Build an UNSIGNED rebalance XDR — Unwind/Invest between a vault's own strategies only; no other instruction is expressible, and none takes a destination address. Sign with the vault's RebalanceManager and broadcast it with submit_treasury_tx. Requires NIRIUM_API_KEY env var. On mainnet this is invite-only (institutional key); a free key gets a 403. Open on testnet.", {
364
+ vault: zod_1.z.string().describe('Vault contract id (C...)'),
365
+ instructions: zod_1.z.array(treasuryInstruction).min(1),
366
+ caller: zod_1.z.string().optional().describe("Defaults to Nirium's configured rebalanceManager address"),
367
+ }, async (args) => callJson(`${API_URL}/api/treasury/rebalance`, {
368
+ method: 'POST',
369
+ headers: { 'Content-Type': 'application/json', ...authHeaders() },
370
+ body: JSON.stringify(args),
371
+ }, fetchFn));
372
+ server.tool('execute_treasury_rebalance', "Sign and submit a rebalance with Nirium's OWN RebalanceManager key, server-side, and wait for confirmation — the only treasury tool that signs anything itself, and it still cannot withdraw funds. Only available where that key actually lives; a receive-only mainnet box returns 501 by design, not a broken 500. Requires NIRIUM_API_KEY env var.", {
373
+ vault: zod_1.z.string().describe('Vault contract id (C...)'),
374
+ instructions: zod_1.z.array(treasuryInstruction).min(1),
375
+ caller: zod_1.z.string().optional().describe("Defaults to Nirium's configured rebalanceManager address"),
376
+ }, async (args) => callJson(`${API_URL}/api/treasury/rebalance/execute`, {
377
+ method: 'POST',
378
+ headers: { 'Content-Type': 'application/json', ...authHeaders() },
379
+ body: JSON.stringify(args),
380
+ }, fetchFn));
381
+ server.tool('submit_treasury_tx', 'Broadcast a treasury XDR you already signed (deploy/deposit/withdraw/rebalance/set-rebalance-manager) and wait for confirmation. Requires NIRIUM_API_KEY env var.', {
382
+ xdr: zod_1.z.string().describe('Signed transaction XDR'),
383
+ }, async (args) => callJson(`${API_URL}/api/treasury/submit`, {
384
+ method: 'POST',
385
+ headers: { 'Content-Type': 'application/json', ...authHeaders() },
386
+ body: JSON.stringify(args),
387
+ }, fetchFn));
388
+ return server;
389
+ }
402
390
  // ─── Start ────────────────────────────────────────────────────
403
391
  async function main() {
392
+ const server = createNiriumMcpServer();
404
393
  const transport = new stdio_js_1.StdioServerTransport();
405
394
  await server.connect(transport);
406
395
  console.error(`[Nirium MCP] v${PKG_VERSION} running on stdio`);
407
- console.error(`[Nirium MCP] Agent API: ${API_URL}`);
408
- console.error(`[Nirium MCP] NIRIUM_API_KEY set: ${!!NIRIUM_API_KEY}`);
409
- console.error(`[Nirium MCP] x402 enabled: ${!!STELLAR_KEY}`);
410
- console.error(`[Nirium MCP] MPP Charge enabled: ${!!STELLAR_KEY}`);
396
+ console.error(`[Nirium MCP] Agent API: ${process.env.AGENT_API_URL || 'http://127.0.0.1:3002'}`);
397
+ console.error(`[Nirium MCP] NIRIUM_API_KEY set: ${!!process.env.NIRIUM_API_KEY}`);
398
+ console.error(`[Nirium MCP] x402 enabled: ${!!process.env.STELLAR_SECRET_KEY}`);
399
+ console.error(`[Nirium MCP] MPP Charge enabled: ${!!process.env.STELLAR_SECRET_KEY}`);
400
+ }
401
+ const isDirectRun = typeof require !== 'undefined'
402
+ ? require.main === module
403
+ : process.argv[1] && (process.argv[1].endsWith('index.js') || process.argv[1].endsWith('index.ts') || process.argv[1].includes('nirium-mcp'));
404
+ if (isDirectRun) {
405
+ main().catch((err) => {
406
+ console.error('[Nirium MCP] Fatal error:', err);
407
+ process.exit(1);
408
+ });
411
409
  }
412
- main().catch((err) => {
413
- console.error('[Nirium MCP] Fatal error:', err);
414
- process.exit(1);
415
- });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nirium-mcp",
3
- "version": "0.6.9",
3
+ "version": "0.6.10",
4
4
  "description": "MCP server that lets an AI assistant (Claude, Cursor, VS Code Copilot) use Nirium on Stellar: paid x402 endpoints in USDC, receipts anyone can verify and treasury vault tools. MPP tools are experimental.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -29,7 +29,8 @@
29
29
  "prepublishOnly": "npm run build",
30
30
  "build": "tsc",
31
31
  "start": "node dist/index.js",
32
- "dev": "tsc --watch"
32
+ "dev": "tsc --watch",
33
+ "test": "tsx --test test/*.test.ts"
33
34
  },
34
35
  "dependencies": {
35
36
  "@modelcontextprotocol/sdk": "^1.27.1",