@poincaretrade/mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,108 @@
1
+ Business Source License 1.1
2
+
3
+ License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved.
4
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
5
+
6
+ -----------------------------------------------------------------------------
7
+
8
+ Parameters
9
+
10
+ Licensor: Prakhar Srivastava
11
+
12
+ Licensed Work: Poincare (the Poincare Uniswap v4 hook, including the
13
+ CUSUM change detector, directional-efficiency signal,
14
+ asymmetric hyperbolic curve, control law, lens, and
15
+ associated frontend and analysis code)
16
+ The Licensed Work is (c) 2026 Prakhar Srivastava.
17
+
18
+ Additional Use Grant: Any uses listed and defined at this time are none.
19
+ Production use of the Licensed Work, or of any derivative
20
+ of it, requires a commercial license from the Licensor.
21
+ Use for review, testing, security research, and
22
+ non-production evaluation is permitted.
23
+
24
+ Change Date: 2030-07-19
25
+
26
+ Change License: MIT
27
+
28
+ For information about alternative licensing arrangements for the Licensed Work,
29
+ please contact srivastavaprakhar3010@gmail.com.
30
+
31
+ -----------------------------------------------------------------------------
32
+
33
+ Notice
34
+
35
+ The Business Source License (this document, or the "License") is not an Open
36
+ Source license. However, the Licensed Work will eventually be made available
37
+ under an Open Source License, as stated in this License.
38
+
39
+ -----------------------------------------------------------------------------
40
+
41
+ Terms
42
+
43
+ The Licensor hereby grants you the right to copy, modify, create derivative
44
+ works, redistribute, and make non-production use of the Licensed Work. The
45
+ Licensor may make an Additional Use Grant, above, permitting limited
46
+ production use.
47
+
48
+ Effective on the Change Date, or the fourth anniversary of the first publicly
49
+ available distribution of a specific version of the Licensed Work under this
50
+ License, whichever comes first, the Licensor hereby grants you rights under
51
+ the terms of the Change License, and the rights granted in the paragraph
52
+ above terminate.
53
+
54
+ If your use of the Licensed Work does not comply with the requirements
55
+ currently in effect as described in this License, you must purchase a
56
+ commercial license from the Licensor, its affiliated entities, or authorized
57
+ resellers, or you must refrain from using the Licensed Work.
58
+
59
+ All copies of the original and modified Licensed Work, and derivative works
60
+ of the Licensed Work, are subject to this License. This License applies
61
+ separately for each version of the Licensed Work and the Change Date may vary
62
+ for each version of the Licensed Work released by Licensor.
63
+
64
+ You must conspicuously display this License on each original or modified copy
65
+ of the Licensed Work. If you receive the Licensed Work in original or
66
+ modified form from a third party, the terms and conditions set forth in this
67
+ License apply to your use of that work.
68
+
69
+ Any use of the Licensed Work in violation of this License will automatically
70
+ terminate your rights under this License for the current and all other
71
+ versions of the Licensed Work.
72
+
73
+ This License does not grant you any right in any trademark or logo of
74
+ Licensor or its affiliates (provided that you may use a trademark or logo of
75
+ Licensor as expressly required by this License).
76
+
77
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
78
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
79
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
80
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
81
+ TITLE.
82
+
83
+ MariaDB hereby grants you permission to use this License's text to license
84
+ your works, and to refer to it using the trademark "Business Source License",
85
+ as long as you comply with the Covenants of Licensor below.
86
+
87
+ -----------------------------------------------------------------------------
88
+
89
+ Covenants of Licensor
90
+
91
+ In consideration of the right to use this License's text and the "Business
92
+ Source License" name and trademark, Licensor covenants to MariaDB, and to all
93
+ other recipients of the licensed work to be provided by Licensor:
94
+
95
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
96
+ or a license that is compatible with GPL Version 2.0 or a later version,
97
+ where "compatible" means that software provided under the Change License can
98
+ be included in a program with software provided under GPL Version 2.0 or a
99
+ later version. Licensor may specify additional Change Licenses without
100
+ limitation.
101
+
102
+ 2. To either: (a) specify an additional grant of rights to use that does not
103
+ impose any additional restriction on the right granted in this License, as
104
+ the Additional Use Grant; or (b) insert the text "None".
105
+
106
+ 3. To specify a Change Date.
107
+
108
+ 4. Not to modify this License in any other way.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @poincaretrade/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
+ An [MCP](https://modelcontextprotocol.io) server that gives Claude, or any MCP client, **Poincaré**'s trend
4
+ regime, swap quotes and spread-aware DCA orders as 15 tools. It reads the live pool on Unichain Sepolia and
5
+ returns **unsigned** transactions; nothing is ever sent unless you add your own key and the agent calls a
6
+ tool with `send: true`.
7
+
8
+ Full docs: **https://www.poincaretrade.in/#/developers/mcp**
9
+
10
+ ## Add it
11
+
12
+ **Claude Code**
13
+
14
+ ```sh
15
+ claude mcp add poincare -- npx -y @poincaretrade/mcp
16
+ ```
17
+
18
+ **Claude Desktop and other clients** (`mcpServers` in the client's config):
19
+
20
+ ```json
21
+ {
22
+ "mcpServers": {
23
+ "poincare": { "command": "npx", "args": ["-y", "@poincaretrade/mcp"] }
24
+ }
25
+ }
26
+ ```
27
+
28
+ | Variable | Meaning |
29
+ |---|---|
30
+ | `POINCARE_RPC_URL` | RPC endpoint (default: the public Unichain Sepolia RPC) |
31
+ | `POINCARE_DCA_ADDRESS` | Overrides the live PoincareDCA |
32
+ | `POINCARE_PRIVATE_KEY` | Optional. With it, tools called with `send: true` broadcast from this key, and owner-only tools refuse orders it does not own. Use a testnet key you are happy to delegate |
33
+
34
+ ## Tools
35
+
36
+ `get_regime` · `get_regime_history` · `wait_for_regime_change` · `quote` · `dca_plan_order` ·
37
+ `dca_create_order` · `dca_get_order` · `dca_list_orders` · `dca_preview_slice` · `dca_pause_order` ·
38
+ `dca_resume_order` · `dca_edit_order` · `dca_execute_slice` · `dca_cancel_order` · `dca_close_expired`
39
+
40
+ Try: *"Is the Poincaré pool trending right now, and which side pays?"* or *"Plan a DCA that buys 500 USDC
41
+ of WETH over a day without ever paying the trend spread."*
42
+
43
+ **Status:** testnet research preview. Licensed under the Business Source License 1.1 (see LICENSE).
@@ -0,0 +1,460 @@
1
+ // src/server.ts
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import {
4
+ DCA_STATUS_TEXT,
5
+ buildOrderParams,
6
+ diffRegime,
7
+ minPriceWadToLimit,
8
+ orderIdFromReceipt,
9
+ planSlice,
10
+ progressOf,
11
+ spentOf,
12
+ formatAmount,
13
+ trendOnsets,
14
+ wadToBpsUp
15
+ } from "@poincaretrade/sdk";
16
+ import { getAddress } from "viem";
17
+ import { z } from "zod";
18
+
19
+ // src/format.ts
20
+ function jsonSafe(v) {
21
+ if (typeof v === "bigint") return v.toString();
22
+ if (Array.isArray(v)) return v.map(jsonSafe);
23
+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, jsonSafe(x)]));
24
+ return v;
25
+ }
26
+ function ok(data) {
27
+ const safe = jsonSafe(data);
28
+ return { content: [{ type: "text", text: JSON.stringify(safe, null, 2) }], structuredContent: safe };
29
+ }
30
+ function fail(err) {
31
+ const message = err instanceof Error && err.name === "DcaNotDeployedError" ? "The DCA contract address is not configured: set POINCARE_DCA_ADDRESS in the MCP server's environment." : err instanceof Error ? err.message : String(err);
32
+ return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
33
+ }
34
+ var pct = (x, dp = 2) => `${(x * 100).toFixed(dp)}%`;
35
+ function describeRegime(r) {
36
+ const trend = r.trend === "none" ? "No confirmed trend" : `Confirmed ${r.trend}-trend (${r.withTrendSide === "buy" ? "buyers" : "sellers"} push with it)`;
37
+ const charge = r.chargedSide === null ? "no side pays a trend spread right now" : `${r.chargedSide === "buy" ? "buys" : "sells"} pay a ${pct(r.spread[r.chargedSide])} spread to LPs and ${r.chargedSide === "buy" ? "sells" : "buys"} trade free`;
38
+ const ev = `evidence ${Math.round(r.evidence.progress * 100)}% of the threshold${r.gated ? " (gated: moves read as chop)" : ""}`;
39
+ return `${trend}; ${charge}; ${ev}. Mid price ${r.price.toFixed(2)} USDC per WETH, base fee ${pct(r.fee)}.`;
40
+ }
41
+
42
+ // src/server.ts
43
+ var side = z.enum(["buy", "sell"]).describe("buy = pay USDC for WETH; sell = pay WETH for USDC");
44
+ var address = z.string().regex(/^0x[0-9a-fA-F]{40}$/, "an 0x address");
45
+ var orderId = z.union([z.number().int().positive(), z.string().regex(/^\d+$/)]).describe("DCA order id");
46
+ var sendFlag = z.boolean().optional().describe("Broadcast with the key configured in POINCARE_PRIVATE_KEY. Omit or false to get unsigned transactions instead.");
47
+ var orderShape = {
48
+ side,
49
+ amount: z.string().regex(/^\d+(\.\d+)?$/).describe('Total budget in the input token (USDC to buy, WETH to sell), e.g. "1000"'),
50
+ slices: z.number().int().min(1).max(1e4).describe("Number of fills"),
51
+ intervalSec: z.number().int().min(60).describe("Seconds between fills (>= 60)"),
52
+ startTime: z.number().int().optional().describe("Unix seconds; omit to start immediately"),
53
+ deadline: z.number().int().optional().describe("Unix seconds; default one spare interval after the last planned fill"),
54
+ maxSpreadBps: z.number().int().min(0).max(1e4).optional().describe("Skip a fill while the trend spread on this side exceeds this (bps). 0 = never pay the spread. Default 10000 (no cap)"),
55
+ pauseOnTrend: z.boolean().optional().describe("Hold fills while a trend runs with this side (the side the pool charges); resume when it ends. Default false"),
56
+ catchUp: z.boolean().optional().describe("Grow later fills to make up skipped ones, so the order completes by the deadline. Default true"),
57
+ maxSlippageBps: z.number().int().min(0).max(1e4).optional().describe("Max shortfall vs the in-transaction quote (bps). Default 50"),
58
+ limitPrice: z.string().regex(/^\d+(\.\d+)?$/).optional().describe("USDC per WETH: the most a buy pays / the least a sell accepts"),
59
+ recipient: address.optional().describe("Receives every fill; default the owner")
60
+ };
61
+ function toInput(a) {
62
+ return {
63
+ side: a.side,
64
+ amount: a.amount,
65
+ slices: a.slices,
66
+ interval: a.intervalSec,
67
+ startTime: a.startTime,
68
+ deadline: a.deadline,
69
+ maxSpreadBps: a.maxSpreadBps,
70
+ pauseOnTrend: a.pauseOnTrend,
71
+ catchUp: a.catchUp,
72
+ maxSlippageBps: a.maxSlippageBps,
73
+ limitPrice: a.limitPrice,
74
+ recipient: a.recipient
75
+ };
76
+ }
77
+ function orderView(o) {
78
+ const tokenIn = o.side === "buy" ? "USDC" : "WETH";
79
+ const tokenOut = o.side === "buy" ? "WETH" : "USDC";
80
+ return {
81
+ ...o,
82
+ tokenIn,
83
+ tokenOut,
84
+ amountInFormatted: `${formatAmount(o.amountIn)} ${tokenIn}`,
85
+ remainingFormatted: `${formatAmount(o.remaining)} ${tokenIn}`,
86
+ amountOutFormatted: `${formatAmount(o.amountOut)} ${tokenOut}`,
87
+ spentFormatted: `${formatAmount(spentOf(o))} ${tokenIn}`,
88
+ refundedFormatted: `${formatAmount(o.refunded)} ${tokenIn}`,
89
+ progress: progressOf(o),
90
+ limitPrice: minPriceWadToLimit(o.side, o.minPriceWad),
91
+ startsAt: new Date(Number(o.startTime) * 1e3).toISOString(),
92
+ deadlineAt: new Date(Number(o.deadline) * 1e3).toISOString()
93
+ };
94
+ }
95
+ function createServer(opts) {
96
+ const { poincare, signer } = opts;
97
+ const now = opts.now ?? (() => Math.floor(Date.now() / 1e3));
98
+ const server = new McpServer({ name: "poincare", version: "0.1.0" });
99
+ const run = async (txs, send) => {
100
+ if (!send) return { sent: false, transactions: txs, note: "Unsigned. Sign and send these in order from the owner's wallet." };
101
+ if (!signer) throw new Error("send=true needs POINCARE_PRIVATE_KEY in the MCP server's environment");
102
+ const receipts = [];
103
+ for (const tx of txs) receipts.push(await signer.send(tx));
104
+ return { sent: true, transactions: receipts.map((r) => ({ hash: r.transactionHash, block: r.blockNumber, status: r.status })), receipts };
105
+ };
106
+ const ownerOf = (given) => {
107
+ if (given) return getAddress(given);
108
+ if (signer) return signer.address;
109
+ throw new Error("pass `owner` (no signing key is configured)");
110
+ };
111
+ server.registerTool(
112
+ "get_regime",
113
+ {
114
+ title: "Current trend regime",
115
+ description: "What the next swap on the Poincar\xE9 WETH/USDC pool sees this block: the confirmed trend (CUSUM, data-dependent), evidence toward the threshold, which side pays the trend spread and how much, base fee and mid price. Market orientation: USDC per WETH.",
116
+ annotations: { readOnlyHint: true, openWorldHint: true }
117
+ },
118
+ async () => {
119
+ try {
120
+ const r = await poincare.regime();
121
+ return ok({ summary: describeRegime(r), regime: r });
122
+ } catch (e) {
123
+ return fail(e);
124
+ }
125
+ }
126
+ );
127
+ server.registerTool(
128
+ "get_regime_history",
129
+ {
130
+ title: "Trend history",
131
+ description: "The hook's own detector samples over recent blocks, with where trends started, ended or flipped.",
132
+ inputSchema: { blocks: z.number().int().min(100).max(2e4).optional().describe("How many recent blocks to scan (default 3000)") },
133
+ annotations: { readOnlyHint: true, openWorldHint: true }
134
+ },
135
+ async ({ blocks }) => {
136
+ try {
137
+ const head = await poincare.publicClient.getBlockNumber();
138
+ const from = head - BigInt(blocks ?? 3e3);
139
+ const samples = await poincare.history(from > 0n ? from : 0n, head);
140
+ return ok({ fromBlock: from, toBlock: head, sampleCount: samples.length, onsets: trendOnsets(samples), latest: samples.slice(-10) });
141
+ } catch (e) {
142
+ return fail(e);
143
+ }
144
+ }
145
+ );
146
+ server.registerTool(
147
+ "wait_for_regime_change",
148
+ {
149
+ title: "Wait for a trend onset",
150
+ description: "Block until the regime changes (trend started/ended/flipped, evidence building, spread engaged/released) or the timeout passes. Use it to react to the onset of a trend instead of polling.",
151
+ inputSchema: {
152
+ timeoutSec: z.number().int().min(5).max(300).optional().describe("Give up after this many seconds (default 60)"),
153
+ events: z.array(z.enum(["trend-started", "trend-ended", "trend-flipped", "evidence-building", "spread-engaged", "spread-released"])).optional().describe("Only return on these event types (default: any)")
154
+ },
155
+ annotations: { readOnlyHint: true, openWorldHint: true }
156
+ },
157
+ async ({ timeoutSec, events }) => {
158
+ try {
159
+ let prev = await poincare.regime();
160
+ const deadline = Date.now() + (timeoutSec ?? 60) * 1e3;
161
+ while (Date.now() < deadline) {
162
+ await new Promise((r) => setTimeout(r, 2e3));
163
+ const next = await poincare.regime();
164
+ const hit = diffRegime(prev, next).filter((e) => !events || events.includes(e.type));
165
+ prev = next;
166
+ if (hit.length) return ok({ changed: true, events: hit, summary: describeRegime(next), regime: next });
167
+ }
168
+ return ok({ changed: false, summary: describeRegime(prev), regime: prev });
169
+ } catch (e) {
170
+ return fail(e);
171
+ }
172
+ }
173
+ );
174
+ server.registerTool(
175
+ "quote",
176
+ {
177
+ title: "Quote a swap",
178
+ description: "Exact-input quote from the pool's Lens (matches router execution in the same block to the wei), with the spread and fee this side pays.",
179
+ inputSchema: { side, amount: z.string().regex(/^\d+(\.\d+)?$/).describe("Input amount: USDC to buy, WETH to sell") },
180
+ annotations: { readOnlyHint: true, openWorldHint: true }
181
+ },
182
+ async ({ side: s, amount }) => {
183
+ try {
184
+ const q = await poincare.quote(s, amount);
185
+ return ok({ ...q, amountOutFormatted: `${formatAmount(q.amountOut)} ${s === "buy" ? "WETH" : "USDC"}` });
186
+ } catch (e) {
187
+ return fail(e);
188
+ }
189
+ }
190
+ );
191
+ server.registerTool(
192
+ "dca_plan_order",
193
+ {
194
+ title: "Plan a spread-aware DCA order",
195
+ description: "Validate a DCA order exactly as the contract will, show its schedule, and say what the first fill would do under the current regime. Sends nothing.",
196
+ inputSchema: orderShape,
197
+ annotations: { readOnlyHint: true, openWorldHint: true }
198
+ },
199
+ async (args) => {
200
+ try {
201
+ const t = now();
202
+ const p = buildOrderParams(toInput(args), t);
203
+ const start = p.startTime === 0n ? BigInt(t) : p.startTime;
204
+ const r = await poincare.regime();
205
+ const sideSpread = args.side === "buy" ? r.raw.spreadBuy : r.raw.spreadSell;
206
+ const first = planSlice(
207
+ {
208
+ id: 0n,
209
+ owner: "0x0000000000000000000000000000000000000000",
210
+ recipient: p.recipient,
211
+ side: args.side,
212
+ zeroForOne: p.zeroForOne,
213
+ pauseOnTrend: p.pauseOnTrend,
214
+ catchUp: p.catchUp,
215
+ cancelled: false,
216
+ paused: false,
217
+ maxSpreadBps: p.maxSpreadBps,
218
+ maxSlippageBps: p.maxSlippageBps,
219
+ slices: p.slices,
220
+ interval: p.interval,
221
+ filled: 0,
222
+ startTime: start,
223
+ deadline: p.deadline,
224
+ lastSlotPlusOne: 0n,
225
+ amountIn: p.amountIn,
226
+ remaining: p.amountIn,
227
+ amountOut: 0n,
228
+ minPriceWad: p.minPriceWad,
229
+ scheduleBudget: p.amountIn,
230
+ scheduleFilled: 0,
231
+ refunded: 0n
232
+ },
233
+ { now: BigInt(t), spreadBps: wadToBpsUp(sideSpread), trendWithSide: r.withTrendSide === args.side }
234
+ );
235
+ const schedule = Array.from({ length: Math.min(p.slices, 12) }, (_, i) => ({
236
+ slice: i + 1,
237
+ opensAt: new Date(Number(start + BigInt(i * p.interval)) * 1e3).toISOString()
238
+ }));
239
+ return ok({
240
+ params: p,
241
+ perSlice: `${formatAmount(p.amountIn / BigInt(p.slices))} ${args.side === "buy" ? "USDC" : "WETH"}`,
242
+ schedule,
243
+ deadlineAt: new Date(Number(p.deadline) * 1e3).toISOString(),
244
+ firstFillNow: { status: first.status, meaning: DCA_STATUS_TEXT[first.status] },
245
+ regime: describeRegime(r)
246
+ });
247
+ } catch (e) {
248
+ return fail(e);
249
+ }
250
+ }
251
+ );
252
+ server.registerTool(
253
+ "dca_create_order",
254
+ {
255
+ title: "Create a DCA order",
256
+ description: "Escrow the budget in the PoincareDCA contract and open the order. Returns the unsigned approve + create transactions, or sends them when send=true and a key is configured.",
257
+ inputSchema: { ...orderShape, owner: address.optional().describe("Order owner; defaults to the configured key's address"), send: sendFlag },
258
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
259
+ },
260
+ async (args) => {
261
+ try {
262
+ const from = ownerOf(args.owner);
263
+ if (args.send && signer && from.toLowerCase() !== signer.address.toLowerCase()) {
264
+ throw new Error("send=true creates the order from the configured key; `owner` must be that address");
265
+ }
266
+ const txs = await poincare.dca.build.create(from, toInput(args));
267
+ const res = await run(txs, args.send);
268
+ if (res.sent) {
269
+ const id = orderIdFromReceipt(poincare.deployment, res.receipts[res.receipts.length - 1]);
270
+ return ok({ sent: true, orderId: id, transactions: res.transactions });
271
+ }
272
+ return ok({ owner: from, ...res });
273
+ } catch (e) {
274
+ return fail(e);
275
+ }
276
+ }
277
+ );
278
+ server.registerTool(
279
+ "dca_get_order",
280
+ {
281
+ title: "Get a DCA order",
282
+ description: "An order's state and progress, plus the contract's own verdict on its next fill.",
283
+ inputSchema: { id: orderId },
284
+ annotations: { readOnlyHint: true, openWorldHint: true }
285
+ },
286
+ async ({ id }) => {
287
+ try {
288
+ const o = await poincare.dca.order(BigInt(id));
289
+ if (!o) return fail(new Error(`no DCA order #${id}`));
290
+ const next = await poincare.dca.preview(BigInt(id));
291
+ return ok({ order: orderView(o), nextFill: { ...next, meaning: DCA_STATUS_TEXT[next.status] } });
292
+ } catch (e) {
293
+ return fail(e);
294
+ }
295
+ }
296
+ );
297
+ server.registerTool(
298
+ "dca_list_orders",
299
+ {
300
+ title: "List DCA orders",
301
+ description: "Every DCA order an address has opened, newest last, with each one's next-fill status.",
302
+ inputSchema: { owner: address.optional().describe("Defaults to the configured key's address") },
303
+ annotations: { readOnlyHint: true, openWorldHint: true }
304
+ },
305
+ async ({ owner }) => {
306
+ try {
307
+ const orders = await poincare.dca.ordersOf(ownerOf(owner));
308
+ const views = await Promise.all(
309
+ orders.slice(-50).map(async (o) => {
310
+ const next = await poincare.dca.preview(o.id);
311
+ return { ...orderView(o), nextFill: next.status };
312
+ })
313
+ );
314
+ return ok({ count: orders.length, orders: views });
315
+ } catch (e) {
316
+ return fail(e);
317
+ }
318
+ }
319
+ );
320
+ server.registerTool(
321
+ "dca_preview_slice",
322
+ {
323
+ title: "Can the next fill run now?",
324
+ description: "PoincareDCA.canExecute: the next fill's size, quote, floor, the spread this block, and why it would be held if it would.",
325
+ inputSchema: { id: orderId },
326
+ annotations: { readOnlyHint: true, openWorldHint: true }
327
+ },
328
+ async ({ id }) => {
329
+ try {
330
+ const p = await poincare.dca.preview(BigInt(id));
331
+ return ok({ ...p, meaning: DCA_STATUS_TEXT[p.status] });
332
+ } catch (e) {
333
+ return fail(e);
334
+ }
335
+ }
336
+ );
337
+ const orderAction = (name, title, description, build, destructive, precheck) => server.registerTool(
338
+ name,
339
+ { title, description, inputSchema: { id: orderId, send: sendFlag }, annotations: { readOnlyHint: false, destructiveHint: destructive, openWorldHint: true } },
340
+ async ({ id, send }) => {
341
+ try {
342
+ const n = BigInt(id);
343
+ if (precheck) await precheck(n, Boolean(send));
344
+ const res = await run([build(n)], send);
345
+ return ok({ orderId: n, sent: res.sent, transactions: res.transactions, ...res.sent ? {} : { note: res.note } });
346
+ } catch (e) {
347
+ return fail(e);
348
+ }
349
+ }
350
+ );
351
+ orderAction(
352
+ "dca_execute_slice",
353
+ "Fill the next slice now",
354
+ "Fill the current slot's slice of your own order (keepers do this automatically; the owner may too). Checks the contract's verdict first and refuses if the fill would be held.",
355
+ (id) => poincare.dca.build.execute(id),
356
+ false,
357
+ async (id) => {
358
+ const p = await poincare.dca.preview(id);
359
+ if (p.status !== "ready") throw new Error(`not fillable now: ${p.status}. ${DCA_STATUS_TEXT[p.status]}`);
360
+ }
361
+ );
362
+ const openOrder = async (id) => {
363
+ const o = await poincare.dca.order(id);
364
+ if (!o) throw new Error(`no DCA order #${id}`);
365
+ if (o.cancelled || o.remaining === 0n) throw new Error(`DCA order #${id} is closed`);
366
+ return o;
367
+ };
368
+ const ownedOpen = async (id, send) => {
369
+ const o = await openOrder(id);
370
+ if (send && signer && o.owner.toLowerCase() !== signer.address.toLowerCase()) {
371
+ throw new Error(`DCA order #${id} belongs to ${o.owner}, not the configured key`);
372
+ }
373
+ return o;
374
+ };
375
+ orderAction(
376
+ "dca_cancel_order",
377
+ "Cancel a DCA order",
378
+ "Cancel your order and refund its unfilled budget. Only the owner can.",
379
+ (id) => poincare.dca.build.cancel(id),
380
+ true,
381
+ async (id, send) => void await ownedOpen(id, send)
382
+ );
383
+ orderAction(
384
+ "dca_close_expired",
385
+ "Refund an expired order",
386
+ "After the deadline, return an order's unfilled budget to its owner. Anyone may send this; the refund always goes to the owner.",
387
+ (id) => poincare.dca.build.closeExpired(id),
388
+ false,
389
+ async (id) => {
390
+ if (BigInt(now()) <= (await openOrder(id)).deadline) throw new Error(`DCA order #${id} has not expired yet`);
391
+ }
392
+ );
393
+ orderAction(
394
+ "dca_pause_order",
395
+ "Pause a DCA order",
396
+ "Hold your order: no buy fills until you resume it. It can still be cancelled, and with catch-up the buys it misses are made up after resuming. Owner only.",
397
+ (id) => poincare.dca.build.pause(id),
398
+ false,
399
+ async (id, send) => {
400
+ if ((await ownedOpen(id, send)).paused) throw new Error(`DCA order #${id} is already paused`);
401
+ }
402
+ );
403
+ orderAction(
404
+ "dca_resume_order",
405
+ "Resume a DCA order",
406
+ "Let a paused order fill again. Owner only.",
407
+ (id) => poincare.dca.build.resume(id),
408
+ false,
409
+ async (id, send) => {
410
+ if (!(await ownedOpen(id, send)).paused) throw new Error(`DCA order #${id} is not paused`);
411
+ }
412
+ );
413
+ server.registerTool(
414
+ "dca_edit_order",
415
+ {
416
+ title: "Edit a DCA order",
417
+ description: "Re-plan an open order's REMAINING budget from now: a new number of buys and interval, and optionally new protection, slippage, limit and end time. Side, recipient and budget cannot change; a paused order stays paused. Validates like the contract. Owner only.",
418
+ inputSchema: {
419
+ id: orderId,
420
+ slices: z.number().int().min(1).max(1e4).optional().describe("Buys to spread the remaining budget over"),
421
+ intervalSec: z.number().int().min(60).optional().describe("Seconds between buys"),
422
+ durationSec: z.number().int().min(60).optional().describe("Alternative end: the new schedule's window in seconds"),
423
+ deadline: z.number().int().optional().describe("Unix seconds; default one spare interval after the last new buy"),
424
+ maxSpreadBps: z.number().int().min(0).max(1e4).optional(),
425
+ pauseOnTrend: z.boolean().optional(),
426
+ catchUp: z.boolean().optional(),
427
+ maxSlippageBps: z.number().int().min(0).max(1e4).optional(),
428
+ limitPrice: z.union([z.string().regex(/^\d+(\.\d+)?$/), z.literal("none")]).optional().describe('USDC per WETH, or "none" to remove the limit'),
429
+ send: sendFlag
430
+ },
431
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
432
+ },
433
+ async (a) => {
434
+ try {
435
+ const id = BigInt(a.id);
436
+ await ownedOpen(id, Boolean(a.send));
437
+ const tx = await poincare.dca.build.edit(id, {
438
+ slices: a.slices,
439
+ interval: a.intervalSec,
440
+ duration: a.durationSec,
441
+ deadline: a.deadline,
442
+ maxSpreadBps: a.maxSpreadBps,
443
+ pauseOnTrend: a.pauseOnTrend,
444
+ catchUp: a.catchUp,
445
+ maxSlippageBps: a.maxSlippageBps,
446
+ limitPrice: a.limitPrice === "none" ? null : a.limitPrice
447
+ });
448
+ const res = await run([tx], a.send);
449
+ return ok({ orderId: id, sent: res.sent, transactions: res.transactions, ...res.sent ? {} : { note: res.note } });
450
+ } catch (e) {
451
+ return fail(e);
452
+ }
453
+ }
454
+ );
455
+ return server;
456
+ }
457
+
458
+ export {
459
+ createServer
460
+ };
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ createServer
4
+ } from "./chunk-4GNLI7ZS.js";
5
+
6
+ // src/index.ts
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { UNICHAIN_SEPOLIA, createPoincareClient, sendTx, withDca } from "@poincaretrade/sdk";
9
+ import { createPublicClient, createWalletClient, getAddress, http } from "viem";
10
+ import { privateKeyToAccount } from "viem/accounts";
11
+ import { unichainSepolia } from "viem/chains";
12
+ var rpcUrl = process.env.POINCARE_RPC_URL || UNICHAIN_SEPOLIA.rpcUrl;
13
+ var dcaAddress = process.env.POINCARE_DCA_ADDRESS;
14
+ var deployment = dcaAddress ? withDca(UNICHAIN_SEPOLIA, getAddress(dcaAddress)) : UNICHAIN_SEPOLIA;
15
+ var publicClient = createPublicClient({ chain: unichainSepolia, transport: http(rpcUrl) });
16
+ var poincare = createPoincareClient({ deployment, publicClient });
17
+ var signer;
18
+ var pk = process.env.POINCARE_PRIVATE_KEY?.trim();
19
+ if (pk) {
20
+ const account = privateKeyToAccount(pk.startsWith("0x") ? pk : `0x${pk}`);
21
+ const wallet = createWalletClient({ account, chain: unichainSepolia, transport: http(rpcUrl) });
22
+ signer = { address: account.address, send: (tx) => sendTx(wallet, publicClient, tx) };
23
+ }
24
+ var server = createServer({ poincare, signer });
25
+ await server.connect(new StdioServerTransport());
26
+ console.error(`poincare-mcp ready on ${deployment.name}${signer ? ` (signing as ${signer.address})` : " (read + unsigned txs only)"}`);
@@ -0,0 +1,18 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { PoincareClient, TxRequest } from '@poincaretrade/sdk';
3
+ import { Address, TransactionReceipt } from 'viem';
4
+
5
+ /** The user's own key, if they configured one. Without it every write tool returns unsigned txs. */
6
+ type Signer = {
7
+ address: Address;
8
+ send: (tx: TxRequest) => Promise<TransactionReceipt>;
9
+ };
10
+ type ServerOptions = {
11
+ poincare: PoincareClient;
12
+ signer?: Signer;
13
+ /** Clock override for tests. */
14
+ now?: () => number;
15
+ };
16
+ declare function createServer(opts: ServerOptions): McpServer;
17
+
18
+ export { type ServerOptions, type Signer, createServer };
package/dist/server.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ createServer
3
+ } from "./chunk-4GNLI7ZS.js";
4
+ export {
5
+ createServer
6
+ };
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@poincaretrade/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "MCP server for the Poincaré hook: lets AI agents read the trend regime and create and manage spread-aware DCA orders.",
5
+ "license": "BUSL-1.1",
6
+ "author": "Prakhar Srivastava",
7
+ "homepage": "https://www.poincaretrade.in/#/developers",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Prakhar-30/POINCARE.git",
11
+ "directory": "packages/mcp"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/Prakhar-30/POINCARE/issues"
15
+ },
16
+ "keywords": [
17
+ "mcp",
18
+ "model-context-protocol",
19
+ "claude",
20
+ "ai-agent",
21
+ "uniswap",
22
+ "uniswap-v4",
23
+ "defi",
24
+ "dca",
25
+ "poincare"
26
+ ],
27
+ "type": "module",
28
+ "bin": {
29
+ "poincare-mcp": "./dist/index.js"
30
+ },
31
+ "main": "./dist/server.js",
32
+ "types": "./dist/server.d.ts",
33
+ "files": [
34
+ "dist",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "dependencies": {
39
+ "@modelcontextprotocol/sdk": "1.32.1",
40
+ "viem": "2.53.1",
41
+ "zod": "4.6.6",
42
+ "@poincaretrade/sdk": "0.1.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "22.18.6",
46
+ "tsup": "8.5.1",
47
+ "typescript": "5.9.3",
48
+ "vitest": "4.1.12"
49
+ },
50
+ "engines": {
51
+ "node": ">=18"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "scripts": {
57
+ "build": "tsup",
58
+ "typecheck": "tsc --noEmit",
59
+ "test": "vitest run",
60
+ "start": "node dist/index.js"
61
+ }
6
62
  }