Skip to content

Model Context Protocol (MCP) & Python Code Mode

microharness ships a zero-dependency, lazy-loaded MCP first-party plugin (plugins/mcp/) built on Python's standard library (subprocess, urllib.request, threading, plus core/sandbox.py) and paired with optional Python Code Mode (core/code_mode.py).

  • core/ remains strictly MCP-agnostic: plugins/mcp/plugin.json declares its defaults (plugins/mcp/defaults.json), CLI flags (--no-mcp, --mcp-mode), agent.md frontmatter keys, and CodeModeHelperProvider (mcp) via the generic Plugin System.
  • Only MCP Tools (initialize, tools/list with pagination, tools/call) are exposed in v1, including pass-through of validated MCP image blocks (and image-typed resource blobs) to vision-capable models.

Adding MCP Servers

Configure "mcp_servers" (or "mcpServers", the standard Claude Desktop / Cursor / .mcp.json alias) in any of the layered JSON/JSONC config files, or pass mcp_servers={...} directly to Harness(...):

Location Scope Trust Behavior
~/.microharness/config.json global Trusted automatically across all projects
~/.microharness/presets/<name>/config.json preset Skipped unless --trust-project-tools (or "trust_project_tools": true in ~/.microharness/config.json)
.microharness/config.json (in workspace) project Skipped unless --trust-project-tools (or "trust_project_tools": true in ~/.microharness/config.json)
Harness(mcp_servers={...}) explicit Trusted automatically

Higher-precedence layers merge with lower layers by server name (e.g. a project .microharness/config.json can set "enabled": false to disable a global server for that repo).

Transports

  1. Local stdio subprocess (set "command"):
{
  "mcp_servers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "env:GITHUB_TOKEN"
      },
      "cwd": ".",
      "description": "GitHub issues, PRs, and repositories"
    }
  }
}
  1. Remote Streamable HTTP (set "url"):
{
  "mcp_servers": {
    "remote-docs": {
      "url": "https://docs.example.com/mcp",
      "headers": {
        "Authorization": "Bearer env:DOCS_TOKEN"
      }
    }
  }
}
  1. Legacy HTTP+SSE (GET /sse + POST /message): Detected automatically when "url" ends with /sse, or set "transport": "sse" explicitly:
{
  "mcp_servers": {
    "memory": {
      "url": "http://127.0.0.1:8000/sse"
    }
  }
}

Secret References (env: / Bearer env:)

Both "env" (for stdio) and "headers" (for HTTP/SSE) support reading secrets from os.environ at runtime without storing raw tokens in config.json:

  • "env:VAR_NAME" resolves to os.environ.get("VAR_NAME", "")
  • "Bearer env:VAR_NAME" resolves to "Bearer <token>" (omitted from headers if the env var is unset or empty)

Per-Server Options

Key Type Default Purpose
command string — Executable for stdio transport (mutually exclusive with url)
args list of strings [] Arguments passed to command
env object {} Environment variables merged onto os.environ (env:VAR supported)
cwd string null Working directory for stdio subprocess
url string — Absolute http:// or https:// endpoint (mutually exclusive with command)
transport string auto "http" ("streamable-http") or "sse" ("type" alias accepted; auto-detects "sse" when URL path ends with /sse)
headers object {} HTTP request headers (env:VAR and Bearer env:VAR supported)
description string "" Short summary shown in the system prompt index (falls back to server instructions)
mode string inherits mcp_mode Per-server override: "progressive", "direct", or "code_mode" ("direct": true also accepted)
enabled bool true Set false in a higher layer (e.g. .microharness/config.json) to suppress an inherited server
required bool false If true, startup fails fast if the server errors; default false warns to stderr and continues
allow_in_sandbox bool false Legacy bypass: allow unsandboxed host stdio in --sandbox / --docker, or host HTTP in --docker without sandbox.allowed_hosts
sandbox bool / string / object mode="auto" Granular per-server sandbox policy (mode, filesystem, read_paths, write_paths, network, allowed_hosts, env_passthrough, inherit_host_env; defaults in plugins/mcp/defaults.json)
startup_timeout float 15.0 Timeout in seconds for startup / initialize / tools/list (mcp_startup_timeout in plugins/mcp/defaults.json)
call_timeout float 30.0 Timeout in seconds for tools/call (mcp_call_timeout in plugins/mcp/defaults.json)

Per-Server Sandbox Policy (sandbox)

Each server entry in mcp_servers accepts an optional sandbox policy (boolean shorthand, mode string, or object; layers deep-merge per server):

{
  "mcp_servers": {
    "workspace-tools": {
      "command": "python3",
      "args": ["tools/mcp_server.py"],
      "env": {
        "TOOL_TOKEN": "env:TOOL_TOKEN"
      },
      "sandbox": {
        "mode": "auto",               // "auto" | "docker" | "os" | "sandbox-exec" | "bwrap" | "off"
        "filesystem": "workspace-ro", // "workspace" | "workspace-ro" | "none"
        "read_paths": [],
        "write_paths": [],
        "network": "none",            // "none" | "allowlist" | "full" | "inherit"
        "allowed_hosts": [],          // e.g. ["api.github.com", "*.example.com:8443"]
        "env_passthrough": [],        // extra host env vars to forward into the sandbox
        "inherit_host_env": false     // strip host os.environ secrets by default
      }
    }
  }
}
  • mode: "auto" (default): Under --sandbox / --docker, stdio servers are automatically sandboxed (docker exec -i inside the active container under --docker, or macOS sandbox-exec / Linux bwrap under --sandbox) when they are workspace-local, project-scoped, or declare an explicit sandbox policy; unannotated global host stdio servers are skipped unless an explicit sandbox policy or allow_in_sandbox: true is configured. Fails closed if an eligible server cannot be sandboxed.
  • filesystem / read_paths / write_paths: Controls workspace access ("workspace", "workspace-ro", "none") and optional host paths for OS-sandboxed stdio servers. Automatically downgraded to read-only under ReadOnlyEnvironment. Under --docker, explicit filesystem: "none" or filesystem: "workspace-ro" fails closed when the container mounts /workspace read-write.
  • network / allowed_hosts: stdio servers default to network: "none" inside sandboxes; on macOS sandbox-exec, network: "allowlist" pairs Seatbelt localhost restrictions with a stdlib HTTP/CONNECT allowlist proxy (_HostAllowlistProxy). Under --docker, network: "allowlist" (for stdio) and explicit network: "none" on containers started without --docker-network none fail closed. For HTTP/SSE servers, allowed_hosts validates the target URL, HTTP redirects, and legacy SSE endpoint events (allowing explicitly allowlisted HTTP/SSE servers in --docker unless --docker-network none or --no-network-tools disables network tools).
  • env_passthrough / inherit_host_env: Sandboxed processes strip host os.environ secrets by default (sandbox_safe_env_keys in core/defaults.json), passing only resolved env entries (env:VAR) and declared env_passthrough variable names (passed to docker exec via -e KEY environment forwarding so values stay out of host process argv).

Exposure Modes (mcp_mode) & Python Code Mode

Mode Tools Exposed Advantages Disadvantages / Trade-offs
"progressive" (default) mcp_search, mcp_call • 1-line-per-server prompt index (~20 tokens/server)
• Works in --docker, --permission-mode read-only, and worker subagents
• Per-tool readOnlyHint enforcement in ask / read-only mode
• Reliable typed JSON args even on smaller models
• +1 discovery step (mcp_search) before calling an unfamiliar tool
• Multi-step loops require 1 LLM turn per tool call; large outputs enter Memory (up to max_tool_tokens)
"direct" mcp__<server>__<tool> • Zero mcp_search discovery overhead
• Native modifies_files / parallel_safe flags per tool in ToolRegistry
• Injects every tool's full JSON schema into every prompt turn (can add 5k–15k+ tokens for 30+ tool servers like chrome-devtools-mcp)
"code_mode" mcp_search, code_mode (mcp_call deferred) • Batch loops, pagination, and joins inside a single Python turn
• Filter/distill huge outputs (e.g. DOM/API responses) in Python before printing to Memory
• Runs inside --docker (including --docker-network none) and OS --sandbox over the stdio JSON-RPC bridge
• Also works standalone without mcp_servers for batching local tools (read_file, grep, etc.)
• Disabled in read-only and child subagents; always prompts in ask mode
• Collapses individual tool traces behind ● CodeMode (N lines)
• Weaker models can hit script/syntax errors on simple 1-call tasks

(Note: Under --docker and OS --sandbox, code_mode executes inside the container or OS sandbox over newline-delimited JSON-RPC stdio; on unsandboxed host runs it uses the local authenticated 127.0.0.1 bridge — see Security and Environment Boundaries.)

Top-level config keys (also configurable via CLI flags or agent.md frontmatter):

  • "enable_mcp": true (default) or false (--no-mcp)
  • "mcp_mode": "progressive" (default), "direct", or "code_mode" (--mcp-mode <mode>) — "code_mode" enables the code_mode Python batching tool (works both with MCP and standalone for local tools)
  • "code_mode_bridge" / "code_mode_sandbox": Optional top-level overrides (defaults in core/defaults.json: "auto" bridge and {mode: "auto", filesystem: "workspace", network: "none"} sandbox; project-level overrides require --trust-project-tools). Explicit "code_mode_sandbox" policies fail closed if the requested sandbox backend is unavailable.

When "mcp_mode": "code_mode" is active, scripts execute via Python in the active environment (container docker exec -i or OS sandbox over stdio JSON-RPC, or host subprocess over 127.0.0.1 loopback HTTP) with pre-injected helpers backed by ToolRegistry.dispatch():

  • tools.list(), tools.call(name, **kwargs), tools.try_call(name, **kwargs)
  • mcp.search(query="", server=None, limit=None), mcp.call(server, tool, **kwargs), mcp.call_json(server, tool, **kwargs)

Design Rationale

  1. core/ stays MCP-agnostic (ToolProvider + plugins/mcp/ plugin bundle)
  2. microharness requires zero third-party runtime dependencies (dependencies = []) and clean pluggable boundaries (Model, Tool, Evaluator, ToolProvider, CodeModeHelperProvider).
  3. Putting the MCP client in plugins/mcp/ with activate_on_config_keys in plugin.json keeps headless AgentLoop / benchmark runs free of MCP imports when unconfigured and lets users disable (microharness plugin disable mcp) or swap in custom ToolProvider implementations without modifying core/.
  4. Pure-stdlib transports (stdio, Streamable HTTP, legacy /sse) avoid pulling heavy async/Pydantic/SDK dependency trees into pyproject.toml.

  5. Why "progressive" is the default (not "direct" or "code_mode")

  6. progressive vs direct: Modern MCP servers often ship 20–50 tools (e.g. chrome-devtools-mcp ships 33 tools = ~19–29 KB of JSON schemas). Progressive disclosure replaces all of those up-front schemas with a 1-line index + ranked mcp_search, preserving prompt tokens across multi-turn sessions while keeping "direct" available per server for small 1–2 tool servers.
  7. progressive vs code_mode: Python script execution carries a wider execution surface (modifies_files=True, blocked in read-only) and adds subprocess/bridge complexity that isn't justified for simple 1–2 tool queries. Making "progressive" the default gives safe, granular readOnlyHint enforcement everywhere out of the box, while "code_mode" remains one flag away (and now runs inside --docker and OS --sandbox via stdio JSON-RPC) for heavy batching.

  8. Why deferred tool registration exists (ToolRegistry)

  9. Under mcp_mode="code_mode", mcp_call is registered with deferred=True: hidden from to_openai_schemas() and to_system_prompt_snippet(), yet still dispatchable through ToolRegistry.dispatch() over _ToolBridgeDispatcher.
  10. Routing code_mode through ToolRegistry.dispatch() rather than calling Python objects directly guarantees PRE_TOOL/POST_TOOL hooks, GuardedEnvironment confirmations, and output spillover apply identically across direct, progressive, and scripted calls.

  11. Why code_mode pairs an authenticated stdio JSON-RPC bridge with OS/Docker sandboxing

  12. Capability-isolated Wasm/V8 runtimes require third-party dependencies. Under the zero-dependency rule, core/code_mode.py + core/sandbox.py isolate execution using docker exec -i (under --docker, including --docker-network none) or OS sandboxes (sandbox-exec / bwrap under --sandbox) communicating over newline-delimited JSON-RPC stdio (isolating fd 0/fd 1 for protocol traffic while redirecting script stdout to stderr), falling back to an allowlisted os.environ + 127.0.0.1 bearer-token bridge only on unsandboxed host runs.
  13. All sandbox operational defaults (code_mode_bridge, code_mode_sandbox_*, sandbox_safe_env_keys, mcp_sandbox_*) live declaratively in core/defaults.json and plugins/mcp/defaults.json.

  14. KV-cache vs. eager observation pruning

  15. Ranked mcp_search (stopword-filtered token scoring, $schema stripped, compact JSON) keeps schema lookup small (~3 KB instead of 29 KB fallback dumps).
  16. Once a tool result enters Memory, microharness intentionally avoids mutating earlier turns before the 80% compaction threshold (trigger_ratio = 0.80) so provider KV prefix caching stays intact across turns (yielding 80%+ cached prompt tokens), collapsing stale reasoning and old tool outputs together cleanly at compaction time.

  17. Multimodal image pass-through (ToolOutput → follow-up user turn)

  18. When an MCP tool (such as Playwright or chrome-devtools-mcp) returns {"type": "image", "data": ..., "mimeType": ...} blocks, _format_mcp_call_result validates the payload using pure-stdlib MIME/base64/size checks (max_image_bytes and allowed_image_mime_types in core/defaults.json), emits a concise [image: image/png, N KB] text placeholder for role="tool", and attaches normalized image_url data URIs via core.types.ToolOutput.
  19. AgentLoop appends all role="tool" messages immediately after the assistant's tool_calls (preserving OpenAI message-ordering requirements across parallel calls) and then appends a single follow-up role="user" multimodal message carrying the image blocks—avoiding HTTP 400 errors on endpoints that reject image_url inside role="tool", and degrading cleanly to text placeholders on non-vision models (supports_vision: false). code_mode bridges and trace.json / trajectory.jsonl see only concise text/metadata without raw base64 bloat.

CLI & Python Usage

# Default progressive disclosure using ~/.microharness/config.json
uv run microharness "List open issues using GitHub MCP"

# Trust repo-local .microharness/config.json MCP servers
uv run microharness --trust-project-tools "Query project MCP"

# Override exposure mode (direct or code_mode)
uv run microharness --mcp-mode direct "Run a direct MCP tool"
uv run microharness --mcp-mode code_mode "Batch and summarize MCP results"

# Disable all MCP connections for a run
uv run microharness --no-mcp "Work strictly offline"
from microharness import Harness

harness = Harness(
    model=my_model,
    workspace_dir=".",
    mcp_mode="progressive",  # "progressive" | "direct" | "code_mode"
    mcp_servers={
        "memory": {"url": "http://127.0.0.1:8000/sse"},
    },
    # Or supply your own custom core.protocols.ToolProvider instances:
    # tool_providers=[my_custom_provider],
)

Security and Environment Boundaries

  • Project/preset trust: Non-global MCP entries (project, preset, path) are skipped with a warning unless --trust-project-tools (or "trust_project_tools": true in ~/.microharness/config.json) is set.
  • Permission modes:
  • read-only (and read_only=True subagents): blocks code_mode and any MCP tool where annotations.readOnlyHint is not true (mcp_search and readOnlyHint: true tools remain allowed).
  • ask: prompts for confirmation before running code_mode or any MCP tool without readOnlyHint: true.
  • Network / Sandbox / Docker:
  • --no-network-tools (or --docker-network none) skips all http / sse MCP servers (even if allow_in_sandbox or sandbox.allowed_hosts is set) and disables network access for sandboxed stdio servers.
  • --sandbox automatically runs sandbox-capable stdio MCP servers (workspace-local, project-scoped, or explicitly declaring sandbox) and code_mode inside an OS sandbox (sandbox-exec on macOS, bwrap on Linux) scoped to the workspace with network="none" and stripped host secrets by default; unannotated global host stdio servers are skipped unless "sandbox" or "allow_in_sandbox": true is set.
  • --docker runs sandbox-capable stdio MCP servers and code_mode inside the active container via docker exec -i (code_mode communicates over the authenticated stdio JSON-RPC bridge so --docker-network none remains completely airtight); unannotated global host stdio servers and host http / sse servers stay skipped in --docker unless sandbox (sandbox.allowed_hosts for HTTP/SSE) or "allow_in_sandbox": true is configured (and network tools are enabled).
  • Subagents: explore and reviewer keep their minimal local tool allowlist; worker inherits active MCP tools (never code_mode, which is blocked in child subagents so child tool allowlists cannot be bypassed).