@profullstack/chat-plugins 0.0.0-stage → 0.2.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 +3 -0
- package/README.md +126 -2
- package/index.d.ts +360 -0
- package/package.json +53 -4
- package/src/catalog.js +79 -0
- package/src/discover.js +180 -0
- package/src/index.js +41 -0
- package/src/loop.js +403 -0
- package/src/mcp.js +323 -0
- package/src/money.js +372 -0
- package/src/net.js +299 -0
- package/src/oauth.js +280 -0
- package/src/seal.js +69 -0
- package/src/tools.js +114 -0
package/src/mcp.js
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// MCP client over Streamable HTTP (protocol 2025-06-18): JSON and SSE responses,
|
|
2
|
+
// Mcp-Session-Id handling, timeouts and size caps.
|
|
3
|
+
|
|
4
|
+
import { PluginError, readCapped, safeFetch } from "./net.js";
|
|
5
|
+
|
|
6
|
+
export const PROTOCOL_VERSION = "2025-06-18";
|
|
7
|
+
export const CLIENT_INFO = { name: "@profullstack/chat-plugins", version: "0.1.0" };
|
|
8
|
+
/** Text handed to the model per tool result. The UI keeps the full text. */
|
|
9
|
+
export const MODEL_TEXT_LIMIT = 16 * 1024;
|
|
10
|
+
|
|
11
|
+
let nextId = 1;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Parse a text/event-stream body and return the JSON-RPC message answering `id`.
|
|
15
|
+
* @param {string} text
|
|
16
|
+
* @param {number | string} id
|
|
17
|
+
*/
|
|
18
|
+
export function parseSse(text, id) {
|
|
19
|
+
const events = [];
|
|
20
|
+
let data = [];
|
|
21
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
22
|
+
if (raw === "") {
|
|
23
|
+
if (data.length) events.push(data.join("\n"));
|
|
24
|
+
data = [];
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (raw.startsWith(":")) continue;
|
|
28
|
+
const idx = raw.indexOf(":");
|
|
29
|
+
const field = idx === -1 ? raw : raw.slice(0, idx);
|
|
30
|
+
let value = idx === -1 ? "" : raw.slice(idx + 1);
|
|
31
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
32
|
+
if (field === "data") data.push(value);
|
|
33
|
+
}
|
|
34
|
+
if (data.length) events.push(data.join("\n"));
|
|
35
|
+
let fallback = null;
|
|
36
|
+
for (const ev of events) {
|
|
37
|
+
let msg;
|
|
38
|
+
try {
|
|
39
|
+
msg = JSON.parse(ev);
|
|
40
|
+
} catch {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
for (const m of Array.isArray(msg) ? msg : [msg]) {
|
|
44
|
+
if (m && m.id === id && ("result" in m || "error" in m)) return m;
|
|
45
|
+
if (m && ("result" in m || "error" in m) && m.id === undefined) fallback = m;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return fallback;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Read an SSE stream until the response for `id` arrives (servers may keep the
|
|
53
|
+
* stream open after it).
|
|
54
|
+
* @param {Response} res
|
|
55
|
+
* @param {number | string} id
|
|
56
|
+
* @param {number} maxBytes
|
|
57
|
+
*/
|
|
58
|
+
async function readSseFor(res, id, maxBytes) {
|
|
59
|
+
if (!res.body) return null;
|
|
60
|
+
const reader = res.body.getReader();
|
|
61
|
+
const decoder = new TextDecoder();
|
|
62
|
+
let buf = "";
|
|
63
|
+
let total = 0;
|
|
64
|
+
try {
|
|
65
|
+
for (;;) {
|
|
66
|
+
const { done, value } = await reader.read();
|
|
67
|
+
if (value) {
|
|
68
|
+
total += value.byteLength;
|
|
69
|
+
if (total > maxBytes) throw new PluginError(`Response larger than ${maxBytes} bytes`, { code: "too_large" });
|
|
70
|
+
buf += decoder.decode(value, { stream: true });
|
|
71
|
+
// Only parse complete events.
|
|
72
|
+
const cut = Math.max(buf.lastIndexOf("\n\n"), buf.lastIndexOf("\r\n\r\n"));
|
|
73
|
+
if (cut !== -1) {
|
|
74
|
+
const msg = parseSse(buf.slice(0, cut + 2), id);
|
|
75
|
+
if (msg && msg.id === id) return msg;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (done) break;
|
|
79
|
+
}
|
|
80
|
+
return parseSse(buf + "\n\n", id);
|
|
81
|
+
} finally {
|
|
82
|
+
try {
|
|
83
|
+
await reader.cancel();
|
|
84
|
+
} catch {}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @typedef {import("../index.js").Connection} Connection
|
|
90
|
+
* @typedef {import("../index.js").NetOptions} NetOptions
|
|
91
|
+
*/
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Send one JSON-RPC message. Returns { result, sessionId } for requests.
|
|
95
|
+
* @param {Connection} conn
|
|
96
|
+
* @param {string} method
|
|
97
|
+
* @param {any} params
|
|
98
|
+
* @param {NetOptions & { sessionId?: string, notification?: boolean }} [opts]
|
|
99
|
+
*/
|
|
100
|
+
export async function rpc(conn, method, params, opts = {}) {
|
|
101
|
+
const id = opts.notification ? undefined : nextId++;
|
|
102
|
+
/** @type {Record<string,string>} */
|
|
103
|
+
const headers = {
|
|
104
|
+
"content-type": "application/json",
|
|
105
|
+
accept: "application/json, text/event-stream",
|
|
106
|
+
"mcp-protocol-version": PROTOCOL_VERSION,
|
|
107
|
+
};
|
|
108
|
+
if (conn.token) headers.authorization = `Bearer ${conn.token}`;
|
|
109
|
+
if (opts.sessionId) headers["mcp-session-id"] = opts.sessionId;
|
|
110
|
+
const body = JSON.stringify({ jsonrpc: "2.0", ...(id !== undefined ? { id } : {}), method, ...(params !== undefined ? { params } : {}) });
|
|
111
|
+
const { res, done } = await safeFetch(conn.url, { method: "POST", headers, body }, opts);
|
|
112
|
+
try {
|
|
113
|
+
const sessionId = res.headers.get("mcp-session-id") || opts.sessionId;
|
|
114
|
+
const maxBytes = opts.maxBytes ?? 4_000_000;
|
|
115
|
+
if (res.status === 401 || res.status === 403) {
|
|
116
|
+
await res.body?.cancel().catch(() => {});
|
|
117
|
+
const err = new PluginError(res.status === 401 ? "Sign-in required" : "Not allowed", {
|
|
118
|
+
code: res.status === 401 ? "unauthorized" : "forbidden",
|
|
119
|
+
status: res.status,
|
|
120
|
+
});
|
|
121
|
+
/** @type {any} */ (err).wwwAuthenticate = res.headers.get("www-authenticate") || "";
|
|
122
|
+
throw err;
|
|
123
|
+
}
|
|
124
|
+
if (res.status === 404 && opts.sessionId) {
|
|
125
|
+
await res.body?.cancel().catch(() => {});
|
|
126
|
+
throw new PluginError("MCP session expired", { code: "session_expired", status: 404 });
|
|
127
|
+
}
|
|
128
|
+
if (id === undefined) {
|
|
129
|
+
await res.body?.cancel().catch(() => {});
|
|
130
|
+
if (!res.ok && res.status !== 202) {
|
|
131
|
+
throw new PluginError(`${method} failed: HTTP ${res.status}`, { code: "http_error", status: res.status });
|
|
132
|
+
}
|
|
133
|
+
return { result: undefined, sessionId };
|
|
134
|
+
}
|
|
135
|
+
const ct = res.headers.get("content-type") || "";
|
|
136
|
+
let msg;
|
|
137
|
+
if (/text\/event-stream/i.test(ct)) {
|
|
138
|
+
msg = await readSseFor(res, id, maxBytes);
|
|
139
|
+
} else {
|
|
140
|
+
const text = await readCapped(res, maxBytes);
|
|
141
|
+
try {
|
|
142
|
+
const parsed = JSON.parse(text);
|
|
143
|
+
msg = Array.isArray(parsed) ? parsed.find((m) => m && m.id === id) : parsed;
|
|
144
|
+
} catch {
|
|
145
|
+
msg = null;
|
|
146
|
+
}
|
|
147
|
+
if (!res.ok && !(msg && msg.error)) {
|
|
148
|
+
throw new PluginError(`${method} failed: HTTP ${res.status}`, { code: "http_error", status: res.status });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (!msg) throw new PluginError(`${method}: no JSON-RPC response from ${new URL(conn.url).host}`, { code: "bad_response" });
|
|
152
|
+
if (msg.error) {
|
|
153
|
+
throw new PluginError(`${method}: ${msg.error.message || "error"}`, { code: "rpc_error", status: msg.error.code });
|
|
154
|
+
}
|
|
155
|
+
return { result: msg.result, sessionId };
|
|
156
|
+
} finally {
|
|
157
|
+
done();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** @type {Map<string, { sessionId?: string, info: any, at: number }>} */
|
|
162
|
+
const sessions = new Map();
|
|
163
|
+
const SESSION_TTL_MS = 10 * 60 * 1000;
|
|
164
|
+
|
|
165
|
+
/** @param {Connection} conn */
|
|
166
|
+
function sessionKey(conn) {
|
|
167
|
+
// The token is part of the key so two people never share a session.
|
|
168
|
+
return `${conn.url}\u0000${conn.token || ""}`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* initialize + notifications/initialized. Returns the server's InitializeResult.
|
|
173
|
+
* @param {Connection} conn
|
|
174
|
+
* @param {NetOptions} [opts]
|
|
175
|
+
*/
|
|
176
|
+
export async function initialize(conn, opts = {}) {
|
|
177
|
+
const { result, sessionId } = await rpc(
|
|
178
|
+
conn,
|
|
179
|
+
"initialize",
|
|
180
|
+
{ protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: opts.clientInfo || CLIENT_INFO },
|
|
181
|
+
opts,
|
|
182
|
+
);
|
|
183
|
+
try {
|
|
184
|
+
await rpc(conn, "notifications/initialized", undefined, { ...opts, sessionId, notification: true });
|
|
185
|
+
} catch (err) {
|
|
186
|
+
if (/** @type {any} */ (err)?.code === "unauthorized") throw err;
|
|
187
|
+
// Some servers answer notifications oddly; the session still works.
|
|
188
|
+
}
|
|
189
|
+
return { info: result || {}, sessionId };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* @param {Connection} conn
|
|
194
|
+
* @param {NetOptions} opts
|
|
195
|
+
*/
|
|
196
|
+
async function getSession(conn, opts) {
|
|
197
|
+
const key = sessionKey(conn);
|
|
198
|
+
const hit = sessions.get(key);
|
|
199
|
+
if (hit && Date.now() - hit.at < SESSION_TTL_MS) return hit;
|
|
200
|
+
const s = await initialize(conn, opts);
|
|
201
|
+
const entry = { ...s, at: Date.now() };
|
|
202
|
+
sessions.set(key, entry);
|
|
203
|
+
if (sessions.size > 500) sessions.delete(sessions.keys().next().value);
|
|
204
|
+
return entry;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Request inside a (cached) session; re-initializes once if the session expired.
|
|
209
|
+
* @param {Connection} conn
|
|
210
|
+
* @param {string} method
|
|
211
|
+
* @param {any} params
|
|
212
|
+
* @param {NetOptions} [opts]
|
|
213
|
+
*/
|
|
214
|
+
export async function request(conn, method, params, opts = {}) {
|
|
215
|
+
let s = await getSession(conn, opts);
|
|
216
|
+
try {
|
|
217
|
+
return (await rpc(conn, method, params, { ...opts, sessionId: s.sessionId })).result;
|
|
218
|
+
} catch (err) {
|
|
219
|
+
const code = /** @type {any} */ (err)?.code;
|
|
220
|
+
if (code === "session_expired" || (code === "http_error" && /** @type {any} */ (err).status === 400 && s.sessionId)) {
|
|
221
|
+
sessions.delete(sessionKey(conn));
|
|
222
|
+
s = await getSession(conn, opts);
|
|
223
|
+
return (await rpc(conn, method, params, { ...opts, sessionId: s.sessionId })).result;
|
|
224
|
+
}
|
|
225
|
+
if (code === "unauthorized") sessions.delete(sessionKey(conn));
|
|
226
|
+
throw err;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Forget cached sessions (all, or one connection's). @param {Connection} [conn] */
|
|
231
|
+
export function resetSessions(conn) {
|
|
232
|
+
if (conn) sessions.delete(sessionKey(conn));
|
|
233
|
+
else sessions.clear();
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* List every tool the server offers (follows nextCursor, capped).
|
|
238
|
+
* @param {Connection} conn
|
|
239
|
+
* @param {NetOptions & { maxTools?: number }} [opts]
|
|
240
|
+
* @returns {Promise<import("../index.js").McpTool[]>}
|
|
241
|
+
*/
|
|
242
|
+
export async function listTools(conn, opts = {}) {
|
|
243
|
+
const max = opts.maxTools ?? 128;
|
|
244
|
+
const tools = [];
|
|
245
|
+
let cursor;
|
|
246
|
+
for (let page = 0; page < 10; page++) {
|
|
247
|
+
const result = await request(conn, "tools/list", cursor ? { cursor } : {}, { timeoutMs: 20_000, ...opts });
|
|
248
|
+
for (const t of result?.tools || []) {
|
|
249
|
+
if (!t || typeof t.name !== "string") continue;
|
|
250
|
+
tools.push({
|
|
251
|
+
name: t.name,
|
|
252
|
+
title: typeof t.title === "string" ? t.title : t.annotations?.title,
|
|
253
|
+
description: typeof t.description === "string" ? t.description.slice(0, 2000) : "",
|
|
254
|
+
inputSchema: t.inputSchema && typeof t.inputSchema === "object" ? t.inputSchema : { type: "object", properties: {} },
|
|
255
|
+
annotations: t.annotations && typeof t.annotations === "object" ? t.annotations : {},
|
|
256
|
+
});
|
|
257
|
+
if (tools.length >= max) return tools;
|
|
258
|
+
}
|
|
259
|
+
cursor = result?.nextCursor;
|
|
260
|
+
if (!cursor) break;
|
|
261
|
+
}
|
|
262
|
+
return tools;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Flatten MCP content blocks to text.
|
|
267
|
+
* @param {any[]} content
|
|
268
|
+
* @param {any} [structured]
|
|
269
|
+
*/
|
|
270
|
+
export function contentToText(content, structured) {
|
|
271
|
+
const parts = [];
|
|
272
|
+
for (const c of Array.isArray(content) ? content : []) {
|
|
273
|
+
if (!c || typeof c !== "object") continue;
|
|
274
|
+
if (c.type === "text" && typeof c.text === "string") parts.push(c.text);
|
|
275
|
+
else if (c.type === "resource" && c.resource) {
|
|
276
|
+
if (typeof c.resource.text === "string") parts.push(c.resource.text);
|
|
277
|
+
else parts.push(`[resource ${c.resource.uri || ""}]`);
|
|
278
|
+
} else if (c.type === "resource_link") parts.push(`[link ${c.name || ""} ${c.uri || ""}]`.trim());
|
|
279
|
+
else if (c.type === "image") parts.push(`[image ${c.mimeType || ""}]`);
|
|
280
|
+
else if (c.type === "audio") parts.push(`[audio ${c.mimeType || ""}]`);
|
|
281
|
+
}
|
|
282
|
+
if (!parts.length && structured !== undefined) {
|
|
283
|
+
try {
|
|
284
|
+
parts.push(JSON.stringify(structured, null, 2));
|
|
285
|
+
} catch {}
|
|
286
|
+
}
|
|
287
|
+
return parts.join("\n\n");
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Cut text to a byte budget on a character boundary, with a marker.
|
|
292
|
+
* @param {string} text
|
|
293
|
+
* @param {number} [limit]
|
|
294
|
+
*/
|
|
295
|
+
export function truncateForModel(text, limit = MODEL_TEXT_LIMIT) {
|
|
296
|
+
const enc = new TextEncoder();
|
|
297
|
+
const bytes = enc.encode(text);
|
|
298
|
+
if (bytes.length <= limit) return text;
|
|
299
|
+
let cut = new TextDecoder().decode(bytes.slice(0, limit));
|
|
300
|
+
cut = cut.replace(/�+$/, "");
|
|
301
|
+
return `${cut}\n\n[truncated: ${bytes.length - enc.encode(cut).length} more bytes not shown]`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Call one tool.
|
|
306
|
+
* @param {Connection} conn
|
|
307
|
+
* @param {string} name
|
|
308
|
+
* @param {Record<string, unknown>} [args]
|
|
309
|
+
* @param {NetOptions & { modelTextLimit?: number }} [opts]
|
|
310
|
+
* @returns {Promise<import("../index.js").ToolResult>}
|
|
311
|
+
*/
|
|
312
|
+
export async function callTool(conn, name, args = {}, opts = {}) {
|
|
313
|
+
const result = await request(conn, "tools/call", { name, arguments: args || {} }, { timeoutMs: 60_000, ...opts });
|
|
314
|
+
const content = Array.isArray(result?.content) ? result.content : [];
|
|
315
|
+
const text = contentToText(content, result?.structuredContent);
|
|
316
|
+
return {
|
|
317
|
+
isError: result?.isError === true,
|
|
318
|
+
content,
|
|
319
|
+
structuredContent: result?.structuredContent,
|
|
320
|
+
text,
|
|
321
|
+
modelText: truncateForModel(text, opts.modelTextLimit ?? MODEL_TEXT_LIMIT),
|
|
322
|
+
};
|
|
323
|
+
}
|
package/src/money.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
// Money plugins: catalog entries for banking (Mercury), crypto payments
|
|
2
|
+
// (CoinPay) and brokerage (moomoo), which of them apps turn on by default,
|
|
3
|
+
// and the confirmation gate for their tools.
|
|
4
|
+
//
|
|
5
|
+
// The gate is meant for the app's tool-call layer, not a prompt: for a plugin
|
|
6
|
+
// with a policy, a tool may run on its own only when its exact name is on that
|
|
7
|
+
// plugin's read-only allowlist. applyPolicy() marks every other tool (a write,
|
|
8
|
+
// or a name never seen) destructiveHint: true before the tool loop sees it, so
|
|
9
|
+
// needsApproval() is true and the loop stops for the person. A server's own
|
|
10
|
+
// annotations cannot loosen it. Policies are chosen by server URL, not slug.
|
|
11
|
+
//
|
|
12
|
+
// Shared by c0mpute chat and Infernet chat so the two cannot drift. No Node
|
|
13
|
+
// imports: describeAction() also runs in the browser.
|
|
14
|
+
|
|
15
|
+
export const MODEL_CAN_BE_WRONG = "The model can be wrong. You decide: nothing here runs until you approve it.";
|
|
16
|
+
export const FINANCE_CATALOG = Object.freeze([
|
|
17
|
+
{
|
|
18
|
+
slug: "mercury",
|
|
19
|
+
name: "Mercury (business banking)",
|
|
20
|
+
url: "https://mcp.mercury.com/mcp",
|
|
21
|
+
description: "Your Mercury accounts in chat: balances, transactions, recipients, cards, statements and cash flow. Payment and transfer requests need your approval here and still go through Mercury's own approval. Sign in with your Mercury account.",
|
|
22
|
+
homepage: "https://mercury.com",
|
|
23
|
+
icon: "https://mercury.com/favicon.ico",
|
|
24
|
+
default: true
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
slug: "coinpay",
|
|
28
|
+
name: "CoinPay (crypto payments)",
|
|
29
|
+
url: "https://coinpayportal.com/api/mcp",
|
|
30
|
+
description: "Your CoinPay business in chat: crypto invoices, receivables aging, projects, contractors and pay runs. Creating anything needs your approval first. Sign in with your CoinPay account.",
|
|
31
|
+
homepage: "https://coinpayportal.com",
|
|
32
|
+
icon: "https://coinpayportal.com/favicon.ico",
|
|
33
|
+
default: true
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
slug: "moomoo",
|
|
37
|
+
name: "moomoo (brokerage and trading)",
|
|
38
|
+
url: "https://mcp.moomoo.com/mcp",
|
|
39
|
+
description: "Quotes, charts, screeners, news and your moomoo positions, balances and orders. Starts on paper trading; switching to live is your call, and every order needs your approval. The model can be wrong and you decide. Sign in with your moomoo account.",
|
|
40
|
+
homepage: "https://www.moomoo.com",
|
|
41
|
+
icon: "https://www.moomoo.com/favicon.ico",
|
|
42
|
+
default: false
|
|
43
|
+
}
|
|
44
|
+
]);
|
|
45
|
+
export const DEFAULT_PLUGINS = FINANCE_CATALOG.filter((e) => e.default);
|
|
46
|
+
const MERCURY_READ = new Set([
|
|
47
|
+
"getCurrentDate",
|
|
48
|
+
"getAccount",
|
|
49
|
+
"getAccounts",
|
|
50
|
+
"getAccountCards",
|
|
51
|
+
"getAccountStatements",
|
|
52
|
+
"getTransaction",
|
|
53
|
+
"getTransactionById",
|
|
54
|
+
"listTransactions",
|
|
55
|
+
"getCashflowSummary",
|
|
56
|
+
"getAutoTransferRules",
|
|
57
|
+
"listCategories",
|
|
58
|
+
"listCredit",
|
|
59
|
+
"getCreditAccountStatements",
|
|
60
|
+
"getOrganization",
|
|
61
|
+
"getRecipient",
|
|
62
|
+
"getRecipients",
|
|
63
|
+
"getRecipientInvite",
|
|
64
|
+
"listRecipientInvites",
|
|
65
|
+
"listRecipientsAttachments",
|
|
66
|
+
"getTreasury",
|
|
67
|
+
"getTreasuryTransactions",
|
|
68
|
+
"getInvest",
|
|
69
|
+
"getInvestActivity",
|
|
70
|
+
"getCard",
|
|
71
|
+
"listCards",
|
|
72
|
+
"listMerchants",
|
|
73
|
+
"getUser",
|
|
74
|
+
"getUsers",
|
|
75
|
+
"getWebhook",
|
|
76
|
+
"getWebhooks",
|
|
77
|
+
"listSendMoneyApprovalRequests",
|
|
78
|
+
"getSendMoneyApprovalRequest",
|
|
79
|
+
"listTransferMoneyApprovalRequests",
|
|
80
|
+
"getTransferMoneyApprovalRequest",
|
|
81
|
+
"listTasks",
|
|
82
|
+
"getTask",
|
|
83
|
+
"getSafeRequest",
|
|
84
|
+
"getSafeRequests",
|
|
85
|
+
"getAttachment",
|
|
86
|
+
"getCustomer",
|
|
87
|
+
"listCustomers",
|
|
88
|
+
"listProducts",
|
|
89
|
+
"getInvoice",
|
|
90
|
+
"listInvoices",
|
|
91
|
+
"listInvoiceAttachments",
|
|
92
|
+
"listInvoicePayments",
|
|
93
|
+
"listBudgets",
|
|
94
|
+
"getBudget",
|
|
95
|
+
"getBudgetMembers",
|
|
96
|
+
"getBudgetExpenditures",
|
|
97
|
+
"listReceipts",
|
|
98
|
+
"getReceipt",
|
|
99
|
+
"listReimbursements",
|
|
100
|
+
"getReimbursement",
|
|
101
|
+
"getBooksInstances",
|
|
102
|
+
"getBooksSourceAccounts",
|
|
103
|
+
"getBooksTransactions",
|
|
104
|
+
"getBooksTransaction",
|
|
105
|
+
"getBooksLedgers",
|
|
106
|
+
"getBooksLedger",
|
|
107
|
+
"getBooksLedgerBalances",
|
|
108
|
+
"getBooksLineEntries",
|
|
109
|
+
"listBooksJournalEntries",
|
|
110
|
+
"retrieveBooksJournalEntry",
|
|
111
|
+
"getBooksTagGroups",
|
|
112
|
+
"getBooksTags",
|
|
113
|
+
"getBooksCategorizationRules",
|
|
114
|
+
"getBooksProfitAndLoss",
|
|
115
|
+
"getBooksBalanceSheet",
|
|
116
|
+
"getBooksCashFlow",
|
|
117
|
+
"getBooksBills",
|
|
118
|
+
"getBooksBill",
|
|
119
|
+
"getBooksInvoices",
|
|
120
|
+
"getBooksInvoice"
|
|
121
|
+
]);
|
|
122
|
+
const COINPAY_READ = new Set([
|
|
123
|
+
"invoice_list",
|
|
124
|
+
"invoice_get",
|
|
125
|
+
"invoice_ar_aging",
|
|
126
|
+
"project_list",
|
|
127
|
+
"project_get",
|
|
128
|
+
"contractor_list",
|
|
129
|
+
"contractor_get",
|
|
130
|
+
"contractor_work_list",
|
|
131
|
+
"pay_run_list",
|
|
132
|
+
"pay_run_get",
|
|
133
|
+
"document_list",
|
|
134
|
+
"document_get"
|
|
135
|
+
]);
|
|
136
|
+
const MOOMOO_READ = new Set([
|
|
137
|
+
"account_authorized_trd_accs",
|
|
138
|
+
"account_funds",
|
|
139
|
+
"account_positions",
|
|
140
|
+
"account_orders_active",
|
|
141
|
+
"account_orders_history",
|
|
142
|
+
"account_orders_detail",
|
|
143
|
+
"account_order_fills_today",
|
|
144
|
+
"account_fills_history",
|
|
145
|
+
"account_trading_info",
|
|
146
|
+
"sim_trade_account_list",
|
|
147
|
+
"sim_trade_cash_info",
|
|
148
|
+
"sim_trade_position_list",
|
|
149
|
+
"sim_trade_history_order_list",
|
|
150
|
+
"sim_trade_max_buy_sell",
|
|
151
|
+
"quote_market_snapshot",
|
|
152
|
+
"quote_market_state",
|
|
153
|
+
"quote_stock_quote",
|
|
154
|
+
"quote_stock_feed",
|
|
155
|
+
"quote_stock_basicinfo",
|
|
156
|
+
"quote_stock_screen",
|
|
157
|
+
"quote_option_screen",
|
|
158
|
+
"quote_warrant_screen",
|
|
159
|
+
"quote_rt_ticker",
|
|
160
|
+
"quote_rt_data",
|
|
161
|
+
"quote_order_book",
|
|
162
|
+
"quote_cur_kline",
|
|
163
|
+
"quote_history_kline",
|
|
164
|
+
"quote_trading_days",
|
|
165
|
+
"quote_top_ten_brokers",
|
|
166
|
+
"quote_capital_flow",
|
|
167
|
+
"quote_capital_flow_history",
|
|
168
|
+
"quote_capital_distribution",
|
|
169
|
+
"quote_plate_list",
|
|
170
|
+
"quote_plate_stock",
|
|
171
|
+
"quote_owner_plate",
|
|
172
|
+
"quote_referencefuture_list",
|
|
173
|
+
"quote_future_info",
|
|
174
|
+
"quote_option_chain",
|
|
175
|
+
"quote_option_expiration_date",
|
|
176
|
+
"quote_option_volatility",
|
|
177
|
+
"quote_option_exercise_probability",
|
|
178
|
+
"quote_user_security",
|
|
179
|
+
"quote_user_security_group",
|
|
180
|
+
"quote_valuation_detail",
|
|
181
|
+
"quote_valuation_plate_stock_list",
|
|
182
|
+
"quote_valuation_index_stock_plate_list",
|
|
183
|
+
"quote_valuation_index_component_stock_list",
|
|
184
|
+
"quote_financials_statements",
|
|
185
|
+
"quote_financials_revenue_breakdown",
|
|
186
|
+
"quote_financials_earnings_price_history",
|
|
187
|
+
"quote_company_profile",
|
|
188
|
+
"quote_company_executives",
|
|
189
|
+
"quote_company_executive_background",
|
|
190
|
+
"quote_company_operational_efficiency",
|
|
191
|
+
"quote_corporate_actions_dividends",
|
|
192
|
+
"quote_corporate_actions_stock_splits",
|
|
193
|
+
"quote_corporate_actions_buybacks",
|
|
194
|
+
"quote_corporate_actions_rehab",
|
|
195
|
+
"quote_shareholders_overview",
|
|
196
|
+
"quote_shareholders_institutional",
|
|
197
|
+
"quote_shareholders_holding_changes",
|
|
198
|
+
"quote_shareholders_holder_detail",
|
|
199
|
+
"quote_insider_trade_list",
|
|
200
|
+
"quote_insider_holder_list",
|
|
201
|
+
"quote_short_interest",
|
|
202
|
+
"quote_daily_short_volume",
|
|
203
|
+
"quote_research_rating_summary",
|
|
204
|
+
"quote_research_analyst_consensus",
|
|
205
|
+
"quote_research_morningstar_report",
|
|
206
|
+
"quote_news_search",
|
|
207
|
+
"quote_community_search",
|
|
208
|
+
"quote_economic_calendar_search",
|
|
209
|
+
"quote_economic_calendar_hot",
|
|
210
|
+
"quote_ipo_list_us",
|
|
211
|
+
"quote_ipo_list_hk",
|
|
212
|
+
"quote_ipo_list_cn",
|
|
213
|
+
"quote_ipo_list_sg",
|
|
214
|
+
"quote_ipo_list_my"
|
|
215
|
+
]);
|
|
216
|
+
const MOOMOO_PAPER_WRITES = new Set(["sim_trade_input_order", "sim_trade_modify_order", "sim_trade_cancel_order"]);
|
|
217
|
+
export const POLICIES = {
|
|
218
|
+
mercury: {
|
|
219
|
+
slug: "mercury",
|
|
220
|
+
kind: "banking",
|
|
221
|
+
readOnly: MERCURY_READ,
|
|
222
|
+
scopes: ["read", "offline_access", "transactions:request", "transfers:request"]
|
|
223
|
+
},
|
|
224
|
+
coinpay: { slug: "coinpay", kind: "crypto", readOnly: COINPAY_READ },
|
|
225
|
+
moomoo: { slug: "moomoo", kind: "trading", readOnly: MOOMOO_READ, paperWrites: MOOMOO_PAPER_WRITES }
|
|
226
|
+
};
|
|
227
|
+
function parse(u) {
|
|
228
|
+
try {
|
|
229
|
+
return new URL(u);
|
|
230
|
+
} catch {
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
export function policyFor(url) {
|
|
235
|
+
const u = parse(url);
|
|
236
|
+
if (!u)
|
|
237
|
+
return null;
|
|
238
|
+
const host = u.hostname.toLowerCase().replace(/\.$/, "");
|
|
239
|
+
if (host === "mcp.mercury.com")
|
|
240
|
+
return POLICIES.mercury;
|
|
241
|
+
if (host === "mcp.moomoo.com")
|
|
242
|
+
return POLICIES.moomoo;
|
|
243
|
+
if (host === "coinpayportal.com" || host === "www.coinpayportal.com")
|
|
244
|
+
return POLICIES.coinpay;
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
export function needsConfirmation(policy, tool) {
|
|
248
|
+
return !policy.readOnly.has(tool);
|
|
249
|
+
}
|
|
250
|
+
export function visibleInMode(policy, tool, mode) {
|
|
251
|
+
if (policy.kind !== "trading" || mode === "live")
|
|
252
|
+
return true;
|
|
253
|
+
return policy.readOnly.has(tool) || !!policy.paperWrites?.has(tool);
|
|
254
|
+
}
|
|
255
|
+
export function applyPolicy(policy, tools, mode = "paper") {
|
|
256
|
+
if (!policy)
|
|
257
|
+
return tools;
|
|
258
|
+
return tools.filter((t) => visibleInMode(policy, t.name, mode)).map((t) => needsConfirmation(policy, t.name) ? { ...t, annotations: { ...t.annotations ?? {}, readOnlyHint: false, destructiveHint: true } } : { ...t, annotations: { ...t.annotations ?? {}, readOnlyHint: true, destructiveHint: false } });
|
|
259
|
+
}
|
|
260
|
+
const str = (v) => v === undefined || v === null ? "" : typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : JSON.stringify(v);
|
|
261
|
+
function pick(args, names) {
|
|
262
|
+
const norm = (k) => k.toLowerCase().replace(/[_-]/g, "");
|
|
263
|
+
const want = names.map(norm);
|
|
264
|
+
const scan = (o) => {
|
|
265
|
+
for (const w of want) {
|
|
266
|
+
for (const [k, v] of Object.entries(o))
|
|
267
|
+
if (norm(k) === w && v !== undefined && v !== null && v !== "")
|
|
268
|
+
return str(v);
|
|
269
|
+
}
|
|
270
|
+
return "";
|
|
271
|
+
};
|
|
272
|
+
const top = scan(args);
|
|
273
|
+
if (top)
|
|
274
|
+
return top;
|
|
275
|
+
for (const v of Object.values(args)) {
|
|
276
|
+
if (v && typeof v === "object" && !Array.isArray(v)) {
|
|
277
|
+
const inner = scan(v);
|
|
278
|
+
if (inner)
|
|
279
|
+
return inner;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return "";
|
|
283
|
+
}
|
|
284
|
+
function humanTool(tool) {
|
|
285
|
+
const s = tool.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/_/g, " ").toLowerCase();
|
|
286
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
287
|
+
}
|
|
288
|
+
const num = (s) => {
|
|
289
|
+
if (!s)
|
|
290
|
+
return null;
|
|
291
|
+
const n = Number(String(s).replace(/,/g, ""));
|
|
292
|
+
return Number.isFinite(n) ? n : null;
|
|
293
|
+
};
|
|
294
|
+
function tradingSummary(tool, args) {
|
|
295
|
+
const paper = tool.startsWith("sim_trade_");
|
|
296
|
+
const lines = [];
|
|
297
|
+
const add = (label, value) => {
|
|
298
|
+
if (value)
|
|
299
|
+
lines.push({ label, value });
|
|
300
|
+
};
|
|
301
|
+
const isCancel = /cancel/.test(tool);
|
|
302
|
+
const isChange = /modify|replace/.test(tool);
|
|
303
|
+
const isPlace = !isCancel && !isChange && /order|place|confirm/.test(tool);
|
|
304
|
+
const title = isCancel ? "Cancel order" : isChange ? "Change order" : /confirm/.test(tool) ? "Confirm order" : isPlace ? "Place order" : humanTool(tool);
|
|
305
|
+
add("Symbol", pick(args, ["code", "symbol", "ticker", "security"]));
|
|
306
|
+
add("Side", pick(args, ["side", "trd_side", "direction"]));
|
|
307
|
+
const qty = pick(args, ["qty", "quantity", "new_qty", "shares"]);
|
|
308
|
+
add("Quantity", qty);
|
|
309
|
+
const type = pick(args, ["order_type", "type"]);
|
|
310
|
+
add("Order type", type);
|
|
311
|
+
const price = pick(args, ["price", "limit_price", "new_price"]);
|
|
312
|
+
add("Limit price", price);
|
|
313
|
+
add("Stop / trigger price", pick(args, ["aux_price", "stop_price", "trigger_price"]));
|
|
314
|
+
add("Time in force", pick(args, ["time_in_force", "tif"]));
|
|
315
|
+
add("Order id", pick(args, ["order_id", "confirm_id"]));
|
|
316
|
+
if (isPlace || isChange) {
|
|
317
|
+
const q = num(qty);
|
|
318
|
+
const p = num(price);
|
|
319
|
+
lines.push({
|
|
320
|
+
label: "Estimated cost",
|
|
321
|
+
value: q !== null && p !== null && !/MARKET/i.test(type) ? `${(q * p).toLocaleString("en-US", { maximumFractionDigits: 4 })} (quantity x price, before fees; options and futures also multiply by the contract size)` : "at the market price, not known until it fills"
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
add("Account id", pick(args, ["acc_id", "account_id"]));
|
|
325
|
+
lines.push({ label: "Account", value: paper ? "PAPER (simulated, no real money)" : "LIVE (real money)" });
|
|
326
|
+
return { title, lines, account: paper ? "paper" : "live", note: MODEL_CAN_BE_WRONG };
|
|
327
|
+
}
|
|
328
|
+
function moneySummary(kind, tool, args) {
|
|
329
|
+
const lines = [];
|
|
330
|
+
const add = (label, value) => {
|
|
331
|
+
if (value)
|
|
332
|
+
lines.push({ label, value });
|
|
333
|
+
};
|
|
334
|
+
let amount = pick(args, ["amount", "amountUsd", "value", "total", "paymentAmount"]);
|
|
335
|
+
let currency = pick(args, ["currency", "currencyCode", "asset", "coin"]);
|
|
336
|
+
const items = Array.isArray(args.lineItems) ? args.lineItems : null;
|
|
337
|
+
if (!amount && items) {
|
|
338
|
+
const t = items.reduce((s, i) => s + (Number(i?.quantity) || 0) * (Number(i?.unit_price) || 0), 0);
|
|
339
|
+
amount = `${t.toLocaleString("en-US", { maximumFractionDigits: 8 })} before tax and discount (${items.length} line item${items.length === 1 ? "" : "s"})`;
|
|
340
|
+
if (!currency)
|
|
341
|
+
currency = "USD";
|
|
342
|
+
}
|
|
343
|
+
if (typeof args.minutes === "number")
|
|
344
|
+
add("Time", `${args.minutes} minutes`);
|
|
345
|
+
add("Amount", amount);
|
|
346
|
+
add("Currency", currency);
|
|
347
|
+
add("From", pick(args, ["fromAccountId", "sourceAccountId", "from", "accountId", "fromAccount", "businessId", "fromWallet"]));
|
|
348
|
+
add("To", pick(args, ["recipientId", "toAccountId", "destinationAccountId", "to", "recipient", "toAddress", "address", "clientId", "contractorId", "projectId"]));
|
|
349
|
+
add("Memo", pick(args, ["memo", "note", "notes", "externalMemo", "description", "purpose", "remark"]));
|
|
350
|
+
add("Payment method", pick(args, ["paymentMethod", "method", "network", "chain"]));
|
|
351
|
+
return {
|
|
352
|
+
title: humanTool(tool),
|
|
353
|
+
lines,
|
|
354
|
+
note: kind === "banking" ? "Mercury payment and transfer requests still need an approver in Mercury." : MODEL_CAN_BE_WRONG
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
export function describeAction(policy, tool, args) {
|
|
358
|
+
if (!policy)
|
|
359
|
+
return null;
|
|
360
|
+
const a = args && typeof args === "object" ? args : {};
|
|
361
|
+
return policy.kind === "trading" ? tradingSummary(tool, a) : moneySummary(policy.kind, tool, a);
|
|
362
|
+
}
|
|
363
|
+
export function redactLog(v) {
|
|
364
|
+
const s = v instanceof Error ? `${v.name}: ${v.message}` : typeof v === "string" ? v : (() => {
|
|
365
|
+
try {
|
|
366
|
+
return JSON.stringify(v);
|
|
367
|
+
} catch {
|
|
368
|
+
return String(v);
|
|
369
|
+
}
|
|
370
|
+
})();
|
|
371
|
+
return s.replace(/(bearer\s+)\S+/gi, "$1[redacted]").replace(/("?(?:access_token|refresh_token|id_token|client_secret|code|code_verifier|token|password|secret)"?\s*[:=]\s*"?)[^"&\s,}]+/gi, "$1[redacted]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g, "[jwt]").replace(/[A-Za-z0-9_\-+/=]{32,}/g, "[opaque]").replace(/\d[\d -]{6,}\d/g, "[number]").replace(/[$€£]\s?\d[\d,]*(\.\d+)?/g, "[amount]").slice(0, 500);
|
|
372
|
+
}
|