openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
280 lines (279 loc) • 11.3 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as filterStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { n as normalizeAgentId, t as isValidAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { i as resolveSandboxRuntimeStatusAsync } from "./runtime-status-C5ZOG7YR.mjs";
import { t as prepareConversationCapabilityProfile } from "./conversation-capability-profile-Be5DqCww.mjs";
import { u as partitionMcpServersByConnectionScope } from "./bundle-mcp-config-Ca9TXxki.mjs";
import { p as releaseSessionMcpRuntime } from "./mcp-app-model-context-Nt0AWggG.mjs";
import { n as acquireSessionMcpRuntime } from "./agent-bundle-mcp-manager-api-Um6GkoIv.mjs";
import { t as buildBundleMcpToolsFromCatalog } from "./agent-bundle-mcp-materialize-DM8C34_b.mjs";
import { t as applyFinalEffectiveToolPolicy } from "./effective-tool-policy-DMFsqGJo.mjs";
import { t as applyEmbeddedAttemptToolsAllow } from "./attempt-tool-construction-plan-Cp8YcsYs.mjs";
import { a as normalizeCodexMcpServerConfig, n as buildCodexMcpServersConfig, t as applyCodexSessionMcpToolDenials } from "./codex-mcp-config-npQyRCZo.mjs";
import { t as loadMcpToolGrants } from "./exec-approvals-mcp-CergmgTH.mjs";
import { r as resolveMcpBearerBundleConfig, t as requiresMcpBearerProjection } from "./mcp-auth-profile-DW3GAdtG.mjs";
import { n as serializeTomlInlineValue } from "./toml-inline-CbBxtJfx.mjs";
//#region src/agents/native-mcp-policy.ts
function buildPolicyProjectionTools(e) {
const t = buildBundleMcpToolsFromCatalog({ catalog: e }).filter((e) => getPluginToolMeta(e)?.mcp?.operation === "tool");
const n = new Set(t.flatMap((e) => {
const t = getPluginToolMeta(e)?.mcp;
return t?.operation === "tool" ? [JSON.stringify([t.serverName, t.toolName])] : [];
}));
const r = (e.policyTools ?? [...e.tools, ...e.sessionDeniedTools ?? []]).filter((e) => !n.has(JSON.stringify([e.serverName, e.toolName])));
const i = buildBundleMcpToolsFromCatalog({
catalog: {
...e,
tools: r,
policyTools: void 0,
sessionDeniedTools: void 0
},
reservedToolNames: t.map((e) => e.name),
includeAppOnlyInventory: true
}).filter((e) => getPluginToolMeta(e)?.mcp?.operation === "tool");
return [...t, ...i];
}
async function prepareNativeMcpPolicy(e) {
e.runtime.markUsed();
const t = buildPolicyProjectionTools(await e.runtime.getCatalog());
const n = applyEmbeddedAttemptToolsAllow(t, e.runtimeToolsAllow, { toolMeta: (e) => getPluginToolMeta(e) });
const r = applyFinalEffectiveToolPolicy({
bundledTools: n,
config: e.config,
workspaceDir: e.workspaceDir,
conversationCapabilityProfile: e.capabilityProfile,
warn: e.warn
});
const i = new Set(r.map((e) => e.name));
const a = {};
for (const e of t) {
const t = getPluginToolMeta(e)?.mcp;
if (!t || t.operation !== "tool") continue;
const n = a[t.serverName] ??= {
serverName: t.serverName,
safeServerName: t.safeServerName,
allowedTools: [],
deniedTools: []
};
(!t.excludedFromOpenClawCatalog && !t.deniedBySession && i.has(e.name) ? n.allowedTools : n.deniedTools).push(t.toolName);
}
for (const e of Object.values(a)) {
e.allowedTools = [...new Set(e.allowedTools)].toSorted();
e.deniedTools = [...new Set(e.deniedTools)].toSorted();
}
return { servers: Object.fromEntries(Object.entries(a).toSorted(([e], [t]) => e.localeCompare(t))) };
}
/** Applies one prepared policy to the provider-neutral MCP config shape. */
function applyPreparedNativeMcpPolicy(e, t) {
return { mcpServers: Object.fromEntries(Object.entries(e.mcpServers).flatMap(([e, n]) => {
const r = t.servers[e];
if (!r || r.allowedTools.length === 0) return [];
const i = isRecord(n.toolFilter) ? n.toolFilter : {};
return [[e, {
...n,
toolFilter: {
...i,
include: r.allowedTools,
exclude: r.deniedTools
}
}]];
})) };
}
/** Returns raw per-server denials for backends that enforce a deny list. */
function preparedNativeMcpDenials(e) {
const t = Object.values(e.servers).filter((e) => e.deniedTools.length > 0).map((e) => [e.serverName, e.deniedTools]);
return t.length > 0 ? Object.fromEntries(t) : void 0;
}
//#endregion
//#region src/agents/cli-runner/native-mcp-context.ts
/** Both native MCP adapters project the same requester facts before selecting runtime policy. */
function projectNativeMcpRunContext(e) {
return {
sessionId: e.sessionId,
runId: e.runId,
agentAccountId: e.agentAccountId,
messageProvider: e.messageProvider ?? e.messageChannel,
messageChannel: e.messageChannel,
groupId: e.groupId,
groupChannel: e.groupChannel,
groupSpace: e.groupSpace,
spawnedBy: e.spawnedBy,
senderId: e.senderId,
senderName: e.senderName,
senderUsername: e.senderUsername,
senderE164: e.senderE164,
senderIsOwner: e.senderIsOwner,
conversationToolPolicy: e.conversationToolPolicy,
requesterOrigin: e.requesterOrigin,
operatorProfileId: e.operatorProfileId,
conversationId: e.conversationId,
chatType: e.chatType,
messageThreadId: e.messageThreadId,
memberRoleIds: e.memberRoleIds,
inputProvenance: e.inputProvenance,
trustedInternalHandoff: e.trustedInternalHandoff,
scheduledToolPolicy: e.scheduledToolPolicy
};
}
//#endregion
//#region src/agents/cli-runner/bundle-mcp-codex.ts
function isCodexMcpServerAllowedForAgent(e, t) {
const n = isRecord(e.codex) ? e.codex : {};
if (!Object.hasOwn(n, "agents")) return true;
if (!t?.agentId) return false;
const r = normalizeAgentId(t.agentId);
return filterStringEntries(n.agents).some((e) => {
const t = e.trim();
return isValidAgentId(t) && normalizeAgentId(t) === r;
});
}
/**
* Applies Codex-only agent scoping before OpenClaw resolves credentials or opens transports.
* Session overrides may narrow this result, but cannot widen `codex.agents`.
*/
function resolveCodexMcpToolOverridesForAgent(e, t) {
const n = Object.entries(e?.mcp?.servers ?? {}).filter(([, e]) => !isCodexMcpServerAllowedForAgent(e, t)).map(([e]) => e);
if (n.length === 0) return t.toolOverrides;
const r = { ...t.toolOverrides?.mcpServers };
for (const e of n) r[e] = false;
return {
...t.toolOverrides,
mcpServers: r
};
}
function readSessionMcpServerOverride(e, t) {
const n = e?.toolOverrides?.mcpServers;
return n && Object.hasOwn(n, t) ? n[t] : void 0;
}
function selectCodexProjectableMcpServers(e, t) {
const n = e?.mcp?.servers ?? {};
const { staticServers: r } = partitionMcpServersByConnectionScope(n);
return Object.fromEntries(Object.entries(r).filter(([e, n]) => {
const r = readSessionMcpServerOverride(t, e);
if (!(r !== false && (r === true || n.enabled !== false) && isCodexMcpServerAllowedForAgent(n, t))) return false;
if (t?.allowLiteralOAuthProjection === false && requiresMcpBearerProjection(n)) {
t.onServerUnavailable?.(e, /* @__PURE__ */ new Error(`MCP OAuth bearer projection is only supported for local app-server connections.`));
return false;
}
return true;
}));
}
/** Returns Codex CLI args with TOML MCP server overrides injected. */
function injectCodexMcpConfigArgs(e, t) {
const n = serializeTomlInlineValue(buildCodexMcpServersConfig(t));
return [
...e ?? [],
"-c",
`mcp_servers=${n}`
];
}
/** Async runtime projection that resolves OpenClaw-managed MCP bearer tokens. */
async function buildCodexUserMcpServersThreadConfigPatchForRuntime(e, t) {
let n = selectCodexProjectableMcpServers(e, t);
if (t?.preparationOnly && Object.values(n).some(requiresMcpBearerProjection)) throw new Error("Native fork preparation cannot resolve MCP bearer credentials. Fork an original imported message instead.");
if (t?.preparedNativeMcpPolicy) n = applyPreparedNativeMcpPolicy({ mcpServers: n }, t.preparedNativeMcpPolicy).mcpServers;
if (Object.keys(n).length === 0) return;
const r = t?.agentId ? await loadMcpToolGrants(t.agentId) : [];
const i = await resolveMcpBearerBundleConfig({
config: { mcpServers: n },
cfg: e,
agentDir: t?.agentDir,
tokenProjection: "literal",
omitUnavailableOAuthServers: true,
onServerUnavailable: t?.onServerUnavailable
});
const a = Object.fromEntries(Object.entries(i.config.mcpServers).map(([e, n]) => [e, normalizeCodexMcpServerConfig(e, applyCodexSessionMcpToolDenials(e, n, t?.toolOverrides), r)]));
return Object.keys(a).length === 0 ? void 0 : { mcp_servers: a };
}
/** Prepares canonical native MCP policy and projects it into Codex before thread creation. */
async function buildCodexUserMcpServersThreadConfigPatchForRun(e) {
const t = e.run;
const n = e.agentId ?? t.agentId;
const r = resolveCodexMcpToolOverridesForAgent(t.config, {
agentId: n,
toolOverrides: t.toolOverrides
});
const i = t.sandboxSessionKey ?? t.sessionKey;
const a = resolveSessionAgentId({
config: t.config,
sessionKey: i,
agentId: t.sandboxAgentId,
fallbackAgentId: n
});
const o = await resolveSandboxRuntimeStatusAsync({
cfg: t.config,
sessionKey: i,
agentId: a
});
const s = await prepareConversationCapabilityProfile({
...projectNativeMcpRunContext(t),
config: t.config,
sessionKey: i,
runSessionKey: t.sessionKey && t.sessionKey !== i ? t.sessionKey : void 0,
agentId: a,
modelProvider: t.provider,
modelId: t.modelId,
workspaceDir: t.workspaceDir,
cwd: e.cwd,
sandboxToolPolicy: o.sandboxed ? o.toolPolicy : void 0,
runtimeToolAllowlist: t.toolsAllow,
inheritRuntimeToolAllowlist: true,
runtimePluginToolGrant: t.runtimePluginToolGrant
});
const c = selectCodexProjectableMcpServers(t.config, {
agentId: n,
allowLiteralOAuthProjection: e.allowLiteralOAuthProjection,
onServerUnavailable: e.onServerUnavailable,
toolOverrides: r
});
if (Object.keys(c).length === 0) return;
const l = {
...t.config,
mcp: {
...t.config?.mcp,
servers: c
}
};
const u = await acquireSessionMcpRuntime({
sessionId: t.sessionId,
sessionKey: t.sessionKey,
agentId: n,
workspaceDir: t.workspaceDir,
agentDir: t.agentDir,
cfg: l,
requesterSenderId: t.senderId,
agentAccountId: t.agentAccountId,
messageChannel: t.messageChannel,
toolOverrides: r,
toolDenylist: s.policy.explicitToolDenylist
});
let d;
try {
const i = await prepareNativeMcpPolicy({
runtime: u.runtime,
config: t.config,
workspaceDir: t.workspaceDir,
capabilityProfile: s,
runtimeToolsAllow: t.toolsAllow,
warn: e.warn ?? (() => {})
});
const a = await buildCodexUserMcpServersThreadConfigPatchForRuntime(l, {
agentId: n,
agentDir: t.agentDir,
allowLiteralOAuthProjection: e.allowLiteralOAuthProjection,
onServerUnavailable: e.onServerUnavailable,
toolOverrides: r,
preparedNativeMcpPolicy: i
});
d = new Set(Object.keys(a?.mcp_servers ?? {}));
return a;
} finally {
await releaseSessionMcpRuntime(u, d);
}
}
//#endregion
export { projectNativeMcpRunContext as a, preparedNativeMcpDenials as c, resolveCodexMcpToolOverridesForAgent as i, buildCodexUserMcpServersThreadConfigPatchForRuntime as n, applyPreparedNativeMcpPolicy as o, injectCodexMcpConfigArgs as r, prepareNativeMcpPolicy as s, buildCodexUserMcpServersThreadConfigPatchForRun as t };