@evex-dev/linejs-cli 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,1241 @@
1
+ import { r as errorMessage } from "./errors-pVbxr1wG.mjs";
2
+ import { a as commandMetadata, i as resolveCommandTokens, n as VERSION, o as isMcpExecutable, r as allCommands, s as splitLeadingGlobalOptions, t as runCli } from "./cli-eG7C8gFC.mjs";
3
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
4
+ import { once } from "node:events";
5
+ import { createInterface } from "node:readline";
6
+ import { lookup } from "node:dns/promises";
7
+ import { request } from "node:https";
8
+ import { isIP } from "node:net";
9
+ // src/mcp/webhook.ts
10
+ /**
11
+ * Webhook delivery for the MCP Events extension.
12
+ *
13
+ * Deliveries follow the Standard Webhooks profile described by
14
+ * https://github.com/modelcontextprotocol/experimental-ext-triggers-events and
15
+ * are hardened against SSRF: the hostname is resolved and validated on every
16
+ * attempt, the connection is pinned to the validated address, and redirects
17
+ * are never followed.
18
+ */
19
+ const WEBHOOK_SECRET_PREFIX = "whsec_";
20
+ const MAX_RESPONSE_BYTES = 65536;
21
+ const DEFAULT_TIMEOUT_MS = 1e4;
22
+ var WebhookDeliveryError = class extends Error {
23
+ category;
24
+ constructor(category, message) {
25
+ super(message);
26
+ this.name = "WebhookDeliveryError";
27
+ this.category = category;
28
+ }
29
+ };
30
+ /** Returns a human-readable problem when `value` is not a Standard Webhooks secret. */
31
+ function webhookSecretProblem(value) {
32
+ if (typeof value !== "string") return "delivery.secret must be a string";
33
+ if (!value.startsWith("whsec_")) return `delivery.secret must start with ${WEBHOOK_SECRET_PREFIX}`;
34
+ const encoded = value.slice(6);
35
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return "delivery.secret must be base64 after the whsec_ prefix";
36
+ const bytes = Buffer.from(encoded, "base64");
37
+ if (bytes.length < 24 || bytes.length > 64) return "delivery.secret must decode to 24-64 bytes";
38
+ return null;
39
+ }
40
+ function decodeWebhookSecret(secret) {
41
+ const encoded = secret.startsWith("whsec_") ? secret.slice(6) : secret;
42
+ return Buffer.from(encoded, "base64");
43
+ }
44
+ /**
45
+ * Standard Webhooks signature: `v1,<base64 HMAC-SHA256(secret, id.timestamp.body)>`.
46
+ * The body must be the exact bytes sent on the wire.
47
+ */
48
+ function signWebhook(secret, webhookId, timestampSeconds, body) {
49
+ return `v1,${createHmac("sha256", decodeWebhookSecret(secret)).update(`${webhookId}.${timestampSeconds}.${body}`, "utf8").digest("base64")}`;
50
+ }
51
+ /** Space-delimited multi-signature header, used for secret rotation. */
52
+ function webhookSignatureHeader(secrets, webhookId, timestampSeconds, body) {
53
+ return secrets.filter((secret) => typeof secret === "string" && secret.length > 0).map((secret) => signWebhook(secret, webhookId, timestampSeconds, body)).join(" ");
54
+ }
55
+ function webhookErrorCategory(status) {
56
+ return status >= 500 ? "http_5xx" : "http_4xx";
57
+ }
58
+ /** Parse and enforce the `https` requirement for callback URLs. */
59
+ function parseCallbackUrl(value) {
60
+ if (typeof value !== "string" || !value.trim()) throw new Error("delivery.url must be a non-empty string");
61
+ let url;
62
+ try {
63
+ url = new URL(value);
64
+ } catch {
65
+ throw new Error("delivery.url must be an absolute URL");
66
+ }
67
+ if (url.protocol !== "https:") throw new Error("delivery.url must use https");
68
+ if (!url.hostname) throw new Error("delivery.url must include a hostname");
69
+ if (url.username || url.password) throw new Error("delivery.url must not embed credentials");
70
+ if (url.hash) throw new Error("delivery.url must not include a fragment");
71
+ return url;
72
+ }
73
+ const V4_BLOCKLIST = [
74
+ ["0.0.0.0", 8],
75
+ ["10.0.0.0", 8],
76
+ ["100.64.0.0", 10],
77
+ ["127.0.0.0", 8],
78
+ ["169.254.0.0", 16],
79
+ ["172.16.0.0", 12],
80
+ ["192.0.0.0", 24],
81
+ ["192.0.2.0", 24],
82
+ ["192.88.99.0", 24],
83
+ ["192.168.0.0", 16],
84
+ ["198.18.0.0", 15],
85
+ ["198.51.100.0", 24],
86
+ ["203.0.113.0", 24],
87
+ ["224.0.0.0", 4],
88
+ ["240.0.0.0", 4]
89
+ ];
90
+ function ipv4ToInt(address) {
91
+ return address.split(".").reduce((total, part) => (total << 8 | Number(part) & 255) >>> 0, 0);
92
+ }
93
+ function inV4Range(value, base, prefix) {
94
+ const mask = prefix === 0 ? 0 : 4294967295 << 32 - prefix >>> 0;
95
+ return (value & mask) >>> 0 === (ipv4ToInt(base) & mask) >>> 0;
96
+ }
97
+ function isPublicV4(address) {
98
+ const value = ipv4ToInt(address);
99
+ return !V4_BLOCKLIST.some(([base, prefix]) => inV4Range(value, base, prefix));
100
+ }
101
+ function isPublicV6(address) {
102
+ const normalized = address.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0] ?? "";
103
+ if (normalized === "::" || normalized === "::1") return false;
104
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(normalized);
105
+ if (mapped?.[1]) return isPublicV4(mapped[1]);
106
+ const first = normalized.split(":")[0] ?? "";
107
+ if (!first) return false;
108
+ const prefix = Number.parseInt(first.padEnd(4, "0"), 16);
109
+ if (Number.isNaN(prefix)) return false;
110
+ if ((prefix & 65024) === 64512) return false;
111
+ if ((prefix & 65472) === 65152) return false;
112
+ if ((prefix & 65280) === 65280) return false;
113
+ if (normalized.startsWith("2001:db8:")) return false;
114
+ if (normalized === "100::" || normalized.startsWith("100::")) return false;
115
+ return true;
116
+ }
117
+ /** True when the address is globally routable per the IANA special-purpose registries. */
118
+ function isPublicAddress(address) {
119
+ const family = isIP(address);
120
+ if (family === 4) return isPublicV4(address);
121
+ if (family === 6) return isPublicV6(address);
122
+ return false;
123
+ }
124
+ /**
125
+ * Deliveries resolve the callback host on every attempt and connect to the
126
+ * validated address while keeping the original hostname for TLS verification.
127
+ */
128
+ function createWebhookTransport(options = {}) {
129
+ const resolve = options.resolve ?? (async (hostname) => lookup(hostname, { all: true }));
130
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
131
+ return { async post(request$1) {
132
+ const url = new URL(request$1.url);
133
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
134
+ let addresses;
135
+ try {
136
+ addresses = await resolve(hostname);
137
+ } catch {
138
+ throw new WebhookDeliveryError("connection_refused", `could not resolve ${hostname}`);
139
+ }
140
+ if (!addresses.length) throw new WebhookDeliveryError("connection_refused", `${hostname} did not resolve`);
141
+ if (addresses.some((entry) => !isPublicAddress(entry.address))) throw new WebhookDeliveryError("connection_refused", `${hostname} resolves to a non-public address`);
142
+ const target = addresses[0];
143
+ const body = request$1.body;
144
+ return await new Promise((resolveRequest, rejectRequest) => {
145
+ const headers = {
146
+ ...request$1.headers,
147
+ host: url.host,
148
+ "content-length": String(Buffer.byteLength(body, "utf8"))
149
+ };
150
+ const signal = AbortSignal.timeout(request$1.timeoutMs ?? timeoutMs);
151
+ const call = request({
152
+ method: "POST",
153
+ host: hostname,
154
+ port: url.port ? Number(url.port) : 443,
155
+ path: `${url.pathname}${url.search}`,
156
+ headers,
157
+ ...isIP(hostname) ? {} : { servername: hostname },
158
+ lookup: (_host, lookupOptions, callback) => {
159
+ if (lookupOptions?.all) {
160
+ callback(null, [{
161
+ address: target.address,
162
+ family: target.family
163
+ }]);
164
+ return;
165
+ }
166
+ callback(null, target.address, target.family);
167
+ },
168
+ signal
169
+ }, (response) => {
170
+ const chunks = [];
171
+ let size = 0;
172
+ response.on("data", (chunk) => {
173
+ if (size >= MAX_RESPONSE_BYTES) return;
174
+ const slice = chunk.subarray(0, MAX_RESPONSE_BYTES - size);
175
+ chunks.push(slice);
176
+ size += slice.length;
177
+ });
178
+ response.on("end", () => {
179
+ resolveRequest({
180
+ status: response.statusCode ?? 0,
181
+ body: Buffer.concat(chunks).toString("utf8")
182
+ });
183
+ });
184
+ response.on("error", rejectRequest);
185
+ });
186
+ call.on("error", rejectRequest);
187
+ call.end(body);
188
+ }).catch((error) => {
189
+ throw toWebhookDeliveryError(error);
190
+ });
191
+ } };
192
+ }
193
+ const TLS_ERROR_CODES = [
194
+ "ERR_TLS_CERT_ALTNAME_INVALID",
195
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
196
+ "SELF_SIGNED_CERT_IN_CHAIN",
197
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
198
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
199
+ "CERT_HAS_EXPIRED",
200
+ "ERR_SSL_WRONG_VERSION_NUMBER",
201
+ "ERR_SSL_PACKET_LENGTH_MISMATCH",
202
+ "EPROTO"
203
+ ];
204
+ function toWebhookDeliveryError(error) {
205
+ if (error instanceof WebhookDeliveryError) return error;
206
+ if (error instanceof Error) {
207
+ const code = error.code ?? "";
208
+ if (error.name === "AbortError" || code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT") return new WebhookDeliveryError("timeout", "callback endpoint timed out");
209
+ if (TLS_ERROR_CODES.includes(code) || code.startsWith("ERR_TLS") || code.startsWith("ERR_SSL")) return new WebhookDeliveryError("tls_error", "callback endpoint failed TLS verification");
210
+ if (code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "EHOSTUNREACH") return new WebhookDeliveryError("connection_refused", "callback endpoint refused the connection");
211
+ return new WebhookDeliveryError("connection_refused", error.message);
212
+ }
213
+ return new WebhookDeliveryError("connection_refused", String(error));
214
+ }
215
+ // src/mcp/events.ts
216
+ /**
217
+ * MCP Events (webhook delivery), following the draft extension in
218
+ * https://github.com/modelcontextprotocol/experimental-ext-triggers-events and
219
+ * the subset ChatGPT implements (events/list, events/subscribe,
220
+ * events/unsubscribe, signed webhook deliveries, callback verification).
221
+ */
222
+ const EVENT_ERROR_NOT_FOUND = -32023;
223
+ const EVENT_ERROR_FORBIDDEN = -32024;
224
+ const EVENT_ERROR_RESOURCE_EXHAUSTED = -32025;
225
+ const EVENT_ERROR_UNSUPPORTED = -32026;
226
+ const EVENT_ERROR_CALLBACK = -32027;
227
+ const EVENT_ERROR_INVALID_PARAMS = -32602;
228
+ var EventRpcError = class extends Error {
229
+ code;
230
+ data;
231
+ constructor(code, message, data) {
232
+ super(message);
233
+ this.name = "EventRpcError";
234
+ this.code = code;
235
+ this.data = data;
236
+ }
237
+ };
238
+ const FILTER_PROPERTIES = {
239
+ chatId: {
240
+ type: "string",
241
+ description: "Only deliver messages from chats whose id matches this glob pattern (e.g. \"c0123456789abcdef\"). Omit to match every chat."
242
+ },
243
+ from: {
244
+ type: "string",
245
+ description: "Only deliver messages whose sender mid matches this glob pattern. Omit to match every sender."
246
+ },
247
+ includeText: {
248
+ type: "boolean",
249
+ default: true,
250
+ description: "Include a truncated text preview in the payload. Disable to keep user-authored text out of webhook infrastructure."
251
+ }
252
+ };
253
+ function inputSchema() {
254
+ return {
255
+ type: "object",
256
+ properties: FILTER_PROPERTIES,
257
+ additionalProperties: false
258
+ };
259
+ }
260
+ function payloadSchema(timestampKey) {
261
+ return {
262
+ type: "object",
263
+ properties: {
264
+ messageId: {
265
+ type: "string",
266
+ description: "Stable LINE message id, usable for dedup."
267
+ },
268
+ chatId: {
269
+ type: "string",
270
+ description: "Chat (or OpenChat room) the message belongs to."
271
+ },
272
+ from: {
273
+ type: "string",
274
+ description: "Sender mid."
275
+ },
276
+ contentType: {
277
+ type: "string",
278
+ description: "LINE content type, e.g. TEXT or IMAGE."
279
+ },
280
+ text: {
281
+ type: "string",
282
+ description: "Truncated text preview. Omitted when includeText is false or the message has no text."
283
+ },
284
+ [timestampKey]: {
285
+ type: "string",
286
+ format: "date-time",
287
+ description: "When the message was sent (ISO 8601)."
288
+ }
289
+ },
290
+ required: [
291
+ "messageId",
292
+ "chatId",
293
+ "from",
294
+ "contentType",
295
+ timestampKey
296
+ ],
297
+ additionalProperties: false
298
+ };
299
+ }
300
+ const EVENT_DEFINITIONS = [
301
+ {
302
+ name: "line.message.received",
303
+ description: "Fires when the connected LINE account receives a new talk message in a one-to-one or group chat.",
304
+ delivery: ["webhook"],
305
+ inputSchema: inputSchema(),
306
+ payloadSchema: payloadSchema("receivedAt")
307
+ },
308
+ {
309
+ name: "line.message.edited",
310
+ description: "Fires when a talk message the account can see is edited.",
311
+ delivery: ["webhook"],
312
+ inputSchema: inputSchema(),
313
+ payloadSchema: payloadSchema("updatedAt")
314
+ },
315
+ {
316
+ name: "line.openchat.message.received",
317
+ description: "Fires when a message arrives in an OpenChat (square) room.",
318
+ delivery: ["webhook"],
319
+ inputSchema: inputSchema(),
320
+ payloadSchema: payloadSchema("receivedAt")
321
+ }
322
+ ];
323
+ /** Collapse whitespace and truncate user-authored text for payload minimality. */
324
+ function previewText(value) {
325
+ if (typeof value !== "string" || !value) return void 0;
326
+ const flat = value.replace(/\s+/g, " ").trim();
327
+ if (!flat) return void 0;
328
+ return flat.length > 400 ? `${flat.slice(0, 400)}…` : flat;
329
+ }
330
+ const DEFAULT_LIMITS = {
331
+ maxSubscriptions: 20,
332
+ maxQueue: 50,
333
+ maxAttempts: 4,
334
+ retryBaseMs: 1e3,
335
+ retryMaxDelayMs: 15e3,
336
+ suspendAfterFailures: 5,
337
+ defaultTtlMs: 9e5,
338
+ minTtlMs: 6e4,
339
+ maxTtlMs: 36e5,
340
+ verificationTtlMs: 18e5
341
+ };
342
+ function canonicalize(value) {
343
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
344
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`;
345
+ return `{${Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalize(entry)}`).join(",")}}`;
346
+ }
347
+ /** Canonical JSON with sorted keys, so equivalent arguments share one subscription. */
348
+ function canonicalJson(value) {
349
+ return canonicalize(value ?? {});
350
+ }
351
+ function globToRegExp(pattern) {
352
+ let source = "";
353
+ for (const character of pattern) if (character === "*") source += ".*";
354
+ else if (character === "?") source += ".";
355
+ else source += character.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
356
+ return new RegExp(`^${source}$`, "u");
357
+ }
358
+ function matchesFilters(filters, data) {
359
+ const chatId = typeof filters.chatId === "string" ? filters.chatId : void 0;
360
+ if (chatId && !globToRegExp(chatId).test(String(data.chatId ?? ""))) return false;
361
+ const from = typeof filters.from === "string" ? filters.from : void 0;
362
+ if (from && !globToRegExp(from).test(String(data.from ?? ""))) return false;
363
+ return true;
364
+ }
365
+ function validateArguments(definition, value) {
366
+ if (value === void 0 || value === null) return {};
367
+ if (typeof value !== "object" || Array.isArray(value)) throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, "params.arguments must be an object");
368
+ const properties = definition.inputSchema.properties ?? {};
369
+ const entries = value;
370
+ for (const key of Object.keys(entries)) if (!(key in properties)) throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, `Unknown argument for ${definition.name}: ${key}`, { argument: key });
371
+ for (const [key, schema] of Object.entries(properties)) {
372
+ const entry = entries[key];
373
+ if (entry === void 0) continue;
374
+ const invalid = () => {
375
+ throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, `Argument ${key} must be ${schema.type}`, { argument: key });
376
+ };
377
+ if (schema.type === "string") {
378
+ if (typeof entry !== "string" || entry.length > 512) invalid();
379
+ } else if (schema.type === "boolean") {
380
+ if (typeof entry !== "boolean") invalid();
381
+ } else if (schema.type === "integer") {
382
+ if (!Number.isInteger(entry)) invalid();
383
+ } else if (schema.type === "number") {
384
+ if (typeof entry !== "number" || !Number.isFinite(entry)) invalid();
385
+ }
386
+ if (schema.enum && !schema.enum.includes(entry)) invalid();
387
+ }
388
+ return entries;
389
+ }
390
+ function constantTimeEqual(left, right) {
391
+ const a = Buffer.from(left, "utf8");
392
+ const b = Buffer.from(right, "utf8");
393
+ if (a.length !== b.length) return false;
394
+ return timingSafeEqual(a, b);
395
+ }
396
+ var McpEventHub = class {
397
+ principal;
398
+ definitions;
399
+ limits;
400
+ transport;
401
+ sourceFactory;
402
+ clock;
403
+ delay;
404
+ log;
405
+ subscriptions = /* @__PURE__ */ new Map();
406
+ sources = /* @__PURE__ */ new Map();
407
+ verified = /* @__PURE__ */ new Map();
408
+ workers = /* @__PURE__ */ new Set();
409
+ timer;
410
+ closed = false;
411
+ constructor(options) {
412
+ this.principal = options.principal;
413
+ this.definitions = options.definitions ?? EVENT_DEFINITIONS;
414
+ this.limits = {
415
+ ...DEFAULT_LIMITS,
416
+ ...options.limits
417
+ };
418
+ this.transport = options.transport ?? createWebhookTransport();
419
+ this.sourceFactory = options.sourceFactory;
420
+ this.clock = options.now ?? Date.now;
421
+ this.delay = options.delay ?? ((ms) => new Promise((resolve) => {
422
+ setTimeout(resolve, ms).unref?.();
423
+ }));
424
+ this.log = options.log ?? (() => {});
425
+ if (options.autoSweep !== false) {
426
+ this.timer = setInterval(() => this.sweep(), 3e4);
427
+ this.timer.unref?.();
428
+ }
429
+ }
430
+ get activeSubscriptionCount() {
431
+ return this.subscriptions.size;
432
+ }
433
+ list(params = {}) {
434
+ const cursor = params.cursor;
435
+ if (cursor !== void 0 && cursor !== null && typeof cursor !== "string") throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, "params.cursor must be a string");
436
+ return { events: this.definitions.map((definition) => ({
437
+ name: definition.name,
438
+ description: definition.description,
439
+ delivery: [...definition.delivery],
440
+ inputSchema: definition.inputSchema,
441
+ payloadSchema: definition.payloadSchema
442
+ })) };
443
+ }
444
+ async subscribe(params) {
445
+ const definition = this.definitionFor(params.name);
446
+ const filters = validateArguments(definition, params.arguments);
447
+ const delivery = this.validateDelivery(params.delivery);
448
+ const ttlMs = this.grantTtl(params.ttlMs);
449
+ const id = this.subscriptionId(delivery.url, definition.name, filters);
450
+ const existing = this.subscriptions.get(id);
451
+ if (!existing && this.subscriptions.size >= this.limits.maxSubscriptions) throw new EventRpcError(EVENT_ERROR_RESOURCE_EXHAUSTED, `At most ${this.limits.maxSubscriptions} webhook subscriptions are supported`, {
452
+ limit: "subscriptions",
453
+ max: this.limits.maxSubscriptions
454
+ });
455
+ await this.verifyEndpoint(delivery.url, delivery.secret, id);
456
+ const now = this.clock();
457
+ const previousStatus = existing ? {
458
+ active: existing.active,
459
+ lastDeliveryAt: existing.lastDeliveryAt ?? null,
460
+ lastError: existing.lastError ?? null,
461
+ ...existing.failedSince ? { failedSince: existing.failedSince } : {}
462
+ } : void 0;
463
+ const subscription = existing ?? {
464
+ id,
465
+ principal: this.principal,
466
+ name: definition.name,
467
+ arguments: filters,
468
+ url: delivery.url,
469
+ secret: delivery.secret,
470
+ expiresAt: now + ttlMs,
471
+ active: true,
472
+ consecutiveFailures: 0,
473
+ queue: [],
474
+ draining: false,
475
+ removed: false
476
+ };
477
+ subscription.secret = delivery.secret;
478
+ if (existing?.secret && existing.secret !== delivery.secret) {
479
+ subscription.previousSecret = existing.secret;
480
+ subscription.previousSecretUntil = now + 3e5;
481
+ }
482
+ subscription.expiresAt = now + ttlMs;
483
+ subscription.active = true;
484
+ subscription.consecutiveFailures = 0;
485
+ subscription.removed = false;
486
+ this.subscriptions.set(id, subscription);
487
+ try {
488
+ await this.ensureSources();
489
+ } catch (error) {
490
+ if (!existing) this.dropSubscription(subscription);
491
+ throw error;
492
+ }
493
+ if (existing) this.scheduleDrain(subscription);
494
+ return {
495
+ id,
496
+ refreshBefore: new Date(subscription.expiresAt).toISOString(),
497
+ cursor: null,
498
+ truncated: false,
499
+ ...previousStatus ? { deliveryStatus: previousStatus } : {}
500
+ };
501
+ }
502
+ unsubscribe(params) {
503
+ const definition = this.definitionFor(params.name);
504
+ const filters = validateArguments(definition, params.arguments);
505
+ const delivery = this.validateDelivery(params.delivery, { requireSecret: false });
506
+ const id = this.subscriptionId(delivery.url, definition.name, filters);
507
+ const subscription = this.subscriptions.get(id);
508
+ if (subscription) this.dropSubscription(subscription);
509
+ this.stopUnusedSources();
510
+ return {};
511
+ }
512
+ /** Deliver one occurrence to every active, matching subscription. */
513
+ emit(record) {
514
+ if (this.closed) return;
515
+ const timestamp = record.occurredAt || new Date(this.clock()).toISOString();
516
+ for (const subscription of this.subscriptions.values()) {
517
+ if (subscription.removed || !subscription.active) continue;
518
+ if (subscription.name !== record.name) continue;
519
+ if (!matchesFilters(subscription.arguments, record.data)) continue;
520
+ const stampKey = subscription.name === "line.message.edited" ? "updatedAt" : "receivedAt";
521
+ const data = this.projectPayload(subscription.name, record.data, stampKey, timestamp);
522
+ if (subscription.arguments.includeText === false) delete data.text;
523
+ this.enqueue(subscription, {
524
+ eventId: this.eventIdFor(subscription.name, data, timestamp),
525
+ name: subscription.name,
526
+ timestamp,
527
+ data,
528
+ cursor: null
529
+ });
530
+ }
531
+ }
532
+ /** Keep only the fields advertised by the event's payloadSchema. */
533
+ projectPayload(name, source, stampKey, timestamp) {
534
+ const properties = this.definitions.find((entry) => entry.name === name)?.payloadSchema.properties ?? {};
535
+ const data = {};
536
+ for (const key of Object.keys(properties)) {
537
+ const value = key === stampKey ? timestamp : source[key];
538
+ if (value !== void 0 && value !== null) data[key] = value;
539
+ }
540
+ return data;
541
+ }
542
+ /** Wait for queued deliveries to finish (used by tests and graceful shutdown). */
543
+ async flushDeliveries() {
544
+ while (this.workers.size) await Promise.allSettled(this.workers);
545
+ }
546
+ /** Drop expired subscriptions. Returns the ids that were removed. */
547
+ sweep() {
548
+ const now = this.clock();
549
+ const removed = [];
550
+ for (const subscription of this.subscriptions.values()) if (subscription.expiresAt <= now) {
551
+ this.dropSubscription(subscription);
552
+ removed.push(subscription.id);
553
+ }
554
+ for (const [key, expiresAt] of this.verified) if (expiresAt <= now) this.verified.delete(key);
555
+ this.stopUnusedSources();
556
+ return removed;
557
+ }
558
+ async close() {
559
+ this.closed = true;
560
+ if (this.timer) clearInterval(this.timer);
561
+ this.timer = void 0;
562
+ for (const subscription of this.subscriptions.values()) this.dropSubscription(subscription);
563
+ const sources = [...this.sources.values()];
564
+ this.sources.clear();
565
+ await Promise.all(sources.map(async (source) => await source.stop().catch(() => {})));
566
+ }
567
+ definitionFor(name) {
568
+ if (typeof name !== "string" || !name) throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, "params.name must be a string");
569
+ const definition = this.definitions.find((entry) => entry.name === name);
570
+ if (!definition) throw new EventRpcError(EVENT_ERROR_NOT_FOUND, `Unknown event: ${name}`, { kind: "event" });
571
+ return definition;
572
+ }
573
+ validateDelivery(value, options = {}) {
574
+ const requireSecret = options.requireSecret ?? true;
575
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, "params.delivery must be an object");
576
+ const delivery = value;
577
+ if (delivery.mode !== void 0 && delivery.mode !== "webhook") throw new EventRpcError(EVENT_ERROR_UNSUPPORTED, `Unsupported delivery mode: ${String(delivery.mode)}`, {
578
+ feature: "deliveryMode",
579
+ value: delivery.mode ?? null
580
+ });
581
+ let url;
582
+ try {
583
+ url = parseCallbackUrl(delivery.url);
584
+ } catch (error) {
585
+ throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, error instanceof Error ? error.message : String(error));
586
+ }
587
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
588
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname) || hostname.includes(":")) {
589
+ if (!isPublicAddress(hostname)) throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, "delivery.url must point at a globally routable address");
590
+ }
591
+ let secret = "";
592
+ if (requireSecret || delivery.secret !== void 0) {
593
+ const problem = webhookSecretProblem(delivery.secret);
594
+ if (problem) throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, problem);
595
+ secret = delivery.secret;
596
+ }
597
+ return {
598
+ url: url.toString(),
599
+ secret
600
+ };
601
+ }
602
+ grantTtl(requested) {
603
+ if (requested === null) return this.limits.maxTtlMs;
604
+ if (requested === void 0) return this.limits.defaultTtlMs;
605
+ if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0) throw new EventRpcError(EVENT_ERROR_INVALID_PARAMS, "params.ttlMs must be a positive integer");
606
+ const floored = Math.max(Math.floor(requested), this.limits.minTtlMs);
607
+ return Math.min(floored, this.limits.maxTtlMs);
608
+ }
609
+ subscriptionId(url, name, filters) {
610
+ return `sub_${createHash("sha256").update(canonicalJson({
611
+ principal: this.principal,
612
+ url,
613
+ name,
614
+ arguments: filters
615
+ })).digest("hex").slice(0, 16)}`;
616
+ }
617
+ async verifyEndpoint(url, secret, subscriptionId) {
618
+ const key = `${this.principal}\u0000${url}`;
619
+ const cached = this.verified.get(key);
620
+ if (cached !== void 0 && cached > this.clock()) return;
621
+ const challenge = randomBytes(24).toString("base64url");
622
+ const body = JSON.stringify({
623
+ type: "verification",
624
+ challenge
625
+ });
626
+ const webhookId = `msg_verification_${randomBytes(8).toString("hex")}`;
627
+ const timestamp = Math.floor(this.clock() / 1e3);
628
+ let response;
629
+ try {
630
+ response = await this.transport.post({
631
+ url,
632
+ body,
633
+ headers: {
634
+ "content-type": "application/json",
635
+ "webhook-id": webhookId,
636
+ "webhook-timestamp": String(timestamp),
637
+ "webhook-signature": webhookSignatureHeader([secret], webhookId, timestamp, body),
638
+ "x-mcp-subscription-id": subscriptionId,
639
+ "user-agent": `linejs-cli/${VERSION}`
640
+ }
641
+ });
642
+ } catch (error) {
643
+ const reason = error instanceof WebhookDeliveryError ? error.category : "connection_refused";
644
+ throw new EventRpcError(EVENT_ERROR_CALLBACK, "Could not verify the callback endpoint", { reason });
645
+ }
646
+ if (response.status < 200 || response.status >= 300) throw new EventRpcError(EVENT_ERROR_CALLBACK, "Could not verify the callback endpoint", { reason: webhookErrorCategory(response.status) });
647
+ let echoed;
648
+ try {
649
+ echoed = JSON.parse(response.body).challenge;
650
+ } catch {
651
+ echoed = void 0;
652
+ }
653
+ if (typeof echoed !== "string" || !constantTimeEqual(echoed, challenge)) throw new EventRpcError(EVENT_ERROR_CALLBACK, "Could not verify the callback endpoint", { reason: "challenge_failed" });
654
+ this.verified.set(key, this.clock() + this.limits.verificationTtlMs);
655
+ }
656
+ eventIdFor(name, data, timestamp) {
657
+ const messageId = typeof data.messageId === "string" ? data.messageId : void 0;
658
+ if (!messageId) return `evt_${randomBytes(12).toString("hex")}`;
659
+ return `evt_${createHash("sha256").update(`${name}\u0000${messageId}\u0000${timestamp}`).digest("hex").slice(0, 24)}`;
660
+ }
661
+ enqueue(subscription, occurrence) {
662
+ const body = JSON.stringify(occurrence);
663
+ if (Buffer.byteLength(body, "utf8") > 262144) {
664
+ this.log(`dropped oversized event ${occurrence.eventId} (${occurrence.name})`);
665
+ return;
666
+ }
667
+ if (subscription.queue.length >= this.limits.maxQueue) {
668
+ const dropped = subscription.queue.shift();
669
+ if (dropped) this.log(`delivery queue full for ${subscription.id}; dropped ${dropped.occurrence.eventId}`);
670
+ }
671
+ subscription.queue.push({
672
+ occurrence,
673
+ body
674
+ });
675
+ this.scheduleDrain(subscription);
676
+ }
677
+ scheduleDrain(subscription) {
678
+ if (subscription.draining) return;
679
+ const worker = this.drain(subscription).finally(() => {
680
+ this.workers.delete(worker);
681
+ });
682
+ this.workers.add(worker);
683
+ }
684
+ async drain(subscription) {
685
+ if (subscription.draining || this.closed) return;
686
+ subscription.draining = true;
687
+ try {
688
+ while (!this.closed && !subscription.removed && subscription.active && subscription.queue.length) {
689
+ const job = subscription.queue.shift();
690
+ await this.deliver(subscription, job);
691
+ }
692
+ } finally {
693
+ subscription.draining = false;
694
+ }
695
+ }
696
+ async deliver(subscription, job) {
697
+ for (let attempt = 1; attempt <= this.limits.maxAttempts; attempt += 1) {
698
+ if (this.closed || subscription.removed || !subscription.active) return;
699
+ const timestamp = Math.floor(this.clock() / 1e3);
700
+ const secrets = [subscription.secret];
701
+ if (subscription.previousSecret) secrets.push(subscription.previousSecret);
702
+ let status = 0;
703
+ try {
704
+ status = (await this.transport.post({
705
+ url: subscription.url,
706
+ body: job.body,
707
+ headers: {
708
+ "content-type": "application/json",
709
+ "webhook-id": job.occurrence.eventId,
710
+ "webhook-timestamp": String(timestamp),
711
+ "webhook-signature": webhookSignatureHeader(secrets, job.occurrence.eventId, timestamp, job.body),
712
+ "x-mcp-subscription-id": subscription.id,
713
+ "user-agent": `linejs-cli/${VERSION}`
714
+ }
715
+ })).status;
716
+ } catch (error) {
717
+ const reason = error instanceof WebhookDeliveryError ? error.category : "connection_refused";
718
+ this.recordFailure(subscription, reason);
719
+ if (attempt >= this.limits.maxAttempts) return;
720
+ await this.backoff(attempt);
721
+ continue;
722
+ }
723
+ if (status >= 200 && status < 300) {
724
+ subscription.lastDeliveryAt = new Date(this.clock()).toISOString();
725
+ subscription.lastError = void 0;
726
+ subscription.failedSince = void 0;
727
+ subscription.consecutiveFailures = 0;
728
+ if (subscription.previousSecretUntil !== void 0 && this.clock() >= subscription.previousSecretUntil) {
729
+ subscription.previousSecret = void 0;
730
+ subscription.previousSecretUntil = void 0;
731
+ }
732
+ return;
733
+ }
734
+ this.recordFailure(subscription, webhookErrorCategory(status));
735
+ if (status === 410 || status === 413) return;
736
+ if (attempt >= this.limits.maxAttempts) return;
737
+ await this.backoff(attempt);
738
+ }
739
+ }
740
+ async backoff(attempt) {
741
+ const delay = Math.min(this.limits.retryBaseMs * 2 ** (attempt - 1), this.limits.retryMaxDelayMs);
742
+ await this.delay(delay);
743
+ }
744
+ recordFailure(subscription, reason) {
745
+ subscription.consecutiveFailures += 1;
746
+ subscription.lastError = reason;
747
+ subscription.failedSince ??= new Date(this.clock()).toISOString();
748
+ if (subscription.consecutiveFailures >= this.limits.suspendAfterFailures) {
749
+ subscription.active = false;
750
+ this.log(`suspended webhook delivery for ${subscription.id} after repeated failures`);
751
+ }
752
+ }
753
+ dropSubscription(subscription) {
754
+ subscription.removed = true;
755
+ subscription.active = false;
756
+ subscription.queue.length = 0;
757
+ this.subscriptions.delete(subscription.id);
758
+ this.stopUnusedSources();
759
+ }
760
+ requiredSourceKinds() {
761
+ const kinds = /* @__PURE__ */ new Set();
762
+ for (const subscription of this.subscriptions.values()) if (subscription.name === "line.openchat.message.received") kinds.add("square");
763
+ else kinds.add("talk");
764
+ return kinds;
765
+ }
766
+ async ensureSources() {
767
+ const required = this.requiredSourceKinds();
768
+ for (const kind of ["talk", "square"]) {
769
+ if (!required.has(kind)) continue;
770
+ const existing = this.sources.get(kind);
771
+ if (!existing) {
772
+ await this.startSource(kind);
773
+ continue;
774
+ }
775
+ await existing.start(this.sourceListener).catch((error) => {
776
+ this.log(`could not restart the ${kind} LINE listener: ${error instanceof Error ? error.message : String(error)}`);
777
+ });
778
+ }
779
+ await this.stopUnusedSources();
780
+ }
781
+ sourceListener = (record) => {
782
+ this.emit(record);
783
+ };
784
+ async startSource(kind) {
785
+ if (!this.sourceFactory) throw new EventRpcError(EVENT_ERROR_UNSUPPORTED, "Webhook delivery is not available: this server has no LINE event source", { feature: "events" });
786
+ const source = this.sourceFactory(kind);
787
+ try {
788
+ await source.start(this.sourceListener);
789
+ } catch (error) {
790
+ throw new EventRpcError(EVENT_ERROR_FORBIDDEN, `The LINE listener could not start: ${error instanceof Error ? error.message : String(error)}`, { reason: "upstream_unavailable" });
791
+ }
792
+ this.sources.set(kind, source);
793
+ }
794
+ async stopUnusedSources() {
795
+ const required = this.requiredSourceKinds();
796
+ for (const [kind, source] of this.sources) {
797
+ if (required.has(kind)) continue;
798
+ this.sources.delete(kind);
799
+ await source.stop().catch(() => {});
800
+ }
801
+ }
802
+ };
803
+ // src/mcp/listen-source.ts
804
+ function asString(value) {
805
+ return typeof value === "string" && value ? value : void 0;
806
+ }
807
+ function asTime(value) {
808
+ if (typeof value === "number" && Number.isFinite(value)) return new Date(value).toISOString();
809
+ if (typeof value === "string") {
810
+ const parsed = new Date(value);
811
+ if (!Number.isNaN(parsed.getTime())) return parsed.toISOString();
812
+ }
813
+ }
814
+ const EVENT_NAMES = {
815
+ talk: "line.message.received",
816
+ "talk:edit": "line.message.edited",
817
+ square: "line.openchat.message.received"
818
+ };
819
+ /** Map one `line listen --json` NDJSON record onto an MCP event occurrence. */
820
+ function toEventRecord(value) {
821
+ const name = typeof value.type === "string" ? EVENT_NAMES[value.type] : void 0;
822
+ if (!name) return void 0;
823
+ const messageId = asString(value.id);
824
+ const chatId = asString(value.chatMid);
825
+ if (!messageId || !chatId) return void 0;
826
+ const occurredAt = asTime(value.createdTime) ?? asTime(value.at) ?? (/* @__PURE__ */ new Date()).toISOString();
827
+ const data = {
828
+ messageId,
829
+ chatId,
830
+ from: asString(value.from) ?? "",
831
+ contentType: asString(value.contentType) ?? "UNKNOWN"
832
+ };
833
+ const text = previewText(value.text);
834
+ if (text !== void 0) data.text = text;
835
+ return {
836
+ name,
837
+ occurredAt,
838
+ data
839
+ };
840
+ }
841
+ /**
842
+ * Event source backed by the CLI's own `listen --json` command. Running the
843
+ * command in-process reuses the profile, token refresh, and reconnect logic
844
+ * that every other CLI command already uses.
845
+ */
846
+ function createLineEventSource(options) {
847
+ const run = options.run ?? runCli;
848
+ const readyTimeoutMs = options.readyTimeoutMs ?? 1500;
849
+ const env = options.env ?? process.env;
850
+ let controller;
851
+ let running;
852
+ return {
853
+ async start(onEvent) {
854
+ if (running) return;
855
+ controller = new AbortController();
856
+ const abortController = controller;
857
+ const args = [
858
+ ...options.profile ? ["--profile", options.profile] : [],
859
+ "listen",
860
+ "--json"
861
+ ];
862
+ if (options.kind === "square") args.push("--square");
863
+ let settled = false;
864
+ let resolveReady = () => {};
865
+ let rejectReady = () => {};
866
+ const ready = new Promise((resolve, reject) => {
867
+ resolveReady = resolve;
868
+ rejectReady = reject;
869
+ });
870
+ const stderr = [];
871
+ let stderrSize = 0;
872
+ const captureStderr = (chunk) => {
873
+ if (stderrSize >= 4e3) return;
874
+ stderr.push(chunk);
875
+ stderrSize += chunk.length;
876
+ };
877
+ let buffer = "";
878
+ const onStdout = (chunk) => {
879
+ buffer += chunk;
880
+ let index = buffer.indexOf("\n");
881
+ while (index >= 0) {
882
+ const line = buffer.slice(0, index).trim();
883
+ buffer = buffer.slice(index + 1);
884
+ index = buffer.indexOf("\n");
885
+ if (!line) continue;
886
+ let parsed;
887
+ try {
888
+ parsed = JSON.parse(line);
889
+ } catch {
890
+ continue;
891
+ }
892
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
893
+ const record = toEventRecord(parsed);
894
+ if (!record) continue;
895
+ if (!settled) {
896
+ settled = true;
897
+ resolveReady();
898
+ }
899
+ onEvent(record);
900
+ }
901
+ };
902
+ const timer = setTimeout(() => {
903
+ if (settled) return;
904
+ settled = true;
905
+ resolveReady();
906
+ }, readyTimeoutMs);
907
+ timer.unref?.();
908
+ const execution = run(args, {
909
+ stdout: onStdout,
910
+ stderr: captureStderr,
911
+ interactive: false,
912
+ mcp: true,
913
+ handleSignals: false,
914
+ signal: abortController.signal,
915
+ env: {
916
+ ...env,
917
+ LINEJS_NONINTERACTIVE: "1"
918
+ }
919
+ }).then(async (result) => {
920
+ clearTimeout(timer);
921
+ const detail = stderr.join("").trim();
922
+ if (!settled) {
923
+ settled = true;
924
+ rejectReady(new Error(detail || `line listen exited with code ${result.exitCode}`));
925
+ return;
926
+ }
927
+ if (!abortController.signal.aborted) options.onExit?.(detail || `line listen exited with code ${result.exitCode}`);
928
+ }, async (error) => {
929
+ clearTimeout(timer);
930
+ const detail = error instanceof Error ? error.message : String(error);
931
+ if (!settled) {
932
+ settled = true;
933
+ rejectReady(new Error(detail));
934
+ return;
935
+ }
936
+ if (!abortController.signal.aborted) options.onExit?.(detail);
937
+ });
938
+ running = execution;
939
+ execution.catch(() => {}).finally(() => {
940
+ if (running === execution) running = void 0;
941
+ });
942
+ try {
943
+ await ready;
944
+ } catch (error) {
945
+ abortController.abort();
946
+ running = void 0;
947
+ throw error;
948
+ }
949
+ },
950
+ async stop() {
951
+ controller?.abort();
952
+ controller = void 0;
953
+ const pending = running;
954
+ running = void 0;
955
+ await pending?.catch(() => {});
956
+ }
957
+ };
958
+ }
959
+ // src/mcp/server.ts
960
+ const LIST_TOOL_NAME = "list_linejs_cli";
961
+ const EXECUTE_TOOL_NAME = "execute_linejs_cli";
962
+ const PROTOCOL_VERSIONS = [
963
+ "2024-11-05",
964
+ "2025-03-26",
965
+ "2025-06-18"
966
+ ];
967
+ const LATEST_PROTOCOL_VERSION = PROTOCOL_VERSIONS[PROTOCOL_VERSIONS.length - 1];
968
+ function createToolDefinitions(commands = allCommands) {
969
+ const categories = [...new Set(commands.map((command) => command.category))].sort();
970
+ return [{
971
+ name: LIST_TOOL_NAME,
972
+ description: "List every LINEJS CLI command with its arguments, options, category, and whether it can run through execute_linejs_cli. Use this before calling execute_linejs_cli.",
973
+ inputSchema: {
974
+ type: "object",
975
+ properties: {
976
+ category: {
977
+ type: "string",
978
+ description: `Only include commands in this category. One of: ${categories.join(", ")}.`
979
+ },
980
+ includeOptions: {
981
+ type: "boolean",
982
+ description: "Include each command's option metadata (default: true)."
983
+ }
984
+ },
985
+ additionalProperties: false
986
+ }
987
+ }, {
988
+ name: EXECUTE_TOOL_NAME,
989
+ description: "Execute the LINEJS CLI directly (no shell) with an argv array. Example: {\"args\":[\"profile\",\"get\",\"--json\"]}. The tool forces --json and rejects long-running or nested MCP commands.",
990
+ inputSchema: {
991
+ type: "object",
992
+ properties: { args: {
993
+ type: "array",
994
+ items: { type: "string" },
995
+ minItems: 1,
996
+ description: "Arguments after the `line` executable, e.g. [\"chats\",\"list\",\"--json\"]."
997
+ } },
998
+ required: ["args"],
999
+ additionalProperties: false
1000
+ }
1001
+ }];
1002
+ }
1003
+ const defaultCliExecutor = async (args) => {
1004
+ const stdout = [];
1005
+ const stderr = [];
1006
+ return {
1007
+ exitCode: (await runCli(args, {
1008
+ stdout: (chunk) => stdout.push(chunk),
1009
+ stderr: (chunk) => stderr.push(chunk),
1010
+ interactive: false,
1011
+ mcp: true,
1012
+ handleSignals: false,
1013
+ env: {
1014
+ ...process.env,
1015
+ LINEJS_NONINTERACTIVE: "1"
1016
+ }
1017
+ })).exitCode,
1018
+ stdout: stdout.join(""),
1019
+ stderr: stderr.join("")
1020
+ };
1021
+ };
1022
+ function jsonRpcResult(id, result) {
1023
+ return {
1024
+ jsonrpc: "2.0",
1025
+ id,
1026
+ result
1027
+ };
1028
+ }
1029
+ function jsonRpcError(id, code, message, data) {
1030
+ return {
1031
+ jsonrpc: "2.0",
1032
+ id,
1033
+ error: {
1034
+ code,
1035
+ message,
1036
+ ...data === void 0 ? {} : { data }
1037
+ }
1038
+ };
1039
+ }
1040
+ function toolText(text, isError = false, structuredContent) {
1041
+ return {
1042
+ content: [{
1043
+ type: "text",
1044
+ text
1045
+ }],
1046
+ ...isError ? { isError: true } : {},
1047
+ ...structuredContent ? { structuredContent } : {}
1048
+ };
1049
+ }
1050
+ function listCommands(argumentsValue) {
1051
+ const category = typeof argumentsValue.category === "string" ? argumentsValue.category : void 0;
1052
+ const includeOptions = argumentsValue.includeOptions !== false;
1053
+ const normalized = category?.trim().toLowerCase();
1054
+ const commands = allCommands.filter((command) => {
1055
+ if (!normalized) return true;
1056
+ return command.category.toLowerCase().includes(normalized) || command.name.toLowerCase().includes(normalized);
1057
+ }).map((command) => commandMetadata(command, includeOptions));
1058
+ return {
1059
+ commandCount: commands.length,
1060
+ commands
1061
+ };
1062
+ }
1063
+ async function executeCommand(argumentsValue, executor) {
1064
+ if (!Array.isArray(argumentsValue.args) || !argumentsValue.args.every((entry) => typeof entry === "string")) return toolText("execute_linejs_cli requires args: string[].", true);
1065
+ const args = argumentsValue.args;
1066
+ if (!args.length) return toolText("execute_linejs_cli requires at least one argument.", true);
1067
+ if (args.includes("--password-stdin")) return toolText("--password-stdin reads stdin, which belongs to the MCP transport. Use --password, or log in from a terminal.", true);
1068
+ const argsFileIndex = args.findIndex((arg) => arg === "--args-file" || arg.startsWith("--args-file="));
1069
+ if (argsFileIndex !== -1 && (args[argsFileIndex] === "--args-file=-" || args[argsFileIndex + 1] === "-")) return toolText("--args-file - reads stdin, which belongs to the MCP transport. Use a file path.", true);
1070
+ let rest;
1071
+ try {
1072
+ ({rest} = splitLeadingGlobalOptions(args));
1073
+ } catch (error) {
1074
+ return toolText(errorMessage(error), true);
1075
+ }
1076
+ const resolution = resolveCommandTokens(rest);
1077
+ const command = resolution.command;
1078
+ if (!command) return toolText(resolution.group ? `"${resolution.group}" is a command group, not an executable command. Run list_linejs_cli for exact names.` : `Unknown command: ${resolution.unknown ?? rest[0] ?? "(none)"}. Run list_linejs_cli first.`, true);
1079
+ if (command.name === "mcp") return toolText("The mcp command cannot be nested inside an MCP server.", true);
1080
+ if (!isMcpExecutable(command)) return toolText(`${command.name} is ${command.longRunning ? "long-running" : "not exposed to MCP"} and cannot run through execute_linejs_cli.`, true);
1081
+ const separator = args.indexOf("--");
1082
+ const execution = await executor(separator === -1 ? [...args, "--json"] : [
1083
+ ...args.slice(0, separator),
1084
+ "--json",
1085
+ ...args.slice(separator)
1086
+ ]);
1087
+ const output = execution.stdout.trimEnd();
1088
+ const errorText = execution.stderr.trimEnd();
1089
+ return {
1090
+ content: [{
1091
+ type: "text",
1092
+ text: output || errorText || `(no output; exit code ${execution.exitCode})`
1093
+ }, ...errorText && output ? [{
1094
+ type: "text",
1095
+ text: `stderr:\n${errorText}`
1096
+ }] : []],
1097
+ ...execution.exitCode === 0 ? {} : { isError: true },
1098
+ structuredContent: {
1099
+ exitCode: execution.exitCode,
1100
+ stdout: execution.stdout,
1101
+ stderr: execution.stderr
1102
+ }
1103
+ };
1104
+ }
1105
+ async function handleMcpMessage(message, options = {}) {
1106
+ if (!message || typeof message !== "object" || Array.isArray(message)) return jsonRpcError(null, -32600, "Invalid Request");
1107
+ const request = message;
1108
+ const id = request.id ?? null;
1109
+ const isNotification = request.id === void 0;
1110
+ const method = request.method;
1111
+ if (typeof method !== "string") return isNotification ? null : jsonRpcError(id, -32600, "Invalid Request");
1112
+ if (request.jsonrpc !== "2.0") return isNotification ? null : jsonRpcError(id, -32600, "Invalid Request");
1113
+ if (isNotification) return null;
1114
+ switch (method) {
1115
+ case "initialize": {
1116
+ const requested = (request.params ?? {}).protocolVersion;
1117
+ return jsonRpcResult(id, {
1118
+ protocolVersion: typeof requested === "string" && PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION,
1119
+ capabilities: {
1120
+ tools: { listChanged: false },
1121
+ events: {}
1122
+ },
1123
+ serverInfo: {
1124
+ name: "@evex-dev/linejs-cli",
1125
+ version: VERSION
1126
+ },
1127
+ instructions: "Use list_linejs_cli to discover commands, then execute_linejs_cli with an argv array. No shell is involved; --json is forced. Long-running commands such as listen are rejected. MCP Events (webhook delivery) are available through events/list, events/subscribe, and events/unsubscribe."
1128
+ });
1129
+ }
1130
+ case "ping": return jsonRpcResult(id, {});
1131
+ case "tools/list": return jsonRpcResult(id, { tools: createToolDefinitions(options.commands ?? allCommands) });
1132
+ case "tools/call": {
1133
+ const params = request.params ?? {};
1134
+ const name = params.name;
1135
+ const argumentsValue = params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? params.arguments : {};
1136
+ if (name === "list_linejs_cli") {
1137
+ const result = listCommands(argumentsValue);
1138
+ return jsonRpcResult(id, {
1139
+ content: [{
1140
+ type: "text",
1141
+ text: JSON.stringify(result, null, 2)
1142
+ }],
1143
+ structuredContent: result
1144
+ });
1145
+ }
1146
+ if (name === "execute_linejs_cli") return jsonRpcResult(id, await executeCommand(argumentsValue, options.executor ?? defaultCliExecutor));
1147
+ return jsonRpcError(id, -32602, `Unknown tool: ${String(name)}`);
1148
+ }
1149
+ case "events/list":
1150
+ case "events/subscribe":
1151
+ case "events/unsubscribe": {
1152
+ const hub = options.events;
1153
+ if (!hub) return jsonRpcError(id, -32601, `Method not found: ${method}`);
1154
+ const params = request.params ?? {};
1155
+ try {
1156
+ if (method === "events/list") return jsonRpcResult(id, hub.list(params));
1157
+ if (method === "events/subscribe") return jsonRpcResult(id, await hub.subscribe(params));
1158
+ return jsonRpcResult(id, hub.unsubscribe(params));
1159
+ } catch (error) {
1160
+ if (error instanceof EventRpcError) return jsonRpcError(id, error.code, error.message, error.data);
1161
+ throw error;
1162
+ }
1163
+ }
1164
+ case "resources/list": return jsonRpcResult(id, { resources: [] });
1165
+ case "prompts/list": return jsonRpcResult(id, { prompts: [] });
1166
+ case "logging/setLevel": return jsonRpcResult(id, {});
1167
+ default: return jsonRpcError(id, -32601, `Method not found: ${method}`);
1168
+ }
1169
+ }
1170
+ async function runMcpServer(options = {}) {
1171
+ const input = options.input ?? process.stdin;
1172
+ const output = options.output ?? process.stdout;
1173
+ const error = options.error ?? process.stderr;
1174
+ const commands = options.commands ?? allCommands;
1175
+ const executor = options.executor ?? defaultCliExecutor;
1176
+ const events = options.events ?? new McpEventHub({
1177
+ principal: options.principal ?? "stdio",
1178
+ sourceFactory: (kind) => createLineEventSource({
1179
+ kind,
1180
+ profile: options.profile,
1181
+ onExit: (reason) => error.write(`[mcp-events] LINE listener exited: ${reason}\n`)
1182
+ }),
1183
+ log: (message) => error.write(`[mcp-events] ${message}\n`)
1184
+ });
1185
+ const write = async (value) => {
1186
+ if (!output.write(`${JSON.stringify(value)}\n`)) await once(output, "drain");
1187
+ };
1188
+ error.write("@evex-dev/linejs-cli MCP server listening on stdio\n");
1189
+ const lines = createInterface({
1190
+ input,
1191
+ crlfDelay: Infinity
1192
+ });
1193
+ const onAbort = () => lines.close();
1194
+ if (options.signal) {
1195
+ if (options.signal.aborted) lines.close();
1196
+ else options.signal.addEventListener("abort", onAbort, { once: true });
1197
+ }
1198
+ let queue = Promise.resolve();
1199
+ for await (const line of lines) {
1200
+ if (!line.trim()) continue;
1201
+ queue = queue.then(async () => {
1202
+ let parsed;
1203
+ try {
1204
+ parsed = JSON.parse(line);
1205
+ } catch (parseError) {
1206
+ await write(jsonRpcError(null, -32700, "Parse error", String(parseError)));
1207
+ return;
1208
+ }
1209
+ try {
1210
+ if (Array.isArray(parsed)) {
1211
+ const responses = [];
1212
+ for (const entry of parsed) {
1213
+ const response = await handleMcpMessage(entry, {
1214
+ commands,
1215
+ executor,
1216
+ events
1217
+ });
1218
+ if (response !== null) responses.push(response);
1219
+ }
1220
+ if (responses.length) await write(responses);
1221
+ return;
1222
+ }
1223
+ const response = await handleMcpMessage(parsed, {
1224
+ commands,
1225
+ executor,
1226
+ events
1227
+ });
1228
+ if (response !== null) await write(response);
1229
+ } catch (handlerError) {
1230
+ await write(jsonRpcError(null, -32603, "Internal error", handlerError instanceof Error ? handlerError.message : String(handlerError)));
1231
+ }
1232
+ });
1233
+ }
1234
+ await queue;
1235
+ options.signal?.removeEventListener("abort", onAbort);
1236
+ await events.close();
1237
+ return 0;
1238
+ }
1239
+ export { runMcpServer };
1240
+
1241
+ //# sourceMappingURL=server-rpmfEN1F.mjs.map