Python API & Pluggability¶
Every core abstraction in microharness is defined as a minimal Python Protocol—you can compose custom models, tools, tool providers, hooks, request signers, and evaluators without subclassing or modifying core/.
Embedding Harness in Python¶
from microharness import Harness, Task
from core.evaluator import CommandTestEvaluator
harness = Harness(
model=my_custom_model, # Any object implementing Model.generate()
workspace_dir=".", # Operates in-place (or pass sandbox=True / docker=True)
global_dir="~/.microharness", # Global config, instructions, skills & auth
tools=[my_custom_tool], # Additional Tool instances
evaluator=CommandTestEvaluator("pytest"),
)
result = harness.run(Task(id="fix-auth", instruction="Fix failing tests in tests/test_auth.py"))
print(result.success, result.final_response)
For interactive frontends:
harness.run_tui("Help me refactor the database layer")
# Or line-oriented CLI chat:
# harness.run_interactive("Help me refactor the database layer")
Top-level exports from microharness: Harness, Task, ToolCall, RunResult, __version__.
Model & Capability Protocols (core/protocols.py)¶
Any model only must implement Model:
from typing import Any
from core.types import Message, ToolCall
class MyModel:
def generate(
self, messages: list[Message], tools: list[dict[str, Any]]
) -> tuple[str, list[ToolCall]]: ...
The harness checks isinstance(model, ...) against optional @runtime_checkable capability protocols and falls back cleanly if a model doesn't advertise them:
| Protocol | Method / Attribute | Purpose |
|---|---|---|
Model (required) |
generate(messages, tools) |
Return (assistant_text, tool_calls) |
StreamingModel |
generate_stream(messages, tools, on_event=None) |
Stream incremental StreamEvent chunks (text, reasoning, tool calls, usage) |
ResettableModel |
reset() |
Clear per-task state between benchmark tasks |
CacheAwareModel |
set_cache_ttl(ttl), get_cache_stats() |
Dynamic cache TTL switching & cache hit stats |
ReasoningAwareModel |
set_reasoning_effort(effort), get_reasoning_effort() |
Dynamic reasoning/thinking effort control |
DeadlineAwareModel |
set_deadline(deadline) |
Bound in-flight HTTP calls to task deadline |
CancellableModel |
set_cancel_probe(probe) |
Abort retry/backoff waits and active SSE streams on user cancel (Esc) |
RateLimitAwareModel |
total_rate_limit_wait_s |
Track cumulative rate-limit throttling wait time |
UsageReportingModel |
get_last_step_usage() |
Normalized token & cache counts per step |
AssistantMetadataModel |
get_last_assistant_fields() |
Opaque replay fields (e.g. reasoning_content) |
NamedModel |
model: str |
Expose active model identifier |
EndpointAwareModel |
endpoint: str |
Expose HTTP endpoint URL |
ProviderAwareModel |
provider: str |
Expose provider name |
ContextWindowAwareModel |
get_context_window() |
Query live context window size |
Tool & ToolProvider Protocols¶
Implementing a Tool¶
class StatusTool:
name = "service_status"
description = "Check internal service health"
parameters = {
"type": "object",
"properties": {"service": {"type": "string"}},
"required": ["service"],
}
parallel_safe = True
modifies_files = False
def execute(self, service: str) -> tuple[int, str]:
return 0, f"{service}: healthy"
Implementing a ToolProvider & CodeModeHelperProvider¶
ToolProvider (core/protocols.py) supplies lifecycle-managed sets of tools (used by plugins/mcp/ and user-installed plugins in ~/.microharness/plugins/). Providers can also implement CodeModeHelperProvider.get_code_mode_helpers() to contribute Python client helpers into code_mode:
from core.code_mode import CodeModeHelper
class MyToolProvider:
name = "custom-provider"
def startup(self, env) -> None: ...
def get_tools(self):
return [StatusTool()]
def get_code_mode_helpers(self):
return [
CodeModeHelper(
name="service",
code="class _Svc:\n def status(self, name): return tools.call('service_status', service=name)\nservice = _Svc()\n",
description="`service.status(name)`",
)
]
def prompt_summary(self) -> str:
return "Custom internal service tools available."
def teardown(self) -> None: ...
harness = Harness(model=my_model, tool_providers=[MyToolProvider()])
See Plugin System for packaging bundles (plugin.json), CLI/TUI management (microharness plugin ..., /plugin), and isolated uv/stdio plugin runtimes.
Evaluators (core/evaluator.py)¶
Implement Evaluator.evaluate(self, env, steps) -> EvalResult or use the built-in graders:
CommandTestEvaluator(command="pytest", expected_exit_code=0, timeout=30.0): Runs a verification command inenvand grades exit code.FileContentEvaluator(file_path, must_contain=..., must_not_contain=...): Verifies file existence and required/forbidden substrings.
Custom Lifecycle Hooks (core/hooks.py)¶
Pass hooks=[...] or a config dict to Harness(...):
from core.hooks import HookContext, HookDecision, POST_TOOL
class AuditHook:
name = "audit_edits"
events = frozenset({POST_TOOL})
def handle(self, ctx: HookContext) -> HookDecision | None:
if ctx.modifies_files and ctx.path:
return HookDecision(message=f"Audit logged edit to {ctx.path}")
return None
Setting block=True (with optional stop_reason) on HookDecision blocks a tool call (pre_tool) or halts execution.