openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,026 lines (1,025 loc) • 36.2 kB
JavaScript
import { a as asOptionalRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { n as sha256Hex } from "../../node-crypto-B6yuTjmm.mjs";
import { n as validateJsonSchemaValue } from "../../schema-validator-NvoOmaWr.mjs";
import { i as generateSecureToken } from "../../secure-random-CW5OZnK1.mjs";
import { f as sendHttpRequestRejection, i as isRequestBodyLimitError, o as readRequestBodyWithLimit } from "../../http-body-B9w7rzPz.mjs";
import { p as resolvePinnedHostnameWithPolicy } from "../../ssrf-DHBNJw0c.mjs";
import "../../channel-outbound-DQFse8vD.mjs";
import { r as sendJsonWithoutCharset } from "../../http-json-ddGJz5CA.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../ssrf-runtime-B6q6NM4E.mjs";
import { a as createWebhookInFlightLimiter } from "../../webhook-request-guards-Br7AftEb.mjs";
import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs";
import "../../json-schema-runtime-OTpXIHVF.mjs";
import { t as CHANNEL_INGRESS_RETENTION_DEFAULTS } from "../../ingress-monitor-CkIIn1aC.mjs";
import "../../secure-random-runtime-5A4mr_Y3.mjs";
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
//#region extensions/mcp-events/src/protocol.ts
/** OpenAI's webhook profile, not the experimental polling/streaming extensions. */
const MCP_EVENTS_PROFILE = "openai-webhook-2026-07-28";
const MAX_EVENT_BYTES = 262144;
const CALLBACK_PREFIX = "/plugins/mcp-events/callback/";
const MAX_CLOCK_SKEW_MS = 3e5;
var CallbackError = class extends Error {
constructor(e, t) {
super(t);
this.status = e;
}
};
function boundedString(e, t = 1024) {
return typeof e === "string" && e.length > 0 && Buffer.byteLength(e) <= t;
}
function isoTimestamp(e) {
return typeof e === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/u.test(e) && Number.isFinite(Date.parse(e));
}
/** Canonical JSON gives subscribe and unsubscribe the same filter identity. */
function canonicalArguments(e) {
const visit = (e, t) => {
if (t > 64) throw new Error("MCP event arguments exceed the nesting limit");
if (e === null || typeof e === "string" || typeof e === "boolean" || typeof e === "number" && Number.isFinite(e)) return JSON.stringify(e);
if (Array.isArray(e)) return "[" + e.map((e) => visit(e, t + 1)).join(",") + "]";
const n = asOptionalRecord(e);
if (!n) throw new Error("MCP event arguments must be JSON");
return "{" + Object.keys(n).toSorted().map((e) => JSON.stringify(e) + ":" + visit(n[e], t + 1)).join(",") + "}";
};
const t = visit(e, 0);
if (Buffer.byteLength(t) > 32768) throw new Error("MCP event arguments exceed 32 KiB");
return t;
}
function identityHash(e) {
return sha256Hex(JSON.stringify(e));
}
function createSigningSecret() {
return generateSecureToken({
bytes: 32,
redact: true,
encoding: "base64",
prefix: "whsec_"
});
}
function decodeBase64(e) {
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(e)) return;
return Buffer.from(e, "base64");
}
/** Authenticate bytes before parsing; the subscription-id header is deliberately unused. */
function verifyWebhook(e) {
const t = e.headers["webhook-id"];
const n = e.headers["webhook-timestamp"];
const r = e.headers["webhook-signature"];
if (!boundedString(t) || typeof n !== "string" || !/^\d{1,12}$/u.test(n) || typeof r !== "string" || r.length > 4096 || Math.abs(e.now - Number(n) * 1e3) > MAX_CLOCK_SKEW_MS) throw new CallbackError(401, "Invalid webhook authentication");
const i = r.split(/\s+/u).flatMap((e) => {
if (!e.startsWith("v1,")) return [];
const t = decodeBase64(e.slice(3));
return t?.length === 32 ? [t] : [];
});
let a = false;
for (const r of e.secrets) {
const o = r.startsWith("whsec_") ? decodeBase64(r.slice(6)) : void 0;
if (!o || o.length < 24 || o.length > 64) continue;
const s = createHmac("sha256", o).update(t + "." + n + ".").update(e.body).digest();
for (const e of i) a = timingSafeEqual(s, e) || a;
}
if (!a) throw new CallbackError(401, "Invalid webhook authentication");
return t;
}
function parseCallback(e, t, n) {
let r;
try {
r = asOptionalRecord(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(e)));
} catch {
throw new CallbackError(400, "Invalid event JSON");
}
if (!r) throw new CallbackError(400, "Expected one event object");
if (Object.hasOwn(r, "type")) {
if (r.type !== "verification" || !boundedString(r.challenge, 4096)) throw new CallbackError(400, "Unsupported control notification");
return {
kind: "verification",
challenge: r.challenge
};
}
const i = asOptionalRecord(r.data);
if (!boundedString(r.eventId) || r.eventId !== t || r.name !== n.name || !isoTimestamp(r.timestamp) || !i || !(r.cursor === null || boundedString(r.cursor, 16384))) throw new CallbackError(400, "Invalid event envelope");
if (!validateJsonSchemaValue({
schema: n.payloadSchema,
value: i
}).ok) throw new CallbackError(400, "Event data does not match payloadSchema");
return {
kind: "event",
event: {
eventId: r.eventId,
name: n.name,
timestamp: r.timestamp,
data: i,
cursor: r.cursor
}
};
}
function parseSubscriptionResult(e, t) {
const n = asOptionalRecord(e);
if (!n || !boundedString(n.id) || !isoTimestamp(n.refreshBefore) || Date.parse(n.refreshBefore) <= t || !(n.cursor === null || boundedString(n.cursor, 16384)) || typeof n.truncated !== "boolean") throw new Error("Invalid MCP subscription response (a finite future refreshBefore is required)");
return {
id: n.id,
refreshBefore: Date.parse(n.refreshBefore),
cursor: n.cursor,
truncated: n.truncated
};
}
function parseEventCatalog(e) {
const t = asOptionalRecord(e);
if (!t || !Array.isArray(t.events) || t.events.length > 1e3 || t.nextCursor !== void 0 && !boundedString(t.nextCursor, 16384)) throw new Error("Invalid MCP event catalog");
const n = [];
for (const e of t.events) {
const t = asOptionalRecord(e);
const r = typeof t?.inputSchema === "boolean" ? t.inputSchema : asOptionalRecord(t?.inputSchema);
const i = typeof t?.payloadSchema === "boolean" ? t.payloadSchema : asOptionalRecord(t?.payloadSchema);
if (!t || !boundedString(t.name, 256) || !Array.isArray(t.delivery) || r === void 0 || i === void 0) throw new Error("Invalid MCP event definition");
if (!t.delivery.includes("webhook")) continue;
validateJsonSchemaValue({
schema: r,
value: {}
});
validateJsonSchemaValue({
schema: i,
value: {}
});
n.push({
name: t.name,
inputSchema: r,
payloadSchema: i,
...typeof t.description === "string" ? { description: t.description.slice(0, 4096) } : {}
});
}
return {
events: n,
...typeof t.nextCursor === "string" ? { nextCursor: t.nextCursor } : {}
};
}
//#endregion
//#region extensions/mcp-events/src/config.ts
function resolveMcpEventsConfig(e) {
const t = asOptionalRecord(e);
if (!t || typeof t.callbackOrigin !== "string") throw new Error("Configure mcp-events.callbackOrigin with a public HTTPS origin; expose only the callback route through your reverse proxy");
let n;
try {
n = new URL(t.callbackOrigin);
} catch {
throw new Error("MCP Events callbackOrigin must be a public HTTPS origin");
}
if (n.protocol !== "https:" || n.username || n.password || n.search || n.hash || n.pathname !== "/") throw new Error("MCP Events callbackOrigin must be a public HTTPS origin without credentials, path, query, or fragment");
const r = t.maxPendingEvents ?? 1e4;
if (typeof r !== "number" || !Number.isSafeInteger(r) || r < 1 || r > 1e5) throw new Error("MCP Events maxPendingEvents must be an integer from 1 to 100000");
return {
callbackOrigin: n.origin,
maxPendingEvents: r
};
}
/** DNS/public-address preflight is not a reachability claim or permission to expose the Gateway. */
async function preflightCallbackOrigin(e, t) {
const n = new URL(e);
await resolvePinnedHostnameWithPolicy(n.hostname, { signal: t });
}
function resolveMcpEventSourceOptions(e) {
const { server: t, name: n, arguments: r = {} } = e;
const i = asOptionalRecord(r);
if (typeof t !== "string" || !t.trim() || t.length > 256 || typeof n !== "string" || !n.trim() || n.length > 256 || !i) throw new Error("MCP event source options require server, name, and object arguments");
const a = asOptionalRecord(JSON.parse(canonicalArguments(i)));
if (!a) throw new Error("MCP event arguments must remain a JSON object");
return {
serverName: t,
name: n,
arguments: a
};
}
//#endregion
//#region extensions/mcp-events/src/source-authority.ts
var SourceRevokedError = class extends Error {};
function isAuthorityUnavailable(e) {
return asOptionalRecord(e)?.code === "MCP_AUTHORIZATION_UNAVAILABLE";
}
function isAuthorityRetired(e) {
return asOptionalRecord(e)?.code === "MCP_AUTHORIZATION_RETIRED";
}
/** Holds no credential state: observations and lifetime identity belong to native credential owners. */
var McpEventsSourceAuthority = class {
constructor(e, t) {
this.prepareSource = e;
this.assertService = t;
}
guard(e) {
const t = e.source;
return () => {
this.assertService();
if (!e.live || e.facts.status === "revoked" || !t) throw new SourceRevokedError("MCP event source revoked");
try {
t.assertCurrent();
} catch (e) {
if (isAuthorityRetired(e)) throw new SourceRevokedError("MCP authorization retired", { cause: e });
throw e;
}
};
}
async refresh(e) {
this.assertService();
if (!e.live) throw new SourceRevokedError("MCP event source revoked");
let t;
try {
if (!e.source) {
t = await this.prepareSource(e.facts);
if (t.accountId !== e.facts.accountId || t.principalId !== e.facts.principalId) throw new SourceRevokedError("MCP event authorization changed");
this.assertService();
if (!e.live) throw new SourceRevokedError("MCP event source revoked");
t.assertCurrent();
e.source ??= t;
}
await e.source.revalidate();
this.guard(e)();
} catch (e) {
if (isAuthorityUnavailable(e)) throw e;
throw new SourceRevokedError("MCP event source is no longer authorized", { cause: e });
} finally {
if (t !== e.source) t?.dispose();
}
}
};
//#endregion
//#region extensions/mcp-events/src/http.ts
function createCallbackHandler(e) {
const t = createWebhookInFlightLimiter({
maxInFlightPerKey: 32,
maxTrackedKeys: 1
});
return async (n, r) => {
const i = new URL(n.url ?? "/", "http://callback.invalid").pathname;
if (!i.startsWith("/plugins/mcp-events/callback/")) return false;
const a = i.slice(CALLBACK_PREFIX.length);
if (!/^[a-f0-9-]{36}$/u.test(a)) {
await sendHttpRequestRejection(n, r, 404, "Unknown callback");
return true;
}
if (n.method !== "POST") {
r.setHeader("Allow", "POST");
await sendHttpRequestRejection(n, r, 405, "POST required");
return true;
}
if (!/^application\/json(?:\s*;|$)/iu.test(n.headers["content-type"] ?? "") || n.headers["content-encoding"] && n.headers["content-encoding"] !== "identity") {
await sendHttpRequestRejection(n, r, 415, "Uncompressed application/json required");
return true;
}
const o = e();
if (!o || !t.tryAcquire("callbacks")) {
r.setHeader("Retry-After", "5");
await sendHttpRequestRejection(n, r, 503, "Callback unavailable; retry later");
return true;
}
try {
const e = await readRequestBodyWithLimit(n, {
maxBytes: MAX_EVENT_BYTES,
timeoutMs: 5e3,
encoding: "base64",
destroyOnLimit: false
});
const t = await receiveCallback(o, a, n.headers, Buffer.from(e, "base64"));
r.setHeader("Cache-Control", "no-store");
sendJsonWithoutCharset(r, 200, t);
} catch (e) {
const t = e instanceof CallbackError ? e.status : isRequestBodyLimitError(e) ? e.statusCode : 503;
if (t === 503) r.setHeader("Retry-After", "5");
await sendHttpRequestRejection(n, r, t, e instanceof CallbackError ? e.message : t === 413 ? "Event exceeds 256 KiB" : "Callback unavailable; retry later");
} finally {
t.release("callbacks");
}
return true;
};
}
/** Called only after bounded raw-body admission by the registered HTTP route. */
async function receiveCallback(e, t, n, r) {
if (e.initialization !== "ready") throw new CallbackError(503, "Subscription state is loading; retry later");
e.assertService();
const i = e.bindings.get(t);
if (!i?.live) throw new CallbackError(410, "Subscription is no longer active");
try {
await e.authority.refresh(i);
} catch (t) {
if (isAuthorityUnavailable(t)) throw new CallbackError(503, "Subscription authority is temporarily unavailable");
await e.revoke(i, "source_unavailable");
throw new CallbackError(410, "Subscription source is no longer authorized");
}
const a = e.authority.guard(i);
a();
const o = [
i.facts.secret,
...i.facts.pendingSecret ? [i.facts.pendingSecret] : [],
...i.facts.previousSecret && i.facts.previousSecret.until > e.now ? [i.facts.previousSecret.value] : []
];
const s = verifyWebhook({
headers: n,
body: r,
secrets: o,
now: e.now
});
const c = parseCallback(r, s, i.facts.definition);
if (c.kind === "verification") {
a();
return { challenge: c.challenge };
}
if (i.facts.status !== "active") throw new CallbackError(503, "Subscription activation is pending");
if (!i.facts.refreshBefore || i.facts.refreshBefore <= e.now) {
if (i.pending || i.facts.pendingSecret) throw new CallbackError(503, "Subscription renewal is pending");
throw new CallbackError(410, "Subscription expired");
}
const l = e.account(i.facts.accountId);
const u = l.admission.then(async () => {
a();
const n = identityHash([
i.facts.accountId,
t,
c.event.eventId
]);
const r = await l.queue.listUnsettled();
a();
if (!(r.pending.some((e) => e.id === n) || r.claims.some((e) => e.id === n)) && r.pending.length + r.claims.length >= e.deps.config.maxPendingEvents) throw new CallbackError(503, "Event queue is full; retry later");
const o = await l.queue.enqueueAuthorized(n, {
jobId: i.facts.jobId,
sourceIdentity: i.facts.sourceIdentity,
eventId: c.event.eventId,
receivedAtMs: e.now,
payload: {
profile: MCP_EVENTS_PROFILE,
bindingId: t,
event: c.event
}
}, {
laneKey: i.facts.jobId,
receivedAt: e.now,
assertCurrent: a
});
a();
if (o.kind === "failed") throw new CallbackError(503, "Event is retained for recovery; inspect ingress diagnostics");
if (o.kind === "accepted" || o.kind === "pending" || o.kind === "claimed") {
const t = o.record.payload.payload.event.cursor;
await e.mutate(i, (e) => {
e.cursor = t;
e.cursorRevision++;
});
}
a();
});
l.admission = u.catch(() => {});
try {
await e.track(u);
} finally {
e.requestDrain();
}
return {};
}
//#endregion
//#region extensions/mcp-events/src/state.ts
function createMcpEventsState(e) {
const t = e.state.openKeyedStore({
namespace: "subscriptions-v1",
maxEntries: 4096,
overflowPolicy: "reject-new"
});
if (!t.withCurrent) throw new Error("MCP Events requires current-authority plugin state writes; update OpenClaw");
return {
bindings: t,
withCurrent: t.withCurrent.bind(t),
openQueue: (t) => e.state.openChannelIngressQueue({ accountId: t })
};
}
//#endregion
//#region extensions/mcp-events/src/service.ts
const REQUEST_TTL_MS = 36e5;
const ROTATION_WINDOW_MS = 3e5;
const MAX_CLEANUP_RETRIES = 8;
const DRAIN_RETRY_MS = 1e3;
var McpEventsService = class {
constructor(e) {
this.deps = e;
this.accounts = /* @__PURE__ */ new Map();
this.drainRetryMs = DRAIN_RETRY_MS;
this.bindings = /* @__PURE__ */ new Map();
this.scheduled = /* @__PURE__ */ new Map();
this.work = /* @__PURE__ */ new Set();
this.initialization = "restoring";
this.reconcileRequested = false;
this.unavailable = /* @__PURE__ */ new Map();
this.assertService = () => {
if (this.signal.aborted) throw new SourceRevokedError("MCP Events service stopped");
};
this.state = createMcpEventsState(e.runtime);
this.authority = new McpEventsSourceAuthority(e.prepareSource, this.assertService);
this.signal = e.scheduler.signal;
}
get now() {
return this.deps.scheduler.now();
}
track(e) {
this.work.add(e);
e.finally(() => this.work.delete(e)).catch(() => {});
return e;
}
schedule(e, t, n, r = false) {
if (this.signal.aborted) return;
this.scheduled.set(e, this.deps.scheduler.schedule({
id: e,
atMs: t,
mode: r ? "earliest" : "replace",
run: async () => {
this.scheduled.delete(e);
await this.track(n());
}
}));
}
cancelScheduled(e) {
this.scheduled.get(e)?.cancel();
this.scheduled.delete(e);
}
/** Draft facts commit only after serialized storage; callbacks can verify during subscribe. */
mutate(e, t, n = this.authority.guard(e)) {
const r = e.writes.then(async () => {
n();
const r = { ...e.facts };
t(r);
r.updatedAt = this.now;
await this.state.withCurrent({ assertCurrent: n }).register(r.bindingId, r);
e.facts = r;
});
e.writes = r.catch(() => {});
return r;
}
async start() {
await preflightCallbackOrigin(this.deps.config.callbackOrigin, this.signal);
this.assertService();
for (const { value: e } of await this.state.bindings.entries()) {
if (e.status === "revoked" && !e.cleanupPending) {
await this.state.withCurrent({ assertCurrent: this.assertService }).delete(e.bindingId);
continue;
}
this.bindings.set(e.bindingId, {
facts: e,
live: e.status !== "revoked",
writes: Promise.resolve()
});
this.account(e.accountId);
}
this.initialization = "reconciling";
await this.reconcile();
this.requestDrain();
}
async stop() {
this.deps.scheduler.beginClose();
this.scheduled.clear();
for (const e of this.bindings.values()) e.live = false;
await Promise.allSettled(this.work);
await Promise.all([...this.bindings.values()].map((e) => e.writes));
for (const e of this.accounts.values()) {
await e.admission;
await e.drain.waitForIdle();
e.drain.dispose();
}
for (const e of this.bindings.values()) e.source?.dispose();
}
requestReconcile() {
if (this.signal.aborted) return;
if (this.initialization === "restoring" || this.reconcileWork) {
this.reconcileRequested = true;
return;
}
this.schedule("reconcile", this.now, () => this.reconcile(), true);
}
reconcile() {
if (this.initialization === "restoring") return Promise.reject(/* @__PURE__ */ new Error("MCP Events subscription state is still restoring"));
if (this.reconcileWork) return this.reconcileWork;
const e = this.reconcileSources();
this.reconcileWork = e;
e.finally(() => {
this.reconcileWork = void 0;
if (this.reconcileRequested) {
this.reconcileRequested = false;
this.requestReconcile();
}
}).catch(() => {});
return this.track(e);
}
async reconcileSources() {
const e = await this.deps.cron.readEventSources();
this.assertService();
this.initialization = "ready";
const t = new Map(e.filter((e) => e.enabled).map((e) => [e.jobId, e]));
for (const e of this.bindings.values()) {
const n = t.get(e.facts.jobId);
if (!n || n.sourceIdentity !== e.facts.sourceIdentity || !e.facts.callbackUrl.startsWith(this.deps.config.callbackOrigin + "/plugins/mcp-events/callback/")) await this.revoke(e);
}
for (const [e, n] of this.unavailable) if (t.get(e)?.sourceIdentity !== n.source.sourceIdentity) {
this.unavailable.delete(e);
this.cancelScheduled("source:" + e);
}
const n = [];
for (const e of t.values()) {
this.assertService();
let t = [...this.bindings.values()].find((t) => t.live && t.facts.jobId === e.jobId && t.facts.sourceIdentity === e.sourceIdentity);
try {
if (!t) t = await this.createBinding(e);
else await this.authority.refresh(t);
this.unavailable.delete(e.jobId);
if (t.pending) continue;
if (t.facts.nextAttemptAt <= this.now) n.push(this.begin(t, this.refresh.bind(this, t)));
else this.armRefresh(t);
} catch (n) {
if (t && !isAuthorityUnavailable(n)) await this.revoke(t, "source_unavailable");
this.retrySource(e);
}
}
await Promise.allSettled(n);
this.requestDrain();
for (const e of this.bindings.values()) if (!e.live && e.facts.cleanupPending && e.facts.nextAttemptAt <= this.now && !e.pending) await this.beginCleanup(e);
else if (!e.live) this.armCleanup(e);
}
retrySource(e) {
const t = this.unavailable.get(e.jobId);
const n = t?.source.sourceIdentity === e.sourceIdentity ? t.attempts + 1 : 1;
this.unavailable.set(e.jobId, {
source: e,
attempts: n
});
this.deps.logger.warn("mcp-events: source unavailable; check MCP account, event filters, and callback reachability");
this.schedule("source:" + e.jobId, this.now + Math.min(3e5, 1e3 * 2 ** Math.min(n, 9)), async () => {
if (this.unavailable.get(e.jobId)?.source !== e) return;
try {
await this.reconcile();
} catch {
if (!this.signal.aborted) this.retrySource(e);
}
});
}
armRefresh(e, t = e.facts.nextAttemptAt) {
this.schedule("refresh:" + e.facts.bindingId, t, async () => {
if (e.live && !e.pending) await this.begin(e, this.refresh.bind(this, e));
});
}
async createBinding(e) {
const t = resolveMcpEventSourceOptions(e.options);
const n = await this.deps.prepareSource({
...e,
serverName: t.serverName
});
try {
const r = asOptionalRecord(await n.request("server/discover", {}, this.signal));
n.assertCurrent();
const i = asOptionalRecord(r?.capabilities);
if (!r || !Array.isArray(r.supportedVersions) || !r.supportedVersions.includes("2026-07-28") || !i || !Object.hasOwn(i, "events")) throw new Error("Configured MCP server does not advertise MCP 2.0 events");
let a;
const o = /* @__PURE__ */ new Set();
let s;
for (let e = 0; e < 100; e++) {
const e = parseEventCatalog(await n.request("events/list", a ? { cursor: a } : {}, this.signal));
n.assertCurrent();
s = e.events.find((e) => e.name === t.name);
if (s || !e.nextCursor) break;
if (o.has(e.nextCursor)) throw new Error("MCP event catalog cursor repeated");
o.add(e.nextCursor);
a = e.nextCursor;
}
if (!s || !validateJsonSchemaValue({
schema: s.inputSchema,
value: t.arguments
}).ok) throw new Error("MCP event or subscription arguments are unavailable");
this.assertService();
n.assertCurrent();
const c = randomUUID();
const l = {
version: 1,
bindingId: c,
jobId: e.jobId,
sourceIdentity: e.sourceIdentity,
serverName: t.serverName,
accountId: n.accountId,
principalId: n.principalId,
arguments: t.arguments,
definition: s,
callbackUrl: this.deps.config.callbackOrigin + CALLBACK_PREFIX + c,
secret: createSigningSecret(),
status: "pending",
cursor: null,
cursorRevision: 0,
truncated: false,
nextAttemptAt: this.now,
failures: 0,
cleanupPending: false,
updatedAt: this.now
};
const u = {
facts: l,
source: n,
live: true,
writes: Promise.resolve()
};
await this.state.withCurrent({ assertCurrent: this.authority.guard(u) }).register(c, l);
this.authority.guard(u)();
this.bindings.set(c, u);
this.account(l.accountId);
return u;
} catch (e) {
n.dispose();
throw e;
}
}
begin(e, t) {
if (e.pending) return e.pending;
const n = t();
e.pending = n;
this.track(n).catch(() => this.deps.logger.warn("mcp-events: subscription state unavailable; retry remains pending"));
n.finally(() => {
e.pending = void 0;
}).catch(() => {});
return n;
}
async refresh(e) {
let t;
try {
await this.authority.refresh(e);
const t = e.source;
const n = this.authority.guard(e);
if (e.facts.status === "active" && !e.facts.pendingSecret) await this.mutate(e, (e) => {
e.pendingSecret = createSigningSecret();
});
const r = e.facts.pendingSecret ?? e.facts.secret;
const i = e.facts.cursorRevision;
n();
const a = await t.request("events/subscribe", {
name: e.facts.definition.name,
arguments: e.facts.arguments,
delivery: {
mode: "webhook",
url: e.facts.callbackUrl,
secret: r
},
cursor: e.facts.cursor,
ttlMs: REQUEST_TTL_MS
}, this.signal);
n();
const o = parseSubscriptionResult(a, this.now);
await this.mutate(e, (e) => {
e.status = "active";
e.remoteId = o.id;
e.refreshBefore = o.refreshBefore;
if (e.secret !== r) e.previousSecret = {
value: e.secret,
until: this.now + ROTATION_WINDOW_MS
};
e.secret = r;
delete e.pendingSecret;
e.cursor = e.cursorRevision === i ? o.cursor : e.cursor;
e.truncated ||= o.truncated;
e.failures = 0;
delete e.lastError;
e.nextAttemptAt = this.now + Math.max(1, Math.floor((o.refreshBefore - this.now) * .8));
});
} catch (n) {
if (!e.live || this.signal.aborted) return;
if (n instanceof SourceRevokedError) {
await this.revoke(e, "source_unavailable");
return;
}
try {
this.authority.guard(e)();
} catch (t) {
if (!isAuthorityUnavailable(t)) {
await this.revoke(e, "source_unavailable");
return;
}
}
const assertBindingCurrent = () => {
this.assertService();
if (!e.live || this.bindings.get(e.facts.bindingId) !== e) throw new SourceRevokedError("MCP event binding retired");
};
const r = this.now + Math.min(3e5, 1e3 * 2 ** Math.min(e.facts.failures, 8));
t = r;
await this.mutate(e, (e) => {
e.failures++;
e.lastError = "subscribe_failed";
e.nextAttemptAt = r;
}, assertBindingCurrent);
} finally {
if (e.live) this.armRefresh(e, t);
}
}
async revoke(e, t) {
if (!e.live && e.facts.status === "revoked") {
this.armCleanup(e);
return;
}
e.live = false;
this.cancelScheduled("refresh:" + e.facts.bindingId);
let n = this.now;
try {
await this.mutate(e, (e) => {
e.status = "revoked";
e.cleanupPending = true;
e.retiredAt = this.now;
e.failures = 0;
if (t === void 0) delete e.lastError;
else e.lastError = t;
e.nextAttemptAt = this.now;
}, this.assertService);
} catch (e) {
n = this.now + 1e3;
throw e;
} finally {
this.armCleanup(e, n);
if (t === "source_unavailable") this.requestReconcile();
}
}
async forgetBinding(e) {
const assertCurrent = () => {
this.assertService();
if (e.live || this.bindings.get(e.facts.bindingId) !== e) throw new SourceRevokedError("Subscription cleanup owner changed");
};
await this.state.withCurrent({ assertCurrent }).delete(e.facts.bindingId);
this.cancelScheduled("cleanup:" + e.facts.bindingId);
e.source?.dispose();
e.source = void 0;
this.bindings.delete(e.facts.bindingId);
}
cleanupExpiry(e) {
return e.facts.refreshBefore ?? (e.facts.retiredAt ?? e.facts.updatedAt) + REQUEST_TTL_MS + ROTATION_WINDOW_MS;
}
armCleanup(e, t = this.now) {
if (e.live || this.bindings.get(e.facts.bindingId) !== e) return;
const n = e.facts.status === "revoked" && e.facts.cleanupPending && e.facts.failures >= MAX_CLEANUP_RETRIES ? this.cleanupExpiry(e) : e.facts.status === "revoked" ? e.facts.nextAttemptAt : this.now;
this.schedule("cleanup:" + e.facts.bindingId, Math.max(t, n), async () => {
await e.pending?.catch(() => {});
if (!this.signal.aborted && !e.live && this.bindings.get(e.facts.bindingId) === e) await this.beginCleanup(e);
});
}
beginCleanup(e) {
return this.begin(e, async () => {
const t = this.now + Math.min(3e5, 1e3 * 2 ** Math.min(e.facts.failures, 8));
try {
if (e.facts.status !== "revoked") await this.revoke(e);
if (!e.facts.cleanupPending || e.facts.failures >= MAX_CLEANUP_RETRIES) {
if (!e.facts.cleanupPending || this.now >= this.cleanupExpiry(e)) await this.forgetBinding(e);
return;
}
if (!e.source) throw new Error("Original account authority unavailable after restart");
await e.source.unsubscribe(this.signal);
await this.mutate(e, (e) => {
e.cleanupPending = false;
delete e.lastError;
}, this.assertService);
await this.forgetBinding(e);
} catch {
if (this.signal.aborted) return;
await this.mutate(e, (e) => {
e.lastError = "cleanup_failed";
e.failures++;
e.nextAttemptAt = t;
}, this.assertService);
} finally {
this.armCleanup(e, t);
}
});
}
account(e) {
const t = this.accounts.get(e);
if (t) return t;
const n = this.state.openQueue(e);
if (!n.listUnsettled || !n.enqueueAuthorized) throw new Error("MCP Events requires coherent durable ingress inspection; update OpenClaw");
const r = {
queue: n,
drain: this.deps.runtime.state.openChannelIngressDrain({
queue: n,
abortSignal: this.signal,
now: () => this.now,
deriveLaneKey: (e) => e.payload.jobId,
startLimit: 8,
formatError: () => "MCP event admission failed; inspect source and automation diagnostics",
onLog: (e) => this.deps.logger.warn(e),
resolveNonRetryableFailure: (e) => e instanceof SourceRevokedError ? {
reason: "source_revoked",
message: "The authored event source was removed, paused, or replaced"
} : null,
dispatchClaimedEvent: async (e) => {
const t = this.bindings.get(e.payload.payload.bindingId);
if (!t?.live) throw new SourceRevokedError("MCP event source revoked");
try {
await this.authority.refresh(t);
const n = this.authority.guard(t);
n();
const { jobId: r, ...i } = e.payload;
const a = await this.deps.cron.runEvent(r, {
...i,
claim: {
queueName: e.queueName,
id: e.id,
token: e.claim.token
},
assertCurrent: n
});
if (a.kind === "invalidated") throw new SourceRevokedError("MCP event source changed");
if (a.kind === "pending") return { kind: "pending" };
return { kind: "transferred" };
} catch (e) {
if (isAuthorityUnavailable(e)) return { kind: "pending" };
if (e instanceof SourceRevokedError) await this.revoke(t, "source_unavailable");
throw e;
}
}
}),
admission: Promise.resolve()
};
this.accounts.set(e, r);
return r;
}
/** Hooks and durable enqueue wake the existing host scheduler; empty queues have no timer. */
requestDrain(e) {
if (this.signal.aborted || e && ![...this.bindings.values()].some((t) => t.facts.jobId === e)) return;
this.drainRetryMs = DRAIN_RETRY_MS;
this.schedule("drain", this.now, () => this.drain(), true);
}
drain() {
if (this.drainWork) return this.drainWork;
const e = (async () => {
let e = false;
try {
for (const t of this.accounts.values()) {
this.assertService();
await t.drain.recoverStaleClaims();
await t.drain.drainOnce();
await t.drain.waitForIdle();
if (t.lastPrunedAt === void 0 || this.now - t.lastPrunedAt >= CHANNEL_INGRESS_RETENTION_DEFAULTS.pruneIntervalMs) {
const { pruneIntervalMs: e, ...n } = CHANNEL_INGRESS_RETENTION_DEFAULTS;
await t.queue.prune({
...n,
now: this.now
});
t.lastPrunedAt = this.now;
}
const n = await t.queue.listUnsettled();
e ||= n.pending.length > 0 || n.claims.length > 0;
}
} catch {
e = true;
this.deps.logger.warn("mcp-events: ingress inspection/admission unavailable; retained work will retry");
} finally {
if (e && !this.signal.aborted) {
this.schedule("drain", this.now + this.drainRetryMs, () => this.drain(), true);
this.drainRetryMs = Math.min(3e4, this.drainRetryMs * 2);
}
}
})();
this.drainWork = e;
e.finally(() => {
this.drainWork = void 0;
}).catch(() => {});
return this.track(e);
}
};
//#endregion
//#region extensions/mcp-events/index.ts
function currentCron(e) {
const t = e.getCron?.();
if (!t?.readEventSources || !t.runEvent) throw new Error("MCP Events requires Gateway event-driven automation admission");
return {
readEventSources: t.readEventSources,
runEvent: t.runEvent
};
}
function getMcpEventsDiagnostics(e) {
return [...[...e.bindings.values()].map(({ facts: t, live: n }) => ({
bindingId: t.bindingId,
jobId: t.jobId,
sourceIdentity: t.sourceIdentity,
serverName: t.serverName,
name: t.definition.name,
profile: MCP_EVENTS_PROFILE,
status: !n ? "revoked" : t.refreshBefore && t.refreshBefore <= e.now ? "expired" : t.status,
refreshBefore: t.refreshBefore,
replayAvailable: t.cursor !== null,
truncated: t.truncated,
failures: t.failures,
nextAttemptAt: t.nextAttemptAt,
cleanupPending: t.cleanupPending,
lastError: t.lastError,
updatedAt: t.updatedAt
})), ...[...e.unavailable.values()].map(({ source: e, attempts: t }) => ({
jobId: e.jobId,
sourceIdentity: e.sourceIdentity,
serverName: typeof e.options.server === "string" ? e.options.server : void 0,
name: typeof e.options.name === "string" ? e.options.name : void 0,
profile: MCP_EVENTS_PROFILE,
status: "unavailable",
lastError: "source_unavailable",
failures: t
}))];
}
var mcp_events_default = definePluginEntry({
id: "mcp-events",
name: "MCP Events",
description: "Authenticated MCP webhook events for authored automations.",
configSchema: { parse: resolveMcpEventsConfig },
register(e) {
e.registerTool({
contextVersion: 2,
create: (t) => ({
name: "mcp_events",
label: "MCP Events",
description: "List webhook events and subscription argument schemas from a configured MCP server. Use the descriptors to create an Automation event source; this tool does not schedule or subscribe by itself. Pass nextCursor as cursor for another page.",
parameters: {
type: "object",
properties: {
serverName: {
type: "string",
minLength: 1,
maxLength: 256
},
cursor: {
type: "string",
minLength: 1,
maxLength: 16384
}
},
required: ["serverName"],
additionalProperties: false
},
execute: async (n, r) => {
t.assertInvocationCurrent();
const i = asOptionalRecord(r);
if (!i || typeof i.serverName !== "string" || !i.serverName.trim() || i.cursor !== void 0 && typeof i.cursor !== "string") throw new Error("Expected a configured serverName and optional cursor");
const a = await e.runtime.gateway.request("mcp.events.list", {
agentId: t.agentId,
serverName: i.serverName,
...i.cursor !== void 0 ? { cursor: i.cursor } : {}
});
t.assertInvocationCurrent();
return {
content: [{
type: "text",
text: JSON.stringify(a)
}],
details: a
};
}
})
}, { names: ["mcp_events"] });
if (e.registrationMode !== "full") return;
let t;
e.registerHttpRoute({
path: CALLBACK_PREFIX,
auth: "plugin",
match: "prefix",
handler: createCallbackHandler(() => t)
});
e.on("cron_changed", (e) => {
if (e.action === "finished") t?.requestDrain(e.jobId);
else if (e.action === "added" || e.action === "updated" || e.action === "removed") t?.requestReconcile();
});
e.on("cron_reconciled", () => {
t?.requestReconcile();
});
e.registerGatewayMethod("mcp-events.status", ({ respond: e }) => {
e(true, {
running: Boolean(t),
profile: MCP_EVENTS_PROFILE,
subscriptions: t ? getMcpEventsDiagnostics(t) : []
});
}, { scope: "operator.admin" });
e.registerService({
id: "mcp-events",
apiVersion: 2,
reload: { configPrefixes: ["plugins.entries.mcp-events", "mcp"] },
async start(n) {
const r = resolveMcpEventsConfig(n.config.plugins?.entries?.["mcp-events"]?.config);
if (!n.mcpEvents?.prepareSource) throw new Error("MCP Events requires the Gateway's source authority and scheduler capabilities");
currentCron(n);
const i = new McpEventsService({
runtime: e.runtime,
config: r,
scheduler: n.scheduler,
prepareSource: n.mcpEvents.prepareSource,
cron: {
readEventSources: () => currentCron(n).readEventSources(),
runEvent: (e, t) => currentCron(n).runEvent(e, t)
},
logger: n.logger
});
t = i;
try {
await i.start();
} catch (e) {
t = void 0;
await i.stop();
throw e;
}
},
async stop() {
const e = t;
t = void 0;
await e?.stop();
}
});
}
});
//#endregion
export { mcp_events_default as default, getMcpEventsDiagnostics };