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.jsondeclares its defaults (plugins/mcp/defaults.json), CLI flags (--no-mcp,--mcp-mode),agent.mdfrontmatter keys, andCodeModeHelperProvider(mcp) via the generic Plugin System.- Only MCP Tools (
initialize,tools/listwith pagination,tools/call) are exposed in v1, including pass-through of validated MCPimageblocks (and image-typedresourceblobs) 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¶
- Local
stdiosubprocess (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"
}
}
}
- Remote Streamable HTTP (set
"url"):
{
"mcp_servers": {
"remote-docs": {
"url": "https://docs.example.com/mcp",
"headers": {
"Authorization": "Bearer env:DOCS_TOKEN"
}
}
}
}
- Legacy HTTP+SSE (
GET /sse+POST /message): Detected automatically when"url"ends with/sse, or set"transport": "sse"explicitly:
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 toos.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,stdioservers are automatically sandboxed (docker exec -iinside the active container under--docker, or macOSsandbox-exec/ Linuxbwrapunder--sandbox) when they are workspace-local,project-scoped, or declare an explicitsandboxpolicy; unannotated global hoststdioservers are skipped unless an explicitsandboxpolicy orallow_in_sandbox: trueis 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-sandboxedstdioservers. Automatically downgraded to read-only underReadOnlyEnvironment. Under--docker, explicitfilesystem: "none"orfilesystem: "workspace-ro"fails closed when the container mounts/workspaceread-write.network/allowed_hosts:stdioservers default tonetwork: "none"inside sandboxes; on macOSsandbox-exec,network: "allowlist"pairs Seatbelt localhost restrictions with a stdlib HTTP/CONNECT allowlist proxy (_HostAllowlistProxy). Under--docker,network: "allowlist"(forstdio) and explicitnetwork: "none"on containers started without--docker-network nonefail closed. For HTTP/SSE servers,allowed_hostsvalidates the target URL, HTTP redirects, and legacy SSEendpointevents (allowing explicitly allowlisted HTTP/SSE servers in--dockerunless--docker-network noneor--no-network-toolsdisables network tools).env_passthrough/inherit_host_env: Sandboxed processes strip hostos.environsecrets by default (sandbox_safe_env_keysincore/defaults.json), passing only resolvedenventries (env:VAR) and declaredenv_passthroughvariable names (passed todocker execvia-e KEYenvironment forwarding so values stay out of host processargv).
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) orfalse(--no-mcp)"mcp_mode":"progressive"(default),"direct", or"code_mode"(--mcp-mode <mode>) —"code_mode"enables thecode_modePython batching tool (works both with MCP and standalone for local tools)"code_mode_bridge"/"code_mode_sandbox": Optional top-level overrides (defaults incore/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¶
core/stays MCP-agnostic (ToolProvider+plugins/mcp/plugin bundle)microharnessrequires zero third-party runtime dependencies (dependencies = []) and clean pluggable boundaries (Model,Tool,Evaluator,ToolProvider,CodeModeHelperProvider).- Putting the MCP client in
plugins/mcp/withactivate_on_config_keysinplugin.jsonkeeps headlessAgentLoop/ benchmark runs free of MCP imports when unconfigured and lets users disable (microharness plugin disable mcp) or swap in customToolProviderimplementations without modifyingcore/. -
Pure-stdlib transports (
stdio, Streamable HTTP, legacy/sse) avoid pulling heavy async/Pydantic/SDK dependency trees intopyproject.toml. -
Why
"progressive"is the default (not"direct"or"code_mode") progressivevsdirect: Modern MCP servers often ship 20–50 tools (e.g.chrome-devtools-mcpships 33 tools = ~19–29 KB of JSON schemas). Progressive disclosure replaces all of those up-front schemas with a 1-line index + rankedmcp_search, preserving prompt tokens across multi-turn sessions while keeping"direct"available per server for small 1–2 tool servers.-
progressivevscode_mode: Python script execution carries a wider execution surface (modifies_files=True, blocked inread-only) and adds subprocess/bridge complexity that isn't justified for simple 1–2 tool queries. Making"progressive"the default gives safe, granularreadOnlyHintenforcement everywhere out of the box, while"code_mode"remains one flag away (and now runs inside--dockerand OS--sandboxviastdioJSON-RPC) for heavy batching. -
Why
deferredtool registration exists (ToolRegistry) - Under
mcp_mode="code_mode",mcp_callis registered withdeferred=True: hidden fromto_openai_schemas()andto_system_prompt_snippet(), yet still dispatchable throughToolRegistry.dispatch()over_ToolBridgeDispatcher. -
Routing
code_modethroughToolRegistry.dispatch()rather than calling Python objects directly guaranteesPRE_TOOL/POST_TOOLhooks,GuardedEnvironmentconfirmations, and output spillover apply identically across direct, progressive, and scripted calls. -
Why
code_modepairs an authenticatedstdioJSON-RPC bridge with OS/Docker sandboxing - Capability-isolated Wasm/V8 runtimes require third-party dependencies. Under the zero-dependency rule,
core/code_mode.py+core/sandbox.pyisolate execution usingdocker exec -i(under--docker, including--docker-network none) or OS sandboxes (sandbox-exec/bwrapunder--sandbox) communicating over newline-delimited JSON-RPCstdio(isolatingfd 0/fd 1for protocol traffic while redirecting scriptstdouttostderr), falling back to an allowlistedos.environ+127.0.0.1bearer-token bridge only on unsandboxed host runs. -
All sandbox operational defaults (
code_mode_bridge,code_mode_sandbox_*,sandbox_safe_env_keys,mcp_sandbox_*) live declaratively incore/defaults.jsonandplugins/mcp/defaults.json. -
KV-cache vs. eager observation pruning
- Ranked
mcp_search(stopword-filtered token scoring,$schemastripped, compact JSON) keeps schema lookup small (~3 KB instead of 29 KB fallback dumps). -
Once a tool result enters
Memory,microharnessintentionally 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. -
Multimodal image pass-through (
ToolOutput→ follow-upuserturn) - When an MCP tool (such as Playwright or
chrome-devtools-mcp) returns{"type": "image", "data": ..., "mimeType": ...}blocks,_format_mcp_call_resultvalidates the payload using pure-stdlib MIME/base64/size checks (max_image_bytesandallowed_image_mime_typesincore/defaults.json), emits a concise[image: image/png, N KB]text placeholder forrole="tool", and attaches normalizedimage_urldata URIs viacore.types.ToolOutput. AgentLoopappends allrole="tool"messages immediately after the assistant'stool_calls(preserving OpenAI message-ordering requirements across parallel calls) and then appends a single follow-uprole="user"multimodal message carrying the image blocks—avoidingHTTP 400errors on endpoints that rejectimage_urlinsiderole="tool", and degrading cleanly to text placeholders on non-vision models (supports_vision: false).code_modebridges andtrace.json/trajectory.jsonlsee 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": truein~/.microharness/config.json) is set. - Permission modes:
read-only(andread_only=Truesubagents): blockscode_modeand any MCP tool whereannotations.readOnlyHintis nottrue(mcp_searchandreadOnlyHint: truetools remain allowed).ask: prompts for confirmation before runningcode_modeor any MCP tool withoutreadOnlyHint: true.- Network / Sandbox / Docker:
--no-network-tools(or--docker-network none) skips allhttp/sseMCP servers (even ifallow_in_sandboxorsandbox.allowed_hostsis set) and disables network access for sandboxedstdioservers.--sandboxautomatically runs sandbox-capablestdioMCP servers (workspace-local,project-scoped, or explicitly declaringsandbox) andcode_modeinside an OS sandbox (sandbox-execon macOS,bwrapon Linux) scoped to the workspace withnetwork="none"and stripped host secrets by default; unannotated global hoststdioservers are skipped unless"sandbox"or"allow_in_sandbox": trueis set.--dockerruns sandbox-capablestdioMCP servers andcode_modeinside the active container viadocker exec -i(code_modecommunicates over the authenticatedstdioJSON-RPC bridge so--docker-network noneremains completely airtight); unannotated global hoststdioservers and hosthttp/sseservers stay skipped in--dockerunlesssandbox(sandbox.allowed_hostsfor HTTP/SSE) or"allow_in_sandbox": trueis configured (and network tools are enabled).- Subagents:
exploreandreviewerkeep their minimal local tool allowlist;workerinherits active MCP tools (nevercode_mode, which is blocked in child subagents so child tool allowlists cannot be bypassed).