Blog · · 12 min read

Embed an agent harness in an existing product without inheriting its coding-agent defaults

Embed an agent harness in an existing product without inheriting its coding-agent defaults

A prebuilt agent harness gives your product a working loop, file tools, a shell, compaction, subagents, and session resume on day one. It also arrives configured for a developer's laptop. Wire it straight to a customer chat endpoint and a tenant session can read the operator's instructions and hooks, start in a permission mode nobody chose, bypass the approval callback you wrote for product policy, lose its transcript when a container scales down, and see your product's own environment variables. This guide is for product and platform engineers adopting the Claude Agent SDK, the Codex SDK, or a similar runtime inside an existing SaaS. It turns those inherited defaults into an explicit adoption contract you can test on every upgrade.

The adoption contract in eight steps

LangChain's anatomy of an agent harness defines the harness as every piece of code, configuration, and execution logic that is not the model. When you embed someone else's harness, all of that configuration becomes an input to your product. Adopt it in this order:

  1. Inventory every input the harness reads, including the ones no option controls.
  2. Pin every option explicitly. Do not rely on an omitted value meaning what it meant last quarter.
  3. Start the harness under a dedicated credential and an explicit environment.
  4. Give each tenant session its own working directory and configuration directory.
  5. Enforce product authorization at the first interception point that runs on every tool call.
  6. Make your product, not the harness's home directory, the owner of session state.
  7. Prove isolation with planted-canary probes in CI.
  8. Gate every SDK upgrade on those probes before it reaches production.

The rest of this article implements each step with the two harnesses whose official docs describe embedding most directly.

Why an embedded agent harness inherits the wrong defaults

Coding-agent harnesses were built to act on one developer's machine, so they read that machine's state on purpose. The Claude Agent SDK hosting guide states that each query() call spawns a claude CLI subprocess that owns a shell, a working directory, and JSONL session transcripts on local disk. By default every session inherits your application's working directory, and transcripts land under ~/.claude/projects/.

Configuration loading follows the same laptop logic. According to Use Claude Code features in the SDK, omitting settingSources is equivalent to ["user", "project", "local"], which loads user and project settings.json, CLAUDE.md files from the working directory and every parent directory, and .claude/ skills, agents, commands, and hooks. On a laptop that is a feature. In a shared container it means one tenant's CLAUDE.md, or the operator's personal hooks, can shape another tenant's session.

The Codex SDK has the same shape with different files. Its npm README says the TypeScript SDK spawns the codex CLI and exchanges JSONL events over stdin and stdout, runs in the current working directory by default, requires that directory to be a Git repository unless you pass skipGitRepoCheck, persists threads in ~/.codex/sessions, and inherits the Node.js process environment unless you supply env.

Practitioners have hit these defaults in released versions. In anthropics/claude-code#44313, a user reported that setting_sources=[] in Python SDK 0.1.56 was silently ignored because the SDK checked the list for truthiness, so user-level hooks from ~/.claude/settings.json merged into SDK sessions and caused duplicate hook runs and ghost sessions. In anthropics/claude-code#45602, another user reported the user-level ~/.claude/CLAUDE.md loading despite setting_sources=["project"] and a redirected CLAUDE_CONFIG_DIR. Both issues were auto-closed as duplicates of an older report, so treat them as evidence about that release only.

Inventory every input before the first tenant session

Start with a table your team owns. The features guide lists inputs that load regardless of settingSources: managed policy settings from the host, the global ~/.claude.json, auto memory under ~/.claude/projects/<project>/memory/, claude.ai MCP connectors when the session authenticates with a claude.ai login, and server-managed settings fetched when the session authenticates with a qualifying organization credential. Filesystem isolation does not remove that last one.

InputWhere it comes fromLoaded whenHow to neutralize
User and project settings, hooks, CLAUDE.md, skills~/.claude/ and the session cwd with its parentssettingSources omitted or includes the sourcePass settingSources: [] and give each session its own cwd
Global config~/.claude.jsonAlwaysPoint CLAUDE_CONFIG_DIR at a per-tenant directory
Auto memory~/.claude/projects/<project>/memory/Session start, regardless of settingSourcesSet CLAUDE_CODE_DISABLE_AUTO_MEMORY=1
claude.ai connectorsThe signed-in claude.ai accountclaude.ai loginDo not run product sessions under a claude.ai login
Server-managed settingsYour Claude organizationQualifying organization credentialUse a credential whose organization settings you control
Codex threads~/.codex/sessionsEvery threadPer-tenant home or container, plus your own session record
Process environmentYour application processCodex by default; Claude via env handlingPass an explicit env built for the session

The hosting guide's multi-tenant section gives the Claude baseline: settingSources: [], CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, a per-tenant CLAUDE_CONFIG_DIR, an explicit per-tenant cwd on every call, and per-tenant egress rules at your proxy. It also warns that in TypeScript, env replaces the subprocess environment, while in Python it merges on top of the inherited one. That difference matters for the environment step below.

Pin options explicitly, because defaults move between releases

Harness defaults are release-dependent behavior, so pin every option explicitly and rerun planted-canary probes on each SDK upgrade instead of trusting an isolation flag you set once.

The Claude Agent SDK permissions page notes that before TypeScript Agent SDK v0.3.286, omitting permissionMode was the same as passing default. Now a session without one starts from settings files or a built-in default that can be auto mode, and an auto-mode session drops broad allow rules such as a bare Bash entry. A product that never set the option changed behavior on a dependency bump. Codex has the same pattern: OpenAI's Codex SDK page says that when you omit sandbox=, the app server uses its configured default. The #44313 report shows a second failure, where an option the developer did set was dropped by a falsy check.

Write the full option set down in code, with every value chosen, and fail fast if the session reports something else at start-up.

// Claude Agent SDK: every isolation and permission option pinned per session
const options = {
  cwd: tenantSessionDir,                 // never the app's own working directory
  settingSources: [],                    // no user, project, or local settings
  permissionMode: "dontAsk",             // deny anything that would prompt
  allowedTools: ["mcp__product__read_order"],
  disallowedTools: ["Bash", "WebFetch", "WebSearch"],
  maxTurns: 20,
  env: {
    PATH: "/usr/bin:/bin",
    ANTHROPIC_BASE_URL: modelProxyUrl,   // proxy injects the model key
    CLAUDE_CONFIG_DIR: tenantConfigDir,
    CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1",
  },
};
with Codex() as codex:
    thread = codex.thread_start(sandbox=Sandbox.read_only)  # explicit, not the app-server default

Two details shape these blocks. dontAsk converts any call that would prompt into a denial without calling your callback, which suits a headless product agent. A bare tool name in disallowedTools removes that tool from the model's context entirely, while a scoped rule such as Bash(rm *) leaves the tool available and only blocks matching commands.

Choose the credential and the environment on purpose

What a harness loads depends on the credential and environment you start it with, so run it under a dedicated service credential and an explicit environment rather than a developer login or the product's own process variables.

Credentials do not look like configuration, so teams leave them off the inventory. The features guide ties two inputs to authentication: a claude.ai login pulls in that account's MCP connectors (passing mcpServers: {} does not suppress them), and a qualifying organization credential fetches server-managed settings that only an organization Owner can change. A prototype built under one engineer's login will therefore behave differently in production for reasons no option in your code explains. Run product sessions under a credential created for the product, in an organization or workspace whose administrative settings your platform team controls, and record which credential each session used.

The process environment is the second risk. The Codex README states that the CLI inherits the Node.js process environment unless you pass env, and that the SDK still injects its required variables such as CODEX_API_KEY on top. If your product process holds a database URL, a payment key, or a signing secret, the default gives a shell-capable agent a route to read them. Build the session environment from an allowlist: a minimal PATH, the proxy endpoints, and per-tenant directories. Keep real credentials outside the agent's environment. Anthropic's secure deployment guide recommends a proxy outside the agent's environment that injects credentials into outgoing requests, so the agent can call an API without ever seeing the key, and the hosting guide puts inbound user authentication at a gateway in front of the agent container rather than inside the agent.

Put product authorization where auto-approval cannot skip it

Put product authorization in the earliest interception point that runs on every tool call, because a harness approval callback is skipped for any tool that an allow rule or permission mode has already approved.

The permissions page spells out the evaluation order: hooks first, then deny rules, then ask rules, then the permission mode, then allow rules, and only then the canUseTool callback. It adds that auto-approved tools never reach canUseTool, so permission checks you put there are silently bypassed for that tool. A bare allowedTools entry auto-approves every call to that tool. With bypassPermissions, every unlisted tool is approved too, so allowedTools constrains nothing in that mode. The TypeScript SDK emits a CLAUDE_SDK_CAN_USE_TOOL_SHADOWED process warning for these configurations, which is worth turning into a start-up error in your service.

A team that writes its tenant and role checks in canUseTool and then pre-approves "safe" tools for latency has removed authorization from the tools it pre-approved. The docs recommend a PreToolUse hook for checks that must run on every call, because hooks run before every other step and a hook deny applies even in bypassPermissions mode. A hook that returns allow does not skip later deny and ask rules, so the hook can only narrow access.

PreToolUse(tool_name, tool_input, session):
  principal = session.product_principal          # set by your gateway, not by the model
  decision  = product_policy.check(principal, tool_name, tool_input)
  if decision.denied:
      return deny(reason = decision.user_safe_reason)
  audit.log(principal, tool_name, decision.policy_version)
  return {}                                      # fall through to deny/ask/mode/allow rules

Two more rules from the same page affect product agents. A subagent runs in the parent session's permission mode unless you set one on its definition, so a parent in bypassPermissions hands that mode to every subagent. Under dontAsk, calls that need no approval in default mode still run, including file reads inside the working directory and calls to the Agent tool. Your per-session cwd is therefore part of your authorization model, not only a filesystem convenience.

Give the product ownership of session state

By default the harness stores the conversation, your product stores the customer record, and nothing links the two. The hosting guide lists three kinds of state on local disk (session transcripts, CLAUDE.md memory files, and working-directory artifacts) and says none of them survives a container restart, a scale-down, or a move to another node. Its SessionStore adapter mirrors transcripts to your own storage, but it mirrors transcripts only, writes local disk first, and treats mirroring as best effort. When a batch cannot be delivered, the SDK drops it, emits a system message with subtype mirror_error, and continues the query.

For a product that promises resumable conversations, a silent mirror_error is data loss with a success status. Store your own record that maps the product's conversation ID, tenant, principal, credential, pinned option hash, and SDK version to the harness session ID. Treat any mirror_error as an incident signal for that session, and decide per workflow whether to stop the run or mark it non-resumable. For long-running sessions, the guide recommends pinning each session to one container with consistent hashing on the session ID. For Codex, give each tenant its own home or container so ~/.codex/sessions never holds two customers' threads, and keep the thread ID in your record so resumeThread() is never the only lookup.

Handle failure and recovery

Decide in advance what the product does when the contract breaks. If the start-up probe detects a loaded instruction file, an unexpected permission mode, or a shadowed callback, refuse to start the session and fall back to the non-agent path, such as the existing form or a handoff to support, rather than running a session you cannot account for.

The hosting guide lists limits that become product failure modes. There is no top-level session timeout, so set maxTurns and give each subagent its own maxTurns. Memory grows over long sessions, so cap session length or recycle subprocesses. Wide parallel subagent fan-outs can hit rate limits, so batch them. When a subprocess exits mid-run, return a typed failure to the caller and leave the product record in a state an operator can inspect, because the transcript on local disk may be the only evidence and it disappears with the container.

Finally, plan teardown. When a tenant leaves or a session expires, delete its working directory, configuration directory, and mirrored transcripts together, and confirm no other session's directory referenced them.

Verify the solution

Planted-canary probes check what the harness loaded, which a config file cannot show. Run them in CI against the exact SDK version you deploy and again on every dependency bump.

Setup on the test host:
  ~/.claude/CLAUDE.md            contains  CANARY-USER-INSTRUCTION
  ~/.claude/settings.json        defines   a PreToolUse hook that writes CANARY-HOOK-RAN
  auto-memory directory          contains  CANARY-MEMORY
  parent of tenant cwd           contains  CLAUDE.md with CANARY-PARENT
  product process env            exports   CANARY_SECRET=do-not-read

Assertions for a tenant session:
  1. The agent cannot quote any CANARY string when asked what instructions it has.
  2. CANARY-HOOK-RAN is never written.
  3. The permission mode reported at session start equals the pinned value.
  4. A tool denied by product policy is blocked even when it is on allowedTools.
  5. Reading CANARY_SECRET from the shell or environment fails.
  6. Tenant A's session cannot list or read tenant B's cwd or config directory.
  7. A session resumed on a different host returns the full transcript.
  8. Forcing the session store offline produces an alert, not a silent mirror_error.

The model's answer in assertion 1 is weak evidence by itself, so pair it with a deterministic check of the session's initialization message and the subprocess's open files, where your platform allows it. If any assertion fails after an upgrade, block the deploy and diff the SDK changelog against your pinned option set.

Common mistakes

One gap is setting isolation options once in a shared helper and never testing them, because the helper keeps passing review while the dependency underneath it changes meaning. Another is writing authorization in the approval callback and then pre-approving tools for speed, which removes the check from the tools that get called most. A third is prototyping under a developer's own login and environment, which ships behavior that depends on one person's connectors, organization settings, and shell variables.

Teams also over-trust definitional guides. Databricks' harness overview and Mervin Praison's ten-component checklist describe what a good harness contains, such as sandboxes, memory, guardrails, observability, and human approval. They help when you build a harness, but they do not say which of those components a prebuilt harness has already configured for someone else's laptop.

What to do next

Take the input table above, fill in the actual value for each row in your deployment today, and write the eight canary assertions as a CI job that runs on your current SDK version. Any row you cannot fill in, or any assertion that fails, is the first fix before your agent harness serves another tenant session.

Be first in line.

Join the waitlist and we'll email you the moment it's ready. No sales call.

Try the demo →
or talk to us