Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(daemon): isolate managed OpenClaw MCP servers without reading user config (MUL-6684, MUL-6857) (#7279)

VvV4dfa08917bdd
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 05507c782d..4c13848e6f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -522,6 +522,16 @@ jobs:
if: ${{ needs.changes.outputs.backend == 'true' }}
run: cd server && go build ./...
+ # The `agentintegration` files execute real agent CLIs, so no CI job runs
+ # them. Nothing compiled them either, which let them rot silently: a
+ # helper renamed in an ordinary test file, or two branches each defining
+ # the same helper in one package, breaks the tagged build with every
+ # untagged job still green. vet type-checks test files, so this is the
+ # cheapest gate that keeps them honest without needing an agent CLI.
+ - name: Vet tag-gated agent integration tests
+ if: ${{ needs.changes.outputs.backend == 'true' }}
+ run: cd server && go vet -tags agentintegration ./...
+
- name: Run migrations
if: ${{ needs.changes.outputs.backend == 'true' }}
run: cd server && go run ./cmd/migrate up
diff --git a/.github/workflows/openclaw-config-smoke.yml b/.github/workflows/openclaw-config-smoke.yml
new file mode 100644
index 0000000000..867ecf06c8
--- /dev/null
+++ b/.github/workflows/openclaw-config-smoke.yml
@@ -0,0 +1,76 @@
+name: OpenClaw config compatibility smoke
+
+on:
+ workflow_dispatch:
+ schedule:
+ - cron: "17 6 * * 1"
+
+permissions:
+ contents: read
+
+concurrency:
+ group: openclaw-config-smoke-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ managed-mcp-isolation:
+ name: Managed MCP isolation (${{ matrix.channel }})
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ strategy:
+ fail-fast: false
+ matrix:
+ # Initial manual measurement on 2026-08-26 resolved these channels to
+ # 2026.6.34, 2026.7.1-2, and 2026.8.1-beta.3 respectively. Keep the
+ # channel names floating so loader-semantic drift is detected when
+ # OpenClaw publishes a replacement.
+ channel:
+ - extended-stable
+ - latest
+ - beta
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - name: Setup Go
+ uses: actions/setup-go@v5
+ with:
+ go-version: "1.26.x"
+ check-latest: true
+ cache-dependency-path: server/go.sum
+
+ - name: Setup Node
+ uses: actions/setup-node@v6
+ with:
+ node-version: "24.x"
+ check-latest: true
+
+ - name: Install OpenClaw (${{ matrix.channel }})
+ run: npm install --global "openclaw@${{ matrix.channel }}"
+
+ - name: Record resolved OpenClaw version
+ run: openclaw --version
+
+ # A skipped Go test reports `ok` at the package level, so without this the
+ # job goes green whenever the CLI is absent, MULTICA_RUN_REAL_AGENT_SMOKE
+ # is unset, or the -run pattern stops matching — i.e. exactly when the
+ # thing being verified is not being verified. #6897's Windows step calls
+ # out the same hazard for the same reason. Require the RUN/PASS line and
+ # reject SKIP explicitly rather than trusting the exit status.
+ - name: Verify managed MCP isolation through the real loader
+ working-directory: server
+ env:
+ MULTICA_RUN_REAL_AGENT_SMOKE: "1"
+ run: |
+ set -o pipefail
+ go test -tags agentintegration ./internal/daemon/execenv/ \
+ -run '^TestPrepareOpenclawConfigRealCLI$' -count=1 -v \
+ 2>&1 | tee smoke.log
+ if grep -q -- '--- SKIP: TestPrepareOpenclawConfigRealCLI' smoke.log; then
+ echo "::error::the real-loader test skipped; nothing was verified for ${{ matrix.channel }}"
+ exit 1
+ fi
+ if ! grep -q -- '--- PASS: TestPrepareOpenclawConfigRealCLI' smoke.log; then
+ echo "::error::no PASS line for the real-loader test on ${{ matrix.channel }}"
+ exit 1
+ fi
diff --git a/server/internal/daemon/execenv/openclaw_config.go b/server/internal/daemon/execenv/openclaw_config.go
index c7a394d5e5..7eb4be08ba 100644
--- a/server/internal/daemon/execenv/openclaw_config.go
+++ b/server/internal/daemon/execenv/openclaw_config.go
@@ -22,13 +22,30 @@ import (
// the rest of the task env.
const openclawConfigFile = "openclaw-config.json"
-// openclawUserSnapshotFile is the sanitized copy of the user's fully
-// resolved openclaw config the wrapper $includes when the agent has a
-// managed mcp_config. It is the user's config minus the `mcp` block so the
-// wrapper's managed `mcp.servers` is the only MCP definition visible to
-// OpenClaw — true strict-replace, not deep-merge-by-name. Lives in envRoot
-// at 0o600 next to the wrapper.
-const openclawUserSnapshotFile = "openclaw-user-snapshot.json"
+// openclawMcpResetFile holds exactly `{"mcp":{"servers":null}}` and is included
+// after the user's live config whenever the agent has a managed mcp_config.
+//
+// One key, and nothing else, is the whole design. OpenClaw's include merge is
+// recursive for objects and replacing for a primitive or null source, so nulling
+// `mcp.servers` clears the user's server map while every sibling under `mcp`
+// continues to arrive from the live config untouched — this code never reads,
+// rewrites or re-emits them. That is what keeps a sibling this daemon has never
+// heard of correct, and what makes it impossible to write a redacted display
+// value back over a working one.
+//
+// The wrapper's own `mcp.servers` then merges over the include result and becomes
+// the only server definition. Because the reset is written only when the wrapper
+// carries that key, the null cannot survive to the resolved root, where
+// OpenClaw's schema would reject it (zod `.strict().optional()` rejects null).
+// TestPrepareOpenclawConfigResetStagePairsWithWrapperMcp pins that pairing.
+//
+// Lives in envRoot at 0o600 next to the wrapper. It carries no user data at all.
+const openclawMcpResetFile = "openclaw-mcp-reset.json"
+
+// openclawMcpResetBody is that file's entire content. A literal rather than a
+// marshalled map: the point of this stage is that it names exactly one key, and a
+// literal is the form a reader can check against the design in one glance.
+const openclawMcpResetBody = "{\n \"mcp\": {\n \"servers\": null\n }\n}\n"
// openclawCLITimeout is the default context deadline set on each
// `openclaw config ...` invocation during task setup.
@@ -97,7 +114,7 @@ const (
// openclawCLIMaxTimeout keeps config discovery inside the outer task
// preparation budget (daemon.defaultTaskPrepareTimeout, 5 minutes). The
// worst case is openclawMaxCLIDeadlinesPerPreparation serial steps, so the
- // ceiling is set so that even then (4 x 60s = 4m) the failure surfaces as a
+ // ceiling is set so that even then (3 x 60s = 3m) the failure surfaces as a
// specific, actionable CLI timeout with room to spare, instead of colliding
// with the outer deadline and collapsing into the generic — and retryable —
// prepare-timeout reason. A step may make more than one invocation — path
@@ -112,23 +129,23 @@ const (
// inside the outer preparation budget, so this is the multiplier
// openclawCLIMaxTimeout is derived from.
//
-// The four steps, in the order they can fire:
+// The three steps, in the order they can fire:
//
// 1. locate the active config — `config validate --json`, then `config file`
// if that did not answer. Two invocations, one deadline: they ask the same
// question and openclawActiveConfigPath shares a context between them
-// precisely so the fallback cannot add a fifth budget.
+// precisely so the fallback cannot add a fourth budget.
// 2. `config get agents.list --json` — pre-2026.6 agents schema
// 3. `agents list --json` — 2026.6+ registry fallback, only
// reached when (2) reports the config path is missing
-// 4. `config get --json` — full resolved config, only for an
-// agent with a managed mcp_config
//
-// Adding a fifth deadline-bearing step means re-deriving the ceiling. The
-// worst-case test counts distinct deadlines rather than calls, so a new
-// invocation that shares an existing budget is free and one that brings its own
-// fails loudly.
-const openclawMaxCLIDeadlinesPerPreparation = 4
+// It was four until managed MCP stopped reading the user's config: the reset
+// stage is a file this package writes, so a managed-MCP agent now costs the same
+// CLI time as any other. Adding a fourth deadline-bearing step means re-deriving
+// the ceiling. The worst-case test counts distinct deadlines rather than calls,
+// so a new invocation that shares an existing budget is free and one that brings
+// its own fails loudly.
+const openclawMaxCLIDeadlinesPerPreparation = 3
// ErrOpenclawCLITimeout marks a task preparation that failed because the local
// openclaw CLI did not answer within the deadline. It is a sentinel rather
@@ -381,44 +398,56 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op
// **Strict replace for managed mcp_config.** When the agent has a managed
// set, deep-merging the wrapper's `mcp.servers` against the user's active
// config via `$include` would let user-only entries leak in (and an empty
- // managed set would not actually clear inherited servers). To enforce the
- // Codex-style "managed wins, user globals invisible" contract, fetch the
- // user's resolved config, drop just the `mcp.servers` map (keep other
- // `mcp.*` settings like `sessionIdleTtlMs`), write a sanitized snapshot
- // in envRoot, and $include the snapshot instead of the live user file.
- // The wrapper's `mcp.servers` then becomes the only MCP server definition
- // the snapshot's resolution can yield, while the user's surrounding `mcp`
- // tuning still flows through.
- snapshotPath := ""
+ // managed set would not actually clear inherited servers).
+ //
+ // What this used to do instead was read the user's whole resolved config
+ // through `config get --json` (no key path), strip `mcp.servers`, and write
+ // the remainder into the task directory as a snapshot the wrapper included.
+ // Two things were wrong with it, and only the first is why the task failed:
+ //
+ // - The read is not a valid invocation. `config get` requires a path, and
+ // every channel measured on 2026-08-26 rejects the pathless form:
+ // 2026.6.34 (extended-stable) exit 1 in 2.9s with
+ // `Missing required argument "path".`, 2026.7.1-2 (latest) the same in
+ // 3.0s, 2026.8.1-beta.3 (beta) the same as a JSON envelope in 4.4s. So
+ // preparation failed for every managed-MCP task on every current channel.
+ // (2026.5.27 instead wrote zero bytes and never exited within 60s;
+ // #6275 made that shape fail predictably rather than hang, which is why
+ // it is adjacent to this fix and not a substitute for it.)
+ // - Even answered, the result is display data rather than a lossless
+ // round-trip: `runConfigGet` applies `redactConfigObject`, so a sensitive
+ // value comes back as the literal `__OPENCLAW_REDACTED__`. OpenClaw can
+ // restore that sentinel from the original file when it writes; this daemon
+ // cannot. Writing the remainder back would eventually overwrite a working
+ // value with a placeholder.
+ //
+ // Both disappear by not reading the config at all. The wrapper includes the
+ // user's live config and then a reset stage carrying exactly
+ // `{"mcp":{"servers":null}}`, and its own `mcp.servers` merges over the
+ // result:
+ //
+ // live config -> mcp.servers: null -> managed servers
+ //
+ // The user's `mcp` siblings arrive from the live config and are never
+ // observed by this process, so nothing can be lost in transit and no key this
+ // daemon does not know about can be dropped or invented. OpenClaw's own
+ // loader still resolves JSON5, nested includes and env substitution behind
+ // the include, and no user config bytes, API keys or provider tokens are
+ // written into the task directory.
+ //
+ // Verified against the real loader on 2026.6.34, 2026.7.1-2 and
+ // 2026.8.1-beta.3: objects merge recursively, a null source replaces, and
+ // sibling keys on the includer win over the include result. See
+ // openclaw_mcp_real_integration_test.go.
+ resetPath := ""
if hasManagedMcp && exists {
- resolved, ferr := openclawResolvedFullConfig(bin, timeout)
- if ferr != nil {
- return OpenclawConfigResult{}, fmt.Errorf("read openclaw resolved config: %w", ferr)
- }
- if resolved == nil {
- // CLI reports the file exists but `config get --json` returned
- // nothing structured. Treat as no user-config-to-strip: the
- // wrapper will carry managed mcp.servers as the sole source.
- exists = false
- activePath = ""
- } else {
- stripUserMcpServers(resolved)
- snapBytes, merr := json.MarshalIndent(resolved, "", " ")
- if merr != nil {
- return OpenclawConfigResult{}, fmt.Errorf("marshal openclaw user snapshot: %w", merr)
- }
- snapshotPath = filepath.Join(envRoot, openclawUserSnapshotFile)
- // 0o600 — the snapshot is now a flat copy of the user's resolved
- // config and may carry API keys / model-provider tokens that
- // $include used to keep on disk in the user's own file. Lock the
- // snapshot to the daemon owner; only the openclaw child reads it.
- if werr := os.WriteFile(snapshotPath, snapBytes, 0o600); werr != nil {
- return OpenclawConfigResult{}, fmt.Errorf("write openclaw user snapshot: %w", werr)
- }
+ resetPath = filepath.Join(envRoot, openclawMcpResetFile)
+ if werr := os.WriteFile(resetPath, []byte(openclawMcpResetBody), 0o600); werr != nil {
+ return OpenclawConfigResult{}, fmt.Errorf("write openclaw mcp reset: %w", werr)
}
}
- cfg := buildPerTaskOpenclawConfig(activePath, exists, snapshotPath, resolvedList, agentsFromRegistry, workDir, managedMcp, hasManagedMcp, opts.Gateway)
+ cfg := buildPerTaskOpenclawConfig(activePath, exists, resetPath, resolvedList, agentsFromRegistry, workDir, managedMcp, hasManagedMcp, opts.Gateway)
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
@@ -433,16 +462,16 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op
}
result := OpenclawConfigResult{ConfigPath: outPath}
includeTarget := "none"
- if snapshotPath != "" {
- // Sanitized snapshot lives in envRoot alongside the wrapper, so the
- // $include never crosses directories — daemon does not need to grant
- // an extra OPENCLAW_INCLUDE_ROOTS entry.
- includeTarget = "sanitized-snapshot"
- } else if exists {
+ if exists {
// Live user config is in its own directory; tell the daemon to grant
- // it so OpenClaw's include-confinement check passes.
+ // it so OpenClaw's include-confinement check passes. The reset stage
+ // needs no grant of its own: it sits in envRoot beside the wrapper that
+ // includes it.
result.IncludeRoot = filepath.Dir(activePath)
includeTarget = "user-config"
+ if resetPath != "" {
+ includeTarget = "user-config+mcp-reset"
+ }
}
if opts.Logger != nil {
opts.Logger.Info("execenv: prepared openclaw config",
@@ -521,21 +550,22 @@ func discoverOpenclawConfig(bin string, timeout time.Duration, opts OpenclawConf
// $include here, so this is not the silent-fallback case the reviewer
// flagged.
//
-// snapshotPath, when non-empty, points at a sanitized copy of the user's
-// resolved config (mcp stripped) sitting in envRoot. It is the $include
-// target whenever the agent has a managed mcp_config — the live user file
-// would otherwise leak global `mcp.servers` past the wrapper. When
-// snapshotPath is empty the wrapper falls back to $include'ing the active
-// path so secrets / nested includes stay in the user's own file (no
-// managed mcp means there is nothing to enforce strictness against).
+// resetPath, when non-empty, names the `{"mcp":{"servers":null}}` stage in
+// envRoot and is appended to the include list after the user's active config.
+// Include order is the mechanism: the user's servers are nulled after arriving
+// and before the wrapper's own `mcp.servers` merges over the result, so the
+// managed set is what resolves while every `mcp` sibling still comes straight
+// from the user's file. Empty means no managed set, in which case there is
+// nothing to enforce strictness against and the wrapper includes the active
+// path alone.
//
// hasManagedMcp distinguishes "agent has a managed mcp_config (possibly an
// empty set)" from "agent inherits the user's global mcp.servers". When
-// true we pin `mcp.servers` to managedMcp on the wrapper. Because the
-// snapshot $include has already dropped the user's `mcp` block, the
-// resulting view of `mcp.servers` is exactly the managed set — including
-// `{}` for "admin saved no servers" (mirrors `hasManagedCodexMcpConfig`).
-func buildPerTaskOpenclawConfig(activePath string, exists bool, snapshotPath string, resolvedList []any, agentsFromRegistry bool, workDir string, managedMcp map[string]any, hasManagedMcp bool, gateway OpenclawGatewayPin) map[string]any {
+// true we pin `mcp.servers` to managedMcp on the wrapper. Because the reset
+// stage has already nulled the user's server map, the resulting view of
+// `mcp.servers` is exactly the managed set — including `{}` for "admin saved
+// no servers" (mirrors `hasManagedCodexMcpConfig`).
+func buildPerTaskOpenclawConfig(activePath string, exists bool, resetPath string, resolvedList []any, agentsFromRegistry bool, workDir string, managedMcp map[string]any, hasManagedMcp bool, gateway OpenclawGatewayPin) map[string]any {
agents := map[string]any{
"defaults": map[string]any{"workspace": workDir},
}
@@ -558,8 +588,10 @@ func buildPerTaskOpenclawConfig(activePath string, exists bool, snapshotPath str
if hasManagedMcp {
// Always emit `mcp.servers` (even when empty) so the wrapper's intent
// — "admin manages this set" — is grep-able on disk and visible to
- // OpenClaw's loader. The snapshot $include has already dropped the
- // user's `mcp` block, so this becomes the only definition.
+ // OpenClaw's loader. The reset stage in the include list has already
+ // nulled the user's server map, so this becomes the only definition —
+ // and emitting it unconditionally here is what keeps that null from
+ // reaching the resolved root, where the schema would reject it.
servers := managedMcp
if servers == nil {
servers = map[string]any{}
@@ -575,15 +607,17 @@ func buildPerTaskOpenclawConfig(activePath string, exists bool, snapshotPath str
if gw := buildGatewayOverride(gateway); gw != nil {
cfg["gateway"] = gw
}
- switch {
- case snapshotPath != "":
- // Sanitized snapshot path; strict-replace flow for managed mcp_config.
- // Array form so OpenClaw deep-merges the snapshot's content with our
+ if exists {
+ // Array form so OpenClaw deep-merges the included content with our
// sibling keys (agents overrides, mcp.servers) rather than letting the
- // include replace the whole wrapper.
- cfg["$include"] = []any{snapshotPath}
- case exists:
- cfg["$include"] = []any{activePath}
+ // include replace the whole wrapper. With a managed set the reset stage
+ // follows the user's config in the same list, so the strict-replace flow
+ // costs one more entry rather than a second file and a nested include.
+ includes := []any{activePath}
+ if resetPath != "" {
+ includes = append(includes, resetPath)
+ }
+ cfg["$include"] = includes
}
return cfg
}
@@ -649,28 +683,6 @@ func rewriteAgentsListWorkspaces(list []any, workDir string) []any {
return out
}
-// stripUserMcpServers removes only `mcp.servers` from a resolved user
-// config, leaving every other key under `mcp` (e.g. `sessionIdleTtlMs`)
-// intact. The wrapper's managed `mcp.servers` becomes the sole server
-// definition while the user's surrounding MCP tuning still applies — see
-// https://docs.openclaw.ai/gateway/configuration-reference#mcp for the
-// full list of sibling settings the snapshot should preserve.
-//
-// If the resulting `mcp` block has no keys left, the parent `mcp` key is
-// dropped too so the snapshot doesn't carry an empty placeholder. Any
-// non-object value for `mcp` is left as-is; we only know how to strip
-// servers from the documented object shape.
-func stripUserMcpServers(resolved map[string]any) {
- mcp, ok := resolved["mcp"].(map[string]any)
- if !ok {
- return
- }
- delete(mcp, "servers")
- if len(mcp) == 0 {
- delete(resolved, "mcp")
- }
-}
-
// openclawActiveConfigPath discovers the path the openclaw CLI considers active.
// Returns (absolutePath, exists, error).
//
@@ -1097,41 +1109,6 @@ func isOpenclawConfigFileUnsupported(err error) bool {
(strings.Contains(msg, "unknown") && strings.Contains(msg, "config") && strings.Contains(msg, "file"))
}
-// openclawResolvedFullConfig fetches the user's fully resolved openclaw
-// config via `openclaw config get --json` (no key path — root). The CLI's
-// loader handles JSON5 / $include / env-substitution and emits a flat JSON
-// object, which is what we need to write a sanitized snapshot that the
-// wrapper can $include without inheriting the user's `mcp.servers`.
-//
-// Returns (nil, nil) when the CLI prints empty / null output for the root
-// — interpreted as "no resolvable user config" by the caller, which then
-// falls through to the fresh-install code path. Any other failure
-// surfaces as an error so the daemon fails closed instead of silently
-// degrading to a leaky non-strict wrapper.
-func openclawResolvedFullConfig(bin string, timeout time.Duration) (map[string]any, error) {
- ctx, cancel := context.WithTimeout(context.Background(), timeout)
- defer cancel()
- out, err := openclawExec(ctx, bin, "config", "get", "--json")
- if err != nil {
- return nil, annotateOpenclawJSONError(err, out)
- }
- trimmed := strings.TrimSpace(out)
- if trimmed == "" || trimmed == "null" {
- return nil, nil
- }
- // This target is an object, so an envelope decodes cleanly and would be
- // carried into the sanitized snapshot as if it were the user's config. There
- // is no graceful reading of an error here: fail closed.
- if message, isEnvelope := openclawJSONErrorMessage(trimmed); isEnvelope {
- return nil, openclawStdoutEnvelopeError("config get --json", message)
- }
- var cfg map[string]any
- if err := json.Unmarshal([]byte(trimmed), &cfg); err != nil {
- return nil, fmt.Errorf("parse `openclaw config get --json` output: %w", err)
- }
- return cfg, nil
-}
-
// openclawResolvedAgentsList fetches the user's resolved per-agent list and
// reports which schema produced it. The schema matters downstream: a config-
// sourced list is itself valid `agents.list[]` config and may be written back
@@ -1154,7 +1131,7 @@ func openclawResolvedAgentsList(bin string, timeout time.Duration) ([]any, bool,
defer cancel()
out, err := openclawExec(ctx, bin, "config", "get", "agents.list", "--json")
if err != nil {
- if isOpenclawKeyMissingResult(out, err) {
+ if isOpenclawKeyMissingResult(out, err, "agents.list") {
// New schema: the config path is gone; the agents live in the
// sqlite registry. Resolve them via the subcommand instead.
list, rerr := openclawRegistryAgentsList(bin, timeout)
@@ -1444,20 +1421,36 @@ const openclawJSONErrorMaxRunes = 1024
func openclawJSONErrorMessage(stdout string) (string, bool) {
var envelope struct {
- Error string `json:"error"`
+ Error json.RawMessage `json:"error"`
}
- if json.Unmarshal([]byte(strings.TrimSpace(stdout)), &envelope) != nil {
+ if json.Unmarshal([]byte(strings.TrimSpace(stdout)), &envelope) != nil || len(envelope.Error) == 0 {
return "", false
}
- message := strings.Join(strings.Fields(envelope.Error), " ")
+ var message string
+ if err := json.Unmarshal(envelope.Error, &message); err != nil {
+ // OpenClaw 2026.8.1-beta.3 changed JSON failures from
+ // {"error":"message"} to
+ // {"ok":false,"error":{"type":"cli_error","message":"message"}}.
+ // Extract only the diagnostic field in either shape; sibling fields can
+ // still carry resolved configuration or secrets.
+ var detail struct {
+ Message string `json:"message"`
+ }
+ if json.Unmarshal(envelope.Error, &detail) != nil {
+ return "", false
+ }
+ message = detail.Message
+ }
+ message = strings.Join(strings.Fields(message), " ")
return message, message != ""
}
// annotateOpenclawJSONError restores diagnostics for JSON-mode commands whose
-// CLI errors are written to stdout. Only the envelope's `error` string is
-// included: sibling fields may contain resolved configuration or secrets. The
-// message is whitespace-normalized for single-line logs and rune-bounded to
-// keep persisted task errors finite while preserving valid UTF-8.
+// CLI errors are written to stdout. Only the envelope's diagnostic message is
+// included, whether `error` is a string or an object: sibling fields may
+// contain resolved configuration or secrets. The message is
+// whitespace-normalized for single-line logs and rune-bounded to keep persisted
+// task errors finite while preserving valid UTF-8.
func annotateOpenclawJSONError(err error, stdout string) error {
if err == nil {
return nil
@@ -1494,29 +1487,129 @@ func openclawStdoutEnvelopeError(command, message string) error {
return fmt.Errorf("`openclaw %s` reported: %s", command, openclawBoundedJSONErrorMessage(message))
}
-// isOpenclawKeyMissingResult recognizes the JSON error envelope observed in
-// OpenClaw 2026.7.2-beta.7 for `config get ... --json` failures. It first
-// preserves the historical stderr/error-text matching, then parses only the
-// explicit `error` field and requires it to name agents.list; broad historical
-// phrases such as "not set" cannot reclassify an unrelated structured error.
-// Cancellation and timeout keep their original meaning even if a child emitted
-// a partial missing-path envelope before it stopped.
-func isOpenclawKeyMissingResult(stdout string, err error) bool {
+// isOpenclawKeyMissingResult recognizes the "you asked for a key that is not
+// there" failures of `config get ... --json`. Which channel reports it where was
+// measured on 2026-08-26, and the spread is why both transports stay supported:
+//
+// 2026.6.34 (extended-stable) stderr text, stdout empty
+// 2026.7.1-2 (latest) stderr text, stdout empty
+// 2026.7.2-beta.7 stdout {"error":"..."}
+// 2026.8.1-beta.3 (beta) stdout {"ok":false,"error":{"message":...}}
+//
+// So the stdout envelope is not "the new way" that replaced stderr — the current
+// stable and latest channels are stderr-only, and only the beta line puts it on
+// stdout. Dropping either transport breaks a channel that is shipping today.
+//
+// Wording also moved: 2026.6.34 and 2026.7.1-2 say "Config path not found: mcp",
+// 2026.8.1-beta.3 says "Config path is valid but unset: mcp" for a key the schema
+// knows and "Unknown config path: agents.list" for one it does not.
+//
+// Structured messages must name the path we asked for. That is what keeps a
+// *usage* error out of this branch: the pathless `config get --json` form fails
+// with `Missing required argument "path".`, which names no path and so cannot be
+// read as an absent key. Cancellation and timeout keep their original meaning
+// even if a child emitted a partial missing-path envelope before it stopped.
+func isOpenclawKeyMissingResult(stdout string, err error, keyPath string) bool {
if err == nil {
return false
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false
}
- if isOpenclawKeyMissing(err) {
+ if openclawKeyMissingMessageForPath(err.Error(), keyPath) {
return true
}
message, ok := openclawJSONErrorMessage(stdout)
if !ok {
return false
}
- return strings.Contains(strings.ToLower(message), "agents.list") &&
- isOpenclawKeyMissingMessage(message)
+ return openclawKeyMissingMessageForPath(message, keyPath)
+}
+
+func openclawKeyMissingMessageForPath(message, keyPath string) bool {
+ message = strings.ToLower(strings.Join(strings.Fields(message), " "))
+ keyPath = strings.ToLower(strings.TrimSpace(keyPath))
+ if keyPath == "" {
+ return false
+ }
+ for _, marker := range []string{
+ "no value at ",
+ "missing key: ",
+ "missing key ",
+ "path not found: ",
+ "config path is valid but unset: ",
+ "unknown config path: ",
+ } {
+ if openclawMessageNamesPathAfter(message, marker, keyPath) {
+ return true
+ }
+ }
+ if openclawMessageNamesPathBefore(message, keyPath, " is not set") ||
+ openclawMessageNamesPathBefore(message, keyPath, " not set") ||
+ strings.Contains(message, "config path "+keyPath+" not found") {
+ return true
+ }
+ // Some pre-2026.6 builds returned only "Path not found" after the
+ // command wrapper. Accept that exact bare diagnostic when the command names
+ // the expected key, but do not combine the command path with an unrelated
+ // "not set" message later in stderr.
+ return strings.Contains(message, "config get "+keyPath) &&
+ (strings.HasSuffix(message, ": path not found") ||
+ strings.Contains(message, ": path not found ("))
+}
+
+func openclawMessageNamesPathBefore(message, keyPath, suffix string) bool {
+ needle := keyPath + suffix
+ for offset := 0; offset < len(message); {
+ relative := strings.Index(message[offset:], needle)
+ if relative < 0 {
+ return false
+ }
+ idx := offset + relative
+ leftBoundary := idx == 0 || isOpenclawPathLeftBoundary(message[idx-1])
+ if leftBoundary && isOpenclawPathBoundary(message[idx+len(needle):]) {
+ return true
+ }
+ offset = idx + len(keyPath)
+ }
+ return false
+}
+
+func openclawMessageNamesPathAfter(message, marker, keyPath string) bool {
+ for search := message; ; {
+ idx := strings.Index(search, marker)
+ if idx < 0 {
+ return false
+ }
+ rest := search[idx+len(marker):]
+ if strings.HasPrefix(rest, keyPath) && isOpenclawPathBoundary(rest[len(keyPath):]) {
+ return true
+ }
+ search = rest
+ }
+}
+
+func isOpenclawPathLeftBoundary(char byte) bool {
+ switch char {
+ case ' ', '(', '[', '{', ',', ';', ':', '\'', '"', '`':
+ return true
+ default:
+ return false
+ }
+}
+
+func isOpenclawPathBoundary(rest string) bool {
+ if rest == "" {
+ return true
+ }
+ switch rest[0] {
+ case ' ', ')', ']', '}', ',', ';', ':', '\'', '"', '`':
+ return true
+ case '.':
+ return len(rest) == 1 || rest[1] == ' ' || rest[1] == ')' || rest[1] == ']'
+ default:
+ return false
+ }
}
func isOpenclawKeyMissingMessage(msg string) bool {
diff --git a/server/internal/daemon/execenv/openclaw_config_cache.go b/server/internal/daemon/execenv/openclaw_config_cache.go
index 1d3d06e17e..a74f3e8caa 100644
--- a/server/internal/daemon/execenv/openclaw_config_cache.go
+++ b/server/internal/daemon/execenv/openclaw_config_cache.go
@@ -28,11 +28,11 @@ import (
// (PrepareIsolated / ReuseIsolated), so an in-process cache would never
// survive to the next task.
//
-// What is NOT cached: the fully resolved config read by
-// openclawResolvedFullConfig. That payload carries the user's API keys and
-// model-provider tokens, and copying it into a long-lived shared file is a
-// secret-spill surface the wrapper flow does not need — that call already
-// only happens for agents with a managed mcp_config.
+// What is NOT cached, and no longer exists to cache: the resolved config read
+// this flow used to make for a managed mcp_config. Managed MCP is now prepared
+// from a reset stage this package writes, so there is no per-agent CLI payload on
+// this path at all — one fewer thing whose staleness would have to be reasoned
+// about, and one fewer copy of the user's configuration anywhere.
const (
// openclawDiscoveryCacheFile is the per-profile cache file name. It sits
// in the profile directory (~/.multica[/profiles/<name>]) so every task on
diff --git a/server/internal/daemon/execenv/openclaw_config_test.go b/server/internal/daemon/execenv/openclaw_config_test.go
index 835ee6bbac..ce7906d130 100644
--- a/server/internal/daemon/execenv/openclaw_config_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_test.go
@@ -820,12 +820,21 @@ func TestPrepareOpenclawConfigWrapperLoadableUnderIncludeConfinement(t *testing.
}
// TestPrepareOpenclawConfigStrictReplacesUserMcpServers — the headline
-// assertion for Elon's strict-replace must-fix on PR #3450. When the user
-// has a global `mcp.servers.global_one` AND the agent has a managed
-// `mcp.servers.shared + managed_only`, the wrapper must NOT $include the
-// live user config (which would leak global_one) and must instead
-// $include a sanitized snapshot that has the user's `mcp` block stripped.
-// The wrapper itself carries managed servers and nothing else.
+// assertion for strict replace. The user has a global `mcp.servers.global_one`
+// and a same-named `shared`; the agent has a managed `shared + managed_only`
+// set; the view OpenClaw resolves must be exactly the managed set.
+//
+// What changed is how that is achieved. It used to be a sanitized copy of the
+// user's resolved config written into the task directory; it is now include
+// order:
+//
+// user's live config -> mcp.servers: null -> wrapper's managed servers
+//
+// So the assertions are the three things that composition rests on — the include
+// list and its order, the reset stage's content, and the wrapper's own block —
+// plus the property the copy could never have: nothing from the user's config is
+// written into the task directory at all, which is what removes the redaction
+// hazard rather than working around it.
func TestPrepareOpenclawConfigStrictReplacesUserMcpServers(t *testing.T) {
envRoot := t.TempDir()
workDir := filepath.Join(envRoot, "workdir")
@@ -833,13 +842,11 @@ func TestPrepareOpenclawConfigStrictReplacesUserMcpServers(t *testing.T) {
t.Fatalf("mkdir workdir: %v", err)
}
- userCfgPath := filepath.Join(t.TempDir(), "openclaw.json")
- if err := os.WriteFile(userCfgPath, []byte(`{}`), 0o600); err != nil {
- t.Fatalf("write user cfg: %v", err)
- }
- // The resolved user config the CLI would return: a user global
- // mcp.servers + some other non-mcp content the snapshot must preserve.
- resolvedUser := `{
+ // A real user config on disk, secrets included. Nothing this package writes
+ // may contain any of it — asserted below by scanning envRoot.
+ userCfgDir := t.TempDir()
+ userCfgPath := filepath.Join(userCfgDir, "openclaw.json")
+ userCfg := `{
"mcp": {"servers": {
"global_one": {"command": "/bin/echo", "args": ["user"]},
"shared": {"command": "/bin/old-version"}
@@ -847,9 +854,11 @@ func TestPrepareOpenclawConfigStrictReplacesUserMcpServers(t *testing.T) {
"gateway": {"port": 18789},
"providers": {"anthropic": {"apiKey": "sk-user-secret"}}
}`
+ if err := os.WriteFile(userCfgPath, []byte(userCfg), 0o600); err != nil {
+ t.Fatalf("write user cfg: %v", err)
+ }
stub := installOpenclawStub(t, map[string]openclawResponse{
"config file": {stdout: userCfgPath},
- "config get --json": {stdout: resolvedUser},
"config get agents.list --json": {stdout: "null"},
})
@@ -890,105 +899,190 @@ func TestPrepareOpenclawConfigStrictReplacesUserMcpServers(t *testing.T) {
t.Errorf("mcp.servers.managed_only missing or wrong shape: %v", managed)
}
- // The wrapper's $include must point at the sanitized snapshot, NOT the
- // live user config — otherwise OpenClaw would deep-merge user.mcp back in.
+ // Include order is the mechanism, so it is what gets pinned: the user's live
+ // config first, then the reset stage. Reversed, the user's servers would
+ // arrive after the null and survive.
+ resetPath := filepath.Join(envRoot, openclawMcpResetFile)
include, _ := got["$include"].([]any)
- if len(include) != 1 {
- t.Fatalf("wrapper $include has %d entries, want 1: %v", len(include), include)
+ if len(include) != 2 || include[0] != userCfgPath || include[1] != resetPath {
+ t.Fatalf("wrapper $include = %#v, want [%q, %q]", got["$include"], userCfgPath, resetPath)
}
- snapshotPath, _ := include[0].(string)
- if snapshotPath == userCfgPath {
- t.Fatalf("wrapper $includes the live user config (%q) — strict replace requires the sanitized snapshot", userCfgPath)
+ if body, rerr := os.ReadFile(resetPath); rerr != nil {
+ t.Fatalf("read mcp reset stage: %v", rerr)
+ } else if string(body) != openclawMcpResetBody {
+ t.Errorf("mcp reset stage = %q, want exactly %q", body, openclawMcpResetBody)
}
- wantSnapshot := filepath.Join(envRoot, openclawUserSnapshotFile)
- if snapshotPath != wantSnapshot {
- t.Errorf("$include = %q, want sanitized snapshot %q", snapshotPath, wantSnapshot)
+
+ // The include reaches the user's own directory, so that hop has to be
+ // granted or OpenClaw's confinement check refuses the chain at load.
+ if result.IncludeRoot != userCfgDir {
+ t.Errorf("IncludeRoot = %q, want %q — the chain includes the live user config", result.IncludeRoot, userCfgDir)
}
- // Snapshot must exist, must drop the `mcp` block, and must preserve the
- // non-mcp keys (gateway, providers, secrets) so OpenClaw still has API
- // keys and other config the user relied on.
- snap := mustReadJSON(t, snapshotPath)
- if _, present := snap["mcp"]; present {
- t.Errorf("snapshot still contains an `mcp` block — strict replace not enforced: %v", snap["mcp"])
+ // And the property that makes this design safe rather than merely working:
+ // no byte of the user's configuration is copied into the task directory, so
+ // there is nothing to redact, truncate or write back stale.
+ assertEnvRootCarriesNoUserConfig(t, envRoot, "sk-user-secret", "global_one", "18789")
+}
+
+// assertEnvRootCarriesNoUserConfig fails if any file the preparer wrote contains
+// a marker from the user's own config.
+//
+// A scan rather than an assertion about one named file, because the guarantee is
+// about the directory: the old design's snapshot was one file, and the point of
+// replacing it is that no file has that content now.
+func assertEnvRootCarriesNoUserConfig(t *testing.T, envRoot string, markers ...string) {
+ t.Helper()
+ entries, err := os.ReadDir(envRoot)
+ if err != nil {
+ t.Fatalf("read envRoot: %v", err)
}
- if gw, ok := snap["gateway"].(map[string]any); !ok || gw["port"] != float64(18789) {
- t.Errorf("snapshot lost gateway.port carryover: %v", snap["gateway"])
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ path := filepath.Join(envRoot, entry.Name())
+ body, rerr := os.ReadFile(path)
+ if rerr != nil {
+ t.Fatalf("read %s: %v", path, rerr)
+ }
+ for _, marker := range markers {
+ if strings.Contains(string(body), marker) {
+ t.Errorf("%s contains %q from the user's config; this path must copy none of it", entry.Name(), marker)
+ }
+ }
}
- if _, ok := snap["providers"].(map[string]any); !ok {
- t.Errorf("snapshot lost providers carryover: %v", snap)
+}
+
+// TestPrepareOpenclawConfigIncludeRootGrants pins which include targets need an
+// OPENCLAW_INCLUDE_ROOTS grant, since getting this wrong fails in a way no
+// wrapper-shape assertion would catch: OpenClaw's include-confinement check
+// rejects the chain at load time, and the task fails with a config error rather
+// than anything pointing back here.
+//
+// The managed-MCP row is the one that changed. The flat resolved-config copy it
+// replaces was self-contained, so it needed no grant; the chain reaches the
+// user's real config, so it does. The reset stage needs none of its own — it sits
+// in envRoot beside the wrapper that includes it.
+func TestPrepareOpenclawConfigIncludeRootGrants(t *testing.T) {
+ cases := []struct {
+ name string
+ mcpConfig json.RawMessage
+ userConfig bool
+ wantGrant bool
+ }{
+ {name: "managed mcp includes the user config", mcpConfig: json.RawMessage(`{"mcpServers":{"m":{"command":"uvx"}}}`), userConfig: true, wantGrant: true},
+ {name: "inherited mcp includes the user config", userConfig: true, wantGrant: true},
+ {name: "fresh install has nothing to include", mcpConfig: json.RawMessage(`{"mcpServers":{"m":{"command":"uvx"}}}`), userConfig: false, wantGrant: false},
}
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ envRoot := t.TempDir()
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir workdir: %v", err)
+ }
+ responses := map[string]openclawResponse{
+ "config get agents.list --json": {stdout: "null"},
+ }
+ userCfgPath := ""
+ if tc.userConfig {
+ userCfgPath = filepath.Join(t.TempDir(), "openclaw.json")
+ if err := os.WriteFile(userCfgPath, []byte(`{}`), 0o600); err != nil {
+ t.Fatalf("write user cfg: %v", err)
+ }
+ responses["config file"] = openclawResponse{stdout: userCfgPath}
+ } else {
+ responses["config file"] = openclawResponse{stdout: filepath.Join(t.TempDir(), "absent.json")}
+ }
+ stub := installOpenclawStub(t, responses)
- // The snapshot lives in envRoot alongside the wrapper, so the daemon
- // does NOT need to grant an OPENCLAW_INCLUDE_ROOTS entry for it.
- if result.IncludeRoot != "" {
- t.Errorf("IncludeRoot = %q, want empty (snapshot lives in envRoot, no cross-dir include)", result.IncludeRoot)
+ result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
+ OpenclawBin: stub.bin,
+ McpConfig: tc.mcpConfig,
+ })
+ if err != nil {
+ t.Fatalf("prepareOpenclawConfig: %v", err)
+ }
+ want := ""
+ if tc.wantGrant {
+ want = filepath.Dir(userCfgPath)
+ }
+ if result.IncludeRoot != want {
+ t.Errorf("IncludeRoot = %q, want %q", result.IncludeRoot, want)
+ }
+ })
}
}
-// TestPrepareOpenclawConfigStrictPreservesNonServerMcpKeys — Elon's
-// follow-up must-fix: the strict-replace path must scope only to
-// `mcp.servers`, not the entire `mcp` block. OpenClaw config has
-// sibling settings under `mcp` (e.g. `sessionIdleTtlMs` — see
-// https://docs.openclaw.ai/gateway/configuration-reference#mcp). The
-// previous implementation deleted the whole `mcp` block which silently
-// reset those siblings to OpenClaw's defaults. This test fixes that
-// scope: managed-MCP path drops `mcp.servers` but leaves
-// `mcp.sessionIdleTtlMs` intact in the snapshot.
-func TestPrepareOpenclawConfigStrictPreservesNonServerMcpKeys(t *testing.T) {
+// TestPrepareOpenclawConfigPreservesNonServerMcpKeys — the scope assertion:
+// strict replace applies to `mcp.servers` and to nothing else. Siblings under
+// `mcp` (`sessionIdleTtlMs`, `apps`, anything a future release adds) must reach
+// the agent exactly as the user wrote them.
+//
+// This used to be enforced by reading the user's resolved `mcp` block and writing
+// the non-server keys back, which is where the review found the hazard: `config
+// get` returns display data, so a sensitive sibling comes back as
+// `__OPENCLAW_REDACTED__` and writing it back would overwrite a working value
+// with a placeholder. It also had to enumerate the keys it knew about.
+//
+// Nothing is read now, so the guarantee is structural and that is what this
+// asserts: the reset stage names exactly one key, and no file this package writes
+// mentions any sibling at all. The end-to-end half — an actual sibling surviving
+// an actual loader — is in openclaw_mcp_real_integration_test.go, which has to
+// run against a real CLI to mean anything.
+func TestPrepareOpenclawConfigPreservesNonServerMcpKeys(t *testing.T) {
envRoot := t.TempDir()
workDir := filepath.Join(envRoot, "workdir")
if err := os.MkdirAll(workDir, 0o755); err != nil {
t.Fatalf("mkdir workdir: %v", err)
}
userCfgPath := filepath.Join(t.TempDir(), "openclaw.json")
- if err := os.WriteFile(userCfgPath, []byte(`{}`), 0o600); err != nil {
- t.Fatalf("write user cfg: %v", err)
- }
- // User's resolved config has BOTH `mcp.servers` (must be stripped) and
- // `mcp.sessionIdleTtlMs` (must survive). The snapshot is what OpenClaw
- // loads via the wrapper's $include, so only the snapshot's `mcp` block
- // is consulted for non-server settings.
- resolvedUser := `{
+ // Both shapes the sibling problem takes: a plain tuning value, and one whose
+ // name would be redacted by `config get`.
+ userCfg := `{
"mcp": {
"sessionIdleTtlMs": 300000,
+ "apps": {"inspector": {"token": "sk-sibling-secret"}},
"servers": {"global_one": {"command": "/bin/echo"}}
- },
- "gateway": {"port": 18789}
+ }
}`
+ if err := os.WriteFile(userCfgPath, []byte(userCfg), 0o600); err != nil {
+ t.Fatalf("write user cfg: %v", err)
+ }
stub := installOpenclawStub(t, map[string]openclawResponse{
"config file": {stdout: userCfgPath},
- "config get --json": {stdout: resolvedUser},
"config get agents.list --json": {stdout: "null"},
})
- mcpConfig := json.RawMessage(`{"mcpServers": {"managed_only": {"command": "uvx", "args": ["m"]}}}`)
result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
OpenclawBin: stub.bin,
- McpConfig: mcpConfig,
+ McpConfig: json.RawMessage(`{"mcpServers": {"managed_only": {"command": "uvx", "args": ["m"]}}}`),
})
if err != nil {
t.Fatalf("prepareOpenclawConfig: %v", err)
}
- snapPath := filepath.Join(envRoot, openclawUserSnapshotFile)
- snap := mustReadJSON(t, snapPath)
- snapMcp, ok := snap["mcp"].(map[string]any)
+ // The reset must name `mcp.servers` and nothing else — a reset of the whole
+ // `mcp` object would take the siblings down with the servers.
+ reset := mustReadJSON(t, filepath.Join(envRoot, openclawMcpResetFile))
+ resetMcp, ok := reset["mcp"].(map[string]any)
if !ok {
- t.Fatalf("snapshot lost the mcp block entirely; mcp.sessionIdleTtlMs should have survived: %v", snap)
+ t.Fatalf("mcp reset = %#v, want an object naming servers", reset)
}
- if _, leaked := snapMcp["servers"]; leaked {
- t.Errorf("snapshot still has mcp.servers; strict scope must drop it: %v", snapMcp)
+ if len(resetMcp) != 1 {
+ t.Errorf("mcp reset names %d keys (%v), want only servers — anything else resets a user setting", len(resetMcp), resetMcp)
}
- // json.Unmarshal decodes JSON numbers as float64.
- if ttl, ok := snapMcp["sessionIdleTtlMs"].(float64); !ok || ttl != 300000 {
- t.Errorf("snapshot lost mcp.sessionIdleTtlMs (should be preserved): %v", snapMcp)
+ if value, present := resetMcp["servers"]; !present || value != nil {
+ t.Errorf("mcp reset servers = %#v, want explicit null", resetMcp["servers"])
}
- // Wrapper still emits the managed-only server set on top, so the
- // effective view post-include is exactly the managed set.
- got := mustReadJSON(t, result.ConfigPath)
- wrapperMcp, _ := got["mcp"].(map[string]any)
+ // The wrapper contributes servers only, so nothing it writes can shadow a
+ // sibling either.
+ wrapperMcp, _ := mustReadJSON(t, result.ConfigPath)["mcp"].(map[string]any)
+ if len(wrapperMcp) != 1 {
+ t.Errorf("wrapper mcp block = %#v, want servers only", wrapperMcp)
+ }
servers, _ := wrapperMcp["servers"].(map[string]any)
if _, ok := servers["managed_only"]; !ok {
t.Errorf("wrapper missing managed_only: %v", servers)
@@ -996,24 +1090,20 @@ func TestPrepareOpenclawConfigStrictPreservesNonServerMcpKeys(t *testing.T) {
if _, leaked := servers["global_one"]; leaked {
t.Errorf("global_one leaked into wrapper: %v", servers)
}
+
+ // And no sibling was observed, copied or re-emitted anywhere.
+ assertEnvRootCarriesNoUserConfig(t, envRoot, "sessionIdleTtlMs", "apps", "sk-sibling-secret")
}
-// TestPrepareOpenclawConfigStrictEmptyManagedSetDropsUserMcp — empty
-// managed set `{}` must drop the user's global mcp.servers too. Without
-// strict replace, OpenClaw would still resolve user-only servers via the
-// $include and the admin's "saved no servers" intent would be silently
-// overridden.
+// TestPrepareOpenclawConfigStrictEmptyManagedSetDropsUserMcp — an empty managed
+// set `{}` must drop the user's global mcp.servers too. Without the reset,
+// OpenClaw would still resolve user-only servers through the include and the
+// admin's "saved no servers" intent would be silently overridden.
func TestPrepareOpenclawConfigStrictEmptyManagedSetDropsUserMcp(t *testing.T) {
- envRoot := t.TempDir()
- workDir := filepath.Join(envRoot, "workdir")
- if err := os.MkdirAll(workDir, 0o755); err != nil {
- t.Fatalf("mkdir workdir: %v", err)
- }
userCfgPath := filepath.Join(t.TempDir(), "openclaw.json")
- if err := os.WriteFile(userCfgPath, []byte(`{}`), 0o600); err != nil {
+ if err := os.WriteFile(userCfgPath, []byte(`{"mcp":{"servers":{"global_one":{"command":"/bin/echo"}}}}`), 0o600); err != nil {
t.Fatalf("write user cfg: %v", err)
}
- resolvedUser := `{"mcp": {"servers": {"global_one": {"command": "/bin/echo"}}}}`
cases := map[string]json.RawMessage{
"object_empty": json.RawMessage(`{}`),
@@ -1021,9 +1111,13 @@ func TestPrepareOpenclawConfigStrictEmptyManagedSetDropsUserMcp(t *testing.T) {
}
for name, raw := range cases {
t.Run(name, func(t *testing.T) {
+ envRoot := t.TempDir()
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir workdir: %v", err)
+ }
stub := installOpenclawStub(t, map[string]openclawResponse{
"config file": {stdout: userCfgPath},
- "config get --json": {stdout: resolvedUser},
"config get agents.list --json": {stdout: "null"},
})
result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
@@ -1045,29 +1139,23 @@ func TestPrepareOpenclawConfigStrictEmptyManagedSetDropsUserMcp(t *testing.T) {
if len(servers) != 0 {
t.Errorf("mcp.servers has %d entries on managed-empty, want 0 (global_one must not leak): %v", len(servers), servers)
}
- // And the snapshot must have dropped the user's mcp block, so the
- // $include resolves with no mcp at all.
- snapPath := filepath.Join(envRoot, openclawUserSnapshotFile)
- snap := mustReadJSON(t, snapPath)
- if _, present := snap["mcp"]; present {
- t.Errorf("snapshot still has `mcp` — strict empty must drop the user block: %v", snap["mcp"])
+ // An empty managed set is exactly the case that needs the reset: with
+ // no server named on the wrapper, the include result is what resolves
+ // unless the user's map has been nulled first.
+ resetPath := filepath.Join(envRoot, openclawMcpResetFile)
+ include, _ := got["$include"].([]any)
+ if len(include) != 2 || include[1] != resetPath {
+ t.Fatalf("wrapper $include = %#v, want the reset stage at %q", got["$include"], resetPath)
}
})
}
}
-// TestPrepareOpenclawConfigNullMcpConfigKeepsUserInclude — when the agent
-// has no managed mcp_config (`null` / absent), the wrapper must NOT write
-// a sanitized snapshot and must $include the live user config so the
-// user's global mcp.servers and other config still flow through. This is
-// the "inherit defaults" branch — must remain a no-op vs. the previous
-// implementation.
+// TestPrepareOpenclawConfigNullMcpConfigKeepsUserInclude — when the agent has no
+// managed mcp_config (`null` / absent), the wrapper must include the live user
+// config with no reset stage, so the user's global mcp.servers and everything
+// else still flow through. This is the "inherit defaults" branch.
func TestPrepareOpenclawConfigNullMcpConfigKeepsUserInclude(t *testing.T) {
- envRoot := t.TempDir()
- workDir := filepath.Join(envRoot, "workdir")
- if err := os.MkdirAll(workDir, 0o755); err != nil {
- t.Fatalf("mkdir workdir: %v", err)
- }
userCfgDir := t.TempDir()
userCfgPath := filepath.Join(userCfgDir, "openclaw.json")
if err := os.WriteFile(userCfgPath, []byte(`{}`), 0o600); err != nil {
@@ -1081,11 +1169,14 @@ func TestPrepareOpenclawConfigNullMcpConfigKeepsUserInclude(t *testing.T) {
}
for name, raw := range cases {
t.Run(name, func(t *testing.T) {
+ envRoot := t.TempDir()
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir workdir: %v", err)
+ }
stub := installOpenclawStub(t, map[string]openclawResponse{
"config file": {stdout: userCfgPath},
"config get agents.list --json": {stdout: "null"},
- // Note: no `config get --json` stub — the inherit path must
- // not call it (would burn an extra CLI roundtrip per task).
})
result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
OpenclawBin: stub.bin,
@@ -1100,22 +1191,24 @@ func TestPrepareOpenclawConfigNullMcpConfigKeepsUserInclude(t *testing.T) {
}
include, _ := got["$include"].([]any)
if len(include) != 1 || include[0] != userCfgPath {
- t.Errorf("$include = %v, want live user config %q on inherit path", got["$include"], userCfgPath)
+ t.Errorf("$include = %v, want the live user config %q alone on the inherit path", got["$include"], userCfgPath)
}
- if _, err := os.Stat(filepath.Join(envRoot, openclawUserSnapshotFile)); !os.IsNotExist(err) {
- t.Errorf("inherit path wrote a snapshot file (should not): err=%v", err)
+ // No managed set means nothing to enforce, so the reset stage must not
+ // exist: it would null the servers the agent is supposed to inherit.
+ if _, err := os.Stat(filepath.Join(envRoot, openclawMcpResetFile)); !os.IsNotExist(err) {
+ t.Errorf("inherit path wrote a reset stage (should not): err=%v", err)
}
if result.IncludeRoot != userCfgDir {
- t.Errorf("IncludeRoot = %q, want %q (cross-dir hop for live $include)", result.IncludeRoot, userCfgDir)
+ t.Errorf("IncludeRoot = %q, want %q (cross-dir hop for the live $include)", result.IncludeRoot, userCfgDir)
}
})
}
}
-// TestPrepareOpenclawConfigManagedSetFreshInstall — managed mcp_config on
-// a fresh install (no on-disk user config) must NOT call `config get
-// --json` (there is nothing to snapshot) and must write a wrapper that
-// carries managed servers as the sole MCP definition with no $include.
+// TestPrepareOpenclawConfigManagedSetFreshInstall — a managed mcp_config on a
+// fresh install (no on-disk user config) has nothing to include and nothing to
+// reset: the wrapper carries the managed servers as the sole MCP definition, with
+// no $include and no reset stage.
func TestPrepareOpenclawConfigManagedSetFreshInstall(t *testing.T) {
envRoot := t.TempDir()
workDir := filepath.Join(envRoot, "workdir")
@@ -1125,7 +1218,6 @@ func TestPrepareOpenclawConfigManagedSetFreshInstall(t *testing.T) {
missingPath := filepath.Join(t.TempDir(), "openclaw.json")
stub := installOpenclawStub(t, map[string]openclawResponse{
"config file": {stdout: missingPath},
- // No `config get --json` stub — fresh install must not call it.
})
mcpConfig := json.RawMessage(`{"mcpServers": {"context7": {"command": "uvx", "args": ["context7-mcp"]}}}`)
@@ -1156,6 +1248,171 @@ func TestPrepareOpenclawConfigManagedSetFreshInstall(t *testing.T) {
if _, present := got["$include"]; present {
t.Errorf("fresh install should not emit $include: %v", got["$include"])
}
+ // A reset with no include to reset would leave `mcp.servers: null` as the
+ // only contribution from the chain, which is a shape the wrapper's own block
+ // then has to undo for no reason.
+ if _, err := os.Stat(filepath.Join(envRoot, openclawMcpResetFile)); !os.IsNotExist(err) {
+ t.Errorf("fresh install wrote a reset stage (should not): err=%v", err)
+ }
+}
+
+// TestPrepareOpenclawConfigManagedMcpCostsNoExtraCLICall pins the removal that
+// makes the deadline arithmetic simpler, and it is the test that fails if the
+// config read ever comes back.
+//
+// A managed-MCP agent used to pay one more CLI round-trip than any other — the
+// invalid pathless `config get --json`, which is what #7551 reported as a task
+// that never starts. The reset stage is a file this package writes, so managed
+// MCP now costs no CLI time at all, which is why
+// openclawMaxCLIDeadlinesPerPreparation dropped from 4 to 3.
+//
+// The stub errors on any invocation it was not given, so a reintroduced read
+// fails preparation here rather than silently widening the budget.
+func TestPrepareOpenclawConfigManagedMcpCostsNoExtraCLICall(t *testing.T) {
+ envRoot := t.TempDir()
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir workdir: %v", err)
+ }
+ userCfgPath := filepath.Join(t.TempDir(), "openclaw.json")
+ if err := os.WriteFile(userCfgPath, []byte(`{"mcp":{"servers":{"user":{"command":"user"}}}}`), 0o600); err != nil {
+ t.Fatalf("write user cfg: %v", err)
+ }
+
+ discovery := map[string]openclawResponse{
+ "config file": {stdout: userCfgPath},
+ "config get agents.list --json": {stdout: "null"},
+ }
+
+ baseline := installOpenclawStub(t, discovery)
+ if _, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{OpenclawBin: baseline.bin}); err != nil {
+ t.Fatalf("prepareOpenclawConfig (inherit): %v", err)
+ }
+ inheritCalls := len(baseline.calls)
+
+ managedEnvRoot := t.TempDir()
+ managedWorkDir := filepath.Join(managedEnvRoot, "workdir")
+ if err := os.MkdirAll(managedWorkDir, 0o755); err != nil {
+ t.Fatalf("mkdir workdir: %v", err)
+ }
+ managed := installOpenclawStub(t, discovery)
+ if _, err := prepareOpenclawConfig(managedEnvRoot, managedWorkDir, OpenclawConfigPrep{
+ OpenclawBin: managed.bin,
+ McpConfig: json.RawMessage(`{"mcpServers":{"managed":{"command":"managed"}}}`),
+ }); err != nil {
+ t.Fatalf("prepareOpenclawConfig (managed): %v", err)
+ }
+
+ var managedArgs []string
+ for _, call := range managed.calls {
+ managedArgs = append(managedArgs, strings.Join(call.args, " "))
+ }
+ if len(managed.calls) != inheritCalls {
+ t.Errorf("managed MCP made %d CLI calls against %d for the same agent without it: %v",
+ len(managed.calls), inheritCalls, managedArgs)
+ }
+ for _, args := range managedArgs {
+ if strings.Contains(args, "mcp") {
+ t.Errorf("managed MCP read configuration from the CLI (%q); the reset stage exists so it does not have to", args)
+ }
+ }
+}
+
+// TestPrepareOpenclawConfigResetStagePairsWithWrapperMcp pins the invariant the
+// reset stage's safety hangs on: a generated chain that contains
+// openclawMcpResetFile must come with an `mcp.servers` object on the wrapper
+// itself.
+//
+// The reset works because OpenClaw's include merge treats a null source as
+// replacement (`src/config/includes.ts` at v2026.7.1-2) — but the same loader
+// rejects a *surviving* null at validation: `McpConfigSchema` is
+// `.strict().optional()` (`src/config/zod-schema.ts`), and zod's `.optional()`
+// accepts undefined, never null. The only thing standing between the reset and
+// that rejection is the wrapper's own block, which the loader merges over the
+// include result.
+//
+// Today the pairing holds by construction — the reset is written under
+// `hasManagedMcp && exists`, and buildPerTaskOpenclawConfig emits `mcp.servers`
+// under `hasManagedMcp` — but nothing named that coupling. A refactor that emits
+// the reset without the wrapper block (an empty managed set optimized away, say)
+// would fail every managed-MCP task at agent start with an `invalid_type` on
+// `mcp.servers` pointing nowhere near this package. Fail-closed, but with a
+// diagnostic bad enough that this test exists to keep it from ever firing.
+func TestPrepareOpenclawConfigResetStagePairsWithWrapperMcp(t *testing.T) {
+ cases := []struct {
+ name string
+ userCfg string
+ mcpConfig json.RawMessage
+ }{
+ {
+ name: "user servers only",
+ userCfg: `{"mcp":{"servers":{"user-only":{"command":"user"}}}}`,
+ mcpConfig: json.RawMessage(`{"mcpServers":{"managed":{"command":"managed"}}}`),
+ },
+ {
+ name: "user siblings alongside servers",
+ userCfg: `{"mcp":{"servers":{"user-only":{"command":"user"}},"sessionIdleTtlMs":300000}}`,
+ mcpConfig: json.RawMessage(`{"mcpServers":{"managed":{"command":"managed"}}}`),
+ },
+ {
+ // The sharpest case: nothing on the wrapper but an empty map stands
+ // between the reset's null and the schema.
+ name: "empty managed set",
+ userCfg: `{"mcp":{"servers":{"user-only":{"command":"user"}}}}`,
+ mcpConfig: json.RawMessage(`{"mcpServers":{}}`),
+ },
+ {
+ name: "user has no mcp key at all",
+ userCfg: `{"gateway":{"mode":"local"}}`,
+ mcpConfig: json.RawMessage(`{"mcpServers":{"managed":{"command":"managed"}}}`),
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ envRoot := t.TempDir()
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir workdir: %v", err)
+ }
+ userCfgPath := filepath.Join(t.TempDir(), "openclaw.json")
+ if err := os.WriteFile(userCfgPath, []byte(tc.userCfg), 0o600); err != nil {
+ t.Fatalf("write user cfg: %v", err)
+ }
+ stub := installOpenclawStub(t, map[string]openclawResponse{
+ "config file": {stdout: userCfgPath},
+ "config get agents.list --json": {stdout: "null"},
+ })
+
+ result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
+ OpenclawBin: stub.bin,
+ McpConfig: tc.mcpConfig,
+ })
+ if err != nil {
+ t.Fatalf("prepareOpenclawConfig: %v", err)
+ }
+
+ // The chain must actually carry the reset stage...
+ resetPath := filepath.Join(envRoot, openclawMcpResetFile)
+ wrapper := mustReadJSON(t, result.ConfigPath)
+ include, ok := wrapper["$include"].([]any)
+ if !ok || len(include) != 2 || include[1] != resetPath {
+ t.Fatalf("wrapper $include = %#v, want [user config, %q]", wrapper["$include"], resetPath)
+ }
+
+ // ...and then the wrapper must carry its own `mcp.servers`. This is
+ // what overwrites the chain's transient null before validation;
+ // without it the loader rejects the resolved config.
+ mcp, ok := wrapper["mcp"].(map[string]any)
+ if !ok {
+ t.Fatalf("reset stage present but wrapper has no mcp object — the "+
+ "resolved chain would keep `mcp.servers: null`, which OpenClaw's "+
+ "schema rejects, failing every managed-MCP task at load: %v", wrapper)
+ }
+ if _, ok := mcp["servers"].(map[string]any); !ok {
+ t.Fatalf("wrapper mcp.servers is not an object: %#v", mcp)
+ }
+ })
+ }
}
// TestPrepareOpenclawConfigFallsBackToRegistryOnEnvelopeWithoutExit — the
@@ -1210,95 +1467,6 @@ func TestPrepareOpenclawConfigFallsBackToRegistryOnEnvelopeWithoutExit(t *testin
}
}
-// TestPrepareOpenclawConfigFailsClosedOnResolvedConfigEnvelopeWithoutExit — the
-// object-target counterpart, and the one with a silent failure mode: an envelope
-// decoded as the user's resolved config would be sanitized and written into the
-// task's snapshot, so preparation has to fail closed with the CLI's own message.
-func TestPrepareOpenclawConfigFailsClosedOnResolvedConfigEnvelopeWithoutExit(t *testing.T) {
- envRoot := t.TempDir()
- workDir := filepath.Join(envRoot, "workdir")
- if err := os.MkdirAll(workDir, 0o755); err != nil {
- t.Fatalf("mkdir workdir: %v", err)
- }
- userCfgPath := filepath.Join(t.TempDir(), "openclaw.json")
- if err := os.WriteFile(userCfgPath, []byte(`{}`), 0o600); err != nil {
- t.Fatalf("write user cfg: %v", err)
- }
- installOpenclawStub(t, map[string]openclawResponse{
- "config file": {stdout: userCfgPath},
- "config get agents.list --json": {stdout: "null"},
- "config get --json": {
- stdout: `{"error":"schema validation failed","resolved":{"apiKey":"must-not-leak"}}`,
- },
- })
-
- _, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
- McpConfig: json.RawMessage(`{"mcpServers": {"context7": {"command": "uvx"}}}`),
- })
- if err == nil {
- t.Fatal("prepareOpenclawConfig succeeded on an error envelope that arrived without a non-zero exit")
- }
- if !strings.Contains(err.Error(), "schema validation failed") {
- t.Errorf("error %q omits the CLI's own diagnostic", err.Error())
- }
- if strings.Contains(err.Error(), "must-not-leak") {
- t.Errorf("error leaked a non-diagnostic JSON field: %q", err.Error())
- }
- if _, statErr := os.Stat(filepath.Join(envRoot, openclawUserSnapshotFile)); !os.IsNotExist(statErr) {
- t.Errorf("snapshot exists after fail-closed: %v", statErr)
- }
-}
-
-// TestPrepareOpenclawConfigFailsClosedOnResolvedConfigError — when the
-// user has a config on disk and the agent has managed mcp_config but
-// `openclaw config get --json` errors, the preparer must NOT fall back to
-// `$include`ing the live user file (which would leak global mcp.servers).
-// Fail closed instead, mirroring the existing fail-closed posture.
-func TestPrepareOpenclawConfigFailsClosedOnResolvedConfigError(t *testing.T) {
- envRoot := t.TempDir()
- workDir := filepath.Join(envRoot, "workdir")
- if err := os.MkdirAll(workDir, 0o755); err != nil {
- t.Fatalf("mkdir workdir: %v", err)
- }
- userCfgPath := filepath.Join(t.TempDir(), "openclaw.json")
- if err := os.WriteFile(userCfgPath, []byte(`{}`), 0o600); err != nil {
- t.Fatalf("write user cfg: %v", err)
- }
- stub := installOpenclawStub(t, map[string]openclawResponse{
- "config file": {stdout: userCfgPath},
- "config get agents.list --json": {stdout: "null"},
- "config get --json": {
- stdout: `{"error":"schema validation failed","resolved":{"apiKey":"must-not-leak"}}`,
- err: errors.New("openclaw config get --json: exit status 1"),
- },
- })
- mcpConfig := json.RawMessage(`{"mcpServers": {"context7": {"command": "uvx"}}}`)
-
- _, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
- OpenclawBin: stub.bin,
- McpConfig: mcpConfig,
- })
- if err == nil {
- t.Fatal("prepareOpenclawConfig succeeded when `config get --json` errored; expected fail closed")
- }
- if !strings.Contains(err.Error(), "resolved config") {
- t.Errorf("error %q does not name the resolved-config step", err.Error())
- }
- if !strings.Contains(err.Error(), "json error: schema validation failed") {
- t.Errorf("error %q omits the structured CLI diagnostic", err.Error())
- }
- if strings.Contains(err.Error(), "must-not-leak") {
- t.Errorf("error leaked a non-diagnostic JSON field: %q", err.Error())
- }
- // No stale wrapper / snapshot left behind.
- if _, err := os.Stat(filepath.Join(envRoot, openclawConfigFile)); !os.IsNotExist(err) {
- t.Errorf("wrapper exists after fail-closed: %v", err)
- }
- if _, err := os.Stat(filepath.Join(envRoot, openclawUserSnapshotFile)); !os.IsNotExist(err) {
- t.Errorf("snapshot exists after fail-closed: %v", err)
- }
-}
-
// TestPrepareOpenclawConfigFailsClosedOnMalformedMcpConfig — keeping with
// the fail-closed posture used for the rest of the preparer: a malformed
// mcp_config must not write any wrapper file, so the daemon surfaces the
@@ -1652,72 +1820,163 @@ func TestIsOpenclawKeyMissing(t *testing.T) {
}
}
-// TestIsOpenclawKeyMissingResult covers the JSON error contract observed in
-// OpenClaw 2026.7.2-beta.7. In JSON mode the CLI writes the missing-path error
-// to stdout and leaves stderr empty, so the process error alone contains only
-// "exit status 1". Only a structured missing-path envelope may trigger the
-// registry fallback; other failures must preserve the preparer's fail-closed
-// posture.
+// TestIsOpenclawKeyMissingResult covers both JSON error contracts observed in
+// OpenClaw: 2026.7.2-beta.7 writes a string `error`, while 2026.8.1-beta.3
+// writes `error.message` and distinguishes valid-but-unset from unknown paths.
+// Only a structured missing-path message for the requested path may trigger a
+// fallback; other failures must preserve the preparer's fail-closed posture.
func TestIsOpenclawKeyMissingResult(t *testing.T) {
t.Parallel()
cases := []struct {
name string
stdout string
err error
+ path string
want bool
}{
{
name: "2026.7.2-beta.7 stdout json missing path",
stdout: `{"error":"Config path not found: agents.list"}`,
err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ path: "agents.list",
+ want: true,
+ },
+ {
+ name: "2026.8.1-beta.3 nested json unknown path",
+ stdout: `{"ok":false,"error":{"type":"cli_error","message":"Unknown config path: agents.list. Run openclaw config schema to inspect valid paths."}}`,
+ err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ path: "agents.list",
+ want: true,
+ },
+ {
+ name: "2026.8.1-beta.3 nested json valid but unset",
+ stdout: `{"ok":false,"error":{"type":"cli_error","message":"Config path is valid but unset: mcp. The runtime default applies."}}`,
+ err: errors.New("openclaw config get mcp --json: exit status 1"),
+ path: "mcp",
want: true,
},
{
name: "2026.6.x stderr missing path remains supported",
err: errors.New("openclaw config get agents.list --json: exit status 1 (stderr: Config path not found: agents.list)"),
+ path: "agents.list",
want: true,
},
{
name: "other json error stays an error",
stdout: `{"error":"OpenClaw config is invalid"}`,
err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ path: "agents.list",
want: false,
},
{
name: "unrelated not-set json error stays an error",
stdout: `{"error":"OPENAI_API_KEY is not set"}`,
err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ path: "agents.list",
+ want: false,
+ },
+ {
+ name: "unrelated not-set process error stays an error",
+ err: errors.New("openclaw config get agents.list --json: exit status 1 (stderr: OPENAI_API_KEY is not set)"),
+ path: "agents.list",
+ want: false,
+ },
+ {
+ name: "environment variable suffix resembling path stays an error",
+ err: errors.New("openclaw config get mcp --json: exit status 1 (stderr: OPENCLAW_MCP is not set)"),
+ path: "mcp",
+ want: false,
+ },
+ {
+ name: "parent path suffix resembling path stays an error",
+ stdout: `{"error":"parent.mcp is not set"}`,
+ err: errors.New("openclaw config get mcp --json: exit status 1"),
+ path: "mcp",
want: false,
},
{
name: "agents-list not-set json error remains compatible",
stdout: `{"error":"agents.list is not set"}`,
err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ path: "agents.list",
want: true,
},
+ {
+ name: "different missing path stays an error",
+ stdout: `{"error":"Config path not found: agents.list"}`,
+ err: errors.New("openclaw config get mcp --json: exit status 1"),
+ path: "mcp",
+ want: false,
+ },
+ {
+ name: "longer path sharing a prefix stays an error",
+ stdout: `{"error":"Config path not found: mcp.apps"}`,
+ err: errors.New("openclaw config get mcp --json: exit status 1"),
+ path: "mcp",
+ want: false,
+ },
{
name: "malformed json stays an error",
stdout: `{"error":`,
err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ path: "agents.list",
want: false,
},
{
name: "successful output is never reclassified",
stdout: `{"error":"Config path not found: agents.list"}`,
+ path: "agents.list",
want: false,
},
{
name: "timeout remains a timeout",
stdout: `{"error":"Config path not found: agents.list"}`,
err: fmt.Errorf("openclaw config get agents.list --json: %w (stderr: Config path not found: agents.list)", context.DeadlineExceeded),
+ path: "agents.list",
+ want: false,
+ },
+ {
+ name: "cancellation remains a cancellation",
+ stdout: `{"error":"Config path not found: mcp"}`,
+ err: fmt.Errorf("openclaw config get mcp --json: %w", context.Canceled),
+ path: "mcp",
+ want: false,
+ },
+ // Measured 2026-08-26. `config get` requires a path, so the pathless form
+ // the old resolved-root read used is rejected as a usage error on every
+ // current channel. It names no path, and must not be read as "the key is
+ // absent" — that would turn a broken invocation into a silent "user has no
+ // mcp block" and hand the task a wrapper built on a false premise.
+ {
+ name: "2026.6.34 / 2026.7.1-2 pathless usage error is not a missing key",
+ err: errors.New(`openclaw config get --json: exit status 1 (stderr: Missing required argument "path". Try: openclaw config get --help)`),
+ path: "mcp",
+ want: false,
+ },
+ {
+ name: "2026.8.1-beta.3 pathless usage envelope is not a missing key",
+ stdout: `{"ok":false,"error":{"type":"cli_error","message":"Missing required argument \"path\".\nTry: openclaw config get --help"}}`,
+ err: errors.New("exit status 1"),
+ path: "mcp",
+ want: false,
+ },
+ // Also measured: beta.3 reports a schema violation through the same
+ // envelope, with the offending key in a sibling `issues` array. An invalid
+ // config is the opposite of an absent key — treating it as absent would
+ // proceed with a config the loader has already refused.
+ {
+ name: "2026.8.1-beta.3 invalid-config envelope is not a missing key",
+ stdout: `{"ok":false,"error":{"type":"cli_error","message":"OpenClaw config is invalid: wrapper.json"},"issues":[{"path":"mcp","message":"Unrecognized key: \"sessionIdleTtlMs\""}]}`,
+ err: errors.New("exit status 1"),
+ path: "mcp",
want: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
- if got := isOpenclawKeyMissingResult(tc.stdout, tc.err); got != tc.want {
- t.Errorf("isOpenclawKeyMissingResult(%q, %v) = %v, want %v", tc.stdout, tc.err, got, tc.want)
+ if got := isOpenclawKeyMissingResult(tc.stdout, tc.err, tc.path); got != tc.want {
+ t.Errorf("isOpenclawKeyMissingResult(%q, %v, %q) = %v, want %v", tc.stdout, tc.err, tc.path, got, tc.want)
}
})
}
diff --git a/server/internal/daemon/execenv/openclaw_config_timeout_test.go b/server/internal/daemon/execenv/openclaw_config_timeout_test.go
index 7ecd3891ed..0f0fa3f33b 100644
--- a/server/internal/daemon/execenv/openclaw_config_timeout_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_timeout_test.go
@@ -240,19 +240,19 @@ func TestOpenclawActiveConfigPathSpendsOneBudgetAcrossBothAttempts(t *testing.T)
//
// That distinction is the review finding it exists for. The worst case is not the
// common two calls: `config validate --json` can fail to answer and fall back to
-// `config file`, a 2026.6+ host falls back to the registry subcommand, and an
-// agent with a managed mcp_config additionally reads the full resolved config —
-// five invocations. The previous version of this test could not see the first of
-// those, because the stub synthesizes a `config validate --json` success from the
+// `config file`, and a 2026.6+ host falls back to the registry subcommand — four
+// invocations. The earlier version of this test could not see the first pair,
+// because the stub synthesizes a `config validate --json` success from the
// `config file` response, so the two never fired in the same run. With the
-// fallback carrying a fresh full deadline, five budgets at the 60s ceiling is 5m
-// of CLI time alone, landing exactly on daemon.defaultTaskPrepareTimeout — and
-// the specific, non-retryable ErrOpenclawCLITimeout collapses back into the
-// generic retryable one.
+// fallback carrying a fresh full deadline, the worst case was five budgets at the
+// 60s ceiling, i.e. 5m of CLI time alone, landing exactly on
+// daemon.defaultTaskPrepareTimeout — and the specific, non-retryable
+// ErrOpenclawCLITimeout collapses back into the generic retryable one.
//
-// So this drives the real worst case and asserts both halves: the call graph is
-// five invocations, and path resolution's two share one deadline, leaving four
-// budgets.
+// A managed mcp_config used to add a fifth invocation of its own. It no longer
+// reads anything (see TestPrepareOpenclawConfigManagedMcpCostsNoExtraCLICall), so
+// this drives the managed path too and still expects four invocations across
+// three deadlines: path resolution's two share one.
func TestPrepareOpenclawConfigWorstCaseCLIBudgets(t *testing.T) {
envRoot := t.TempDir()
workDir := filepath.Join(envRoot, "workdir")
@@ -273,8 +273,10 @@ func TestPrepareOpenclawConfigWorstCaseCLIBudgets(t *testing.T) {
"config get agents.list --json": {err: errors.New("Config path not found: agents.list")},
// 3. registry fallback
"agents list --json": {stdout: `[{"id":"scout"}]`},
- // 4. full resolved config, reached only via a managed mcp_config
- "config get --json": {stdout: `{"agents":{"list":[{"id":"scout"}]}}`},
+ // No fourth entry, and the managed mcp_config below is why that is worth
+ // stating: managed MCP is prepared from a file this package writes, so it
+ // adds no invocation. The stub errors on anything unregistered, so a
+ // reintroduced read fails here instead of quietly costing a budget.
})
if _, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
@@ -303,7 +305,6 @@ func TestPrepareOpenclawConfigWorstCaseCLIBudgets(t *testing.T) {
"config file",
"config get agents.list --json",
"agents list --json",
- "config get --json",
}
if strings.Join(invocations, " | ") != strings.Join(wantInvocations, " | ") {
t.Errorf("worst-case invocations:\n got: %v\nwant: %v", invocations, wantInvocations)
diff --git a/server/internal/daemon/execenv/openclaw_mcp_real_integration_test.go b/server/internal/daemon/execenv/openclaw_mcp_real_integration_test.go
new file mode 100644
index 0000000000..89f2bf980c
--- /dev/null
+++ b/server/internal/daemon/execenv/openclaw_mcp_real_integration_test.go
@@ -0,0 +1,223 @@
+//go:build agentintegration
+
+package execenv
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+// Real-CLI coverage for the managed-MCP include chain. Opt-in twice over: the
+// agentintegration build tag, and MULTICA_RUN_REAL_AGENT_SMOKE, because this
+// executes the openclaw binary installed on the host.
+//
+// The unit tests assert the JSON this package writes. That is not enough for a
+// design whose correctness lives in OpenClaw's include-merge semantics — ordered
+// array includes, a null source replacing an object, and sibling keys on the
+// includer winning over the include result. Only the real loader can confirm
+// that, which is why this test asks the CLI to resolve the chain we generated
+// rather than inspecting our own files.
+//
+// Those three behaviours and the exact managed-server isolation were measured on
+// 2026-08-26 on Windows 10.0.19045.6466 (PowerShell 7.6.4, Go 1.26.6
+// windows/amd64) against the npm extended-stable (2026.6.34), latest (2026.7.1-2)
+// and beta (2026.8.1-beta.3) channels. Windows on purpose — that is the platform
+// where the npm shim puts `cmd.exe → node → node` between the daemon and the CLI,
+// so it is the least forgiving place to assert include resolution.
+//
+// The control that makes a pass mean something was run by hand rather than
+// asserted here: dropping the reset stage from the chain leaks `user-only` back
+// into the resolved server map on all three channels. Without that, a green test
+// could equally mean "the wrapper's own block happened to win".
+//
+// The OpenClaw config compatibility smoke workflow keeps those three moving
+// channels under scheduled and manually dispatched coverage.
+//
+// realOpenclawBin — the opt-in gate and binary lookup — is shared with
+// openclaw_real_integration_test.go.
+
+// mcpSibling is a non-server setting under `mcp` that must survive the reset
+// untouched, together with the value the loader should report back.
+//
+// A list of candidates rather than one hard-coded key, because the `mcp` schema
+// is not the same across the channels this runs against: 2026.8.1-beta.3 declares
+// `mcp` as exactly `servers` + `apps` with additionalProperties:false, while
+// `sessionIdleTtlMs` is accepted on the older channels. Hard-coding either one
+// turns a schema difference into a red smoke run that says nothing about this
+// change. So the fixture asks the CLI which shape it accepts.
+type mcpSibling struct {
+ key string
+ fragment string
+ want any
+}
+
+var mcpSiblingCandidates = []mcpSibling{
+ {key: "sessionIdleTtlMs", fragment: `"sessionIdleTtlMs": 300000`, want: float64(300000)},
+ {key: "apps", fragment: `"apps": {}`, want: map[string]any{}},
+}
+
+// realOpenclawConfig points the CLI at an isolated HOME holding a user config
+// with a user-only MCP server (which must not survive the reset), a same-name
+// server whose definition the managed set must replace, and a non-server `mcp`
+// sibling this host's schema accepts (which must survive untouched).
+func realOpenclawConfig(t *testing.T) (bin, activeConfig string, sibling mcpSibling) {
+ t.Helper()
+ bin = realOpenclawBin(t)
+
+ home := t.TempDir()
+ stateDir := filepath.Join(home, ".openclaw")
+ if err := os.MkdirAll(stateDir, 0o700); err != nil {
+ t.Fatalf("create isolated OpenClaw state: %v", err)
+ }
+ activeConfig = filepath.Join(stateDir, "openclaw.json")
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ t.Setenv("OPENCLAW_HOME", home)
+ t.Setenv("OPENCLAW_STATE_DIR", stateDir)
+ t.Setenv("OPENCLAW_CONFIG_PATH", activeConfig)
+
+ for _, candidate := range mcpSiblingCandidates {
+ writeRealOpenclawUserConfig(t, activeConfig, candidate)
+ if realOpenclawConfigValid(t, bin) {
+ return bin, activeConfig, candidate
+ }
+ t.Logf("channel rejects mcp.%s; trying the next sibling shape", candidate.key)
+ }
+ t.Fatalf("no candidate mcp sibling is accepted by this channel; the fixture needs a shape from its schema")
+ return "", "", mcpSibling{}
+}
+
+func writeRealOpenclawUserConfig(t *testing.T, path string, sibling mcpSibling) {
+ t.Helper()
+ config := fmt.Sprintf(`{
+ "gateway": {"mode": "local"},
+ "logging": {"level": "debug"},
+ "mcp": {
+ %s,
+ "servers": {
+ "user-only": {"command": "user-only"},
+ "shared": {"command": "user-shared"}
+ }
+ }
+ }`, sibling.fragment)
+ if err := os.WriteFile(path, []byte(config), 0o600); err != nil {
+ t.Fatalf("write isolated OpenClaw config: %v", err)
+ }
+}
+
+// realOpenclawConfigValid reports whether the CLI accepts the config it is
+// currently pointed at. `config validate --json` carries `valid` on every branch
+// since 2026.5.5 and exits non-zero for an invalid config, so the exit status is
+// deliberately ignored in favour of the payload.
+func realOpenclawConfigValid(t *testing.T, bin string) bool {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), openclawCLITimeout)
+ defer cancel()
+ out, _ := openclawExec(ctx, bin, "config", "validate", "--json")
+ var payload struct {
+ Valid bool `json:"valid"`
+ }
+ if err := json.Unmarshal([]byte(out), &payload); err != nil {
+ t.Fatalf("parse `config validate --json` output %q: %v", out, err)
+ }
+ return payload.Valid
+}
+
+func realOpenclawConfigGetJSON(t *testing.T, bin, keyPath string) any {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), openclawCLITimeout)
+ defer cancel()
+ out, err := openclawExec(ctx, bin, "config", "get", keyPath, "--json")
+ if err != nil {
+ t.Fatalf("resolve %s through the real CLI: %v", keyPath, annotateOpenclawJSONError(err, out))
+ }
+ var value any
+ if err := json.Unmarshal([]byte(out), &value); err != nil {
+ t.Fatalf("parse resolved %s JSON %q: %v", keyPath, out, err)
+ }
+ return value
+}
+
+func TestPrepareOpenclawConfigRealCLI(t *testing.T) {
+ bin, activeConfig, sibling := realOpenclawConfig(t)
+
+ envRoot := t.TempDir()
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir workdir: %v", err)
+ }
+
+ result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
+ OpenclawBin: bin,
+ McpConfig: json.RawMessage(`{"mcpServers":{
+ "managed-only":{"command":"managed-only"},
+ "shared":{"command":"managed-shared"}
+ }}`),
+ })
+ if err != nil {
+ t.Fatalf("prepareOpenclawConfig against the real CLI: %v", err)
+ }
+
+ // The chain we generated, before asking the loader what it makes of it.
+ wrapper := mustReadJSON(t, result.ConfigPath)
+ resetPath := filepath.Join(envRoot, openclawMcpResetFile)
+ include, ok := wrapper["$include"].([]any)
+ if !ok || len(include) != 2 || include[0] != activeConfig || include[1] != resetPath {
+ t.Fatalf("wrapper $include = %#v, want [%q, %q]", wrapper["$include"], activeConfig, resetPath)
+ }
+ if result.IncludeRoot != filepath.Dir(activeConfig) {
+ t.Fatalf("include root = %q, want %q", result.IncludeRoot, filepath.Dir(activeConfig))
+ }
+
+ // Ask the real CLI to resolve it. This is what verifies the reset rather than
+ // merely inspecting the JSON we wrote.
+ t.Setenv("OPENCLAW_CONFIG_PATH", result.ConfigPath)
+ t.Setenv("OPENCLAW_INCLUDE_ROOTS", result.IncludeRoot)
+
+ // The generated chain has to load at all: a `mcp.servers: null` that survived
+ // to the resolved root would be rejected here, which is the failure
+ // TestPrepareOpenclawConfigResetStagePairsWithWrapperMcp guards in unit form.
+ if !realOpenclawConfigValid(t, bin) {
+ t.Fatalf("the generated config does not validate; the reset stage is not paired with a wrapper mcp.servers block")
+ }
+
+ // A field that exists only in the live user config, so seeing it proves the
+ // wrapper's include followed through to the user's file rather than merely
+ // leaving its own managed block intact.
+ if level := realOpenclawConfigGetJSON(t, bin, "logging.level"); level != "debug" {
+ t.Fatalf("resolved logging.level = %#v, want debug through the include", level)
+ }
+
+ resolvedMcp, ok := realOpenclawConfigGetJSON(t, bin, "mcp").(map[string]any)
+ if !ok {
+ t.Fatalf("resolved mcp is not an object")
+ }
+
+ // Half one: the server map is exactly the managed set. `user-only` must be
+ // gone and `shared` must carry the managed definition, not the user's.
+ wantServers := map[string]any{
+ "managed-only": map[string]any{"command": "managed-only"},
+ "shared": map[string]any{"command": "managed-shared"},
+ }
+ servers, ok := resolvedMcp["servers"].(map[string]any)
+ if !ok || !reflect.DeepEqual(servers, wantServers) {
+ t.Fatalf("resolved mcp.servers = %#v, want exactly %#v", resolvedMcp["servers"], wantServers)
+ }
+
+ // Half two, and the reason the reset names one key instead of the whole
+ // object: the user's non-server MCP setting has to arrive unchanged, straight
+ // from their own file, without this package having read or re-emitted it.
+ got, present := resolvedMcp[sibling.key]
+ if !present {
+ t.Fatalf("resolved mcp lost the user's %s; the reset replaced more than the server map: %#v",
+ sibling.key, resolvedMcp)
+ }
+ if !reflect.DeepEqual(got, sibling.want) {
+ t.Fatalf("resolved mcp.%s = %#v, want the user's own %#v", sibling.key, got, sibling.want)
+ }
+}