fix: wire MCP config into CLI passthrough (#1078)

* fix: wire MCP config into CLI passthrough

* fix: address passthrough MCP review feedback

* fix: fail fast when passthrough MCP port is missing

* fix: track passthrough MCP config with nil metadata
This commit is contained in:
José Almeida
2026-05-26 11:38:30 +01:00
committed by GitHub
parent 8345480fe5
commit 823117ba48
9 changed files with 414 additions and 15 deletions
@@ -157,6 +157,7 @@ type PassthroughOptions struct {
Resume bool // generic "continue last session" (e.g. -c, --resume latest)
PermissionValues map[string]bool // e.g. {"auto_approve": true}
WorkDir string
MCPConfigPath string // path to generated MCP config file for passthrough CLIs that support it
// CLIFlagTokens are user-configured CLI flag argv tokens derived from
// AgentProfile.CLIFlags (only Enabled entries, shell-tokenised). Appended
// verbatim to the built passthrough command, mirroring CommandOptions.
@@ -251,6 +252,7 @@ type PassthroughConfig struct {
StabilityWindow time.Duration
ResumeFlag Param // generic "continue last session" (e.g. NewParam("-c"), NewParam("--resume", "latest"))
SessionResumeFlag Param // resume a specific session by ID (e.g. NewParam("--resume"))
MCPConfigFlag Param // flag used to load an MCP config file, e.g. NewParam("--mcp-config", "{mcp_config}")
WaitForTerminal bool
// AutoInjectPrompt enables writing the task description to the PTY stdin
// after the first idle window. Default false preserves today's behavior.
@@ -44,6 +44,7 @@ func NewClaudeACP() *ClaudeACP {
BufferMaxBytes: DefaultBufferMaxBytes,
ResumeFlag: NewParam("-c"),
SessionResumeFlag: NewParam("--resume"),
MCPConfigFlag: NewParam("--mcp-config", "{mcp_config}"),
AutoInjectPrompt: true,
SubmitSequence: "\r",
DisableBracketedPaste: true,
@@ -104,6 +104,25 @@ func (b *CmdBuilder) Prompt(flag Param, prompt string) *CmdBuilder {
return b
}
// MCPConfig appends an MCP config flag when a passthrough CLI supports one.
// flag args support {mcp_config} placeholder, e.g. NewParam("--mcp-config", "{mcp_config}").
func (b *CmdBuilder) MCPConfig(flag Param, path string) *CmdBuilder {
if flag.IsEmpty() || path == "" {
return b
}
hasPlaceholder := false
for _, arg := range flag.args {
if strings.Contains(arg, "{mcp_config}") {
hasPlaceholder = true
}
b.args = append(b.args, strings.ReplaceAll(arg, "{mcp_config}", path))
}
if !hasPlaceholder {
b.args = append(b.args, path)
}
return b
}
// Flag appends arbitrary flag parts to the command.
func (b *CmdBuilder) Flag(parts ...string) *CmdBuilder {
b.args = append(b.args, parts...)
@@ -27,6 +27,7 @@ func (p *StandardPassthrough) BuildPassthroughCommand(opts PassthroughOptions) C
case opts.Prompt != "":
b.Prompt(p.Cfg.PromptFlag, opts.Prompt)
}
b.MCPConfig(p.Cfg.MCPConfigFlag, opts.MCPConfigPath)
return b.Build()
}
@@ -447,7 +447,7 @@ func (m *Manager) StopAgentWithReason(ctx context.Context, executionID string, r
// End session trace span
execution.EndSessionSpan()
m.executionStore.Remove(executionID)
m.RemoveExecution(executionID)
m.clearRemoteStatus(execution.SessionID)
m.logger.Info("agent stopped and removed from tracking",
@@ -313,7 +313,7 @@ func (m *Manager) CleanupStaleExecutionBySessionID(ctx context.Context, sessionI
}
// Remove from execution store
m.executionStore.Remove(execution.ID)
m.RemoveExecution(execution.ID)
// Delete the persistence row in lockstep with store removal so we never
// leave a phantom executors_running row pointing at a non-existent
@@ -343,6 +343,9 @@ func (m *Manager) CleanupStaleExecutionBySessionID(ctx context.Context, sessionI
// Typical usage: Called by cleanup loops or after successful StopAgent completion.
// For stale/dead executions, use CleanupStaleExecutionBySessionID instead.
func (m *Manager) RemoveExecution(executionID string) {
if execution, ok := m.executionStore.Get(executionID); ok {
m.cleanupPassthroughMCPConfig(execution)
}
m.executionStore.Remove(executionID)
m.logger.Debug("removed execution from tracking",
zap.String("execution_id", executionID))
@@ -2,7 +2,10 @@ package lifecycle
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
@@ -214,6 +217,125 @@ func promptForPassthroughCommand(pt agents.PassthroughConfig, taskDescription st
return taskDescription
}
type passthroughMCPServerConfig struct {
Type string `json:"type"`
URL string `json:"url"`
}
type passthroughMCPConfigFile struct {
MCPServers map[string]passthroughMCPServerConfig `json:"mcpServers"`
}
func passthroughMCPConfigPort(execution *AgentExecution) int {
if execution == nil {
return 0
}
if execution.standalonePort > 0 {
return execution.standalonePort
}
if execution.Metadata == nil {
return 0
}
switch value := execution.Metadata["standalone_port"].(type) {
case int:
return value
case int64:
return int(value)
case float64:
return int(value)
}
return 0
}
func safePassthroughMCPConfigName(value string) string {
if value == "" {
return "session"
}
var out strings.Builder
for _, r := range value {
switch {
case r >= 'a' && r <= 'z':
out.WriteRune(r)
case r >= 'A' && r <= 'Z':
out.WriteRune(r)
case r >= '0' && r <= '9':
out.WriteRune(r)
case r == '-' || r == '_' || r == '.':
out.WriteRune(r)
default:
out.WriteByte('_')
}
}
return out.String()
}
func passthroughMCPConfigPath(execution *AgentExecution) string {
if execution == nil || execution.Metadata == nil {
return ""
}
path, _ := execution.Metadata["passthrough_mcp_config_path"].(string)
return path
}
func (m *Manager) writePassthroughMCPConfig(execution *AgentExecution, pt agents.PassthroughConfig) (string, error) {
if pt.MCPConfigFlag.IsEmpty() {
return "", nil
}
port := passthroughMCPConfigPort(execution)
if port <= 0 {
return "", fmt.Errorf("standalone port unavailable for passthrough MCP config")
}
root := m.dataDir
if root == "" {
root = filepath.Join(os.TempDir(), "kandev")
}
dir := filepath.Join(root, "passthrough-mcp")
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", fmt.Errorf("create passthrough MCP config dir: %w", err)
}
name := safePassthroughMCPConfigName(execution.SessionID)
if execution.SessionID == "" {
name = safePassthroughMCPConfigName(execution.ID)
}
path := filepath.Join(dir, name+".json")
cfg := passthroughMCPConfigFile{
MCPServers: map[string]passthroughMCPServerConfig{
"kandev": {
Type: "http",
URL: fmt.Sprintf("http://localhost:%d/mcp", port),
},
},
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return "", fmt.Errorf("marshal passthrough MCP config: %w", err)
}
data = append(data, '\n')
if err := os.WriteFile(path, data, 0o600); err != nil {
return "", fmt.Errorf("write passthrough MCP config: %w", err)
}
if execution.Metadata == nil {
execution.Metadata = map[string]interface{}{}
}
execution.Metadata["passthrough_mcp_config_path"] = path
return path, nil
}
func (m *Manager) cleanupPassthroughMCPConfig(execution *AgentExecution) {
path := passthroughMCPConfigPath(execution)
if path == "" {
return
}
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
m.logger.Warn("failed to remove passthrough MCP config",
zap.String("path", path),
zap.Error(err))
}
if execution.Metadata != nil {
delete(execution.Metadata, "passthrough_mcp_config_path")
}
}
// passthroughAgentCommand validates passthrough support and builds the command for a passthrough session.
// Returns the PassthroughAgent, PassthroughConfig, RuntimeConfig pointer, command, and any error.
func (m *Manager) passthroughAgentCommand(execution *AgentExecution, profileInfo *AgentProfileInfo) (agents.PassthroughAgent, agents.PassthroughConfig, *agents.RuntimeConfig, agents.Command, error) {
@@ -231,12 +353,17 @@ func (m *Manager) passthroughAgentCommand(execution *AgentExecution, profileInfo
rt := agentConfig.Runtime()
taskDescription := getTaskDescriptionFromMetadata(execution)
promptForCmd := promptForPassthroughCommand(pt, taskDescription)
mcpConfigPath, err := m.writePassthroughMCPConfig(execution, pt)
if err != nil {
return nil, agents.PassthroughConfig{}, nil, agents.Command{}, err
}
cmd := ptAgent.BuildPassthroughCommand(agents.PassthroughOptions{
Model: profileModel(profileInfo),
SessionID: execution.ACPSessionID,
Prompt: promptForCmd,
PermissionValues: profilePermissionValues(profileInfo),
MCPConfigPath: mcpConfigPath,
CLIFlagTokens: m.profileCLIFlagTokens(profileInfo),
})
if cmd.IsEmpty() {
@@ -376,10 +503,15 @@ func (m *Manager) freshPassthroughCommand(ctx context.Context, execution *AgentE
if err != nil {
return agents.PassthroughConfig{}, nil, agents.Command{}, err
}
mcpConfigPath, err := m.writePassthroughMCPConfig(execution, resolved.pt)
if err != nil {
return agents.PassthroughConfig{}, nil, agents.Command{}, err
}
cmd := resolved.agent.BuildPassthroughCommand(agents.PassthroughOptions{
Model: profileModel(resolved.profile),
PermissionValues: profilePermissionValues(resolved.profile),
MCPConfigPath: mcpConfigPath,
CLIFlagTokens: m.profileCLIFlagTokens(resolved.profile),
})
if cmd.IsEmpty() {
@@ -389,6 +521,24 @@ func (m *Manager) freshPassthroughCommand(ctx context.Context, execution *AgentE
return resolved.pt, resolved.rt, cmd, nil
}
func (m *Manager) resumePassthroughCommand(execution *AgentExecution, resolved *resolvedPassthrough, useResume bool) (agents.Command, error) {
mcpConfigPath, err := m.writePassthroughMCPConfig(execution, resolved.pt)
if err != nil {
return agents.Command{}, err
}
cmd := resolved.agent.BuildPassthroughCommand(agents.PassthroughOptions{
Model: profileModel(resolved.profile),
Resume: useResume,
PermissionValues: profilePermissionValues(resolved.profile),
MCPConfigPath: mcpConfigPath,
CLIFlagTokens: m.profileCLIFlagTokens(resolved.profile),
})
if cmd.IsEmpty() {
return agents.Command{}, fmt.Errorf("passthrough resume command is empty for agent %s", resolved.agentID)
}
return cmd, nil
}
// restartPassthroughProcess kills the current PTY process and relaunches a fresh one
// without --resume, effectively clearing the agent's conversation context.
// The workflow step prompt is delivered afterwards via stdin (autoStartPassthroughPrompt).
@@ -471,20 +621,20 @@ func (m *Manager) ResumePassthroughSession(ctx context.Context, sessionID string
return err
}
interactiveRunner := m.GetInteractiveRunner()
if interactiveRunner == nil {
return fmt.Errorf("interactive runner not available")
}
// Skip the resume flag if a previous resume already fast-failed for this
// execution: re-attaching `-c` / `--resume` would just reproduce the same
// "No conversation found to continue" exit on every WS reconnect after
// backend restart. Once the sticky flag is set, every subsequent launch
// for this execution starts fresh.
useResume := !execution.passthroughResumeFailed
cmd := resolved.agent.BuildPassthroughCommand(agents.PassthroughOptions{
Model: profileModel(resolved.profile),
Resume: useResume,
PermissionValues: profilePermissionValues(resolved.profile),
CLIFlagTokens: m.profileCLIFlagTokens(resolved.profile),
})
if cmd.IsEmpty() {
return fmt.Errorf("passthrough resume command is empty for agent %s", resolved.agentID)
cmd, err := m.resumePassthroughCommand(execution, resolved, useResume)
if err != nil {
return err
}
m.logger.Info("resuming passthrough session",
@@ -493,11 +643,6 @@ func (m *Manager) ResumePassthroughSession(ctx context.Context, sessionID string
zap.Bool("use_resume", useResume),
zap.Strings("command", cmd.Args()))
interactiveRunner := m.GetInteractiveRunner()
if interactiveRunner == nil {
return fmt.Errorf("interactive runner not available")
}
env := m.buildPassthroughEnv(ctx, execution, resolved.rt.RequiredEnv)
// Always use immediate start on resume — the terminal WebSocket is already connected,
@@ -2,6 +2,9 @@ package lifecycle
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"testing/synctest"
"time"
@@ -16,6 +19,7 @@ type mockPassthroughProfileResolver struct {
cliPassthrough bool
envVars []settingsmodels.ProfileEnvVar
err error
agentName string
}
func (m *mockPassthroughProfileResolver) ResolveProfile(ctx context.Context, profileID string) (*AgentProfileInfo, error) {
@@ -24,11 +28,80 @@ func (m *mockPassthroughProfileResolver) ResolveProfile(ctx context.Context, pro
}
return &AgentProfileInfo{
ProfileID: profileID,
AgentName: m.agentName,
CLIPassthrough: m.cliPassthrough,
EnvVars: m.envVars,
}, nil
}
func assertClaudePassthroughMCPConfig(t *testing.T, cmd agents.Command, wantURL string) {
t.Helper()
args := cmd.Args()
for i, arg := range args {
if arg != "--mcp-config" {
continue
}
if i+1 >= len(args) {
t.Fatalf("--mcp-config missing path in command %v", args)
}
if i != len(args)-2 {
t.Fatalf("--mcp-config must be final flag pair for claude variadic parsing: %v", args)
}
var payload struct {
MCPServers map[string]struct {
Type string `json:"type"`
URL string `json:"url"`
} `json:"mcpServers"`
}
data, err := os.ReadFile(args[i+1])
if err != nil {
t.Fatalf("read generated MCP config: %v", err)
}
if err := json.Unmarshal(data, &payload); err != nil {
t.Fatalf("generated MCP config is not JSON: %v\n%s", err, data)
}
kandev := payload.MCPServers["kandev"]
if kandev.Type != "http" {
t.Fatalf("kandev MCP type = %q, want http", kandev.Type)
}
if kandev.URL != wantURL {
t.Fatalf("kandev MCP url = %q, want %q", kandev.URL, wantURL)
}
return
}
t.Fatalf("passthrough command missing --mcp-config: %v", args)
}
func newClaudePassthroughMCPTestManager(t *testing.T) (*Manager, *AgentExecution, *AgentProfileInfo) {
t.Helper()
mgr := newTestManager()
mgr.dataDir = t.TempDir()
mgr.profileResolver = &mockPassthroughProfileResolver{
agentName: "claude-acp",
cliPassthrough: true,
}
execution := &AgentExecution{
ID: "exec-1",
TaskID: "task-1",
SessionID: "session-1",
AgentProfileID: "profile-1",
WorkspacePath: t.TempDir(),
Metadata: map[string]interface{}{
"standalone_port": 45678,
},
standalonePort: 45678,
}
profile := &AgentProfileInfo{
ProfileID: "profile-1",
AgentName: "claude-acp",
Model: "default",
CLIPassthrough: true,
}
return mgr, execution, profile
}
func TestBuildPassthroughCommand(t *testing.T) {
tests := []struct {
name string
@@ -228,6 +301,41 @@ func TestBuildPassthroughCommand(t *testing.T) {
},
wantCmd: []string{"test-cli", "--model", "gpt-4", "--yes", "--debug", "--log-level", "trace", "-c"},
},
{
name: "mcp config flag goes after positional prompt because claude treats it as variadic",
agent: &testAgent{
id: "test-agent",
StandardPassthrough: agents.StandardPassthrough{
Cfg: agents.PassthroughConfig{
Supported: true,
PassthroughCmd: agents.NewCommand("test-cli"),
MCPConfigFlag: agents.NewParam("--mcp-config", "{mcp_config}"),
},
},
},
opts: agents.PassthroughOptions{
Prompt: "fix the bug",
MCPConfigPath: "/tmp/kandev-mcp.json",
},
wantCmd: []string{"test-cli", "fix the bug", "--mcp-config", "/tmp/kandev-mcp.json"},
},
{
name: "mcp config flag without placeholder still appends path",
agent: &testAgent{
id: "test-agent",
StandardPassthrough: agents.StandardPassthrough{
Cfg: agents.PassthroughConfig{
Supported: true,
PassthroughCmd: agents.NewCommand("test-cli"),
MCPConfigFlag: agents.NewParam("--mcp-config"),
},
},
},
opts: agents.PassthroughOptions{
MCPConfigPath: "/tmp/kandev-mcp.json",
},
wantCmd: []string{"test-cli", "--mcp-config", "/tmp/kandev-mcp.json"},
},
}
for _, tt := range tests {
@@ -248,6 +356,114 @@ func TestBuildPassthroughCommand(t *testing.T) {
}
}
func TestPassthroughAgentCommandInjectsKandevMCPConfig(t *testing.T) {
mgr, execution, profile := newClaudePassthroughMCPTestManager(t)
_, _, _, cmd, err := mgr.passthroughAgentCommand(execution, profile)
if err != nil {
t.Fatalf("passthroughAgentCommand returned error: %v", err)
}
assertClaudePassthroughMCPConfig(t, cmd, "http://localhost:45678/mcp")
}
func TestFreshPassthroughCommandInjectsKandevMCPConfig(t *testing.T) {
mgr, execution, _ := newClaudePassthroughMCPTestManager(t)
_, _, cmd, err := mgr.freshPassthroughCommand(context.Background(), execution)
if err != nil {
t.Fatalf("freshPassthroughCommand returned error: %v", err)
}
assertClaudePassthroughMCPConfig(t, cmd, "http://localhost:45678/mcp")
}
func TestResumePassthroughCommandInjectsKandevMCPConfig(t *testing.T) {
mgr, execution, _ := newClaudePassthroughMCPTestManager(t)
resolved, err := mgr.resolvePassthroughAgent(context.Background(), execution)
if err != nil {
t.Fatalf("resolvePassthroughAgent returned error: %v", err)
}
cmd, err := mgr.resumePassthroughCommand(execution, resolved, true)
if err != nil {
t.Fatalf("resumePassthroughCommand returned error: %v", err)
}
assertClaudePassthroughMCPConfig(t, cmd, "http://localhost:45678/mcp")
}
func TestResumePassthroughSessionWithoutRunnerDoesNotWriteMCPConfig(t *testing.T) {
mgr, execution, _ := newClaudePassthroughMCPTestManager(t)
mgr.executorRegistry = nil
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("add execution: %v", err)
}
err := mgr.ResumePassthroughSession(context.Background(), execution.SessionID)
if err == nil {
t.Fatal("ResumePassthroughSession returned nil, want missing runner error")
}
if path := passthroughMCPConfigPath(execution); path != "" {
t.Fatalf("passthrough MCP config path = %q, want empty", path)
}
}
func TestPassthroughAgentCommandErrorsWhenMCPPortMissing(t *testing.T) {
mgr, execution, profile := newClaudePassthroughMCPTestManager(t)
execution.standalonePort = 0
delete(execution.Metadata, "standalone_port")
_, _, _, _, err := mgr.passthroughAgentCommand(execution, profile)
if err == nil {
t.Fatal("passthroughAgentCommand returned nil, want missing MCP port error")
}
if err.Error() != "standalone port unavailable for passthrough MCP config" {
t.Fatalf("error = %q, want missing MCP port error", err.Error())
}
}
func TestRemoveExecutionCleansPassthroughMCPConfig(t *testing.T) {
mgr, execution, profile := newClaudePassthroughMCPTestManager(t)
execution.Metadata = nil
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("add execution: %v", err)
}
_, _, _, cmd, err := mgr.passthroughAgentCommand(execution, profile)
if err != nil {
t.Fatalf("passthroughAgentCommand returned error: %v", err)
}
assertClaudePassthroughMCPConfig(t, cmd, "http://localhost:45678/mcp")
path := passthroughMCPConfigPath(execution)
if path == "" {
t.Fatal("passthrough MCP config path was not stored")
}
mgr.RemoveExecution(execution.ID)
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("generated MCP config still exists or stat failed: %v", err)
}
if path := passthroughMCPConfigPath(execution); path != "" {
t.Fatalf("passthrough MCP config path metadata = %q, want empty", path)
}
}
func TestWritePassthroughMCPConfigKeepsLiteralSessionFilename(t *testing.T) {
mgr, execution, profile := newClaudePassthroughMCPTestManager(t)
execution.SessionID = "session"
_, _, _, cmd, err := mgr.passthroughAgentCommand(execution, profile)
if err != nil {
t.Fatalf("passthroughAgentCommand returned error: %v", err)
}
assertClaudePassthroughMCPConfig(t, cmd, "http://localhost:45678/mcp")
if got, want := passthroughMCPConfigPath(execution), filepath.Join(mgr.dataDir, "passthrough-mcp", "session.json"); got != want {
t.Fatalf("passthrough MCP config path = %q, want session filename", got)
}
}
// TestManager_HandlePassthroughExit_SkipsDuringShutdown verifies that the
// detached goroutine spawned when a passthrough child exits bails out
// immediately once graceful shutdown has begun, instead of racing the
+12
View File
@@ -44,6 +44,12 @@ The orchestrator's `PromptTask` handler branches on `IsPassthroughSession(sessio
**UI gap (deferred):** kandev's chat compose box is rendered by `ChatInputArea`, which is replaced entirely by `PassthroughTerminal` when `session.is_passthrough` is true. There is no compose surface in passthrough mode today. Users send follow-ups by typing directly into the terminal (xterm forwards each keystroke to the PTY) — which works perfectly for the Claude CLI use case. A dedicated kandev compose box that drives the PTY (without replacing the terminal) is a follow-up.
### Kandev MCP tools are wired for CLI mode
When a passthrough agent supports an MCP config flag, kandev generates a per-session MCP config file that points at the task's local agentctl MCP endpoint and launches the CLI with that config. The generated config exposes the same kandev tool server used by ACP sessions, scoped by the already-known `KANDEV_TASK_ID` / `KANDEV_SESSION_ID` context.
For the Claude case, the passthrough command includes `--mcp-config <generated-file>` with an `mcpServers.kandev` HTTP entry for the local agentctl `/mcp` endpoint.
### Stop sends Ctrl-C (backend route landed; UI surface deferred)
The orchestrator's `CancelAgent` handler branches on `IsPassthroughSession(sessionID)` and writes `\x03` to the PTY's stdin instead of sending an ACP cancel. DB reconciliation still runs so the UI unsticks regardless of the write outcome.
@@ -78,6 +84,12 @@ The orchestrator's `CancelAgent` handler branches on `IsPassthroughSession(sessi
- THEN the text + `SubmitSequence` is written to the PTY
- AND no ACP prompt is sent
### Kandev MCP config is present for Claude passthrough
- GIVEN a Claude profile with `cli_passthrough: true`
- WHEN kandev starts or fresh-starts its passthrough command
- THEN the argv includes `--mcp-config <generated-file>`
- AND the generated file contains `mcpServers.kandev` pointing at the local agentctl `/mcp` endpoint
### Stop / cancel route is in place (UI surface follow-up)
- GIVEN a CLI-mode task running
- WHEN any caller invokes `CancelAgent` for the session