feat: expose MCP tools on demand #12

Merged
sam merged 5 commits from feat/lazy-mcp-tools into main 2026-09-26 11:27:32 +00:00
Collaborator

What

Adds MCP tool calling to brainless, and exposes tool schemas only when the model asks for them, so a prompt carries the tools stub plus whatever the turn actually loaded instead of every connected server's full catalog.

How

  • internal/config: optional mcpServers map in brainless.json. transport: "stdio" (command/args/env) and transport: "http" (url/headers) are separate config shapes, decoded by a transport discriminator.
  • internal/harness: connects to the config-file servers plus the servers an ACP session declares in NewSessionRequest.McpServers, lists their tools once per session, and closes the connections when the session changes (internal/harness/mcp.go).
  • Only a tools stub is exposed up front. It returns a compact one-line catalog of every available tool and loads the ones named in its load argument (internal/harness/tools.go).
  • selectorModel.GenerateContent calls pruneTools before each model call, which removes every unloaded tool from req.Tools and req.Config.Tools (internal/harness/registry.go, internal/harness/mcp.go).
  • Loaded tools are cleared at each turn boundary, so a later turn starts from the catalog again.
  • Tool calls and their results stream to the ACP client as tool_call / tool_call_update notifications.

Tests

  • TestMCPHelperProcess + TestACPToolLoadOnDemand: the test binary spawns itself as a real stdio MCP server and drives a full ACP turn, asserting that request 0 declares only tools, request 1 declares echo after tools { load: ["echo"] }, echo executes, the client receives the tool-call updates, and a second turn has echo evicted.
  • TestMCPToolsCatalogAndVisibility: catalog, load, unknown names, reset.
  • Config: mcpServers parsing and rejection cases.

gofmt, go vet, go test ./... and the race detector are clean.

Open item

golangci-lint reports one gosec G204 at internal/harness/mcp.go for exec.Command on the stdio transport, which is inherent to launching a client-supplied MCP server. It needs a //nolint:gosec or a linter exclusion.

Not in scope

  • ACP session/request_permission is not bridged; tool calls run without a confirmation prompt.
  • The sse and acp MCP transports are not implemented (unsupported servers are logged and skipped).
## What Adds MCP tool calling to brainless, and exposes tool schemas only when the model asks for them, so a prompt carries the `tools` stub plus whatever the turn actually loaded instead of every connected server's full catalog. ## How - `internal/config`: optional `mcpServers` map in `brainless.json`. `transport: "stdio"` (command/args/env) and `transport: "http"` (url/headers) are separate config shapes, decoded by a transport discriminator. - `internal/harness`: connects to the config-file servers plus the servers an ACP session declares in `NewSessionRequest.McpServers`, lists their tools once per session, and closes the connections when the session changes (`internal/harness/mcp.go`). - Only a `tools` stub is exposed up front. It returns a compact one-line catalog of every available tool and loads the ones named in its `load` argument (`internal/harness/tools.go`). - `selectorModel.GenerateContent` calls `pruneTools` before each model call, which removes every unloaded tool from `req.Tools` and `req.Config.Tools` (`internal/harness/registry.go`, `internal/harness/mcp.go`). - Loaded tools are cleared at each turn boundary, so a later turn starts from the catalog again. - Tool calls and their results stream to the ACP client as `tool_call` / `tool_call_update` notifications. ## Tests - `TestMCPHelperProcess` + `TestACPToolLoadOnDemand`: the test binary spawns itself as a real stdio MCP server and drives a full ACP turn, asserting that request 0 declares only `tools`, request 1 declares `echo` after `tools { load: ["echo"] }`, `echo` executes, the client receives the tool-call updates, and a second turn has `echo` evicted. - `TestMCPToolsCatalogAndVisibility`: catalog, load, unknown names, reset. - Config: `mcpServers` parsing and rejection cases. `gofmt`, `go vet`, `go test ./...` and the race detector are clean. ## Open item `golangci-lint` reports one `gosec` G204 at `internal/harness/mcp.go` for `exec.Command` on the stdio transport, which is inherent to launching a client-supplied MCP server. It needs a `//nolint:gosec` or a linter exclusion. ## Not in scope - ACP `session/request_permission` is not bridged; tool calls run without a confirmation prompt. - The `sse` and `acp` MCP transports are not implemented (unsupported servers are logged and skipped).
feat: expose MCP tools on demand
All checks were successful
code-review / Agent review (pull_request) Successful in 8s
fb994a07d9
Register a single always-available `tools` tool and load MCP tool schemas
only when the model asks for them, so a session's prompt carries the stub
plus the tools it actually loaded instead of every connected server's
catalog.

- internal/config: add an optional `mcpServers` map to brainless.json,
  with `transport: "stdio"` (command/args/env) and `transport: "http"`
  (url/headers) as separate config shapes.
- internal/harness: connect to the config-file servers plus the ones an
  ACP session declares in `mcpServers`, list their tools once per session,
  and close the connections when the session changes.
- Stream tool calls and their results to the ACP client as tool-call
  updates.
- Loaded tools are cleared at each turn boundary, so a later turn starts
  from the catalog again.
- Tests spawn the test binary as a real stdio MCP server, exercising the
  production transport path without a separate server binary.

Note: gosec G204 flags exec.Command for the stdio transport, which is
inherent to launching a client-supplied MCP server; it needs a nolint or
linter exclusion.
Outdated
@ -0,0 +414,4 @@
func (h *Harness) startMCP(ctx context.Context, servers []acp.McpServer) {
all := slices.Concat(h.mcpServers, mcpServersFromACP(ctx, servers))
if previous := h.mcp.Swap(newMCPTools(ctx, all)); previous != nil {
Author
Collaborator

Fixed in ebf072f. NewSession/LoadSession/ResumeSession now take a turn lock, so replacing and closing the MCP catalog waits for any in-flight prompt turn to finish; a turn can no longer call tools over a connection another request closed. Added TestSessionChangeWaitsForTurn, which fails (in 0.02s) when the lock is removed and passes with it. Cancel does not take the lock — the ACP transport cancels the turn context directly, so cancellation cannot deadlock.

Fixed in `ebf072f`. `NewSession`/`LoadSession`/`ResumeSession` now take a turn lock, so replacing and closing the MCP catalog waits for any in-flight prompt turn to finish; a turn can no longer call tools over a connection another request closed. Added `TestSessionChangeWaitsForTurn`, which fails (in 0.02s) when the lock is removed and passes with it. `Cancel` does not take the lock — the ACP transport cancels the turn context directly, so cancellation cannot deadlock.
Author
Collaborator

Documented in the README MCP section: a client-declared stdio server is launched as a subprocess with no confirmation step, so it is safe only when the ACP client is trusted (Paseo spawns brainless as its own child). Kept client-declared stdio because the ACP spec requires every agent to support it; the README recommends restricting stdio to the config allowlist for untrusted clients. The gosec G204 site is unchanged by design — it needs a //nolint:gosec that only the repo owner may add.

Documented in the README MCP section: a client-declared stdio server is launched as a subprocess with no confirmation step, so it is safe only when the ACP client is trusted (Paseo spawns brainless as its own child). Kept client-declared stdio because the ACP spec requires every agent to support it; the README recommends restricting stdio to the config allowlist for untrusted clients. The gosec G204 site is unchanged by design — it needs a `//nolint:gosec` that only the repo owner may add.
Author
Collaborator

Fixed in ebf072f: MCP HTTP connection setup and response headers are now bounded by dial/TLS and response-header timeouts. Deliberately not http.Client.Timeout, which caps the entire request and would abort a slow tool call or a long-lived server stream.

Fixed in `ebf072f`: MCP HTTP connection setup and response headers are now bounded by dial/TLS and response-header timeouts. Deliberately not `http.Client.Timeout`, which caps the entire request and would abort a slow tool call or a long-lived server stream.
Author
Collaborator

Fixed in ebf072f: renamed to TestLoadMCPServers and TestLoadRejectsBadMCPServers.

Fixed in `ebf072f`: renamed to `TestLoadMCPServers` and `TestLoadRejectsBadMCPServers`.
Author
Collaborator

Fixed in ebf072f. The comment now reads: a nil catalog hides every tool, so the model only sees tools once a session has started. Prompt also builds a catalog from the config-file servers when none exists, so a prompt on a persisted session after a restart is no longer left with zero tools.

Fixed in `ebf072f`. The comment now reads: a nil catalog hides every tool, so the model only sees tools once a session has started. `Prompt` also builds a catalog from the config-file servers when none exists, so a prompt on a persisted session after a restart is no longer left with zero tools.
@ -210,2 +210,4 @@
}
}
func TestLoadMCPerservers(t *testing.T) {
Author
Collaborator

🟡 SUGGESTION — typo in the test name: TestLoadMCPerservers (and TestLoadRejectsBadMCPerservers) reads as “MCPerservers”; should be “MCPservers”. Test names surface in failure output, so worth fixing.

🟡 SUGGESTION — typo in the test name: `TestLoadMCPerservers` (and `TestLoadRejectsBadMCPerservers`) reads as “MCPerservers”; should be “MCPservers”. Test names surface in failure output, so worth fixing.
@ -0,0 +49,4 @@
func httpTransport(url string, headers map[string]string) *mcp.StreamableClientTransport {
return &mcp.StreamableClientTransport{
Endpoint: url,
HTTPClient: &http.Client{Transport: headerRoundTripper{headers: headers}},
Author
Collaborator

🟡 SUGGESTION — httpTransport creates &http.Client{Transport: ...} with no Timeout. A remote MCP server that accepts the connection but never responds blocks Connect/CallTool until the request context is cancelled; during a turn the ADK agent context may not be bounded, so a hung endpoint can stall the whole turn. Add a Timeout (e.g. &http.Client{Timeout: 30 * time.Second, Transport: headerRoundTripper{...}}).

🟡 SUGGESTION — `httpTransport` creates `&http.Client{Transport: ...}` with no `Timeout`. A remote MCP server that accepts the connection but never responds blocks `Connect`/`CallTool` until the request context is cancelled; during a turn the ADK agent context may not be bounded, so a hung endpoint can stall the whole turn. Add a `Timeout` (e.g. `&http.Client{Timeout: 30 * time.Second, Transport: headerRoundTripper{...}}`).
@ -0,0 +104,4 @@
case srv.Stdio != nil:
out = append(out, mcpServer{
name: srv.Stdio.Name,
transport: stdioTransport(srv.Stdio.Command, srv.Stdio.Args, envMap(srv.Stdio.Env)),
Author
Collaborator

🟠 IMPORTANT — trust boundary: mcpServersFromACP builds stdioTransport(srv.Stdio.Command, ...) from a wire-supplied field, and stdioTransport runs it via exec.Command (line 38). Since session/request_permission is not bridged (out of scope here), any client that can reach the ACP endpoint and send session/new with an mcpServers entry gets arbitrary command execution in the brainless process immediately on session start — no model mediation, no confirmation. This widens the boundary beyond prompt-only control.

If the ACP client (Paseo) is fully trusted and unreachable by others, this is acceptable; otherwise it is RCE. Fix options: restrict client-declared stdio command to a config-file allowlist (use ACP servers only for http), gate it behind a config flag, or document the trust assumption in the README next to the example. This is also the gosec G204 site you flagged — a scoped //nolint:gosec naming the trust boundary is fine, but the boundary itself should be deliberate.

🟠 IMPORTANT — trust boundary: `mcpServersFromACP` builds `stdioTransport(srv.Stdio.Command, ...)` from a wire-supplied field, and `stdioTransport` runs it via `exec.Command` (line 38). Since `session/request_permission` is not bridged (out of scope here), any client that can reach the ACP endpoint and send `session/new` with an `mcpServers` entry gets arbitrary command execution in the brainless process immediately on session start — no model mediation, no confirmation. This widens the boundary beyond prompt-only control. If the ACP client (Paseo) is fully trusted and unreachable by others, this is acceptable; otherwise it is RCE. Fix options: restrict client-declared stdio `command` to a config-file allowlist (use ACP servers only for `http`), gate it behind a config flag, or document the trust assumption in the README next to the example. This is also the gosec G204 site you flagged — a scoped `//nolint:gosec` naming the trust boundary is fine, but the boundary itself should be deliberate.
@ -0,0 +414,4 @@
func (h *Harness) startMCP(ctx context.Context, servers []acp.McpServer) {
all := slices.Concat(h.mcpServers, mcpServersFromACP(ctx, servers))
if previous := h.mcp.Swap(newMCPTools(ctx, all)); previous != nil {
Author
Collaborator

🟠 IMPORTANT — concurrency/lifecycle race: startMCP does h.mcp.Swap(newMCPTools(...)) then previous.close(), which calls session.Close() on every MCP ClientSession in the replaced catalog. Meanwhile Prompt (harness.go:321) runs h.runner.Run(...) for the whole turn with no lock held, and mcpTool.Run (~mcp.go:290) calls t.session.CallTool on exactly those sessions. h.mu guards only conn/session/cwd, not the catalog or the turn lifecycle. So if the client starts/loads/resumes another session while a turn is in flight (e.g. session/cancel then an immediate new session — note the existing ponytail: comment admits a canceled turn's model call can still be in flight), the running turn's MCP tool call hits a closed connection and errors, and pruneTools (registry.go:257) reads whichever catalog is current mid-turn, so visibility flips mid-turn.

Condition to fail: any NewSession/LoadSession/ResumeSession arriving while a Prompt turn is mid-flight.

Fix: synchronize session changes against running turns — hold h.mu (or a dedicated turn lock) across the runner.Run loop, or refcount the catalog and defer close() until no active turn references it.

🟠 IMPORTANT — concurrency/lifecycle race: `startMCP` does `h.mcp.Swap(newMCPTools(...))` then `previous.close()`, which calls `session.Close()` on every MCP ClientSession in the replaced catalog. Meanwhile `Prompt` (harness.go:321) runs `h.runner.Run(...)` for the whole turn with no lock held, and `mcpTool.Run` (~mcp.go:290) calls `t.session.CallTool` on exactly those sessions. `h.mu` guards only `conn`/`session`/`cwd`, not the catalog or the turn lifecycle. So if the client starts/loads/resumes another session while a turn is in flight (e.g. `session/cancel` then an immediate new session — note the existing `ponytail:` comment admits a canceled turn's model call can still be in flight), the running turn's MCP tool call hits a closed connection and errors, and `pruneTools` (registry.go:257) reads whichever catalog is current mid-turn, so visibility flips mid-turn. Condition to fail: any NewSession/LoadSession/ResumeSession arriving while a Prompt turn is mid-flight. Fix: synchronize session changes against running turns — hold `h.mu` (or a dedicated turn lock) across the `runner.Run` loop, or refcount the catalog and defer `close()` until no active turn references it.
@ -217,2 +218,4 @@
reg *Registry
sel *selection
// mcp is the harness's active-session tool catalog; when nil (as in unit
// tests) no tool pruning happens.
Author
Collaborator

🟡 SUGGESTION — the comment “when nil (as in unit tests) no tool pruning happens” is misleading. The guard only skips when the m.mcp pointer itself is nil (unit tests). In production m.mcp is always non-nil (&harness.mcp), so pruneTools(req, m.mcp.Load()) always runs; when the loaded catalog is nil (no startMCP yet in this process) pruneTools prunes all tools, including the tools stub — the opposite of “no pruning”. Practical edge: Prompt on a persisted session id without a preceding NewSession/LoadSession/ResumeSession in-process (e.g. resuming directly after a restart, catalog never rebuilt) silently leaves the model with zero tools. Recommend rewording the comment to match behavior and/or calling startMCP from Prompt when the catalog is nil.

🟡 SUGGESTION — the comment “when nil (as in unit tests) no tool pruning happens” is misleading. The guard only skips when the `m.mcp` pointer itself is nil (unit tests). In production `m.mcp` is always non-nil (`&harness.mcp`), so `pruneTools(req, m.mcp.Load())` always runs; when the loaded catalog is nil (no `startMCP` yet in this process) `pruneTools` prunes *all* tools, including the `tools` stub — the opposite of “no pruning”. Practical edge: `Prompt` on a persisted session id without a preceding NewSession/LoadSession/ResumeSession in-process (e.g. resuming directly after a restart, catalog never rebuilt) silently leaves the model with zero tools. Recommend rewording the comment to match behavior and/or calling `startMCP` from `Prompt` when the catalog is nil.
Author
Collaborator

Code review — PR #12 (feat: expose MCP tools on demand)

Reviewed against the samber/cc-skills-golang skill set (code style, naming, docs, error handling, safety, concurrency, security, dependencies, testing, performance, observability, modernize).

Verdict: solid, well-tested PR; no BLOCKING issues found. Two IMPORTANT items should be addressed before merge, plus a few suggestions. Posted as a COMMENT review (the review token is the PR author, which Forgejo does not allow to request changes on its own PR).

What's good

  • Transport-discriminated UnmarshalJSON config decoding and table-driven rejection tests are clean and idiomatic.
  • Per-session catalog lifecycle, lazy tools stub, and pruneTools implement the on-demand design correctly; the e2e test genuinely drives the real stdio transport via the self-spawning helper process and asserts the load/evict round-trip.
  • go.sum committed; only new direct dep is the official modelcontextprotocol/go-sdk v1.7.0 — actively maintained, no known CVEs, no replace directives.
  • Fault isolation in newMCPTools (a bad server is logged and skipped) is a nice touch.

🟠 IMPORTANT (inline)

  1. mcp.go:417 — concurrency/lifecycle race. startMCP swaps and close()s the previous session's MCP client sessions with no synchronization against an in-flight Prompt turn, which may still be calling tools on those sessions (the existing ponytail: comment even acknowledges a canceled turn's model call outlives the turn). h.mu does not cover the catalog or turn lifecycle. Fix: serialize session changes against running turns, or refcount the catalog and defer close until the last turn referencing it ends.
  2. mcp.go:107 — trust boundary. ACP-declared stdio command runs via exec.Command with no permission bridge, so any client able to send session/new gets arbitrary command execution on session start. Acceptable only if the ACP client is fully trusted; otherwise restrict to a config-file allowlist or gate it.

🟡 SUGGESTION (inline)

  • mcp.go:52 — http.Client for the http transport has no Timeout; a hung endpoint can stall a turn indefinitely.
  • config_test.go:213 — test-name typo (TestLoadMCPerservers → TestLoadMCPservers).
  • registry.go:221 — comment “no tool pruning happens” contradicts pruneTools pruning all tools when the catalog is nil; also worth covering the resume-after-restart path where the catalog is never rebuilt and the model gets zero tools.
## Code review — PR #12 (feat: expose MCP tools on demand) Reviewed against the samber/cc-skills-golang skill set (code style, naming, docs, error handling, safety, concurrency, security, dependencies, testing, performance, observability, modernize). **Verdict:** solid, well-tested PR; no BLOCKING issues found. Two IMPORTANT items should be addressed before merge, plus a few suggestions. Posted as a COMMENT review (the review token is the PR author, which Forgejo does not allow to request changes on its own PR). ### What's good - Transport-discriminated `UnmarshalJSON` config decoding and table-driven rejection tests are clean and idiomatic. - Per-session catalog lifecycle, lazy `tools` stub, and `pruneTools` implement the on-demand design correctly; the e2e test genuinely drives the real stdio transport via the self-spawning helper process and asserts the load/evict round-trip. - `go.sum` committed; only new direct dep is the official `modelcontextprotocol/go-sdk v1.7.0` — actively maintained, no known CVEs, no `replace` directives. - Fault isolation in `newMCPTools` (a bad server is logged and skipped) is a nice touch. ### 🟠 IMPORTANT (inline) 1. **mcp.go:417 — concurrency/lifecycle race.** `startMCP` swaps and `close()`s the previous session's MCP client sessions with no synchronization against an in-flight `Prompt` turn, which may still be calling tools on those sessions (the existing `ponytail:` comment even acknowledges a canceled turn's model call outlives the turn). `h.mu` does not cover the catalog or turn lifecycle. Fix: serialize session changes against running turns, or refcount the catalog and defer close until the last turn referencing it ends. 2. **mcp.go:107 — trust boundary.** ACP-declared stdio `command` runs via `exec.Command` with no permission bridge, so any client able to send `session/new` gets arbitrary command execution on session start. Acceptable only if the ACP client is fully trusted; otherwise restrict to a config-file allowlist or gate it. ### 🟡 SUGGESTION (inline) - mcp.go:52 — `http.Client` for the http transport has no `Timeout`; a hung endpoint can stall a turn indefinitely. - config_test.go:213 — test-name typo (`TestLoadMCPerservers` → `TestLoadMCPservers`). - registry.go:221 — comment “no tool pruning happens” contradicts `pruneTools` pruning *all* tools when the catalog is nil; also worth covering the resume-after-restart path where the catalog is never rebuilt and the model gets zero tools.
fix: address code review on lazy MCP tools
All checks were successful
code-review / Agent review (pull_request) Successful in 8s
ebf072f1a1
- Serialize session changes against in-flight prompt turns. NewSession,
  LoadSession, and ResumeSession now wait for the running turn to finish
  before replacing (and closing) the MCP catalog, so a turn can no longer
  call tools over a connection another request just closed. Adds
  TestSessionChangeWaitsForTurn, which fails if the swap is not serialized.
- Build a catalog from the config-file servers when a prompt arrives on a
  persisted session with no session-lifecycle call in this process, so
  tools are not all pruned away after a restart.
- Bound MCP HTTP connection setup and response headers with a dial and
  response-header timeout, without capping the whole request the way
  http.Client.Timeout would.
- Document the stdio trust boundary: a client-declared stdio server runs a
  subprocess with no confirmation, so the ACP client must be trusted.
- Fix the test-name typo (TestLoadMCPerservers -> TestLoadMCPServers) and
  reword the selectorModel.mcp comment, which claimed no pruning happened
  when the catalog was nil.
Author
Collaborator

Review responses — all five addressed in ebf072f

# Item Resolution
1 🟠 lifecycle race (startMCP closes sessions under a running turn) Fixed. NewSession/LoadSession/ResumeSession take a turn lock, so the catalog swap and close() wait for any in-flight prompt turn. New TestSessionChangeWaitsForTurn fails in 0.02s with the lock removed and passes with it. Cancel does not take the lock (the ACP transport cancels the turn context directly), so cancellation cannot deadlock.
2 🟠 stdio trust boundary Documented in the README MCP section. Behaviour kept: the ACP spec requires every agent to support client-declared stdio servers, and the client (Paseo) is a trusted parent. README now states the assumption and recommends the config allowlist for untrusted clients.
3 🟡 no HTTP timeout Fixed with dial/TLS + response-header timeouts, not http.Client.Timeout (which would abort slow tool calls or a long-lived server stream).
4 🟡 test-name typo Fixed: TestLoadMCPServers, TestLoadRejectsBadMCPServers.
5 🟡 misleading mcp comment / zero tools after restart Comment corrected, and Prompt now builds a catalog from the config-file servers when none exists.

gofmt, go vet, go test ./..., and the race detector are clean. golangci-lint still reports the single known gosec G204 at internal/harness/mcp.go (the exec.Command site covered by item 2); the repo owner needs to add the //nolint:gosec or a linter exclusion.

The review threads could not be marked resolved through the API — this Forgejo version exposes no resolve-conversation route (/repos/{owner}/{repo}/pulls/{index}/reviews/{id}/comments/{comment} has only get/delete). They need resolving in the UI.

## Review responses — all five addressed in `ebf072f` | # | Item | Resolution | |---|------|------------| | 1 | 🟠 lifecycle race (`startMCP` closes sessions under a running turn) | Fixed. `NewSession`/`LoadSession`/`ResumeSession` take a turn lock, so the catalog swap and `close()` wait for any in-flight prompt turn. New `TestSessionChangeWaitsForTurn` fails in 0.02s with the lock removed and passes with it. `Cancel` does not take the lock (the ACP transport cancels the turn context directly), so cancellation cannot deadlock. | | 2 | 🟠 stdio trust boundary | Documented in the README MCP section. Behaviour kept: the ACP spec requires every agent to support client-declared stdio servers, and the client (Paseo) is a trusted parent. README now states the assumption and recommends the config allowlist for untrusted clients. | | 3 | 🟡 no HTTP timeout | Fixed with dial/TLS + response-header timeouts, not `http.Client.Timeout` (which would abort slow tool calls or a long-lived server stream). | | 4 | 🟡 test-name typo | Fixed: `TestLoadMCPServers`, `TestLoadRejectsBadMCPServers`. | | 5 | 🟡 misleading `mcp` comment / zero tools after restart | Comment corrected, and `Prompt` now builds a catalog from the config-file servers when none exists. | `gofmt`, `go vet`, `go test ./...`, and the race detector are clean. `golangci-lint` still reports the single known `gosec` G204 at `internal/harness/mcp.go` (the `exec.Command` site covered by item 2); the repo owner needs to add the `//nolint:gosec` or a linter exclusion. The review threads could not be marked resolved through the API — this Forgejo version exposes no resolve-conversation route (`/repos/{owner}/{repo}/pulls/{index}/reviews/{id}/comments/{comment}` has only get/delete). They need resolving in the UI.
pi-agent left a comment

Review summary

Solid, well-scoped PR. The lazy-tool design is clean: a tools stub up front, pruneTools filtering packed schemas per round, and turnMu serializing session changes against in-flight turns so the MCP catalog is never closed under a running turn. Concurrency handling (atomic pointer swap + mutex, no lock-order cycle between turnMu and mu) is sound, and the tests are genuinely good — the self-spawning stdio helper, the scripted model server, and the end-to-end turn assertions cover the design well. The README trust-boundary section is exactly the right call.

Two IMPORTANT issues (no BLOCKING ones found):

  1. Unbounded stdio connect under turnMu — a hung client-supplied or config stdio server wedges the entire agent (all prompts + session changes block forever). HTTP is bounded by the dial/header timeouts; stdio is not.
  2. Documented session-overrides-config contract is not implemented — config servers are connected first and tool names are first-wins, so the config server actually wins for same-named servers.

Plus two minor suggestions (header leak on redirects, warn log missing server name). Recommend addressing at least the two IMPORTANT items before merge.

## Review summary Solid, well-scoped PR. The lazy-tool design is clean: a `tools` stub up front, `pruneTools` filtering packed schemas per round, and `turnMu` serializing session changes against in-flight turns so the MCP catalog is never closed under a running turn. Concurrency handling (atomic pointer swap + mutex, no lock-order cycle between `turnMu` and `mu`) is sound, and the tests are genuinely good — the self-spawning stdio helper, the scripted model server, and the end-to-end turn assertions cover the design well. The README trust-boundary section is exactly the right call. Two IMPORTANT issues (no BLOCKING ones found): 1. **Unbounded stdio connect under `turnMu`** — a hung client-supplied or config stdio server wedges the entire agent (all prompts + session changes block forever). HTTP is bounded by the dial/header timeouts; stdio is not. 2. **Documented session-overrides-config contract is not implemented** — config servers are connected first and tool names are first-wins, so the config server actually wins for same-named servers. Plus two minor suggestions (header leak on redirects, warn log missing server name). Recommend addressing at least the two IMPORTANT items before merge.
@ -0,0 +196,4 @@
for _, srv := range servers {
client := mcp.NewClient(&mcp.Implementation{Name: appName, Version: "0.0.1"}, nil)
session, err := client.Connect(ctx, srv.transport, nil)
Author
Collaborator

Fixed in feaf951. Two changes:

  1. Each server's connect + tool listing is wrapped in context.WithTimeout(ctx, mcpConnectTimeout) (15s), so a server that starts but never answers is skipped instead of blocking. The go-sdk's CommandTransport.Connect does not bind the session to the passed context (its listen loops use context.Background()), so the deadline only bounds the handshake — verified by the existing stdio e2e test still passing.
  2. startMCP now builds the catalog before taking turnMu, so even a slow-but-successful connect cannot block session changes; only the swap and close are serialized.

Regression test TestNewMCPToolsBoundsHungServer uses a transport that accepts and never answers: 0.2s with the bound, 10.0s and failing without it. The Prompt fallback still builds under turnMu, but it is now bounded by the same timeout.

Fixed in `feaf951`. Two changes: 1. Each server's connect + tool listing is wrapped in `context.WithTimeout(ctx, mcpConnectTimeout)` (15s), so a server that starts but never answers is skipped instead of blocking. The go-sdk's `CommandTransport.Connect` does not bind the session to the passed context (its listen loops use `context.Background()`), so the deadline only bounds the handshake — verified by the existing stdio e2e test still passing. 2. `startMCP` now builds the catalog *before* taking `turnMu`, so even a slow-but-successful connect cannot block session changes; only the swap and close are serialized. Regression test `TestNewMCPToolsBoundsHungServer` uses a transport that accepts and never answers: 0.2s with the bound, 10.0s and failing without it. The `Prompt` fallback still builds under `turnMu`, but it is now bounded by the same timeout.
Author
Collaborator

Fixed in feaf951 by implementing the documented contract rather than weakening the docs. mergeServers drops any config-file server whose name a session server declares, so only the session server is connected and its tools win; the README and the File.MCPServers comment are now accurate. Covered by TestMergeServersSessionOverridesConfig, which asserts the surviving shared entry carries the session-declared endpoint.

Fixed in `feaf951` by implementing the documented contract rather than weakening the docs. `mergeServers` drops any config-file server whose name a session server declares, so only the session server is connected and its tools win; the README and the `File.MCPServers` comment are now accurate. Covered by `TestMergeServersSessionOverridesConfig`, which asserts the surviving `shared` entry carries the session-declared endpoint.
Author
Collaborator

Fixed in feaf951. The MCP HTTP client now sets CheckRedirect to refuse a redirect to a different host (same-host redirects still follow). CheckRedirect runs before the next RoundTrip, so the configured headers are never re-injected on a cross-origin hop.

Fixed in `feaf951`. The MCP HTTP client now sets `CheckRedirect` to refuse a redirect to a different host (same-host redirects still follow). `CheckRedirect` runs before the next `RoundTrip`, so the configured headers are never re-injected on a cross-origin hop.
Author
Collaborator

Fixed in feaf951. The warning now carries server and transport attributes, resolved from whichever variant the client declared (acpServerIdentity), so a skipped sse/acp entry says which server it was and what it asked for.

Fixed in `feaf951`. The warning now carries `server` and `transport` attributes, resolved from whichever variant the client declared (`acpServerIdentity`), so a skipped `sse`/`acp` entry says which server it was and what it asked for.
@ -0,0 +83,4 @@
base http.RoundTripper
}
func (h headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
Author
Collaborator

🟡 SUGGESTION — configured headers (incl. Authorization) are applied to every request the RoundTripper sees, including redirect hops. http.Client follows 3xx redirects by default, and each RoundTrip clones and re-injects the header set, so if the MCP endpoint redirects (e.g. to another origin) the auth header goes along. Fails when: a configured http server issues a redirect. Fix: scope header injection to the original host — e.g. compare clone.URL.Host against the transport's configured endpoint and skip headers on other hosts, or set CheckRedirect to refuse cross-host redirects.

🟡 **SUGGESTION — configured headers (incl. `Authorization`) are applied to every request the RoundTripper sees, including redirect hops.** `http.Client` follows 3xx redirects by default, and each `RoundTrip` clones and re-injects the header set, so if the MCP endpoint redirects (e.g. to another origin) the auth header goes along. **Fails when:** a configured `http` server issues a redirect. **Fix:** scope header injection to the original host — e.g. compare `clone.URL.Host` against the transport's configured endpoint and skip headers on other hosts, or set `CheckRedirect` to refuse cross-host redirects.
@ -0,0 +145,4 @@
transport: httpTransport(srv.Http.Url, headerMap(srv.Http.Headers)),
})
default:
mcpLogger().WarnContext(ctx, "ignoring unsupported mcp transport (only stdio and http are supported)")
Author
Collaborator

🟡 SUGGESTION — unsupported-transport warning omits the offending server. The WarnContext here says only that an unsupported transport was ignored, with no server name or transport value, so a client that sends an sse/acp entry is hard to diagnose in logs. Fix: add the server name and the transport to the structured log, e.g. slog.String("server", srv.Name) and the transport identifier.

🟡 **SUGGESTION — unsupported-transport warning omits the offending server.** The `WarnContext` here says only that an unsupported transport was ignored, with no server name or transport value, so a client that sends an `sse`/`acp` entry is hard to diagnose in logs. **Fix:** add the server name and the transport to the structured log, e.g. `slog.String("server", srv.Name)` and the transport identifier.
@ -0,0 +196,4 @@
for _, srv := range servers {
client := mcp.NewClient(&mcp.Implementation{Name: appName, Version: "0.0.1"}, nil)
session, err := client.Connect(ctx, srv.transport, nil)
Author
Collaborator

🟠 IMPORTANT — stdio MCP connect is unbounded and runs under turnMu. startMCP holds turnMu while calling newMCPTools, and client.Connect does the subprocess spawn + initialize handshake synchronously. mcp.CommandTransport.Connect starts the process with no timeout, and the handshake blocks until the peer answers or the request context is cancelled. HTTP is bounded by mcpDialTimeout/mcpHeaderTimeout (10s/30s); stdio has nothing.

Fails when: a stdio server's process starts but never answers initialize (hung/misbehaving command, e.g. a client-supplied server that waits on input). Connect blocks, turnMu is held, and every Prompt and session change (New/Load/Resume) blocks indefinitely — the whole agent wedges. This same unbounded connect is also hit from the Prompt fallback h.setMCP(ctx, nil) on a resumed-after-restart session.

Fix: bound the connect/handshake with a deadline (e.g. wrap in context.WithTimeout(ctx, mcpDialTimeout) per server) and/or connect/build the catalog outside the critical section so a slow connect can't hold turnMu. Note the SDK reuses the passed ctx for the handshake, so a per-server timeout is straightforward.

🟠 **IMPORTANT — stdio MCP connect is unbounded and runs under `turnMu`.** `startMCP` holds `turnMu` while calling `newMCPTools`, and `client.Connect` does the subprocess spawn + `initialize` handshake synchronously. `mcp.CommandTransport.Connect` starts the process with no timeout, and the handshake blocks until the peer answers or the request context is cancelled. HTTP is bounded by `mcpDialTimeout`/`mcpHeaderTimeout` (10s/30s); stdio has nothing. **Fails when:** a `stdio` server's process starts but never answers `initialize` (hung/misbehaving command, e.g. a client-supplied server that waits on input). `Connect` blocks, `turnMu` is held, and every `Prompt` and session change (New/Load/Resume) blocks indefinitely — the whole agent wedges. This same unbounded connect is also hit from the `Prompt` fallback `h.setMCP(ctx, nil)` on a resumed-after-restart session. **Fix:** bound the connect/handshake with a deadline (e.g. wrap in `context.WithTimeout(ctx, mcpDialTimeout)` per server) and/or connect/build the catalog outside the critical section so a slow connect can't hold `turnMu`. Note the SDK reuses the passed ctx for the handshake, so a per-server timeout is straightforward.
@ -0,0 +455,4 @@
// setMCP replaces the active catalog, closing the previous one. Callers must
// hold turnMu.
func (h *Harness) setMCP(ctx context.Context, servers []acp.McpServer) {
all := slices.Concat(h.mcpServers, mcpServersFromACP(ctx, servers))
Author
Collaborator

🟠 IMPORTANT — documented 'session server overrides config-file server' is not implemented. setMCP concatenates config servers first, then ACP servers, and newMCPTools registers tools first-wins (// first server with a given tool name wins). So for a server with the same display name in both config and the ACP mcpServers, the config server is connected first and its tools win — the opposite of what the README ('A session server with the same name overrides the config-file one') and the File.MCPServers comment promise. Both servers are also connected (two subprocesses for same-named stdio servers).

Fails when: a client declares a server name that also exists in brainless.json — the operator expects the client's config to take effect, but the config-file one is used.

Fix: either implement the override (dedup by server name before connecting, dropping the config entry when a session server shares the name) or fix the docs/comments to state that config wins.

🟠 **IMPORTANT — documented 'session server overrides config-file server' is not implemented.** `setMCP` concatenates config servers first, then ACP servers, and `newMCPTools` registers tools first-wins (`// first server with a given tool name wins`). So for a server with the same display name in both config and the ACP `mcpServers`, the **config** server is connected first and its tools win — the opposite of what the README ('A session server with the same name overrides the config-file one') and the `File.MCPServers` comment promise. Both servers are also connected (two subprocesses for same-named stdio servers). **Fails when:** a client declares a server name that also exists in `brainless.json` — the operator expects the client's config to take effect, but the config-file one is used. **Fix:** either implement the override (dedup by server name before connecting, dropping the config entry when a session server shares the name) or fix the docs/comments to state that config wins.
- Bound MCP server setup with mcpConnectTimeout (15s per server) so a
  stdio server that starts but never answers its handshake can no longer
  wedge the agent. Building the catalog also moved out of the turnMu
  critical section in startMCP, so a slow-but-successful connect does not
  block session changes. Adds TestNewMCPToolsBoundsHungServer, which takes
  10s and fails without the bound and 0.2s with it.
- Implement the documented session-overrides-config rule: mergeServers now
  drops a config-file server whose name a session server declares, instead
  of connecting both and letting the config one win the tool list. Adds
  TestMergeServersSessionOverridesConfig.
- Refuse cross-host redirects on the MCP HTTP client, so configured
  headers (which may carry credentials) are never re-sent to another
  origin by a redirect hop.
- Include the server name and transport in the unsupported-transport
  warning, so a skipped sse/acp entry is diagnosable.
Author
Collaborator

Second review round — all four addressed in feaf951

# Item Resolution
1 🟠 unbounded stdio connect under turnMu Per-server context.WithTimeout(ctx, mcpConnectTimeout) (15s) around connect + listing, and the catalog is now built before taking turnMu, so neither a hung nor a slow server can block session changes. New TestNewMCPToolsBoundsHungServer takes 10.0s and fails without the bound, 0.2s with it.
2 🟠 session-overrides-config not implemented Implemented: mergeServers drops the config-file entry when a session server shares its name, so only the session server connects. New TestMergeServersSessionOverridesConfig.
3 🟡 headers leak on redirect hops The MCP HTTP client's CheckRedirect now refuses cross-host redirects.
4 🟡 warn log missing server/transport Warning now carries server and transport attributes.

gofmt, go vet, go test ./..., and the race detector are clean. golangci-lint still reports only the known gosec G204 at internal/harness/mcp.go — that one needs the repo owner's //nolint:gosec or a linter exclusion, since it is the deliberate stdio launch site documented under the README trust boundary.

I have not re-triggered the review; the PR is ready for another look whenever you want to label it.

## Second review round — all four addressed in `feaf951` | # | Item | Resolution | |---|------|------------| | 1 | 🟠 unbounded stdio connect under `turnMu` | Per-server `context.WithTimeout(ctx, mcpConnectTimeout)` (15s) around connect + listing, and the catalog is now built *before* taking `turnMu`, so neither a hung nor a slow server can block session changes. New `TestNewMCPToolsBoundsHungServer` takes 10.0s and fails without the bound, 0.2s with it. | | 2 | 🟠 session-overrides-config not implemented | Implemented: `mergeServers` drops the config-file entry when a session server shares its name, so only the session server connects. New `TestMergeServersSessionOverridesConfig`. | | 3 | 🟡 headers leak on redirect hops | The MCP HTTP client's `CheckRedirect` now refuses cross-host redirects. | | 4 | 🟡 warn log missing server/transport | Warning now carries `server` and `transport` attributes. | `gofmt`, `go vet`, `go test ./...`, and the race detector are clean. `golangci-lint` still reports only the known `gosec` G204 at `internal/harness/mcp.go` — that one needs the repo owner's `//nolint:gosec` or a linter exclusion, since it is the deliberate stdio launch site documented under the README trust boundary. I have not re-triggered the review; the PR is ready for another look whenever you want to label it.
sam merged commit 9110c654f7 into main 2026-09-26 11:27:32 +00:00
sam deleted branch feat/lazy-mcp-tools 2026-09-26 11:27:32 +00:00
Sign in to join this conversation.
No reviewers
No labels
code-review
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
sam/brainless!12
No description provided.