Files
adolf/scripts/e2e/mcp-code-mode-gateway-client.ts
alvis bedb527145
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Vendor OpenClaw source as Adolf fork baseline
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

182 lines
6.1 KiB
TypeScript

// Mcp Code Mode Gateway Client script supports OpenClaw repository automation.
import path from "node:path";
import { setTimeout as setNodeTimeout, clearTimeout as clearNodeTimeout } from "node:timers";
import { pathToFileURL } from "node:url";
import { readBoundedResponseText } from "../lib/bounded-response.ts";
import { readPositiveIntEnv } from "./lib/env-limits.mjs";
import {
type McpCodeModeMentions,
validateMcpCodeModeResult,
} from "./lib/mcp-code-mode-validation.ts";
import { countSessionLogMentions } from "./lib/session-log-mentions.ts";
type FetchJsonOptions = {
fetchImpl?: (url: string, init: RequestInit) => Promise<Response>;
maxBodyBytes?: number;
timeoutMs?: number;
};
export type McpCodeModeClientFetchLimits = {
bodyMaxBytes: number;
timeoutMs: number;
};
export function readMcpCodeModeClientFetchLimits(
env: NodeJS.ProcessEnv = process.env,
): McpCodeModeClientFetchLimits {
return {
bodyMaxBytes: readPositiveIntEnv(
"OPENCLAW_MCP_CODE_MODE_CLIENT_BODY_MAX_BYTES",
1024 * 1024,
env,
),
timeoutMs: readPositiveIntEnv("OPENCLAW_MCP_CODE_MODE_CLIENT_TIMEOUT_MS", 300_000, env),
};
}
const DEFAULT_FETCH_LIMITS = readMcpCodeModeClientFetchLimits();
function assert(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
function taggedError(message: string, code: string) {
return Object.assign(new Error(message), { code });
}
export async function fetchJson(
url: string,
init: RequestInit = {},
options: FetchJsonOptions = {},
): Promise<unknown> {
const timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_FETCH_LIMITS.timeoutMs);
const maxBodyBytes = Math.max(1, options.maxBodyBytes ?? DEFAULT_FETCH_LIMITS.bodyMaxBytes);
const controller = new AbortController();
const timeoutError = taggedError(
`HTTP request to ${url} timed out after ${timeoutMs}ms`,
"ETIMEDOUT",
);
let timeout: ReturnType<typeof setNodeTimeout> | undefined;
const timeoutPromise = new Promise<never>((_, reject) => {
timeout = setNodeTimeout(() => {
controller.abort(timeoutError);
reject(timeoutError);
}, timeoutMs);
timeout.unref?.();
});
let response: Response | undefined;
let text = "";
try {
response = await Promise.race([
(options.fetchImpl ?? fetch)(url, { ...init, signal: controller.signal }),
timeoutPromise,
]);
text = await readBoundedResponseText(response, url, maxBodyBytes, {
createTooLargeError(message) {
return taggedError(message, "ETOOBIG");
},
formatTooLargeMessage(targetUrl, byteLimit) {
return `HTTP response from ${targetUrl} exceeded ${byteLimit} bytes`;
},
signal: controller.signal,
timeoutPromise,
});
} finally {
if (timeout) {
clearNodeTimeout(timeout);
}
}
if (!response) {
throw new Error(`HTTP request to ${url} did not return a response`);
}
if (!response.ok) {
throw new Error(`HTTP ${response.status} from ${url}: ${text}`);
}
return text ? JSON.parse(text) : {};
}
async function readSessionLogMentions(stateDir: string): Promise<Record<string, number>> {
const sessionsDir = path.join(stateDir, "agents", "main", "sessions");
return await countSessionLogMentions({
sessionsDir,
needles: {
apiCall: "MCP.$api",
apiFileList: "API.list",
apiFileRead: "API.read",
mcpNamespace: "MCP.fixture",
mcpTool: "fixture__lookup_note",
toolSearchPollution: 'tools.search("lookup note"',
},
});
}
async function main() {
const gatewayUrl = process.env.GW_URL?.trim();
const gatewayToken = process.env.GW_TOKEN?.trim();
const stateDir = process.env.OPENCLAW_STATE_DIR?.trim();
const model = process.env.OPENCLAW_MCP_CODE_MODE_MODEL?.trim() || "openclaw/main";
assert(gatewayUrl, "missing GW_URL");
assert(gatewayToken, "missing GW_TOKEN");
assert(stateDir, "missing OPENCLAW_STATE_DIR");
const response = await fetchJson(`${gatewayUrl.replace(/\/$/, "")}/v1/responses`, {
method: "POST",
headers: {
authorization: `Bearer ${gatewayToken}`,
"content-type": "application/json",
"x-openclaw-agent": "main",
"x-openclaw-scopes": "operator.write",
},
body: JSON.stringify({
model,
input: [
{
type: "message",
role: "user",
content: [
{
type: "input_text",
text: [
"mcp code mode api file qa check:",
"MCP and API are code-mode globals; they are defined only inside the exec tool, not in normal chat.",
"Call exec with language javascript and this exact code:",
'const files = await API.list("mcp");',
'const root = await API.read("mcp/index.d.ts");',
'const api = await API.read("mcp/fixture.d.ts");',
'const result = await MCP.fixture.lookupNote({ id: "alpha" });',
'return { marker: "MCP_CODE_MODE_FILE_TOOL_RESULT", files: files.files.map((file) => file.path), rootHasFixture: root.content.includes("fixture"), headerHasLookup: api.content.includes("function lookupNote"), note: result.content?.[0]?.text };',
"Do not use tools.search for MCP and do not call the inline MCP API helper.",
"After exec finishes, send a normal assistant reply; do not stop after only the tool call.",
"Reply with MCP_CODE_MODE_FILE_OK note=fixture-note-alpha unclear=none only after the MCP call returns fixture-note-alpha.",
].join(" "),
},
],
},
],
max_output_tokens: 1024,
stream: false,
}),
});
const mentions = await readSessionLogMentions(stateDir);
const finalText = validateMcpCodeModeResult(response, mentions as McpCodeModeMentions);
process.stdout.write(
`${JSON.stringify(
{
ok: true,
gatewayUrl,
finalText,
sessionLogMentions: mentions,
},
null,
2,
)}\n`,
);
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
await main();
}