Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): add per-agent mcp_config field to restore MCP access (#1168)
Korkyzer63800f05ff8c
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 5640714ac8..3ab9fc0b42 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -2,6 +2,7 @@ package daemonimport ("context"+ "encoding/json""errors""fmt""log/slog"@@ -27,7 +28,7 @@ var ErrRepoNotConfigured = errors.New("repo is not configured for this workspacetype workspaceState struct {workspaceID stringruntimeIDs []string- reposVersion string // stored for future use: skip refresh when version unchanged+ reposVersion string // stored for future use: skip refresh when version unchangedallowedRepoURLs map[string]struct{}lastRepoSyncErr stringrepoRefreshMu sync.Mutex@@ -1006,8 +1007,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLotaskStart := time.Now()var customArgs []string+ var mcpConfig json.RawMessageif task.Agent != nil {customArgs = task.Agent.CustomArgs+ mcpConfig = task.Agent.McpConfig}execOpts := agent.ExecOptions{Cwd: env.WorkDir,@@ -1015,6 +1018,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLoTimeout: d.cfg.AgentTimeout,ResumeSessionID: task.PriorSessionID,CustomArgs: customArgs,+ McpConfig: mcpConfig,}result, tools, err := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID)diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 1366a62dd5..8dd1e859ec 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -1,5 +1,7 @@package daemon+import "encoding/json"+// AgentEntry describes a single available agent CLI.type AgentEntry struct {Path string // path to CLI binary@@ -23,15 +25,15 @@ type RepoData struct {// Task represents a claimed task from the server.// Agent data (name, skills) is populated by the claim endpoint.type Task struct {- ID string `json:"id"`- AgentID string `json:"agent_id"`- RuntimeID string `json:"runtime_id"`- IssueID string `json:"issue_id"`- WorkspaceID string `json:"workspace_id"`- Agent *AgentData `json:"agent,omitempty"`- Repos []RepoData `json:"repos,omitempty"`- PriorSessionID string `json:"prior_session_id,omitempty"` // Claude session ID from a previous task on this issue- PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on this issue+ ID string `json:"id"`+ AgentID string `json:"agent_id"`+ RuntimeID string `json:"runtime_id"`+ IssueID string `json:"issue_id"`+ WorkspaceID string `json:"workspace_id"`+ Agent *AgentData `json:"agent,omitempty"`+ Repos []RepoData `json:"repos,omitempty"`+ PriorSessionID string `json:"prior_session_id,omitempty"` // Claude session ID from a previous task on this issue+ PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on this issueTriggerCommentID string `json:"trigger_comment_id,omitempty"` // comment that triggered this taskTriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering commentChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks@@ -46,6 +48,7 @@ type AgentData struct {Skills []SkillData `json:"skills"`CustomEnv map[string]string `json:"custom_env,omitempty"`CustomArgs []string `json:"custom_args,omitempty"`+ McpConfig json.RawMessage `json:"mcp_config,omitempty"`}// SkillData represents a structured skill for task execution.diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 80be91906b..09a14299de 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -1,9 +1,11 @@package handlerimport (+ "bytes""encoding/json""errors""fmt"+ "io""log/slog""net/http"@@ -28,7 +30,9 @@ type AgentResponse struct {RuntimeConfig any `json:"runtime_config"`CustomEnv map[string]string `json:"custom_env"`CustomArgs []string `json:"custom_args"`+ McpConfig json.RawMessage `json:"mcp_config"`CustomEnvRedacted bool `json:"custom_env_redacted"`+ McpConfigRedacted bool `json:"mcp_config_redacted"`Visibility string `json:"visibility"`Status string `json:"status"`MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`@@ -69,6 +73,11 @@ func agentToResponse(a db.Agent) AgentResponse {customArgs = []string{}}+ var mcpConfig json.RawMessage+ if a.McpConfig != nil {+ mcpConfig = json.RawMessage(a.McpConfig)+ }+return AgentResponse{ID: uuidToString(a.ID),WorkspaceID: uuidToString(a.WorkspaceID),@@ -81,6 +90,7 @@ func agentToResponse(a db.Agent) AgentResponse {RuntimeConfig: rc,CustomEnv: customEnv,CustomArgs: customArgs,+ McpConfig: mcpConfig,Visibility: a.Visibility,Status: a.Status,MaxConcurrentTasks: a.MaxConcurrentTasks,@@ -101,23 +111,23 @@ type RepoData struct {}type AgentTaskResponse struct {- ID string `json:"id"`- AgentID string `json:"agent_id"`- RuntimeID string `json:"runtime_id"`- IssueID string `json:"issue_id"`- WorkspaceID string `json:"workspace_id"`- Status string `json:"status"`- Priority int32 `json:"priority"`- DispatchedAt *string `json:"dispatched_at"`- StartedAt *string `json:"started_at"`- CompletedAt *string `json:"completed_at"`- Result any `json:"result"`- Error *string `json:"error"`- Agent *TaskAgentData `json:"agent,omitempty"`- Repos []RepoData `json:"repos,omitempty"`- CreatedAt string `json:"created_at"`- PriorSessionID string `json:"prior_session_id,omitempty"` // session ID from a previous task on same issue- PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issue+ ID string `json:"id"`+ AgentID string `json:"agent_id"`+ RuntimeID string `json:"runtime_id"`+ IssueID string `json:"issue_id"`+ WorkspaceID string `json:"workspace_id"`+ Status string `json:"status"`+ Priority int32 `json:"priority"`+ DispatchedAt *string `json:"dispatched_at"`+ StartedAt *string `json:"started_at"`+ CompletedAt *string `json:"completed_at"`+ Result any `json:"result"`+ Error *string `json:"error"`+ Agent *TaskAgentData `json:"agent,omitempty"`+ Repos []RepoData `json:"repos,omitempty"`+ CreatedAt string `json:"created_at"`+ PriorSessionID string `json:"prior_session_id,omitempty"` // session ID from a previous task on same issue+ PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issueTriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this taskTriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering commentChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks@@ -133,6 +143,7 @@ type TaskAgentData struct {Skills []service.AgentSkillData `json:"skills,omitempty"`CustomEnv map[string]string `json:"custom_env,omitempty"`CustomArgs []string `json:"custom_args,omitempty"`+ McpConfig json.RawMessage `json:"mcp_config,omitempty"`}func taskToResponse(t db.AgentTaskQueue) AgentTaskResponse {@@ -141,16 +152,16 @@ func taskToResponse(t db.AgentTaskQueue) AgentTaskResponse {json.Unmarshal(t.Result, &result)}return AgentTaskResponse{- ID: uuidToString(t.ID),- AgentID: uuidToString(t.AgentID),- RuntimeID: uuidToString(t.RuntimeID),- IssueID: uuidToString(t.IssueID),- Status: t.Status,- Priority: t.Priority,- DispatchedAt: timestampToPtr(t.DispatchedAt),- StartedAt: timestampToPtr(t.StartedAt),- CompletedAt: timestampToPtr(t.CompletedAt),- Result: result,+ ID: uuidToString(t.ID),+ AgentID: uuidToString(t.AgentID),+ RuntimeID: uuidToString(t.RuntimeID),+ IssueID: uuidToString(t.IssueID),+ Status: t.Status,+ Priority: t.Priority,+ DispatchedAt: timestampToPtr(t.DispatchedAt),+ StartedAt: timestampToPtr(t.StartedAt),+ CompletedAt: timestampToPtr(t.CompletedAt),+ Result: result,Error: textToPtr(t.Error),CreatedAt: timestampToString(t.CreatedAt),TriggerCommentID: uuidToPtr(t.TriggerCommentID),@@ -200,9 +211,10 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {if skills, ok := skillMap[resp.ID]; ok {resp.Skills = skills}- // Redact custom_env for users who are not the agent owner or workspace owner/admin.+ // Redact sensitive fields for users who are not the agent owner or workspace owner/admin.if !canViewAgentEnv(a, userID, member.Role) {redactEnv(&resp)+ redactMcpConfig(&resp)}visible = append(visible, resp)}@@ -229,11 +241,12 @@ func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) {}}- // Redact custom_env for users who are not the agent owner or workspace owner/admin.+ // Redact sensitive fields for users who are not the agent owner or workspace owner/admin.userID := requestUserID(r)if member, ok := ctxMember(r.Context()); ok {if !canViewAgentEnv(agent, userID, member.Role) {redactEnv(&resp)+ redactMcpConfig(&resp)}}@@ -249,15 +262,38 @@ type CreateAgentRequest struct {RuntimeConfig any `json:"runtime_config"`CustomEnv map[string]string `json:"custom_env"`CustomArgs []string `json:"custom_args"`+ McpConfig json.RawMessage `json:"mcp_config"`Visibility string `json:"visibility"`MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`}+func decodeJSONBodyWithRawFields(body io.Reader, dst any) (map[string]json.RawMessage, error) {+ payload, err := io.ReadAll(body)+ if err != nil {+ return nil, err+ }++ if err := json.Unmarshal(payload, dst); err != nil {+ return nil, err+ }++ var raw map[string]json.RawMessage+ if err := json.Unmarshal(payload, &raw); err != nil {+ return nil, err+ }+ if raw == nil {+ raw = map[string]json.RawMessage{}+ }++ return raw, nil+}+func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {workspaceID := h.resolveWorkspaceID(r)var req CreateAgentRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ rawFields, err := decodeJSONBodyWithRawFields(r.Body, &req)+ if err != nil {writeError(w, http.StatusBadRequest, "invalid request body")return}@@ -306,6 +342,11 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {ca = []byte("[]")}+ var mc []byte+ if rawMcpConfig, ok := rawFields["mcp_config"]; ok && !bytes.Equal(bytes.TrimSpace(rawMcpConfig), []byte("null")) {+ mc = append([]byte(nil), rawMcpConfig...)+ }+agent, err := h.Queries.CreateAgent(r.Context(), db.CreateAgentParams{WorkspaceID: parseUUID(workspaceID),Name: req.Name,@@ -320,6 +361,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {OwnerID: parseUUID(ownerID),CustomEnv: ce,CustomArgs: ca,+ McpConfig: mc,})if err != nil {// Unique constraint on (workspace_id, name) — return a clear conflict error@@ -346,8 +388,6 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusCreated, resp)}--type UpdateAgentRequest struct {Name *string `json:"name"`Description *string `json:"description"`@@ -357,6 +397,7 @@ type UpdateAgentRequest struct {RuntimeConfig any `json:"runtime_config"`CustomEnv *map[string]string `json:"custom_env"`CustomArgs *[]string `json:"custom_args"`+ McpConfig *json.RawMessage `json:"mcp_config"`Visibility *string `json:"visibility"`Status *string `json:"status"`MaxConcurrentTasks *int32 `json:"max_concurrent_tasks"`@@ -384,6 +425,16 @@ func redactEnv(resp *AgentResponse) {resp.CustomEnvRedacted = true}+// redactMcpConfig removes the mcp_config value from the response when the caller is not+// authorised to view it. The field is set to null; McpConfigRedacted is set to true so+// callers know a config exists without seeing its contents (which may contain secrets).+func redactMcpConfig(resp *AgentResponse) {+ if resp.McpConfig != nil {+ resp.McpConfig = nil+ resp.McpConfigRedacted = true+ }+}+// canManageAgent checks whether the current user can update or archive an agent.// Only the agent owner or workspace owner/admin can manage any agent,// regardless of whether it is public or private.@@ -413,7 +464,8 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {}var req UpdateAgentRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ rawFields, err := decodeJSONBodyWithRawFields(r.Body, &req)+ if err != nil {writeError(w, http.StatusBadRequest, "invalid request body")return}@@ -445,6 +497,11 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {ca, _ := json.Marshal(*req.CustomArgs)params.CustomArgs = ca}+ rawMcpConfig, hasMcpConfig := rawFields["mcp_config"]+ shouldClearMcpConfig := hasMcpConfig && bytes.Equal(bytes.TrimSpace(rawMcpConfig), []byte("null"))+ if hasMcpConfig && !shouldClearMcpConfig {+ params.McpConfig = append([]byte(nil), rawMcpConfig...)+ }if req.RuntimeID != nil {runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{ID: parseUUID(*req.RuntimeID),@@ -467,13 +524,24 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {params.MaxConcurrentTasks = pgtype.Int4{Int32: *req.MaxConcurrentTasks, Valid: true}}- agent, err := h.Queries.UpdateAgent(r.Context(), params)+ agent, err = h.Queries.UpdateAgent(r.Context(), params)if err != nil {slog.Warn("update agent failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)writeError(w, http.StatusInternalServerError, "failed to update agent: "+err.Error())return}+ // mcp_config: null in the request means explicitly clear the field.+ // COALESCE in UpdateAgent cannot set a column to NULL, so we use a dedicated query.+ if shouldClearMcpConfig {+ agent, err = h.Queries.ClearAgentMcpConfig(r.Context(), parseUUID(id))+ if err != nil {+ slog.Warn("clear agent mcp_config failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)+ writeError(w, http.StatusInternalServerError, "failed to clear mcp_config: "+err.Error())+ return+ }+ }+resp := agentToResponse(agent)slog.Info("agent updated", append(logger.RequestAttrs(r), "agent_id", id, "workspace_id", uuidToString(agent.WorkspaceID))...)userID := requestUserID(r)diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex b754fbdad6..0dcd1232cd 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -534,6 +534,10 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {slog.Warn("failed to unmarshal agent custom_args", "agent_id", uuidToString(agent.ID), "error", err)}}+ var mcpConfig json.RawMessage+ if agent.McpConfig != nil {+ mcpConfig = json.RawMessage(agent.McpConfig)+ }resp.Agent = &TaskAgentData{ID: uuidToString(agent.ID),Name: agent.Name,@@ -541,6 +545,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {Skills: skills,CustomEnv: customEnv,CustomArgs: customArgs,+ McpConfig: mcpConfig,}}diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex 0b3ea69da2..278386df53 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -158,6 +158,81 @@ func withURLParam(req *http.Request, key, value string) *http.Request {return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))}+func handlerTestRuntimeID(t *testing.T) string {+ t.Helper()++ var runtimeID string+ if err := testPool.QueryRow(context.Background(),+ `SELECT id FROM agent_runtime WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,+ testWorkspaceID,+ ).Scan(&runtimeID); err != nil {+ t.Fatalf("failed to load handler test runtime: %v", err)+ }++ return runtimeID+}++func createHandlerTestAgent(t *testing.T, name string, mcpConfig []byte) string {+ t.Helper()++ var agentID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks, owner_id,+ instructions, custom_env, custom_args, mcp_config+ )+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4, '', '{}'::jsonb, '[]'::jsonb, $5)+ RETURNING id+ `, testWorkspaceID, name, handlerTestRuntimeID(t), testUserID, mcpConfig).Scan(&agentID); err != nil {+ t.Fatalf("failed to create handler test agent: %v", err)+ }++ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)+ })++ return agentID+}++func fetchAgentMcpConfig(t *testing.T, agentID string) []byte {+ t.Helper()++ var mcpConfig []byte+ if err := testPool.QueryRow(context.Background(), `SELECT mcp_config FROM agent WHERE id = $1`, agentID).Scan(&mcpConfig); err != nil {+ t.Fatalf("failed to load agent mcp_config: %v", err)+ }++ return mcpConfig+}++func assertJSONEqual(t *testing.T, got []byte, want string) {+ t.Helper()++ var gotValue any+ if err := json.Unmarshal(got, &gotValue); err != nil {+ t.Fatalf("failed to unmarshal got JSON %q: %v", string(got), err)+ }++ var wantValue any+ if err := json.Unmarshal([]byte(want), &wantValue); err != nil {+ t.Fatalf("failed to unmarshal want JSON %q: %v", want, err)+ }++ gotJSON, err := json.Marshal(gotValue)+ if err != nil {+ t.Fatalf("failed to marshal normalized got JSON: %v", err)+ }+ wantJSON, err := json.Marshal(wantValue)+ if err != nil {+ t.Fatalf("failed to marshal normalized want JSON: %v", err)+ }++ if string(gotJSON) != string(wantJSON) {+ t.Fatalf("expected JSON %s, got %s", string(wantJSON), string(gotJSON))+ }+}+func TestIssueCRUD(t *testing.T) {// Createw := httptest.NewRecorder()@@ -538,6 +613,99 @@ func TestAgentCRUD(t *testing.T) {}}+func TestUpdateAgentMcpConfigAbsentPreservesValue(t *testing.T) {+ agentID := createHandlerTestAgent(t, "Handler Mcp Preserve", []byte(`{"preset":"keep"}`))++ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/agents/"+agentID, map[string]any{+ "name": "Handler Mcp Preserve Updated",+ })+ req = withURLParam(req, "id", agentID)+ testHandler.UpdateAgent(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgent: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var updated AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {+ t.Fatalf("UpdateAgent: decode response: %v", err)+ }+ assertJSONEqual(t, updated.McpConfig, `{"preset":"keep"}`)+ assertJSONEqual(t, fetchAgentMcpConfig(t, agentID), `{"preset":"keep"}`)+}++func TestUpdateAgentMcpConfigNullClearsValue(t *testing.T) {+ agentID := createHandlerTestAgent(t, "Handler Mcp Clear", []byte(`{"preset":"clear"}`))++ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/agents/"+agentID, map[string]any{+ "mcp_config": nil,+ })+ req = withURLParam(req, "id", agentID)+ testHandler.UpdateAgent(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgent: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var updated AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {+ t.Fatalf("UpdateAgent: decode response: %v", err)+ }+ assertJSONEqual(t, updated.McpConfig, `null`)+ if fetchAgentMcpConfig(t, agentID) != nil {+ t.Fatalf("UpdateAgent: expected DB mcp_config to be SQL NULL")+ }+}++func TestUpdateAgentMcpConfigObjectUpdatesValue(t *testing.T) {+ agentID := createHandlerTestAgent(t, "Handler Mcp Update", []byte(`{"preset":"old"}`))++ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/agents/"+agentID, map[string]any{+ "mcp_config": map[string]any{"preset": "new"},+ })+ req = withURLParam(req, "id", agentID)+ testHandler.UpdateAgent(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgent: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var updated AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {+ t.Fatalf("UpdateAgent: decode response: %v", err)+ }+ assertJSONEqual(t, updated.McpConfig, `{"preset":"new"}`)+ assertJSONEqual(t, fetchAgentMcpConfig(t, agentID), `{"preset":"new"}`)+}++func TestCreateAgentMcpConfigNullStoresSQLNull(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/agents", map[string]any{+ "name": "Handler Mcp Create Null",+ "runtime_id": handlerTestRuntimeID(t),+ "mcp_config": nil,+ "custom_env": map[string]string{},+ "custom_args": []string{},+ })+ testHandler.CreateAgent(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateAgent: expected 201, got %d: %s", w.Code, w.Body.String())+ }++ var created AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {+ t.Fatalf("CreateAgent: decode response: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, created.ID)+ })++ assertJSONEqual(t, created.McpConfig, `null`)+ if fetchAgentMcpConfig(t, created.ID) != nil {+ t.Fatalf("CreateAgent: expected DB mcp_config to be SQL NULL")+ }+}+func TestWorkspaceCRUD(t *testing.T) {// List workspacesw := httptest.NewRecorder()diff --git a/server/migrations/046_agent_mcp_config.down.sql b/server/migrations/046_agent_mcp_config.down.sqlnew file mode 100644index 0000000000..bf0d3575c8--- /dev/null+++ b/server/migrations/046_agent_mcp_config.down.sql@@ -0,0 +1 @@+ALTER TABLE agent DROP COLUMN IF EXISTS mcp_config;diff --git a/server/migrations/046_agent_mcp_config.up.sql b/server/migrations/046_agent_mcp_config.up.sqlnew file mode 100644index 0000000000..1526091ac1--- /dev/null+++ b/server/migrations/046_agent_mcp_config.up.sql@@ -0,0 +1 @@+ALTER TABLE agent ADD COLUMN mcp_config jsonb;diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 01914e780b..9801f79ca2 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -5,6 +5,7 @@ package agentimport ("context"+ "encoding/json""fmt""log/slog""time"@@ -25,8 +26,9 @@ type ExecOptions struct {SystemPrompt stringMaxTurns intTimeout time.Duration- ResumeSessionID string // if non-empty, resume a previous agent session- CustomArgs []string // additional CLI arguments appended to the agent command+ ResumeSessionID string // if non-empty, resume a previous agent session+ CustomArgs []string // additional CLI arguments appended to the agent command+ McpConfig json.RawMessage // if non-nil, MCP server config to pass via --mcp-config}// Session represents a running agent execution.diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex a6929ebdd4..f2f6b2baf0 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -36,6 +36,28 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptargs := buildClaudeArgs(opts, b.cfg.Logger)+ // If the caller provided an MCP config, write it to a temp file and pass+ // --mcp-config <path> so the agent uses a controlled set of MCP servers+ // instead of inheriting from the outer Claude Code session.+ var mcpConfigPath string+ var mcpFileCleanup func() // non-nil while this function owns the temp file+ if len(opts.McpConfig) > 0 {+ path, err := writeMcpConfigToTemp(opts.McpConfig)+ if err != nil {+ cancel()+ return nil, err+ }+ mcpConfigPath = path+ mcpFileCleanup = func() { os.Remove(mcpConfigPath) }+ args = append(args, "--mcp-config", mcpConfigPath)+ }+ // Clean up the temp file if we return before the goroutine takes ownership.+ defer func() {+ if mcpFileCleanup != nil {+ mcpFileCleanup()+ }+ }()+cmd := exec.CommandContext(runCtx, execPath, args...)b.cfg.Logger.Debug("agent command", "exec", execPath, "args", args)cmd.WaitDelay = 10 * time.Second@@ -77,6 +99,9 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptb.cfg.Logger.Info("claude started", "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)+ // cmd.Start() succeeded — transfer temp file ownership to the goroutine.+ mcpFileCleanup = nil+msgCh := make(chan Message, 256)resCh := make(chan Result, 1)@@ -84,6 +109,9 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptdefer cancel()defer close(msgCh)defer close(resCh)+ if mcpConfigPath != "" {+ defer os.Remove(mcpConfigPath)+ }startTime := time.Now()var output strings.Builder@@ -347,10 +375,11 @@ func trySend(ch chan<- Message, msg Message) {// overridden by user-configured custom_args. Overriding these would break// the daemon↔Claude communication protocol.var claudeBlockedArgs = map[string]blockedArgMode{- "-p": blockedStandalone, // non-interactive mode- "--output-format": blockedWithValue, // stream-json protocol- "--input-format": blockedWithValue, // stream-json protocol+ "-p": blockedStandalone, // non-interactive mode+ "--output-format": blockedWithValue, // stream-json protocol+ "--input-format": blockedWithValue, // stream-json protocol"--permission-mode": blockedWithValue, // bypassPermissions for autonomous operation+ "--mcp-config": blockedWithValue, // set by daemon from agent.mcp_config}func buildClaudeArgs(opts ExecOptions, logger *slog.Logger) []string {@@ -438,7 +467,7 @@ func isFilteredChildEnvKey(key string) bool {type blockedArgMode intconst (- blockedWithValue blockedArgMode = iota // flag takes a value (next arg or =value)+ blockedWithValue blockedArgMode = iota // flag takes a value (next arg or =value)blockedStandalone // flag is boolean, no value)@@ -480,6 +509,25 @@ func filterCustomArgs(args []string, blocked map[string]blockedArgMode, logger *return filtered}+// writeMcpConfigToTemp writes raw MCP config JSON to a temporary file and returns+// its path. The caller is responsible for removing the file when done.+func writeMcpConfigToTemp(raw json.RawMessage) (string, error) {+ f, err := os.CreateTemp("", "multica-mcp-*.json")+ if err != nil {+ return "", fmt.Errorf("create mcp config temp file: %w", err)+ }+ if _, err := f.Write(raw); err != nil {+ f.Close()+ os.Remove(f.Name())+ return "", fmt.Errorf("write mcp config temp file: %w", err)+ }+ if err := f.Close(); err != nil {+ os.Remove(f.Name())+ return "", fmt.Errorf("close mcp config temp file: %w", err)+ }+ return f.Name(), nil+}+func detectCLIVersion(ctx context.Context, execPath string) (string, error) {cmd := exec.CommandContext(ctx, execPath, "--version")data, err := cmd.Output()diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.goindex 9ab4d1c2de..97b17e1157 100644--- a/server/pkg/agent/claude_test.go+++ b/server/pkg/agent/claude_test.go@@ -4,6 +4,7 @@ import ("bytes""encoding/json""log/slog"+ "os""strings""testing")@@ -221,9 +222,9 @@ func TestFilterCustomArgsBlocksProtocolFlags(t *testing.T) {t.Parallel()blocked := map[string]blockedArgMode{- "--output-format": blockedWithValue,+ "--output-format": blockedWithValue,"--permission-mode": blockedWithValue,- "-p": blockedStandalone,+ "-p": blockedStandalone,}logger := slog.Default()@@ -409,6 +410,62 @@ func TestBuildEnvNilExtras(t *testing.T) {}}+func TestBuildClaudeArgsBlocksMcpConfig(t *testing.T) {+ t.Parallel()++ // --mcp-config is hardcoded by the daemon — it must not be overridable via custom_args.+ args := buildClaudeArgs(ExecOptions{+ CustomArgs: []string{"--mcp-config", "/tmp/evil.json", "--model", "o3"},+ }, slog.Default())++ for i, a := range args {+ if a == "--mcp-config" {+ t.Fatalf("--mcp-config should be blocked from custom_args, found at index %d: %v", i, args)+ }+ if a == "/tmp/evil.json" {+ t.Fatalf("--mcp-config value should be consumed when blocking, but found it at index %d: %v", i, args)+ }+ }++ // Non-blocked args should still pass through.+ foundModel := false+ for i, a := range args {+ if a == "--model" && i+1 < len(args) && args[i+1] == "o3" {+ foundModel = true+ }+ }+ if !foundModel {+ t.Fatalf("expected --model o3 in args after blocking --mcp-config: %v", args)+ }+}++func TestWriteMcpConfigToTemp(t *testing.T) {+ t.Parallel()++ raw := json.RawMessage(`{"mcpServers":{"test":{"command":"echo","args":["hello"]}}}`)+ path, err := writeMcpConfigToTemp(raw)+ if err != nil {+ t.Fatalf("writeMcpConfigToTemp: %v", err)+ }++ // File should exist and contain exactly the raw JSON.+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read temp file %s: %v", path, err)+ }+ if !bytes.Equal(data, []byte(raw)) {+ t.Fatalf("expected %s, got %s", raw, data)+ }++ // Cleanup should remove the file.+ if err := os.Remove(path); err != nil {+ t.Fatalf("remove temp file: %v", err)+ }+ if _, err := os.Stat(path); !os.IsNotExist(err) {+ t.Fatalf("expected temp file to be removed, but it still exists")+ }+}+func mustMarshal(t *testing.T, v any) json.RawMessage {t.Helper()data, err := json.Marshal(v)diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 24c71ca941..d6dccb966f 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -14,7 +14,7 @@ import (const archiveAgent = `-- name: ArchiveAgent :oneUPDATE agent SET archived_at = now(), archived_by = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config`type ArchiveAgentParams struct {@@ -45,6 +45,41 @@ func (q *Queries) ArchiveAgent(ctx context.Context, arg ArchiveAgentParams) (Age&i.ArchivedBy,&i.CustomEnv,&i.CustomArgs,+ &i.McpConfig,+ )+ return i, err+}++const clearAgentMcpConfig = `-- name: ClearAgentMcpConfig :one+UPDATE agent SET mcp_config = NULL, updated_at = now()+WHERE id = $1+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config+`++func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agent, error) {+ row := q.db.QueryRow(ctx, clearAgentMcpConfig, id)+ var i Agent+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.AvatarUrl,+ &i.RuntimeMode,+ &i.RuntimeConfig,+ &i.Visibility,+ &i.Status,+ &i.MaxConcurrentTasks,+ &i.OwnerID,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Description,+ &i.RuntimeID,+ &i.Instructions,+ &i.ArchivedAt,+ &i.ArchivedBy,+ &i.CustomEnv,+ &i.CustomArgs,+ &i.McpConfig,)return i, err}@@ -218,9 +253,9 @@ const createAgent = `-- name: CreateAgent :oneINSERT INTO agent (workspace_id, name, description, avatar_url, runtime_mode,runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id,- instructions, custom_env, custom_args-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args+ instructions, custom_env, custom_args, mcp_config+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config`type CreateAgentParams struct {@@ -237,6 +272,7 @@ type CreateAgentParams struct {Instructions string `json:"instructions"`CustomEnv []byte `json:"custom_env"`CustomArgs []byte `json:"custom_args"`+ McpConfig []byte `json:"mcp_config"`}func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) {@@ -254,6 +290,7 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agentarg.Instructions,arg.CustomEnv,arg.CustomArgs,+ arg.McpConfig,)var i Agenterr := row.Scan(@@ -276,6 +313,7 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent&i.ArchivedBy,&i.CustomEnv,&i.CustomArgs,+ &i.McpConfig,)return i, err}@@ -407,7 +445,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)}const getAgent = `-- name: GetAgent :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config FROM agentWHERE id = $1`@@ -434,12 +472,13 @@ func (q *Queries) GetAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {&i.ArchivedBy,&i.CustomEnv,&i.CustomArgs,+ &i.McpConfig,)return i, err}const getAgentInWorkspace = `-- name: GetAgentInWorkspace :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config FROM agentWHERE id = $1 AND workspace_id = $2`@@ -471,6 +510,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa&i.ArchivedBy,&i.CustomEnv,&i.CustomArgs,+ &i.McpConfig,)return i, err}@@ -671,7 +711,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag}const listAgents = `-- name: ListAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config FROM agentWHERE workspace_id = $1 AND archived_at IS NULLORDER BY created_at ASC`@@ -705,6 +745,7 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag&i.ArchivedBy,&i.CustomEnv,&i.CustomArgs,+ &i.McpConfig,); err != nil {return nil, err}@@ -717,7 +758,7 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag}const listAllAgents = `-- name: ListAllAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config FROM agentWHERE workspace_id = $1ORDER BY created_at ASC`@@ -751,6 +792,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([&i.ArchivedBy,&i.CustomEnv,&i.CustomArgs,+ &i.McpConfig,); err != nil {return nil, err}@@ -855,7 +897,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]const restoreAgent = `-- name: RestoreAgent :oneUPDATE agent SET archived_at = NULL, archived_by = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config`func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -881,6 +923,7 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erro&i.ArchivedBy,&i.CustomEnv,&i.CustomArgs,+ &i.McpConfig,)return i, err}@@ -932,9 +975,10 @@ UPDATE agent SETinstructions = COALESCE($11, instructions),custom_env = COALESCE($12, custom_env),custom_args = COALESCE($13, custom_args),+ mcp_config = COALESCE($14, mcp_config),updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config`type UpdateAgentParams struct {@@ -951,6 +995,7 @@ type UpdateAgentParams struct {Instructions pgtype.Text `json:"instructions"`CustomEnv []byte `json:"custom_env"`CustomArgs []byte `json:"custom_args"`+ McpConfig []byte `json:"mcp_config"`}func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agent, error) {@@ -968,6 +1013,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agentarg.Instructions,arg.CustomEnv,arg.CustomArgs,+ arg.McpConfig,)var i Agenterr := row.Scan(@@ -990,6 +1036,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agent&i.ArchivedBy,&i.CustomEnv,&i.CustomArgs,+ &i.McpConfig,)return i, err}@@ -997,7 +1044,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agentconst updateAgentStatus = `-- name: UpdateAgentStatus :oneUPDATE agent SET status = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config`type UpdateAgentStatusParams struct {@@ -1028,6 +1075,7 @@ func (q *Queries) UpdateAgentStatus(ctx context.Context, arg UpdateAgentStatusPa&i.ArchivedBy,&i.CustomEnv,&i.CustomArgs,+ &i.McpConfig,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 2bc21ed112..f0a0957b08 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -39,6 +39,7 @@ type Agent struct {ArchivedBy pgtype.UUID `json:"archived_by"`CustomEnv []byte `json:"custom_env"`CustomArgs []byte `json:"custom_args"`+ McpConfig []byte `json:"mcp_config"`}type AgentRuntime struct {diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex b89d3efc85..c2734f614f 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -20,8 +20,8 @@ WHERE id = $1 AND workspace_id = $2;INSERT INTO agent (workspace_id, name, description, avatar_url, runtime_mode,runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id,- instructions, custom_env, custom_args-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)+ instructions, custom_env, custom_args, mcp_config+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)RETURNING *;-- name: UpdateAgent :one@@ -38,10 +38,16 @@ UPDATE agent SETinstructions = COALESCE(sqlc.narg('instructions'), instructions),custom_env = COALESCE(sqlc.narg('custom_env'), custom_env),custom_args = COALESCE(sqlc.narg('custom_args'), custom_args),+ mcp_config = COALESCE(sqlc.narg('mcp_config'), mcp_config),updated_at = now()WHERE id = $1RETURNING *;+-- name: ClearAgentMcpConfig :one+UPDATE agent SET mcp_config = NULL, updated_at = now()+WHERE id = $1+RETURNING *;+-- name: ArchiveAgent :oneUPDATE agent SET archived_at = now(), archived_by = $2, updated_at = now()WHERE id = $1