diff --git a/.gitignore b/.gitignore index 279570c..5ffa593 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,10 @@ *.swp *~ +# Example runtime artifacts (audit logs, scratch dirs, etc.) +support-agent-audit.jsonl +/_scratch/ + # Env .env .env.local diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..607aa89 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Chang Sau Sheong + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 15906a3..279da28 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,46 @@ streaming agent loop, tool registry, session storage, compaction, and token budgeting needed to run a multi-provider agent in production. BYO concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins. +> **Status: pre-1.0.** The `runtime` API surface is still being shaped +> — expect breaking changes until a `v0.1.0` tag. + +## Why harness + +If you're building an LLM agent in Go and you find yourself writing +the same things over and over — a streaming think-act loop, parallel +tool dispatch, prompt-cache-stable request building, summarize-and- +splice context compaction, JSONL session storage, MCP-server glue — +that's what harness is. It's the substrate. You bring the tools, the +prompts, and the binary; it brings the loop. + +It is **not** a CLI, a UI, an agent product, or a framework with +opinions about how your agents should be deployed. There is no +`harness` binary. You import packages, compose a `Runtime`, and call +`rt.Run(ctx, msg, nil)`. + +## Requirements + +- **Go 1.25.1 or newer.** The module declares `go 1.25.1` and uses + `iter.Seq` from `iter` (Go 1.23+) plus a few stdlib calls that + hardened in 1.25. Older toolchains will fail at `go build`. +- **An LLM API key**, depending on which provider(s) you wire in: + `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Google ADC for Gemini, or a + Qwen DashScope key. For local models, point `openai.NewOpenAIProviderWithKind` + at an Ollama endpoint — no key required. +- **Optional: an MCP server** for `tools/mcp` integrations (any + binary that speaks the Model Context Protocol — `npx + @modelcontextprotocol/server-filesystem`, etc.). + +## Install + +```bash +go get github.com/sausheong/harness@latest +``` + +The library has no submodules — every package is importable directly. +The `tools/` subpackages are individually importable so you can pull +in only what you need (e.g. `tools/file` without `tools/browser`). + ## Packages ``` @@ -29,20 +69,26 @@ github.com/sausheong/harness/ ├── bash/ # bash (with ExecPolicy: deny | allowlist | full) ├── web/ # web_fetch, web_search, ssrf guard ├── browser/ # chromedp wrapper with per-session reuse + ├── mcp/ # Connect to external MCP servers; adapt their tools └── todo/ # todo_write ``` ## Quick start ```go +package main + import ( "context" + "fmt" + "os" + + "github.com/sausheong/harness/providers/anthropic" "github.com/sausheong/harness/runtime" "github.com/sausheong/harness/session" "github.com/sausheong/harness/tool" - "github.com/sausheong/harness/providers/anthropic" - "github.com/sausheong/harness/tools/file" "github.com/sausheong/harness/tools/bash" + "github.com/sausheong/harness/tools/file" ) func main() { @@ -50,30 +96,85 @@ func main() { reg.Register(&file.ReadFileTool{WorkDir: "/tmp/work"}) reg.Register(&bash.BashTool{WorkDir: "/tmp/work"}) - rt, _ := runtime.New( - runtime.AgentSpec{ - ID: "demo", Name: "Demo", - Model: "claude-haiku-4-5-20251001", - Workspace: "/tmp/work", - SystemPrompt: "You are a helpful coding assistant.", - MaxTurns: 25, + rt, err := runtime.BuildRuntime( + runtime.RuntimeDeps{}, + runtime.RuntimeInputs{ + Provider: anthropic.NewAnthropicProvider(os.Getenv("ANTHROPIC_API_KEY"), ""), + Tools: reg, + Session: session.NewSession("demo", "main"), }, - runtime.Deps{ - LLM: anthropic.New("sk-ant-..."), - Tools: reg, - Session: session.NewSession("demo", "main"), + runtime.AgentSpec{ + ID: "demo", + Name: "Demo", + Model: "anthropic/claude-haiku-4-5-20251001", + Workspace: "/tmp/work", + SystemPrompt: "You are a helpful coding assistant.", + MaxTurns: 25, }, ) + if err != nil { + panic(err) + } + defer rt.Close() // releases MCP sessions if any were declared events, _ := rt.Run(context.Background(), "list files in workspace", nil) for ev := range events { if ev.Type == runtime.EventTextDelta { - print(ev.Text) + fmt.Print(ev.Text) } } } ``` +See [`examples/minimal/`](./examples/minimal) for the runnable +end-to-end version, and [`developer.md`](./developer.md) for +how to plug in hooks, MCP servers, skills, permissions, and more. + +## Examples + +Four end-to-end agents ship in [`examples/`](./examples). Each is a +self-contained `main.go` you can `go run`: + +| Example | What it shows | API surface | +|---|---|---| +| [`minimal/`](./examples/minimal) | Smallest useful agent — file + bash + web tools, REPL, streaming output. ~80 lines. | `tool.Registry`, `session.Session`, `anthropic.NewAnthropicProvider`, `runtime.BuildRuntime` | +| [`data-agent/`](./examples/data-agent) | BYO custom tools (no `tools/*` deps) hitting Singapore's open-data APIs (`data.gov.sg`). Includes a `//go:build live` smoke test. | `tool.Tool` interface for 5 custom HTTP-backed tools | +| [`lta-agent/`](./examples/lta-agent) | Same shape as data-agent, talks to LTA Datamall. Demonstrates `IsConcurrencySafe=true` for parallel HTTP fanout. | Custom tools + parallel dispatch via `MaxToolConcurrency` | +| [`support-agent/`](./examples/support-agent) | Mock customer-support agent showing **`SkillProvider` + `PermissionChecker` + `LifecycleHooks`** wired together. KB articles via `//go:embed`; supervisor-mode gating; JSONL audit log. Closest to a real product. | All of the above, plus `runtime.SkillProvider`, `tool.PermissionChecker`, `runtime.LifecycleHooks` (`AfterToolUse` + `OnStop`) | + +To run any of them: + +```bash +export ANTHROPIC_API_KEY=sk-ant-... +go run ./examples/minimal +go run ./examples/support-agent +# etc. +``` + +The `lta-agent` additionally needs `LTA_DATAMALL_KEY`. The +`support-agent` honours `--supervisor` (or +`SUPPORT_AGENT_SUPERVISOR=1`) to unlock write tools and +`SUPPORT_AGENT_AUDIT_LOG=path/to/audit.jsonl` to redirect the audit +trail. + +## Configuration + +Three environment variables tune the runtime when you don't override +them via `LoopConfig`: + +| Variable | Default | What it controls | +|---|---|---| +| `HARNESS_MAX_TOOL_CONCURRENCY` | `10` | Max parallel tool calls within a concurrency-safe batch | +| `HARNESS_MAX_AGENT_DEPTH` | `3` | Max subagent recursion depth (a child at depth N can spawn at N+1) | +| `HARNESS_STREAMING_TOOLS` | unset (off) | When `"1"`, concurrency-safe tools start executing while the model is still streaming text — latency win for I/O-bound tools | + +`LoopConfig` field values win over env vars when set. Set the field +to its zero value (or omit it) to fall back to env, then to defaults. + +Everything else (provider API keys, model selection, workspace path, +skill paths, etc.) is your config's responsibility — harness reads +none of it. + ## Components A general agent harness has ~13 conceptual components: the loop, the @@ -92,15 +193,13 @@ caller — you own the binary, you own the UI, you own the channel. | 5 | **Context & compaction** | `compaction.Manager` — summarize-and-splice at a clean user-message boundary; tool-result pruning at request time | | 6 | **System prompt assembly** | `llm.SystemPromptPart` — splits the static cacheable prefix from the per-turn dynamic suffix; provider-side `cache_control` placement is automatic | | 7 | **Sub-agents / delegation** | `runtime.SubagentResolver` interface + `MaxAgentDepth=3` cap; subagents run as in-process goroutines with their own `Runtime` | +| 8 | **Hooks** | `runtime.LifecycleHooks` (on `LoopConfig.Hooks`): `OnUserPromptSubmit`, `OnSessionStart`, `BeforeToolUse`, `AfterToolUse`, `OnStop`. Go callbacks — type-safe, in-process, nil-friendly | +| 9 | **MCP** | `tools/mcp` package: `mcp.Connect(ctx, ServerConfig)` adapts an external MCP server's tools as `tool.Tool`s. Declare `AgentSpec.MCPServers` for auto-wiring; `Runtime.Close()` releases sessions | | 10 | **Skills** | `runtime.SkillProvider` (`FormatIndex` + `Get`); auto-registers `load_skill` so the model can pull a skill on demand. See `examples/support-agent/` for a `//go:embed kb/*.md` example | | 11 | **Session persistence** | `session.Session` (in-memory, append-only) + optional `session.Store` for JSONL persistence and cross-process resume | Deliberately not in scope (numbers from the same conceptual list): -- **8 — Hooks**: no PreToolUse/PostToolUse/Stop hooks. If you need - them, wrap the event channel. -- **9 — MCP**: not built in. Register MCP-backed tools manually as - `tool.Tool` implementations. - **12 — UI**: harness emits events; the caller renders. - **13 — Entrypoints**: harness is a library. There is no `harness` binary. The example agents in `examples/` show how a binary is @@ -128,21 +227,102 @@ Deliberately not in scope (numbers from the same conceptual list): envelope; the `` block is stripped before re-injection. - **Plug-points are nil-friendly.** `MemoryProvider`, `KnowledgeGraph`, `SkillProvider`, `SubagentResolver`, - `PermissionChecker`, and `session.Store` are all optional. Pass - `nil` and the corresponding feature disappears with no degraded - behaviour. + `PermissionChecker`, `LifecycleHooks`, and `session.Store` are all + optional. Pass `nil` (or leave the field zero) and the corresponding + feature disappears with no degraded behaviour. +- **Hooks are Go callbacks, not shell scripts.** `LifecycleHooks` + fires `OnUserPromptSubmit` (may rewrite the prompt), + `OnSessionStart`, `BeforeToolUse` (may deny like a + `PermissionChecker`), `AfterToolUse`, and `OnStop` (with reason: + `completed | max_turns | error | aborted`). Hooks run synchronously + on the runtime goroutine — keep them quick. +- **MCP is just another tool source.** `mcp.Connect` returns a + `Client` whose `Tools()` are regular `tool.Tool`s namespaced as + `mcp____`. Either register them yourself or declare + `AgentSpec.MCPServers` and let `BuildRuntime` wire them in. Stdio + (`Command + Args`) and Streamable HTTP (`URL` + optional `Headers` + / `HTTPClient`) are both supported via the official + `github.com/modelcontextprotocol/go-sdk`. For OAuth, pass an + `oauth2.NewClient(ctx, tokenSource)` (or + `clientcredentials.Config.Client(ctx)`) as `HTTPClient` — + auto-refresh comes for free. Call `Runtime.Close()` to release + sessions. - **Four providers, one interface.** Anthropic, OpenAI (and OpenAI-compatible / local Ollama), Gemini, and Qwen ship built-in. Adding a fifth is implementing `llm.Provider` (~300 LOC). See [`developer.md`](./developer.md) for a step-by-step guide to -building agents on top of harness. +building agents on top of harness, including diagrams of the +composition surface and the per-Run loop. + +## Non-goals + +The list of things harness deliberately does **not** do is as much +part of its design as the list of things it does. If you need any of +these, you'll need to bring them yourself or layer them on top: + +- **A binary or CLI.** harness is a library. The `examples/` agents + show how a binary is assembled — pick the one closest to your + shape and copy it. +- **A UI or TUI.** The runtime emits `<-chan AgentEvent`; rendering + is the caller's job. Wire it to stdout, a TUI, a websocket, an + HTTP SSE endpoint, a Slack adapter — whatever you need. +- **Channel adapters.** No WhatsApp / Telegram / Slack / Discord + bridges. Harness doesn't know what a "channel" is — it speaks + `(userMsg, images) → events`. Build the bridge in your own + binary. +- **Hot-reload of MCP servers mid-Run.** MCP servers are connected + at `BuildRuntime` time. To add or replace one, build a new + Runtime. +- **Server-side MCP.** The `tools/mcp` package is client-side only — + it consumes other servers' tools. Exposing harness's tools as an + MCP server for other agents is a future addition, not a current + feature. +- **A skill / plugin marketplace.** Skills are `//go:embed` markdown + in your binary, or whatever your `SkillProvider` resolves at + runtime. There is no central registry. +- **Auth / billing / multi-tenant infrastructure.** Per-agent + policy lives in `PermissionChecker`; everything else is your + problem. +- **Shell-command hooks (Claude Code style).** Hooks are typed Go + callbacks on `LifecycleHooks`, not subprocess invocations. + +## Testing + +```bash +go test ./... # unit tests for every package +go vet ./... # static checks +go build ./... # all packages + examples compile +``` + +Live integration tests (the ones that hit real APIs) are gated +behind the `live` build tag so the default `go test ./...` stays +hermetic: + +```bash +LTA_DATAMALL_KEY=... go test -tags live ./examples/lta-agent/... +``` + +The runtime test suite includes some rare timing-sensitive cases — +if a streaming-tools test flakes once, re-run before treating it as +a real failure. ## Status Pre-1.0. The `runtime` API surface is still being shaped; expect -breaking changes until a v0.1.0 tag. +breaking changes until a `v0.1.0` tag. Specifically: + +- `RuntimeDeps` / `RuntimeInputs` / `AgentSpec` field names may + shift as new optional plug-points land. +- New `LifecycleHooks` callbacks may be added (additive, but watch + for new fields if you construct the struct positionally — use + named fields). +- The `tools/mcp` package's `ServerConfig` may grow new fields for + the MCP-spec OAuth handshake. + +Tagged releases will follow the usual Go module semver discipline +once the v0.x line stabilizes. ## License -MIT. +MIT — see [`LICENSE`](./LICENSE). diff --git a/developer.md b/developer.md index b6bd73f..d12af57 100644 --- a/developer.md +++ b/developer.md @@ -12,37 +12,121 @@ on `github.com/sausheong/harness`. ## 1. Mental model -A harness agent is four things composed together: +There are two views worth holding in your head: **how a Runtime is +composed** (what you assemble at boot) and **what one Run does** (the +think-act loop that fires per user message). + +### Composition: what you wire to build a Runtime + +`runtime.BuildRuntime(deps, inputs, spec)` takes three arguments. The +required pieces are inside `inputs`; everything in `deps` is optional; +`spec` is per-agent config. ``` -┌──────────────────────────────────────────────────────────────────┐ -│ runtime.Runtime │ -│ │ -│ user msg ──► [ provider ] ──► [ tool calls ] ──► assistant │ -│ ▲ ▲ ▲ ▲ │ -│ │ │ │ │ │ -│ └────── Session (history) ───────┘ │ │ -│ │ │ -│ ┌──────────────────────────┘ │ -│ ▼ │ -│ AgentSpec │ -│ (id, model, system prompt, │ -│ max turns, workspace, …) │ -└──────────────────────────────────────────────────────────────────┘ + ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ + │ llm.LLMProvider│ │ *tool.Registry │ │ *session.Session│ + │ (anthropic / │ │ (built-in tools│ │ (in-memory or │ + │ openai / …) │ │ + your own) │ │ JSONL-backed) │ + └────────┬───────┘ └────────┬───────┘ └────────┬───────┘ + │ │ │ + └────────┬──────────┴───────────────────┘ + ▼ + RuntimeInputs ◄── required + │ + │ + RuntimeDeps ────►├◄──── AgentSpec + (optional) │ (id, name, model, + • Skills │ workspace, MaxTurns, + • Memory │ SystemPrompt, + • Permission │ LoopConfig{Hooks…}, + • KGFn │ MCPServers, …) + • LifecycleHooks │ + • Compaction │ + • CalibratorStore │ + ▼ + runtime.BuildRuntime + │ + ▼ + runtime.Runtime + │ + │ events, _ := rt.Run(ctx, userMsg, images) + ▼ + <-chan runtime.AgentEvent + (EventTextDelta, EventToolCallStart, + EventToolResult, EventDone, EventError, EventAborted) ``` -* **`llm.LLMProvider`** — a streaming chat client (Anthropic / OpenAI / - Gemini / Qwen, or your own). -* **`tool.Registry`** — the tools the LLM may invoke. Each tool is a Go - type implementing `tool.Tool`. -* **`session.Session`** — append-only conversation history. In-memory by - default; attach a `*session.Store` to persist as JSONL on disk. -* **`runtime.Runtime`** — the think-act loop. You build one with - `runtime.BuildRuntime(deps, inputs, spec)` and call `rt.Run(ctx, msg, nil)` - to drive a turn. +The four mandatory pieces: -Everything else (Skills, Memory, KnowledgeGraph, Permission, Compaction, -Subagents) is **optional** — pass `nil` and it disappears. +* **`llm.LLMProvider`** (in `RuntimeInputs.Provider`) — a streaming + chat client (Anthropic / OpenAI / Gemini / Qwen, or your own). +* **`tool.Registry`** (in `RuntimeInputs.Tools`) — the tools the LLM + may invoke. Each tool implements `tool.Tool`. +* **`session.Session`** (in `RuntimeInputs.Session`) — append-only + conversation history. In-memory by default; attach a + `*session.Store` to persist as JSONL on disk. +* **`runtime.AgentSpec`** — per-agent identity (id, model, workspace, + system prompt, MaxTurns, LoopConfig, MCPServers). + +Everything in `RuntimeDeps` is optional. Leave a field zero (or pass +`nil`) and the corresponding subsystem disappears. + +### Per-Run: what `rt.Run(ctx, msg, images)` actually does + +``` + userMsg, images + │ + ▼ + ┌──────────────────────────────────────────────────────────────┐ + │ Hooks.OnUserPromptSubmit (may rewrite prompt/images) │ + │ Session.Append(user message) │ + │ Hooks.OnSessionStart │ + │ KG.Recall (optional, ≤800ms cap) │ + └──────────────────────────────────────────────────────────────┘ + │ + ▼ + ┌── for turn := 0; turn < MaxTurns; turn++ ────────────────────┐ + │ │ + │ Provider.ChatStream(messages, system, tools) │ + │ │ │ + │ │ streams text + tool_use blocks │ + │ ▼ │ + │ ┌─────────────────────────────────────────────┐ │ + │ │ emit EventTextDelta as text arrives │ │ + │ │ collect tool_use blocks │ │ + │ │ (StreamingTools? execute concurrency-safe │ │ + │ │ tools BEFORE stream ends) │ │ + │ └─────────────────────────────────────────────┘ │ + │ │ │ + │ ▼ │ + │ no tool calls? ───► emit EventDone, return │ + │ │ │ + │ ▼ tool calls present │ + │ │ + │ partition into concurrency-safe batches │ + │ for each batch (parallel up to MaxToolConcurrency): │ + │ • Hooks.BeforeToolUse (may deny) │ + │ • Permission.Check (may deny) │ + │ • tool.Execute │ + │ • Hooks.AfterToolUse (observe) │ + │ • Session.Append(tool_call + tool_result) │ + │ • emit EventToolResult │ + │ │ + │ loop: feed tool_results back to Provider for next turn │ + │ │ + └──────────────────────────────────────────────────────────────┘ + │ + ▼ + ┌──────────────────────────────────────────────────────────────┐ + │ Hooks.OnStop(reason) │ + │ reason ∈ {completed, max_turns, error, aborted} │ + │ KG.Ingest (deferred-async, optional) │ + │ Compaction.MaybeCompactAsync (if near threshold) │ + └──────────────────────────────────────────────────────────────┘ +``` + +This is what every section in the rest of this guide is hooking into +or extending. --- @@ -407,9 +491,10 @@ runtime relies on that to write paired session entries (especially when ```go type LoopConfig struct { - MaxToolConcurrency int // 0 → env HARNESS_MAX_TOOL_CONCURRENCY → 10 - MaxAgentDepth int // 0 → env HARNESS_MAX_AGENT_DEPTH → 3 - StreamingTools bool // false → env HARNESS_STREAMING_TOOLS=="1" → off + MaxToolConcurrency int // 0 → env HARNESS_MAX_TOOL_CONCURRENCY → 10 + MaxAgentDepth int // 0 → env HARNESS_MAX_AGENT_DEPTH → 3 + StreamingTools bool // false → env HARNESS_STREAMING_TOOLS=="1" → off + Hooks LifecycleHooks // zero value = all hooks disabled } ``` @@ -426,6 +511,10 @@ type LoopConfig struct { executing as soon as the model finishes emitting their call, *while* the model is still streaming text. Latency win for I/O-bound tools; harmless to keep off until you measure that you need it. +* **`Hooks`** — Lifecycle callbacks fired on key events + (user prompt submitted, tool about to run, tool result, run + finished). Use these for audit logging, dynamic gating, prompt + rewriting. See section 10 (`LifecycleHooks`) for the full surface. --- @@ -549,6 +638,205 @@ deps.KGFn = func(model string) runtime.KnowledgeGraph { return &myKG{} } moves on; respect `ctx`. `Ingest` runs deferred-async with `context.Background()`. +### Lifecycle hooks (`runtime.LifecycleHooks`) + +Five callback fields on `LoopConfig.Hooks`. Every field is optional; +zero value disables the hook entirely. Hooks run **synchronously on +the runtime goroutine** — keep them quick, defer heavy work yourself. + +```go +deps.AgentLoop.Hooks = runtime.LifecycleHooks{ + // Rewrite (or reject) the user's message before the loop sees it. + OnUserPromptSubmit: func(ctx context.Context, prompt string, imgs []llm.ImageContent) (string, []llm.ImageContent, error) { + return strings.TrimSpace(prompt), imgs, nil + }, + + // Fires once at Run start, after the user message is appended. + OnSessionStart: func(ctx context.Context, sess *session.Session) { + slog.Info("agent run started", "session", sess.Key) + }, + + // Fires BEFORE PermissionChecker. Returning Allow=false is a + // denial — same shape as a PermissionChecker denial. + BeforeToolUse: func(ctx context.Context, name string, input json.RawMessage) (runtime.HookDecision, error) { + if name == "bash" && businessHoursOnly() && !isBusinessHours() { + return runtime.HookDecision{Allow: false, Reason: "bash disabled outside business hours"}, nil + } + return runtime.HookDecision{Allow: true}, nil + }, + + // Fires AFTER Execute. Observe-only — perfect for audit trails. + AfterToolUse: func(ctx context.Context, name string, input json.RawMessage, res tool.ToolResult) { + auditLog.Record(name, input, res.Error == "") + }, + + // Fires once at Run end. reason ∈ {completed, max_turns, error, aborted}. + OnStop: func(ctx context.Context, reason string) { + metrics.AgentRuns.WithLabelValues(reason).Inc() + }, +} +``` + +Common uses: + +* **Audit logging** — `AfterToolUse` is the right place to write a + durable record of what the agent did. It fires on every tool call, + including denials and errors. +* **Dynamic policy** — `BeforeToolUse` can deny based on runtime + state (time of day, user role, rate limits) that a static + `PermissionChecker` can't express. +* **Prompt sanitization** — `OnUserPromptSubmit` can strip secrets, + expand short-codes, or redact PII before the message reaches the + LLM. The rewritten prompt is what gets persisted to the session. +* **Metrics & tracing** — `OnStop`'s reason argument distinguishes + clean completions from aborts and max-turn timeouts. + +### MCP servers (`AgentSpec.MCPServers` / `tools/mcp`) + +Two ways to wire in an external MCP server. Both produce regular +`tool.Tool`s namespaced as `mcp____`. + +**Declarative — let `BuildRuntime` do it:** + +```go +import "github.com/sausheong/harness/tools/mcp" + +spec := runtime.AgentSpec{ + ID: "demo", Name: "Demo", Model: "anthropic/claude-haiku-4-5-20251001", + MCPServers: []mcp.ServerConfig{ + { + Name: "fs", + Command: "npx", + Args: []string{"-y", "@modelcontextprotocol/server-filesystem", "/tmp"}, + }, + { + Name: "github", + URL: "https://mcp.example.com/github", + }, + }, +} + +rt, err := runtime.BuildRuntime(deps, inputs, spec) +if err != nil { /* connection failure */ } +defer rt.Close() // releases all MCP sessions +``` + +`BuildRuntime` connects each server, lists its tools, registers each +one into the agent's `*tool.Registry`, and stores the client handles +on the Runtime so `Close` can release them. A connection failure on +any server aborts `BuildRuntime` and tears down whatever was already +connected — no half-built state. + +**Imperative — wire it yourself:** + +```go +cli, err := mcp.Connect(ctx, mcp.ServerConfig{ + Name: "fs", Command: "npx", + Args: []string{"-y", "@modelcontextprotocol/server-filesystem", "/tmp"}, +}) +if err != nil { /* … */ } +defer cli.Close() + +for _, t := range cli.Tools() { + reg.Register(t) +} +``` + +Use this when you want full control over registration order, want to +filter the server's tools, or want to keep one MCP client alive +across many `Runtime`s. + +**Streamable HTTP with auth:** + +Most remote MCP servers need a bearer token or API key. `Headers` is +attached to every outgoing request via a RoundTripper wrapper around +`HTTPClient.Transport` — your custom client (mTLS, retries, etc.) +still runs. + +```go +mcp.ServerConfig{ + Name: "github", + URL: "https://mcp.githubmcp.com/v1", + Headers: map[string]string{ + "Authorization": "Bearer " + os.Getenv("GITHUB_MCP_TOKEN"), + "X-Tenant": "acme", + }, + // Optional: full client control. Default is &http.Client{}. + HTTPClient: &http.Client{Timeout: 30 * time.Second}, +} +``` + +The wrapper clones each request before adding headers, so SDK retries +see a clean request and your `Headers` map is read-only at runtime. + +**OAuth with auto-refresh (recommended for production):** + +For OAuth-protected MCP servers, the cleanest path is to use +`golang.org/x/oauth2` to build an `*http.Client` whose transport +handles token refresh automatically, then pass it via `HTTPClient`. +The MCP transport sees a normal `*http.Client`; the oauth2 layer +adds `Authorization: Bearer ` and refreshes when the token +nears expiry. + +Client-credentials (M2M agent — no user in the loop): + +```go +import "golang.org/x/oauth2/clientcredentials" + +cfg := clientcredentials.Config{ + ClientID: os.Getenv("CLIENT_ID"), + ClientSecret: os.Getenv("CLIENT_SECRET"), + TokenURL: "https://auth.example.com/oauth/token", + Scopes: []string{"mcp:read", "mcp:write"}, +} + +mcp.ServerConfig{ + Name: "internal", + URL: "https://mcp.example.com", + HTTPClient: cfg.Client(ctx), // auto-fetches + refreshes +} +``` + +Authorization code with refresh token (you've already done the user +handshake elsewhere and held onto the refresh token): + +```go +import "golang.org/x/oauth2" + +ts := myProvider.TokenSource(ctx, &oauth2.Token{ + AccessToken: accessToken, + RefreshToken: refreshToken, + Expiry: expiry, +}) +mcp.ServerConfig{ + Name: "remote", + URL: "https://mcp.example.com", + HTTPClient: oauth2.NewClient(ctx, ts), +} +``` + +Both keep the OAuth lifecycle out of `tools/mcp` and let the +canonical `golang.org/x/oauth2` package own it. The MCP-spec OAuth +handshake (server-driven discovery + dynamic client registration + +PKCE) is **not** wired through `ServerConfig` today — if you hit a +server that requires it, drop down to the SDK's `auth` / `oauthex` +packages and register tools imperatively. + +A few notes: + +* The official `github.com/modelcontextprotocol/go-sdk` v1.5.0+ is + the underlying transport. Stdio (`Command + Args + Env`) and + Streamable HTTP (`URL` + optional `Headers` / `HTTPClient`) are + both supported; the package picks the right transport from the + fields you set. +* MCP tools default to `IsConcurrencySafe=false` because MCP doesn't + expose a per-tool safety hint. Wrap the adapter if you know a + specific tool is read-only and want it in the parallel batch. +* MCP `IsError` results surface as `tool.ToolResult.Error` so the + agent sees them the same way it sees a harness-native tool error. +* `Runtime.Close()` is idempotent and safe to call when no MCP + servers were declared — useful as a default `defer`. + --- ## 11. Common patterns @@ -625,11 +913,19 @@ func(id string) (runtime.SubagentSpec, bool) { open-data APIs (`data.gov.sg`). Includes a `//go:build live` smoke test showing how to test custom tools against real endpoints without blocking `go test ./...`. +* **`examples/support-agent/`** — `SkillProvider` + `PermissionChecker` + + `LifecycleHooks` (`AfterToolUse` audit trail) all wired into one + agent. Closest pattern to copy if you're building a real product. * **`runtime/types.go`** — every interface a consumer can implement - (`SkillProvider`, `MemoryProvider`, `KnowledgeGraph`, - `SubagentResolver`) is defined here with full doc comments. + (`LifecycleHooks`, `HookDecision`, `SkillProvider`, `MemoryProvider`, + `KnowledgeGraph`, `SubagentResolver`) is defined here with full doc + comments. * **`tool/tool.go`** — the `Tool`, `Executor`, `Registry`, `ToolResult` surface. Read it before writing anything non-trivial. +* **`tools/mcp/`** — the MCP adapter package. `mcp.go` shows the + Connect / Close lifecycle, `adapter.go` shows the + `tool.Tool` ↔ MCP CallTool translation, `mcp_test.go` shows how to + drive it with an in-process MCP server for tests. * **`compaction/compaction.go`** — if you want to understand exactly what triggers a compaction and what survives one. diff --git a/examples/data-agent/main.go b/examples/data-agent/main.go index d8dd297..fae7108 100644 --- a/examples/data-agent/main.go +++ b/examples/data-agent/main.go @@ -98,6 +98,7 @@ Format responses concisely. Round temperatures to 1 decimal. Quote PSI / PM2.5 w fmt.Fprintln(os.Stderr, "build runtime:", err) os.Exit(1) } + defer rt.Close() // no-op here (no MCP), but idiomatic fmt.Println("Singapore Open-Data Assistant — type a question, blank line to exit") fmt.Println("Examples:") diff --git a/examples/lta-agent/main.go b/examples/lta-agent/main.go index 6cc58d5..347949c 100644 --- a/examples/lta-agent/main.go +++ b/examples/lta-agent/main.go @@ -101,6 +101,7 @@ func main() { fmt.Fprintln(os.Stderr, "build runtime:", err) os.Exit(1) } + defer rt.Close() // no-op here (no MCP), but idiomatic fmt.Println("LTA Singapore Transit Assistant — type a question, blank line to exit") fmt.Println("Examples:") diff --git a/examples/minimal/main.go b/examples/minimal/main.go index 6884579..3fa2a5b 100644 --- a/examples/minimal/main.go +++ b/examples/minimal/main.go @@ -80,6 +80,7 @@ func main() { fmt.Fprintln(os.Stderr, "build runtime:", err) os.Exit(1) } + defer rt.Close() // no-op here (no MCP), but idiomatic // 5. REPL loop. in := bufio.NewScanner(os.Stdin) diff --git a/examples/support-agent/audit.go b/examples/support-agent/audit.go new file mode 100644 index 0000000..f83036b --- /dev/null +++ b/examples/support-agent/audit.go @@ -0,0 +1,49 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "sync" + "time" +) + +// auditLog appends one JSON object per line to a file. Used by the +// LifecycleHooks (AfterToolUse + OnStop) to record every tool action +// and run outcome, the way a real compliance-sensitive support +// deployment would. Synchronous, mutex-guarded — fine for an +// interactive REPL with one Run at a time. +type auditLog struct { + mu sync.Mutex + f *os.File +} + +func newAuditLog(path string) (*auditLog, error) { + f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return nil, err + } + return &auditLog{f: f}, nil +} + +// Log writes one JSON record. The record gets a "ts" field stamped +// at write time; callers should not set "ts" themselves. +func (a *auditLog) Log(record map[string]any) { + a.mu.Lock() + defer a.mu.Unlock() + record["ts"] = time.Now().UTC().Format(time.RFC3339Nano) + b, err := json.Marshal(record) + if err != nil { + fmt.Fprintln(os.Stderr, "audit marshal:", err) + return + } + if _, err := a.f.Write(append(b, '\n')); err != nil { + fmt.Fprintln(os.Stderr, "audit write:", err) + } +} + +func (a *auditLog) Close() error { + a.mu.Lock() + defer a.mu.Unlock() + return a.f.Close() +} diff --git a/examples/support-agent/main.go b/examples/support-agent/main.go index 9170a79..4babea1 100644 --- a/examples/support-agent/main.go +++ b/examples/support-agent/main.go @@ -1,4 +1,4 @@ -// Mock customer-support agent — third example demonstrating two harness +// Mock customer-support agent — third example demonstrating three harness // surfaces the previous agents skip: // // - SkillProvider: the knowledge base is exposed as harness "skills". @@ -11,6 +11,11 @@ // read tickets and the KB but cannot mutate state — flip // SUPPORT_AGENT_SUPERVISOR=1 (or pass --supervisor) to unlock. // +// - LifecycleHooks: every tool call (including denials and errors) is +// written to an audit log via AfterToolUse. The OnStop hook records +// the run outcome. This is the pattern any compliance-sensitive +// support deployment will want. +// // Backend is fully in-memory: a few seed tickets are pre-populated. Run: // // export ANTHROPIC_API_KEY=sk-ant-... @@ -28,6 +33,7 @@ package main import ( "bufio" "context" + "encoding/json" "flag" "fmt" "log/slog" @@ -72,11 +78,44 @@ func main() { sess := session.NewSession("support-agent", "main") prov := anthropic.NewAnthropicProvider(apiKey, "") + // LifecycleHooks: write a JSONL audit log of every tool call (with + // outcome) and a record of every Run's stop reason. Compliance- + // sensitive support deployments will want this kind of trail. + auditPath := "support-agent-audit.jsonl" + if v := os.Getenv("SUPPORT_AGENT_AUDIT_LOG"); v != "" { + auditPath = v + } + audit, err := newAuditLog(auditPath) + if err != nil { + fmt.Fprintln(os.Stderr, "open audit log:", err) + os.Exit(1) + } + defer audit.Close() + fmt.Fprintf(os.Stderr, "Auditing tool calls to %s\n", auditPath) + rt, err := runtime.BuildRuntime( runtime.RuntimeDeps{ AgentLoop: runtime.LoopConfig{ MaxToolConcurrency: 3, MaxAgentDepth: 1, + Hooks: runtime.LifecycleHooks{ + AfterToolUse: func(_ context.Context, name string, input json.RawMessage, res tool.ToolResult) { + audit.Log(map[string]any{ + "kind": "tool", + "name": name, + "input": json.RawMessage(input), + "ok": res.Error == "", + "error": res.Error, + "outchars": len(res.Output), + }) + }, + OnStop: func(_ context.Context, reason string) { + audit.Log(map[string]any{ + "kind": "run_end", + "reason": reason, + }) + }, + }, }, // SkillProvider: contributes a KB index to the static system // prompt and backs the auto-registered load_skill tool. @@ -124,6 +163,7 @@ Tone: fmt.Fprintln(os.Stderr, "build runtime:", err) os.Exit(1) } + defer rt.Close() // no-op here (no MCP), but idiomatic mode := "agent mode" if supervisor { diff --git a/go.mod b/go.mod index fdeb625..005a829 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/anthropics/anthropic-sdk-go v1.35.0 github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 github.com/chromedp/chromedp v0.14.2 + github.com/modelcontextprotocol/go-sdk v1.5.0 github.com/sashabaranov/go-openai v1.41.2 github.com/stretchr/testify v1.11.1 go.opentelemetry.io/otel v1.43.0 @@ -28,18 +29,23 @@ require ( github.com/gobwas/ws v1.4.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/google/go-cmp v0.7.0 // indirect + github.com/google/jsonschema-go v0.4.2 // indirect github.com/google/s2a-go v0.1.8 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect github.com/gorilla/websocket v1.5.3 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/segmentio/asm v1.1.3 // indirect + github.com/segmentio/encoding v0.5.4 // indirect github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect github.com/tidwall/sjson v1.2.5 // indirect + github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.opencensus.io v0.24.0 // indirect go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect golang.org/x/crypto v0.49.0 // indirect golang.org/x/net v0.52.0 // indirect + golang.org/x/oauth2 v0.35.0 // indirect golang.org/x/sync v0.20.0 // indirect golang.org/x/sys v0.42.0 // indirect golang.org/x/text v0.35.0 // indirect diff --git a/go.sum b/go.sum index cedcfdf..b34fd64 100644 --- a/go.sum +++ b/go.sum @@ -44,6 +44,8 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs= github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= @@ -68,6 +70,8 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8= +github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE= github.com/google/s2a-go v0.1.8 h1:zZDs9gcbt9ZPLV0ndSyQk6Kacx2g/X+SKYovpnz3SMM= github.com/google/s2a-go v0.1.8/go.mod h1:6iNWHTpQ+nfNRN5E00MSdfDwVesa8hhS32PhPO8deJA= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -79,6 +83,8 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo= github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs= +github.com/modelcontextprotocol/go-sdk v1.5.0 h1:CHU0FIX9kpueNkxuYtfYQn1Z0slhFzBZuq+x6IiblIU= +github.com/modelcontextprotocol/go-sdk v1.5.0/go.mod h1:gggDIhoemhWs3BGkGwd1umzEXCEMMvAnhTrnbXJKKKA= github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw= github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -88,6 +94,10 @@ github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TV github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg= github.com/sebdah/goldie/v2 v2.8.0 h1:dZb9wR8q5++oplmEiJT+U/5KyotVD+HNGCAc5gNr8rc= github.com/sebdah/goldie/v2 v2.8.0/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI= +github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= +github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= +github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= +github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -108,6 +118,8 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= +github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA= github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= @@ -141,6 +153,8 @@ golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= +golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -162,6 +176,8 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= +golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= diff --git a/runtime/builder.go b/runtime/builder.go index 19d8cfd..4860e39 100644 --- a/runtime/builder.go +++ b/runtime/builder.go @@ -1,6 +1,8 @@ package runtime import ( + "context" + "fmt" "log/slog" "github.com/sausheong/harness/compaction" @@ -8,6 +10,7 @@ import ( "github.com/sausheong/harness/session" "github.com/sausheong/harness/tokens" "github.com/sausheong/harness/tool" + "github.com/sausheong/harness/tools/mcp" ) // RuntimeDeps holds the long-lived dependencies that every Runtime in this @@ -87,6 +90,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt // *tool.Registry rather than widening tool.Executor — production // callers always pass *tool.Registry; test paths that don't won't // get load tools registered (which is fine for them). + var mcpClients []*mcp.Client if reg, ok := inputs.Tools.(*tool.Registry); ok { if deps.Skills != nil { skills := deps.Skills @@ -104,6 +108,24 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt }, }) } + // Connect declared MCP servers and register their adapter tools. + // On any failure, close everything connected so far before + // returning — a partially-built Runtime would leak processes. + for _, srv := range spec.MCPServers { + cli, err := mcp.Connect(context.Background(), srv) + if err != nil { + for _, c := range mcpClients { + _ = c.Close() + } + return nil, fmt.Errorf("mcp server %q: %w", srv.Name, err) + } + for _, t := range cli.Tools() { + reg.Register(t) + } + mcpClients = append(mcpClients, cli) + } + } else if len(spec.MCPServers) > 0 { + return nil, fmt.Errorf("AgentSpec.MCPServers requires inputs.Tools to be *tool.Registry") } // Pre-compute the static portion of the system prompt so the per-turn @@ -167,6 +189,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt AgentLoop: deps.AgentLoop, StaticSystemPrompt: staticPrompt, CalibratorStore: deps.CalibratorStore, + mcpClients: mcpClients, } // Seed the calibrator from prior (ratio, count) for this session so a diff --git a/runtime/builder_test.go b/runtime/builder_test.go index 515e5eb..c9d6128 100644 --- a/runtime/builder_test.go +++ b/runtime/builder_test.go @@ -3,6 +3,9 @@ package runtime import ( "testing" + "github.com/sausheong/harness/tool" + "github.com/sausheong/harness/tools/mcp" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -51,3 +54,49 @@ func TestBuildRuntimeUsesCallerProvidedMemoryFiles(t *testing.T) { require.Contains(t, rt.StaticSystemPrompt, sentinel) require.Contains(t, rt.StaticSystemPrompt, "## Project memory:") } + +// TestBuildRuntime_MCPServers_BadConfigErrors confirms BuildRuntime +// surfaces MCP connection failures (here: invalid empty ServerConfig) +// rather than returning a partially-built Runtime. +func TestBuildRuntime_MCPServers_BadConfigErrors(t *testing.T) { + reg := tool.NewRegistry() + rt, err := BuildRuntime( + RuntimeDeps{}, + RuntimeInputs{Tools: reg}, + AgentSpec{ + ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5", + MCPServers: []mcp.ServerConfig{{Name: ""}}, // invalid: name missing + }, + ) + require.Error(t, err) + assert.Nil(t, rt) + assert.Contains(t, err.Error(), "mcp server") +} + +// TestBuildRuntime_MCPServers_RequiresRegistry confirms that declaring +// MCPServers when inputs.Tools is not a *tool.Registry is a clean error +// rather than a silent no-op. +func TestBuildRuntime_MCPServers_RequiresRegistry(t *testing.T) { + rt, err := BuildRuntime( + RuntimeDeps{}, + RuntimeInputs{Tools: nil}, // not a *tool.Registry + AgentSpec{ + ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5", + MCPServers: []mcp.ServerConfig{{Name: "x", Command: "true"}}, + }, + ) + require.Error(t, err) + assert.Nil(t, rt) + assert.Contains(t, err.Error(), "*tool.Registry") +} + +// TestRuntime_Close_NoOpWithoutMCP confirms Close on a runtime with no +// MCP clients is a safe no-op (returns nil, doesn't panic). +func TestRuntime_Close_NoOpWithoutMCP(t *testing.T) { + rt, err := BuildRuntime(RuntimeDeps{}, RuntimeInputs{}, AgentSpec{ + ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5", + }) + require.NoError(t, err) + assert.NoError(t, rt.Close()) + assert.NoError(t, rt.Close(), "second Close must also be a no-op") +} diff --git a/runtime/hooks_test.go b/runtime/hooks_test.go new file mode 100644 index 0000000..0395598 --- /dev/null +++ b/runtime/hooks_test.go @@ -0,0 +1,346 @@ +package runtime + +import ( + "context" + "encoding/json" + "errors" + "sync/atomic" + "testing" + + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/session" + "github.com/sausheong/harness/tool" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// hookFixture builds a Runtime wired to a mock LLM that emits the given +// canned event stream. Returns the Runtime and the session so tests can +// assert on session entries. +func hookFixture(t *testing.T, hooks LifecycleHooks, events []llm.ChatEvent, reg *tool.Registry) *Runtime { + t.Helper() + if reg == nil { + reg = tool.NewRegistry() + } + return &Runtime{ + LLM: &mockLLMProvider{events: events}, + Tools: reg, + Session: session.NewSession("test-agent", "test-key"), + Model: "mock-model", + Workspace: t.TempDir(), + MaxTurns: 3, + AgentLoop: LoopConfig{Hooks: hooks}, + } +} + +// drainEvents consumes the channel and returns any error events seen. +func drainEvents(t *testing.T, events <-chan AgentEvent) { + t.Helper() + for e := range events { + if e.Type == EventError { + t.Fatalf("unexpected error: %v", e.Error) + } + } +} + +func TestHook_OnSessionStart_FiresOnce(t *testing.T) { + var fires int32 + var sawSession *session.Session + hooks := LifecycleHooks{ + OnSessionStart: func(_ context.Context, s *session.Session) { + atomic.AddInt32(&fires, 1) + sawSession = s + }, + } + rt := hookFixture(t, hooks, []llm.ChatEvent{ + {Type: llm.EventTextDelta, Text: "hi"}, + {Type: llm.EventDone}, + }, nil) + + events, err := rt.Run(context.Background(), "ping", nil) + require.NoError(t, err) + drainEvents(t, events) + + assert.Equal(t, int32(1), atomic.LoadInt32(&fires)) + assert.Same(t, rt.Session, sawSession, "hook receives the runtime's own session") +} + +func TestHook_OnUserPromptSubmit_RewritesPrompt(t *testing.T) { + hooks := LifecycleHooks{ + OnUserPromptSubmit: func(_ context.Context, prompt string, imgs []llm.ImageContent) (string, []llm.ImageContent, error) { + return "REWRITTEN: " + prompt, imgs, nil + }, + } + rt := hookFixture(t, hooks, []llm.ChatEvent{ + {Type: llm.EventTextDelta, Text: "ok"}, + {Type: llm.EventDone}, + }, nil) + + events, err := rt.Run(context.Background(), "original", nil) + require.NoError(t, err) + drainEvents(t, events) + + // First session entry is the user message — assert the rewritten one + // landed there. + view := rt.Session.View() + require.NotEmpty(t, view) + first := view[0] + require.Equal(t, session.EntryTypeMessage, first.Type) + require.Equal(t, "user", first.Role) + var md session.MessageData + require.NoError(t, json.Unmarshal(first.Data, &md)) + assert.Equal(t, "REWRITTEN: original", md.Text) +} + +func TestHook_OnUserPromptSubmit_ErrorAbortsRun(t *testing.T) { + hooks := LifecycleHooks{ + OnUserPromptSubmit: func(_ context.Context, _ string, _ []llm.ImageContent) (string, []llm.ImageContent, error) { + return "", nil, errors.New("rejected") + }, + } + rt := hookFixture(t, hooks, []llm.ChatEvent{{Type: llm.EventDone}}, nil) + + events, err := rt.Run(context.Background(), "x", nil) + require.NoError(t, err) + + var sawError bool + for e := range events { + if e.Type == EventError { + sawError = true + require.Error(t, e.Error) + assert.Contains(t, e.Error.Error(), "rejected") + } + } + assert.True(t, sawError, "expected EventError when OnUserPromptSubmit returns err") +} + +func TestHook_BeforeToolUse_DenialBlocksExecute(t *testing.T) { + var executed int32 + reg := tool.NewRegistry() + reg.Register(&countingTool{name: "noop", executed: &executed}) + + callCount := 0 + llmMock := &statefulMockLLMProvider{ + responses: [][]llm.ChatEvent{ + { + {Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ + ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`), + }}, + {Type: llm.EventDone}, + }, + {{Type: llm.EventTextDelta, Text: "after"}, {Type: llm.EventDone}}, + }, + callCount: &callCount, + } + + hooks := LifecycleHooks{ + BeforeToolUse: func(_ context.Context, name string, _ json.RawMessage) (HookDecision, error) { + return HookDecision{Allow: false, Reason: "policy: " + name + " forbidden"}, nil + }, + } + rt := &Runtime{ + LLM: llmMock, + Tools: reg, + Session: session.NewSession("a", "k"), + Model: "m", + Workspace: t.TempDir(), + MaxTurns: 3, + AgentLoop: LoopConfig{Hooks: hooks}, + } + events, err := rt.Run(context.Background(), "go", nil) + require.NoError(t, err) + drainEvents(t, events) + + assert.Equal(t, int32(0), atomic.LoadInt32(&executed), + "tool Execute must not run when BeforeToolUse denies") + + // Walk the session for the tool_result entry — it should carry the + // denial reason. + var foundDenial bool + for _, e := range rt.Session.View() { + if e.Type != session.EntryTypeToolResult { + continue + } + var tr session.ToolResultData + require.NoError(t, json.Unmarshal(e.Data, &tr)) + if tr.Error == "policy: noop forbidden" { + foundDenial = true + break + } + } + assert.True(t, foundDenial, "denial reason must surface in the tool_result entry") +} + +func TestHook_BeforeToolUse_AllowsThroughToPermission(t *testing.T) { + var executed int32 + reg := tool.NewRegistry() + reg.Register(&countingTool{name: "noop", executed: &executed}) + + callCount := 0 + llmMock := &statefulMockLLMProvider{ + responses: [][]llm.ChatEvent{ + { + {Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ + ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`), + }}, + {Type: llm.EventDone}, + }, + {{Type: llm.EventTextDelta, Text: "done"}, {Type: llm.EventDone}}, + }, + callCount: &callCount, + } + + var permissionConsulted int32 + perm := &countingPermission{calls: &permissionConsulted} + + hooks := LifecycleHooks{ + BeforeToolUse: func(_ context.Context, _ string, _ json.RawMessage) (HookDecision, error) { + return HookDecision{Allow: true}, nil + }, + } + rt := &Runtime{ + LLM: llmMock, + Tools: reg, + Session: session.NewSession("a", "k"), + Model: "m", + Workspace: t.TempDir(), + MaxTurns: 3, + Permission: perm, + AgentLoop: LoopConfig{Hooks: hooks}, + } + + events, err := rt.Run(context.Background(), "go", nil) + require.NoError(t, err) + drainEvents(t, events) + + assert.Equal(t, int32(1), atomic.LoadInt32(&permissionConsulted), + "PermissionChecker.Check must still run when BeforeToolUse allows") + assert.Equal(t, int32(1), atomic.LoadInt32(&executed), + "tool must execute when both BeforeToolUse and PermissionChecker allow") +} + +func TestHook_AfterToolUse_ObservesResult(t *testing.T) { + reg := tool.NewRegistry() + reg.Register(&mockTool{name: "noop", output: "tool-said-this"}) + + callCount := 0 + llmMock := &statefulMockLLMProvider{ + responses: [][]llm.ChatEvent{ + { + {Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ + ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`), + }}, + {Type: llm.EventDone}, + }, + {{Type: llm.EventTextDelta, Text: "fin"}, {Type: llm.EventDone}}, + }, + callCount: &callCount, + } + + var capturedName string + var capturedOutput string + hooks := LifecycleHooks{ + AfterToolUse: func(_ context.Context, name string, _ json.RawMessage, res tool.ToolResult) { + capturedName = name + capturedOutput = res.Output + }, + } + rt := &Runtime{ + LLM: llmMock, + Tools: reg, + Session: session.NewSession("a", "k"), + Model: "m", + Workspace: t.TempDir(), + MaxTurns: 3, + AgentLoop: LoopConfig{Hooks: hooks}, + } + + events, err := rt.Run(context.Background(), "go", nil) + require.NoError(t, err) + drainEvents(t, events) + + assert.Equal(t, "noop", capturedName) + assert.Equal(t, "tool-said-this", capturedOutput) +} + +func TestHook_OnStop_FiresWithCompletedReason(t *testing.T) { + var captured string + hooks := LifecycleHooks{ + OnStop: func(_ context.Context, reason string) { captured = reason }, + } + rt := hookFixture(t, hooks, []llm.ChatEvent{ + {Type: llm.EventTextDelta, Text: "hi"}, + {Type: llm.EventDone}, + }, nil) + + events, err := rt.Run(context.Background(), "ping", nil) + require.NoError(t, err) + drainEvents(t, events) + + assert.Equal(t, "completed", captured) +} + +func TestHook_OnStop_FiresWithAbortedReason(t *testing.T) { + var captured string + hooks := LifecycleHooks{ + OnStop: func(_ context.Context, reason string) { captured = reason }, + } + // Cancel ctx before Run starts → first turn's ctx.Err() check trips + // immediately and we emit Aborted. + rt := hookFixture(t, hooks, []llm.ChatEvent{{Type: llm.EventDone}}, nil) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + events, err := rt.Run(ctx, "ping", nil) + require.NoError(t, err) + for range events { + } + + assert.Equal(t, "aborted", captured) +} + +func TestHook_NilHooks_NoChange(t *testing.T) { + // Sanity: zero LifecycleHooks behaves identically to current behavior. + rt := hookFixture(t, LifecycleHooks{}, []llm.ChatEvent{ + {Type: llm.EventTextDelta, Text: "hello"}, + {Type: llm.EventDone}, + }, nil) + events, err := rt.Run(context.Background(), "x", nil) + require.NoError(t, err) + var got string + for e := range events { + if e.Type == EventTextDelta { + got += e.Text + } + } + assert.Equal(t, "hello", got) +} + +// --- test fixtures --- + +type countingTool struct { + name string + executed *int32 +} + +func (t *countingTool) Name() string { return t.name } +func (t *countingTool) Description() string { return "counting" } +func (t *countingTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) } +func (t *countingTool) IsConcurrencySafe(_ json.RawMessage) bool { return false } +func (t *countingTool) Execute(_ context.Context, _ json.RawMessage) (tool.ToolResult, error) { + atomic.AddInt32(t.executed, 1) + return tool.ToolResult{Output: "ok"}, nil +} + +type countingPermission struct { + calls *int32 +} + +func (p *countingPermission) Check(_ context.Context, _, _ string, _ json.RawMessage) tool.Decision { + atomic.AddInt32(p.calls, 1) + return tool.Decision{Behavior: tool.DecisionAllow} +} + +func (p *countingPermission) FilterToolDefs(defs []llm.ToolDef, _ string) []llm.ToolDef { + return defs +} diff --git a/runtime/runtime.go b/runtime/runtime.go index b859043..b18c8ba 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -15,6 +15,7 @@ import ( "github.com/sausheong/harness/session" "github.com/sausheong/harness/tokens" "github.com/sausheong/harness/tool" + "github.com/sausheong/harness/tools/mcp" ) // EventType identifies the kind of agent event. @@ -112,6 +113,28 @@ type Runtime struct { CalibratorStore *tokens.CalibratorStore calibrator *tokens.Calibrator + + // mcpClients holds the MCP client sessions resolved from + // AgentSpec.MCPServers. Released by Close. Untouched when MCP is + // not used. + mcpClients []*mcp.Client +} + +// Close releases external resources owned by the Runtime — currently +// just the MCP client sessions resolved from AgentSpec.MCPServers. +// Optional: callers who never use MCP can skip it. Safe to call +// multiple times; safe to call before or after Run completes. +// Returns the first Close error encountered, if any; remaining +// clients are still closed. +func (r *Runtime) Close() error { + var firstErr error + for _, c := range r.mcpClients { + if err := c.Close(); err != nil && firstErr == nil { + firstErr = err + } + } + r.mcpClients = nil + return firstErr } // emit sends ev to this runtime's events channel and forwards a copy to @@ -219,6 +242,28 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon defer close(r.events) defer tr.Summary() + // stopReason is read by the OnStop deferred hook below. Each early + // return path reassigns it before returning. Default is "max_turns" + // so the natural fall-through (loop exhausted MaxTurns) records the + // right reason without an explicit assignment at that exit. + stopReason := "max_turns" + if hook := r.AgentLoop.Hooks.OnStop; hook != nil { + defer func() { hook(ctx, stopReason) }() + } + + // OnUserPromptSubmit may rewrite prompt and/or images BEFORE the + // session sees them. Returning err aborts Run with EventError. + if hook := r.AgentLoop.Hooks.OnUserPromptSubmit; hook != nil { + newMsg, newImgs, err := hook(ctx, userMsg, images) + if err != nil { + stopReason = "error" + r.emit(AgentEvent{Type: EventError, Error: err}) + return + } + userMsg = newMsg + images = newImgs + } + if len(images) > 0 { var imgData []session.ImageData for _, img := range images { @@ -232,6 +277,10 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon r.Session.Append(session.UserMessageEntry(userMsg)) } + if hook := r.AgentLoop.Hooks.OnSessionStart; hook != nil { + hook(ctx, r.Session) + } + // Initialise KG thread and recall (once, before the loop). Recall // runs in a background goroutine so it overlaps with message // assembly. The main goroutine waits for it (with an 800ms cap) @@ -279,6 +328,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon for turn := 0; turn < maxTurns; turn++ { if ctx.Err() != nil { + stopReason = "aborted" r.emit(AgentEvent{Type: EventAborted}) return } @@ -418,6 +468,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon stream, err = r.LLM.ChatStream(ctx, req) } if err != nil { + stopReason = "error" r.emit(AgentEvent{Type: EventError, Error: fmt.Errorf("llm error: %w", err)}) return } @@ -501,6 +552,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon kickoffStopped = false nsStream, retryErr := ns.ChatNonStreaming(ctx, req) if retryErr != nil { + stopReason = "error" r.emit(AgentEvent{Type: EventError, Error: retryErr}) return } @@ -510,6 +562,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon } } drainKickoffs(kickoffs) + stopReason = "error" r.emit(AgentEvent{Type: EventError, Error: event.Error}) return } @@ -538,6 +591,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon drainKickoffs(kickoffs) } tr.Mark("agent.done", "turn", turn, "reason", "no_tool_calls") + stopReason = "completed" r.emit(AgentEvent{Type: EventDone, Usage: lastUsage}) r.maybeKickoffAsyncCompaction(msgs, parts, toolDefs) return @@ -584,6 +638,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon r.kgMu.Unlock() } } + stopReason = "aborted" r.emit(AgentEvent{Type: EventAborted}) return } @@ -606,12 +661,15 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon batches := partitionToolCalls(pending, r.Tools) for _, b := range batches { if r.runBatch(ctx, b, kgThreadOrNil(r.KG, &thread), turn, tr) { + stopReason = "aborted" r.emit(AgentEvent{Type: EventAborted}) return } } } + // stopReason already "max_turns" by default — fall through to + // the EventError below records "agent exceeded maximum turns". r.emit(AgentEvent{ Type: EventError, Error: fmt.Errorf("agent exceeded maximum turns (%d)", maxTurns), @@ -660,9 +718,33 @@ func (r *Runtime) dispatchTool( r.kgMu.Unlock() } + // BeforeToolUse fires before the PermissionChecker. A hook denial + // has the same observable shape as a Permission.Check denial. + if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil { + d, err := hook(ctx, tc.Name, tc.Input) + if err != nil { + res := r.appendDenialResult(tc.ID, err.Error(), kgThread) + if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { + after(ctx, tc.Name, tc.Input, res) + } + return res, false + } + if !d.Allow { + res := r.appendDenialResult(tc.ID, d.Reason, kgThread) + if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { + after(ctx, tc.Name, tc.Input, res) + } + return res, false + } + } + if r.Permission != nil { if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny { - return r.appendDenialResult(tc.ID, d.Reason, kgThread), false + res := r.appendDenialResult(tc.ID, d.Reason, kgThread) + if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { + after(ctx, tc.Name, tc.Input, res) + } + return res, false } } @@ -695,6 +777,10 @@ func (r *Runtime) dispatchTool( r.recordFileTouch(extractPathFromInput(tc.Input)) } + if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil { + hook(ctx, tc.Name, tc.Input, result) + } + return result, false } @@ -702,9 +788,30 @@ func (r *Runtime) dispatchTool( // Execute call WITHOUT touching session or KG thread. Used by the // streaming kickoff goroutines. func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (result tool.ToolResult, aborted bool) { + if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil { + d, err := hook(ctx, tc.Name, tc.Input) + if err != nil { + res := tool.ToolResult{Error: err.Error()} + if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { + after(ctx, tc.Name, tc.Input, res) + } + return res, false + } + if !d.Allow { + res := tool.ToolResult{Error: d.Reason} + if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { + after(ctx, tc.Name, tc.Input, res) + } + return res, false + } + } if r.Permission != nil { if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny { - return tool.ToolResult{Error: d.Reason}, false + res := tool.ToolResult{Error: d.Reason} + if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { + after(ctx, tc.Name, tc.Input, res) + } + return res, false } } if ctx.Err() != nil { @@ -720,6 +827,9 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu if result.Error == "" && isFileTool(tc.Name) { r.recordFileTouch(extractPathFromInput(tc.Input)) } + if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil { + hook(ctx, tc.Name, tc.Input, result) + } return result, false } diff --git a/runtime/types.go b/runtime/types.go index b7cf00f..10c997f 100644 --- a/runtime/types.go +++ b/runtime/types.go @@ -1,6 +1,14 @@ package runtime -import "context" +import ( + "context" + "encoding/json" + + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/session" + "github.com/sausheong/harness/tool" + "github.com/sausheong/harness/tools/mcp" +) // AgentSpec is the framework's view of an agent. Consumers convert their // own agent-config types into this struct before invoking BuildRuntime. @@ -42,6 +50,11 @@ type AgentSpec struct { // cap, depth cap, streaming-tools toggle). Zero value ⇒ env-var // fallback then compiled-in defaults. Loop LoopConfig + // MCPServers, when non-empty, are connected by BuildRuntime: each + // server's tools are namespaced ("mcp____") and added + // to the agent's tool registry. Runtime.Close releases the + // underlying sessions. Connection failures abort BuildRuntime. + MCPServers []mcp.ServerConfig } // LoopConfig tunes the agent runtime's tool-execution behavior. Each @@ -58,6 +71,53 @@ type LoopConfig struct { // StreamingTools enables mid-stream concurrency-safe tool kickoff. // false ⇒ env fallback (HARNESS_STREAMING_TOOLS=1) then off. StreamingTools bool + // Hooks are optional callbacks the runtime fires at well-known + // points in the loop. Zero value (all nil fields) disables every + // hook with no overhead. + Hooks LifecycleHooks +} + +// HookDecision is the outcome of a BeforeToolUse hook. Mirrors +// tool.Decision so callers familiar with PermissionChecker get a +// consistent shape: Allow=true permits the call to continue (still +// subject to PermissionChecker); Allow=false denies it with Reason +// surfaced as the tool result error. +type HookDecision struct { + Allow bool + Reason string +} + +// LifecycleHooks bundles optional callbacks the runtime fires at +// well-known points. All fields are nil-safe — leave a field nil and +// that hook is skipped. Hooks run synchronously on the runtime +// goroutine; expensive work should be deferred by the implementation. +type LifecycleHooks struct { + // OnUserPromptSubmit fires once at the top of Run, BEFORE the + // user message is appended to the session. The hook may rewrite + // the prompt and/or images; the rewritten values are what the + // session and the LLM see. Returning err != nil aborts Run with + // EventError. + OnUserPromptSubmit func(ctx context.Context, prompt string, images []llm.ImageContent) (string, []llm.ImageContent, error) + + // OnSessionStart fires once at the top of Run, AFTER the user + // message is appended to the session. Observe-only. + OnSessionStart func(ctx context.Context, sess *session.Session) + + // BeforeToolUse fires inside dispatchTool / executeToolKickoff + // BEFORE PermissionChecker. Returning Allow=false denies the call + // with the given Reason (same shape as a PermissionChecker + // denial). Returning err != nil treats the call as a denial with + // err.Error() as the reason. nil → no-op (call proceeds). + BeforeToolUse func(ctx context.Context, toolName string, input json.RawMessage) (HookDecision, error) + + // AfterToolUse fires after the tool's Execute returns (including + // on error or denial). Observe-only — no result rewrite. + AfterToolUse func(ctx context.Context, toolName string, input json.RawMessage, result tool.ToolResult) + + // OnStop fires exactly once at the end of Run, regardless of + // outcome. reason is one of: "completed", "max_turns", "error", + // "aborted". Observe-only. + OnStop func(ctx context.Context, reason string) } // SkillProvider lets the runtime advertise the available skills in the diff --git a/tools/mcp/adapter.go b/tools/mcp/adapter.go new file mode 100644 index 0000000..1faa916 --- /dev/null +++ b/tools/mcp/adapter.go @@ -0,0 +1,114 @@ +package mcp + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + sdk "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/tool" +) + +// mcpToolAdapter implements tool.Tool by delegating Execute to an MCP +// session's CallTool. Constructed by Client.Connect via discoverTools. +type mcpToolAdapter struct { + serverName string + sdkTool *sdk.Tool + session *sdk.ClientSession +} + +// Name returns "mcp____". The double-underscore +// namespacing matches Claude Code so the LLM treats these tools the +// same way it would in CC and so they can't collide with built-in +// harness tools. +func (a *mcpToolAdapter) Name() string { + return "mcp__" + a.serverName + "__" + a.sdkTool.Name +} + +func (a *mcpToolAdapter) Description() string { return a.sdkTool.Description } + +// Parameters returns the server-supplied JSON Schema. SDK leaves +// InputSchema as `any`; we marshal it. If the schema fails to marshal +// (vanishingly unlikely — server-supplied JSON), we return an empty +// object schema so the LLM still sees the tool as callable. +func (a *mcpToolAdapter) Parameters() json.RawMessage { + if a.sdkTool.InputSchema == nil { + return json.RawMessage(`{"type":"object"}`) + } + b, err := json.Marshal(a.sdkTool.InputSchema) + if err != nil { + return json.RawMessage(`{"type":"object"}`) + } + return b +} + +// IsConcurrencySafe reports false — MCP doesn't expose a safety hint +// per tool, and the only safe default for arbitrary external code is +// "no". Callers who know a specific MCP tool is read-only can wrap the +// adapter to override this. +func (a *mcpToolAdapter) IsConcurrencySafe(_ json.RawMessage) bool { return false } + +// Execute marshals input into the MCP CallTool payload, invokes the +// server, and translates the response back into a tool.ToolResult. +// +// MCP's tool-error model differs from harness's: +// - Protocol errors (transport, schema validation) → returned as Go +// error, surfaced to the runtime as a tool result with Error set. +// - Tool errors (CallToolResult.IsError=true) → also surfaced as +// ToolResult.Error so the agent sees them the same way it sees a +// harness-native tool error. +func (a *mcpToolAdapter) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) { + var args any + if len(input) > 0 { + if err := json.Unmarshal(input, &args); err != nil { + return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil + } + } + res, err := a.session.CallTool(ctx, &sdk.CallToolParams{ + Name: a.sdkTool.Name, + Arguments: args, + }) + if err != nil { + return tool.ToolResult{Error: err.Error()}, nil + } + return mcpResultToToolResult(res), nil +} + +// mcpResultToToolResult flattens MCP content blocks into a harness +// ToolResult: TextContent concatenated into Output (or Error if +// IsError), ImageContent collected into Images. Other content types +// (audio, embedded resources) are described in Output as a placeholder. +func mcpResultToToolResult(res *sdk.CallToolResult) tool.ToolResult { + var text strings.Builder + var images []llm.ImageContent + for _, c := range res.Content { + switch v := c.(type) { + case *sdk.TextContent: + if text.Len() > 0 { + text.WriteByte('\n') + } + text.WriteString(v.Text) + case *sdk.ImageContent: + images = append(images, llm.ImageContent{ + MimeType: v.MIMEType, + Data: v.Data, + }) + default: + // Unknown content type — note it so the agent isn't silently + // missing data. + if text.Len() > 0 { + text.WriteByte('\n') + } + fmt.Fprintf(&text, "[unsupported MCP content: %T]", c) + } + } + out := tool.ToolResult{Images: images} + if res.IsError { + out.Error = text.String() + } else { + out.Output = text.String() + } + return out +} diff --git a/tools/mcp/mcp.go b/tools/mcp/mcp.go new file mode 100644 index 0000000..f812a12 --- /dev/null +++ b/tools/mcp/mcp.go @@ -0,0 +1,247 @@ +// Package mcp adapts an external Model Context Protocol (MCP) server's +// tools into harness tool.Tool implementations. +// +// Typical usage: +// +// cli, err := mcp.Connect(ctx, mcp.ServerConfig{ +// Name: "fs", +// Command: "npx", +// Args: []string{"-y", "@modelcontextprotocol/server-filesystem", "/tmp"}, +// }) +// if err != nil { ... } +// defer cli.Close() +// for _, t := range cli.Tools() { +// reg.Register(t) +// } +// +// For declarative wiring, set runtime.AgentSpec.MCPServers — the runtime +// builder will Connect each server, register its tools into the agent's +// registry, and tear them down via Runtime.Close. +package mcp + +import ( + "context" + "fmt" + "net/http" + "os" + "os/exec" + + sdk "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/sausheong/harness/tool" +) + +// ServerConfig describes one MCP server to connect to. Exactly one +// transport must be specified: Command (stdio, the most common) or URL +// (Streamable HTTP via the SDK's StreamableClientTransport). +type ServerConfig struct { + // Name namespaces the server's tools. Adapter tool names become + // "mcp____", matching Claude Code's convention so the + // LLM treats them the same way. + Name string + + // Command + Args + Env wire the stdio transport. Env is merged into + // the spawned process's environment (replacing duplicates from + // os.Environ()). + Command string + Args []string + Env map[string]string + + // URL wires the Streamable HTTP transport (StreamableClientTransport). + // Mutually exclusive with Command — set exactly one. + URL string + + // Headers attaches static HTTP headers to every request the + // Streamable HTTP transport makes. Typical use: auth tokens + // ("Authorization": "Bearer …", "X-API-Key": …). Ignored for + // stdio. Wrapped around HTTPClient.Transport — your custom + // RoundTripper still runs. + Headers map[string]string + + // HTTPClient overrides the default *http.Client used by the + // Streamable HTTP transport. Use this for mTLS, custom timeouts, + // or full RoundTripper control. Ignored for stdio. nil ⇒ a fresh + // http.Client{} with default transport. + HTTPClient *http.Client + + // ClientImplementation is sent to the server during the initialize + // handshake. Optional — defaults to {Name: "harness", Version: "v1"}. + ClientImplementation *sdk.Implementation +} + +// Client is a connected MCP server with its discovered tools adapted as +// harness tool.Tool implementations. +type Client struct { + name string + session *sdk.ClientSession + tools []tool.Tool + closed bool +} + +// Connect opens a session to the MCP server in cfg, lists its tools, +// and adapts each into a tool.Tool. Returned Client owns the session; +// call Close to release it. +func Connect(ctx context.Context, cfg ServerConfig) (*Client, error) { + if cfg.Name == "" { + return nil, fmt.Errorf("mcp: ServerConfig.Name is required") + } + if cfg.Command == "" && cfg.URL == "" { + return nil, fmt.Errorf("mcp: one of Command or URL must be set") + } + if cfg.Command != "" && cfg.URL != "" { + return nil, fmt.Errorf("mcp: Command and URL are mutually exclusive") + } + + transport, err := buildTransport(cfg) + if err != nil { + return nil, err + } + return connectWithTransport(ctx, cfg.Name, transport, cfg.ClientImplementation) +} + +// connectWithTransport is the lower-level entrypoint shared by Connect +// and the test helpers. Exposed via mcp_test_helpers.go so tests can +// pair the client with an InMemoryTransport. +func connectWithTransport(ctx context.Context, name string, transport sdk.Transport, impl *sdk.Implementation) (*Client, error) { + if impl == nil { + impl = &sdk.Implementation{Name: "harness", Version: "v1"} + } + client := sdk.NewClient(impl, nil) + session, err := client.Connect(ctx, transport, nil) + if err != nil { + return nil, fmt.Errorf("mcp: connect %q: %w", name, err) + } + tools, err := discoverTools(ctx, name, session) + if err != nil { + _ = session.Close() + return nil, err + } + return &Client{name: name, session: session, tools: tools}, nil +} + +// Tools returns the adapter tool.Tool slice. Safe to call multiple +// times; the slice header is shared (callers should not mutate it). +func (c *Client) Tools() []tool.Tool { return c.tools } + +// Name returns the configured server name. +func (c *Client) Name() string { return c.name } + +// Close releases the underlying MCP session. Safe to call multiple +// times — subsequent calls are no-ops. +func (c *Client) Close() error { + if c.closed { + return nil + } + c.closed = true + return c.session.Close() +} + +// buildTransport selects a transport based on cfg. stdio uses +// CommandTransport with a process whose env is os.Environ() merged +// with cfg.Env (cfg.Env wins on conflict). Streamable HTTP uses +// StreamableClientTransport, with optional Headers + HTTPClient +// applied via wrapHTTPClient. +func buildTransport(cfg ServerConfig) (sdk.Transport, error) { + if cfg.Command != "" { + cmd := exec.Command(cfg.Command, cfg.Args...) + cmd.Env = mergeEnv(os.Environ(), cfg.Env) + return &sdk.CommandTransport{Command: cmd}, nil + } + return &sdk.StreamableClientTransport{ + Endpoint: cfg.URL, + HTTPClient: wrapHTTPClient(cfg.HTTPClient, cfg.Headers), + }, nil +} + +// wrapHTTPClient returns the *http.Client the Streamable HTTP transport +// should use. If headers is non-empty, the client's Transport is +// wrapped in a header-injecting RoundTripper so every outgoing request +// carries them. The caller's *http.Client is NOT mutated — a shallow +// copy is returned when wrapping is needed. +func wrapHTTPClient(client *http.Client, headers map[string]string) *http.Client { + if client == nil { + client = &http.Client{} + } + if len(headers) == 0 { + return client + } + base := client.Transport + if base == nil { + base = http.DefaultTransport + } + out := *client // shallow copy — leave caller's struct alone + out.Transport = &headerInjector{base: base, headers: headers} + return &out +} + +// headerInjector is an http.RoundTripper that adds static headers to +// every request before delegating. Request is cloned so the caller's +// *http.Request is never mutated (matters for retries inside the SDK). +type headerInjector struct { + base http.RoundTripper + headers map[string]string +} + +func (h *headerInjector) RoundTrip(req *http.Request) (*http.Response, error) { + req2 := req.Clone(req.Context()) + for k, v := range h.headers { + req2.Header.Set(k, v) + } + return h.base.RoundTrip(req2) +} + +// mergeEnv returns base with overrides applied. Order is preserved for +// base; overrides are appended at the end after pruning duplicates so +// the spawned process sees override values win. +func mergeEnv(base []string, overrides map[string]string) []string { + if len(overrides) == 0 { + return base + } + out := make([]string, 0, len(base)+len(overrides)) + for _, kv := range base { + // "K=V" — keep only entries whose key is NOT being overridden. + key := envKey(kv) + if _, ok := overrides[key]; ok { + continue + } + out = append(out, kv) + } + for k, v := range overrides { + out = append(out, k+"="+v) + } + return out +} + +func envKey(kv string) string { + for i := 0; i < len(kv); i++ { + if kv[i] == '=' { + return kv[:i] + } + } + return kv +} + +// discoverTools lists tools from the server (paginating if necessary) +// and wraps each in an adapter. +func discoverTools(ctx context.Context, serverName string, session *sdk.ClientSession) ([]tool.Tool, error) { + var out []tool.Tool + cursor := "" + for { + params := &sdk.ListToolsParams{Cursor: cursor} + res, err := session.ListTools(ctx, params) + if err != nil { + return nil, fmt.Errorf("mcp: list tools for %q: %w", serverName, err) + } + for _, t := range res.Tools { + out = append(out, &mcpToolAdapter{ + serverName: serverName, + sdkTool: t, + session: session, + }) + } + if res.NextCursor == "" { + break + } + cursor = res.NextCursor + } + return out, nil +} diff --git a/tools/mcp/mcp_test.go b/tools/mcp/mcp_test.go new file mode 100644 index 0000000..ca17b5a --- /dev/null +++ b/tools/mcp/mcp_test.go @@ -0,0 +1,303 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "sync" + "testing" + + sdk "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/sausheong/harness/llm" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// startInProcessServer spins up an in-process MCP server with the +// supplied tool configurations and returns a connected harness *Client +// pointing at it. The server is shut down via t.Cleanup. +// +// toolFns lets each test customise per-tool handler behaviour (return +// text, image, error, etc.). +func startInProcessServer(t *testing.T, name string, tools []sdkToolFixture) *Client { + t.Helper() + ctx := context.Background() + + server := sdk.NewServer(&sdk.Implementation{Name: "test-server", Version: "v0"}, nil) + for _, tf := range tools { + t := tf // capture + server.AddTool(t.Tool, t.Handler) + } + clientTransport, serverTransport := sdk.NewInMemoryTransports() + serverSession, err := server.Connect(ctx, serverTransport, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = serverSession.Close() }) + + cli, err := connectWithTransport(ctx, name, clientTransport, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = cli.Close() }) + return cli +} + +type sdkToolFixture struct { + Tool *sdk.Tool + Handler sdk.ToolHandler +} + +// helper: build a JSON-schema RawMessage tool with a single string arg. +func stringArgTool(name, desc string, handler sdk.ToolHandler) sdkToolFixture { + return sdkToolFixture{ + Tool: &sdk.Tool{ + Name: name, + Description: desc, + InputSchema: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}}}`), + }, + Handler: handler, + } +} + +func TestMCPAdapter_NameNamespacing(t *testing.T) { + cli := startInProcessServer(t, "fs", []sdkToolFixture{ + stringArgTool("read", "read it", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "ok"}}}, nil + }), + }) + tools := cli.Tools() + require.Len(t, tools, 1) + assert.Equal(t, "mcp__fs__read", tools[0].Name()) +} + +func TestMCPAdapter_ParametersPassthrough(t *testing.T) { + cli := startInProcessServer(t, "srv", []sdkToolFixture{ + stringArgTool("echo", "echo back", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "x"}}}, nil + }), + }) + require.Len(t, cli.Tools(), 1) + params := cli.Tools()[0].Parameters() + var schema map[string]any + require.NoError(t, json.Unmarshal(params, &schema)) + assert.Equal(t, "object", schema["type"]) + props, _ := schema["properties"].(map[string]any) + require.NotNil(t, props["q"], "server-supplied schema property must round-trip") +} + +func TestMCPAdapter_ExecuteCallsTool(t *testing.T) { + var sawArgs json.RawMessage + cli := startInProcessServer(t, "srv", []sdkToolFixture{ + stringArgTool("echo", "echo", func(_ context.Context, req *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + sawArgs = req.Params.Arguments + return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "got: " + string(req.Params.Arguments)}}}, nil + }), + }) + require.Len(t, cli.Tools(), 1) + res, err := cli.Tools()[0].Execute(context.Background(), json.RawMessage(`{"q":"hello"}`)) + require.NoError(t, err) + assert.Empty(t, res.Error) + assert.Contains(t, res.Output, "hello") + assert.JSONEq(t, `{"q":"hello"}`, string(sawArgs)) +} + +func TestMCPAdapter_ExecuteErrorPath(t *testing.T) { + cli := startInProcessServer(t, "srv", []sdkToolFixture{ + stringArgTool("boom", "fails", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + return nil, errors.New("kaboom") + }), + }) + require.Len(t, cli.Tools(), 1) + res, err := cli.Tools()[0].Execute(context.Background(), json.RawMessage(`{}`)) + require.NoError(t, err, "Execute itself returns nil; the tool error surfaces in result.Error") + assert.NotEmpty(t, res.Error, "MCP tool error must surface as ToolResult.Error") +} + +func TestMCPAdapter_ImageContentMapping(t *testing.T) { + pngBytes := []byte{0x89, 'P', 'N', 'G', 0x0d} + cli := startInProcessServer(t, "srv", []sdkToolFixture{ + stringArgTool("snap", "take a snapshot", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + return &sdk.CallToolResult{ + Content: []sdk.Content{ + &sdk.ImageContent{Data: pngBytes, MIMEType: "image/png"}, + &sdk.TextContent{Text: "caption"}, + }, + }, nil + }), + }) + require.Len(t, cli.Tools(), 1) + res, err := cli.Tools()[0].Execute(context.Background(), json.RawMessage(`{}`)) + require.NoError(t, err) + require.Len(t, res.Images, 1) + assert.Equal(t, "image/png", res.Images[0].MimeType) + assert.Equal(t, pngBytes, []byte(res.Images[0].Data)) + assert.Equal(t, "caption", res.Output) + // Sanity: the harness ImageContent type is what tools expect. + var _ llm.ImageContent = res.Images[0] +} + +func TestMCPClient_ConnectDiscovers(t *testing.T) { + cli := startInProcessServer(t, "srv", []sdkToolFixture{ + stringArgTool("a", "first", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: ""}}}, nil + }), + stringArgTool("b", "second", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: ""}}}, nil + }), + }) + tools := cli.Tools() + require.Len(t, tools, 2) + got := []string{tools[0].Name(), tools[1].Name()} + assert.ElementsMatch(t, []string{"mcp__srv__a", "mcp__srv__b"}, got) +} + +func TestMCPClient_CloseIsIdempotent(t *testing.T) { + cli := startInProcessServer(t, "srv", []sdkToolFixture{ + stringArgTool("noop", "no-op", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { + return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: ""}}}, nil + }), + }) + require.NoError(t, cli.Close()) + require.NoError(t, cli.Close(), "second Close must be a no-op (no panic, no error)") +} + +func TestConnect_ValidatesConfig(t *testing.T) { + ctx := context.Background() + _, err := Connect(ctx, ServerConfig{}) + require.Error(t, err, "empty config must fail") + + _, err = Connect(ctx, ServerConfig{Name: "x"}) + require.Error(t, err, "no transport set must fail") + + _, err = Connect(ctx, ServerConfig{Name: "x", Command: "true", URL: "http://x"}) + require.Error(t, err, "both transports set must fail") +} + +func TestMergeEnv_OverrideWins(t *testing.T) { + base := []string{"PATH=/usr/bin", "FOO=bar"} + out := mergeEnv(base, map[string]string{"FOO": "baz", "NEW": "v"}) + // The PATH entry must be preserved verbatim; FOO must be replaced; + // NEW must be appended. + assert.Contains(t, out, "PATH=/usr/bin") + assert.NotContains(t, out, "FOO=bar") + assert.Contains(t, out, "FOO=baz") + assert.Contains(t, out, "NEW=v") +} + +// recordingRT captures every Request that hits its RoundTrip, then +// returns a canned 200 response. Used to verify the headerInjector +// passes headers through and doesn't mutate the caller's request. +type recordingRT struct { + mu sync.Mutex + headers []http.Header +} + +func (r *recordingRT) RoundTrip(req *http.Request) (*http.Response, error) { + r.mu.Lock() + r.headers = append(r.headers, req.Header.Clone()) + r.mu.Unlock() + return &http.Response{ + StatusCode: 200, + Header: make(http.Header), + Body: http.NoBody, + Request: req, + }, nil +} + +func TestHeaderInjector_AddsHeadersAndDelegates(t *testing.T) { + base := &recordingRT{} + rt := &headerInjector{ + base: base, + headers: map[string]string{"Authorization": "Bearer t1", "X-Trace": "abc"}, + } + req, err := http.NewRequest("POST", "https://example.com/mcp", nil) + require.NoError(t, err) + req.Header.Set("X-Existing", "kept") + + _, err = rt.RoundTrip(req) + require.NoError(t, err) + + require.Len(t, base.headers, 1) + got := base.headers[0] + assert.Equal(t, "Bearer t1", got.Get("Authorization")) + assert.Equal(t, "abc", got.Get("X-Trace")) + assert.Equal(t, "kept", got.Get("X-Existing"), "pre-existing headers must survive") + + // The caller's req must NOT have been mutated. + assert.Empty(t, req.Header.Get("Authorization"), + "original request must remain unchanged so SDK retries see a clean req") +} + +func TestWrapHTTPClient_NoHeadersReturnsSameClient(t *testing.T) { + in := &http.Client{} + out := wrapHTTPClient(in, nil) + assert.Same(t, in, out, "no headers ⇒ no copy, no wrap") +} + +func TestWrapHTTPClient_NilClientGetsDefaulted(t *testing.T) { + out := wrapHTTPClient(nil, map[string]string{"X": "y"}) + require.NotNil(t, out) + require.NotNil(t, out.Transport) + _, ok := out.Transport.(*headerInjector) + assert.True(t, ok, "headers ⇒ transport must be wrapped") +} + +func TestWrapHTTPClient_DoesNotMutateCallerClient(t *testing.T) { + original := &http.Client{Transport: http.DefaultTransport} + out := wrapHTTPClient(original, map[string]string{"X": "y"}) + assert.NotSame(t, original, out, "wrapping must clone the client") + assert.Equal(t, http.DefaultTransport, original.Transport, + "caller's Transport must be untouched") +} + +func TestBuildTransport_HTTPWithHeaders(t *testing.T) { + tr, err := buildTransport(ServerConfig{ + Name: "x", URL: "https://example.com/mcp", + Headers: map[string]string{"Authorization": "Bearer t1"}, + }) + require.NoError(t, err) + st, ok := tr.(*sdk.StreamableClientTransport) + require.True(t, ok) + assert.Equal(t, "https://example.com/mcp", st.Endpoint) + require.NotNil(t, st.HTTPClient) + _, ok = st.HTTPClient.Transport.(*headerInjector) + assert.True(t, ok, "HTTPClient.Transport must be a headerInjector when Headers set") +} + +// TestStreamableHTTP_HeadersReachServer drives the whole transport via +// httptest.Server to confirm headers actually arrive. The handshake +// will fail (we don't speak MCP back), but the server captures the +// inbound request before that — proving header propagation end-to-end +// through the SDK. +func TestStreamableHTTP_HeadersReachServer(t *testing.T) { + var ( + mu sync.Mutex + got http.Header + ) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + if got == nil { + got = r.Header.Clone() + } + mu.Unlock() + // Reply with something that won't satisfy the MCP handshake — + // the transport will error, but only AFTER the server has seen + // the request, which is what we're asserting. + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(srv.Close) + + ctx := context.Background() + _, _ = Connect(ctx, ServerConfig{ + Name: "remote", URL: srv.URL, + Headers: map[string]string{"Authorization": "Bearer real-token", "X-Tenant": "acme"}, + }) + // We don't assert err: depending on SDK retry behavior the call may + // or may not return immediately. The header check is the contract. + + mu.Lock() + defer mu.Unlock() + require.NotNil(t, got, "server must have seen at least one request") + assert.Equal(t, "Bearer real-token", got.Get("Authorization"), + "Streamable HTTP transport must carry caller's Headers to the server") + assert.Equal(t, "acme", got.Get("X-Tenant")) +}