From f1da9644f466b5bd3f11f7a03ecec9f55afd4c4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Almeida?= <57680069+zeval@users.noreply.github.com> Date: Fri, 13 Mar 2026 00:44:06 +0000 Subject: [PATCH] feat: agent-native config mode (#396) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add MCP mode pipeline for config vs task tool registration Thread McpMode field through the entire instance creation chain: CreateInstanceRequest → InstanceOverrides → InstanceConfig → MCP Server. This allows config-mode MCP sessions to register a different set of tools than the default task-mode sessions. * feat: add config-mode MCP tools and agentctl handlers Register config-mode tools (workflow steps, agents, MCP config, tasks) when MCP server mode is "config". Add 16 new WS action constants and agentctl-side handlers that forward tool calls to the backend via the existing BackendClient channel. * feat: add backend MCP handlers for config-mode operations Add backend WebSocket handlers for workflow step CRUD, agent CRUD, MCP config get/update, and task move/delete/archive/state operations. Wire config dependencies via SetConfigDeps pattern to avoid breaking the existing NewHandlers constructor. * feat: add config-mode system prompt and unit tests Add ConfigContext system prompt listing all config-mode MCP tools. Add unit tests for mode-based tool registration, agentctl config handler forwarding, backend handler validation, and system prompt content. * test: add exhaustive E2E tests for config-mode MCP handlers 38 end-to-end tests covering the full handler → service → DB pipeline for all 16 config-mode operations: workflow step CRUD, agent CRUD, agent profiles, MCP config, and task management (move, delete, archive, update state). Includes handler registration verification and two full pipeline integration tests. * fix: remove E2E test that depends on agent CLIs installed in CI TestE2E_Agent_CreateMultipleAndList tried to create claude-code and codex agents, which aren't available in CI. Agents are unique by type ID so creating duplicates also fails. Removed the test since CreateAndList already validates the create+list flow. * test: remove Go E2E tests for config-mode handlers Replacing with Playwright E2E tests. * test: add Playwright E2E tests for config-mode features 13 tests covering workflow steps, task operations, agent/profile settings pages, MCP config, and workflow settings round-trips. * feat: add dynamic MCP mode reconfiguration for agentctl instances Add SetMode() to the MCP server that clears and re-registers tools for the new mode. Expose it via PUT /api/v1/mcp/mode on per-instance servers, a SetMcpMode client method, and a lifecycle Manager.SetMcpMode wrapper. This enables switching from task to config MCP tools on workspaces that were prepared before plan_mode was set on the session. * feat: wire McpMode through executor launch and resume pipelines Add McpMode to LaunchOptions so callers can set it at launch time. StartTask and StartTaskWithSession now pass McpMode="config" when plan mode is active. startAgentOnExistingWorkspace reconfigures the MCP server via SetMcpMode before starting the agent subprocess. The AgentManagerClient interface gains SetMcpMode; the lifecycle adapter, executor, and all mock implementations are updated. * fix: pass plan_mode from workflow step when auto-starting moved tasks handleTaskMovedNoSession was hardcoding planMode=false when calling StartTask. Now it loads the target step and checks for enable_plan_mode in on_enter actions, passing the correct value so config-mode MCP tools are registered for the agent. * test: fix config-mode E2E tests and add SetMcpMode mock stubs - Add SetMcpMode stubs to all AgentManager mock implementations - Fix strict mode violations with { exact: true } on tool name assertions - Expand collapsed tool call groups before asserting individual names - Remove temporary diagnostic code * fix: address CodeRabbit review comments - Add servers parameter to update_mcp_config tool schema - Add mutex protection to SetMode for thread safety - Create session before building prompt so config context has session ID - Fix inconsistent ask_user_question tool name reference (use _kandev suffix) * refactor: use canonical ws.ActionMCP constants and handle marshal errors - Import ActionMCP* constants from pkg/websocket instead of duplicating them locally in config_handlers.go and handlers.go - Handle json.MarshalIndent error in forwardToBackend instead of ignoring it * fix: extract McpModeConfig constant and fix Prettier formatting - Add McpModeConfig constant to avoid repeated "config" string (goconst) - Fix Prettier formatting in config-management E2E spec * fix: validate task state before update and strengthen sysprompt tests - Add TaskState validation in handleUpdateTaskState to return proper validation error instead of internal error for invalid states - Strengthen format-contract assertions (exact %s counts, no %! markers) - Extract repeated test data into constants per project guidelines * refactor: decouple config MCP mode from plan_mode, use session metadata Replace plan_mode-based config MCP activation with config_mode in session metadata. Add isConfigModeSession() helper used across executor_execute, executor_interaction, and executor_resume. Propagate task.Metadata to session.Metadata in PrepareSession so config_mode flows from task creation through to the agent launch. * refactor: remove task tools from config MCP mode and update sysprompt Remove task management tools (list_tasks, move_task, delete_task, archive_task) from ModeConfig registration — they remain available in ModeTask. Update ConfigContext system prompt to remove task tool docs and add example requests section. Update MCP server tests for new tool count (18→14) and remove deleted task handler tests. * feat: add config-chat endpoint and workspace config agent profile Add default_config_agent_profile_id column to workspaces with SQLite migration. Add POST /workspaces/:id/config-chat endpoint that creates an ephemeral task with config_mode metadata and starts a session with config MCP tools. Extract resolveConfigChatDefaults helper to stay within lint complexity limits. * feat: add config chat UI with workspace settings integration Add config chat modal component and hook for starting config sessions. Add configChat state slice with open/close actions. Add workspace API client for config-chat endpoint. Add configuration agent profile selector to workspace settings form. Add config chat button to settings layout sidebar. * test: rewrite config-mode E2E tests to use metadata and session_id Rewrite config-management E2E tests to use createTaskWithAgent with config_mode metadata instead of a custom fetch helper. Fix navigation to use task.session_id instead of task.id. Add metadata parameter support to ApiClient.createTaskWithAgent. * fix: use floating FAB for config chat and pass default agent profile Move config chat button from header to a floating action button in the bottom-right corner with a sparkles icon. Pass the workspace's default agent profile ID when opening the config chat to avoid "no agent profile configured" error. Add default_config_agent_profile_id to workspace slice type. * feat: async agent launch for config-chat and extract helpers The config-chat endpoint now launches the agent asynchronously when a prompt is provided, matching the start_agent flow used by task creation. Extract deleteTaskOnError and launchConfigChatAgent helpers. Remove LaunchWorkspace from prepare step to avoid blocking. * feat: first-interaction agent profile selection for config chat Open the config chat modal immediately on FAB click. If no default config agent profile is set, the empty state now shows a profile selector before starting. The selected profile is saved as the workspace default_config_agent_profile_id for future sessions. * test: fix config E2E tests — remove duplicate method, use real tools Remove duplicate startConfigChat method in ApiClient that overrode the correct 3-param signature. Replace invalid create_agent test (requires registered agent type) with update_agent test. Remove fragile tool calls group UI assertion from multi-tool test. * fix: resolve 'no active session' error in config chat Add openConfigChatModal action that only sets isOpen and workspaceId without touching sessionId. Previously, open() called openConfigChat with empty sessionId which was truthy, causing QuickChatContent to render with an invalid session. * feat: add minimal toolbar mode for config chat input Thread minimalToolbar prop through ChatInputArea → ChatInputContainer → ChatInputBody → ChatInputToolbar → QuickChatContent. When enabled, renders only the submit/cancel button, hiding plan toggle, MCP indicator, context popover, model selector, and other controls. * feat: replace config chat dialog with floating popover panel Replace Dialog with Popover from @kandev/ui so the config chat floats up from the FAB button. Reduce FAB size to h-12/w-12 with larger h-7/w-7 icon. Rename tooltip to "Configuration Chat". Remove standalone ConfigChatFAB component from settings layout. * feat: filter config chat tasks from quick chat listing Add exclude_config query parameter to ListTasksByWorkspace that filters out tasks with metadata.config_mode=true. Apply it in the quick chat sessions API call to prevent config chat tasks from appearing as tabs. * refactor: move config agent profile setting to agents page Remove the Configuration Agent Profile selector from workspace settings and add a dedicated ConfigChatAgentSection to the agents settings page with auto-save on change. * feat: redesign config chat empty state with inline text input Replace clickable template buttons with subtle suggestion hints that fill the textarea on click and disappear once the user starts typing. Add a persistent Textarea + send button at the bottom so users can type directly without clicking templates. This prevents the "no active session" error since QuickChatContent only renders after startSession succeeds. * fix: config chat UX polish — non-clickable suggestions, profile persistence - Make suggestion prompts purely visual (non-interactive text hints) - Update workspace store after saving config agent profile so the profile selector doesn't reappear on subsequent opens - Use useAppStoreApi for store access in callbacks * fix: add inline error display and prevent accidental popover dismiss - Show API errors inline below the input instead of via toast (which can be hidden behind the popover) - Prevent popover from closing on outside click via onInteractOutside, so the user doesn't lose their typed input or active session - Surface error state from useConfigChat hook to the empty state UI * fix: use config-specific placeholder in config chat input Add placeholderOverride prop through ChatInputArea and QuickChatContent so the config chat shows "Ask anything about your configuration..." instead of the default "Continue working on the task..." placeholder. * feat: add default_config_agent_profile_id to workspace DTO and API Wire the field through WorkspaceDTO, FromWorkspace(), HTTP/WS request structs, service layer, and public API types so the config chat default profile persists across page reloads and SSR hydration. * feat: add config chat store actions and prompt delivery via WS Add configChat slice actions (open, close, rename, tab management), pendingPrompt state in useConfigChat hook, and initialPrompt support in QuickChatContent so prompts are delivered via WS after subscription is established rather than via HTTP (avoiding race condition). * fix: resolve dual store issue and message fetch race condition Replace StateProvider with StateHydrator in settings layout to prevent a shadow Zustand store that intercepted WS events. Fix message fetch race condition by merging WS-delivered messages with fetch results instead of replacing them. * feat: make config chat global with command panel integration Add ConfigChatProvider at root layout so the popover is available on all pages. FAB button only visible on settings pages; hidden anchor on other pages for popover positioning. Add "Configuration Chat" command to the command panel (Cmd+K). Add close button and header bar to the popover. * test: add E2E tests for config chat popover and command panel Add tests for opening config chat via FAB on settings page (with full agent response flow) and opening via command panel on kanban page. Fix api-client endpoint and add workspace update fields for E2E setup. * fix: compress props destructuring to satisfy max-lines-per-function lint Rebase merged both sides' additions into ChatInputEditorArea and ChatInputToolbar, pushing them over the 100-line function limit. Use object parameter with compact destructuring to reduce line count. * fix: register config task tools and add exhaustive E2E coverage Config-mode MCP task tools (list_tasks, move_task, delete_task, archive_task) were defined but never registered — registerConfigTaskTools() was never called in registerTools(). Fixed the registration and expanded E2E tests from 5 to 15, covering all testable config-mode MCP tools (workflow, agent, MCP config, and task management) with API-side verification of side effects. * feat: replace create/delete agent with create/delete agent profile in config mode Agent creation/deletion via MCP isn't practical since agents map to registered types. Replace with create_agent_profile and delete_agent_profile tools that manage the per-agent configuration presets users actually need to work with. Wires full chain: agentctl MCP tools → WS actions → backend handlers → controller layer. * chore: fix Prettier formatting * fix: compress props destructuring to satisfy max-lines-per-function lint * test: update MCP tests for agent profile tools and correct config tool count * fix: address CodeRabbit review — normalize MCP mode, set default, consolidate tests * fix: address CodeRabbit review — error leaks, search filter bug, stale prompt, sysprompt tools * feat: expose all workflow step fields in config-mode MCP tools * feat: add workflow CRUD to config-mode MCP tools * fix: split workflow CRUD E2E test into separate tests * fix: prevent cascade deletion of config session in delete workflow E2E test The config-chat endpoint picks the newest workflow (ORDER BY created_at DESC) for the ephemeral task. When the test created a deletable workflow right before starting the config session, the session's own task landed under that workflow. Deleting the workflow then cascaded and wiped the running session's task, causing the MCP tool call to hang. Add a "Config Anchor" bumper workflow so the config session uses it instead of the deletable one. * feat: add executor management to config-mode MCP tools Add 8 new MCP tools for executor and executor profile CRUD in config mode: list/create/update/delete for both executors and profiles. Wired through the full stack (WS actions, backend handlers, agentctl tools, sysprompt) with unit tests and E2E coverage. * fix: auto-focus config chat input and rename popover title * fix: remove executor CRUD MCP tools, keep executor profile management Executors are pre-defined system entities (local, worktree, docker, sprites). Only executor profiles should be managed via config chat. Removes create_executor, update_executor, delete_executor MCP tools while keeping list_executors and all executor profile tools. * fix: add realtime UI sync for workflow steps and agent profiles via MCP Workflow step and agent profile changes made through the config chat MCP tools were not broadcasting events to the frontend. Executor profile events worked because they went through the task service which has event bus integration. - Add WorkflowStep and AgentProfile event types to the event bus - Add WS notification action constants for workflow step events - Publish events from MCP handlers after step/profile CRUD operations - Register gateway subscriptions for the new event types - Add frontend WS handlers for workflow.step.created/updated/deleted * fix: reuse existing config chat session when opened from command panel The command panel always called openConfigChatModal() which reset the session state, causing the profile picker to show again. Now it checks for an existing active session first, matching the FAB behavior. * fix: suppress FAB tooltip while config chat popover is open When closing the popover via the X button, the mouse ends up over the FAB area and the tooltip re-appears. Force the tooltip closed while the popover is open so it cannot re-trigger on close. * fix: thread default_config_agent_profile_id through all workspace data paths The field was defined on the workspace type but never populated in: - SSR mapper (page.tsx) — missing from initial hydration - WS workspace handlers — wiped on workspace.created/updated events - Backend publishWorkspaceEvent — not included in event data This caused the config chat to always show the profile picker when opened from the command panel, since the saved default was lost. * fix: address PR review comments — workspace sync, type fixes, missing tool doc - Sync configChat.workspaceId when promoting next tab in closeConfigChatSession - Add update_task_state_kandev to ConfigContext system prompt - Fix workflow step WS event types (workflow.step.* instead of step.*) - Fix const reassignment in E2E tests (const → let) * refactor: clean up dead code and register missing MCP tools - Register update_task_state, delete_workflow_step, and reorder_workflow_steps as MCP tools in agentctl config mode - Remove dead handleCreateAgent/handleDeleteAgent WS handlers and their ActionMCP constants (only profiles are managed) - Rename openConfigChatModal to startNewConfigChat across frontend - Update sysprompt, tests, and tool counts * fix: remove extra next.config.ts machine * fix: address CI failures — prettier formatting and funlen split * fix: address coderabbit review comments across config-mode stack - Include prompt field in workflow step broadcast payloads - Align sysprompt task-state values with actual backend enum - Return error instead of continuing when MCP mode switch fails - Validate mode values in agentctl set-mcp-mode endpoint - Use errors.Is() for sentinel error comparison - Fix nullish coalescing to allow clearing config agent profile - Expand StepPayload type with missing config-step fields - Derive config agent Select value from store instead of local state * fix: reuse persisted config chat session and reduce toolbar complexity - Look up configChat.sessions for workspace before creating new session - Extract MinimalToolbar and move defaults to module-level object to reduce ChatInputToolbar cyclomatic complexity from 16 to 7 * fix: E2E executor test strict mode violation and invalid cleanup - Use exact match for list_executors text to avoid matching 2 elements - Remove cleanup that tried to delete pre-existing system executor - Reuse persisted config chat session for workspace in global commands - Reduce ChatInputToolbar cyclomatic complexity with module-level defaults --- apps/backend/cmd/agentctl/main.go | 2 +- apps/backend/cmd/kandev/adapters.go | 6 + apps/backend/cmd/kandev/helpers.go | 5 + apps/backend/cmd/kandev/main.go | 2 + .../internal/agent/lifecycle/container.go | 2 + .../agent/lifecycle/executor_backend.go | 1 + .../lifecycle/executor_sprites_operations.go | 1 + .../agent/lifecycle/executor_standalone.go | 1 + .../agent/lifecycle/manager_launch.go | 15 + .../backend/internal/agent/lifecycle/types.go | 1 + .../internal/agentctl/client/client.go | 39 + .../internal/agentctl/client/control.go | 1 + .../internal/agentctl/server/api/server.go | 18 + .../internal/agentctl/server/config/config.go | 9 + .../agentctl/server/instance/instance.go | 3 + .../agentctl/server/instance/manager.go | 1 + .../agentctl/server/mcp/config_handlers.go | 697 ++++++++++++++++++ .../server/mcp/config_handlers_test.go | 674 +++++++++++++++++ .../internal/agentctl/server/mcp/handlers.go | 42 +- .../internal/agentctl/server/mcp/server.go | 69 +- .../agentctl/server/mcp/server_test.go | 226 ++++++ apps/backend/internal/events/types.go | 14 + .../gateway/websocket/task_notifications.go | 6 + .../simulated_agent_manager_test.go | 4 + .../mcp/handlers/config_agent_handlers.go | 167 +++++ .../mcp/handlers/config_executor_handlers.go | 113 +++ .../mcp/handlers/config_handlers_test.go | 466 ++++++++++++ .../mcp/handlers/config_mcp_handlers.go | 62 ++ .../mcp/handlers/config_task_handlers.go | 104 +++ .../mcp/handlers/config_workflow_handlers.go | 242 ++++++ .../backend/internal/mcp/handlers/handlers.go | 87 ++- .../orchestrator/event_handlers_test.go | 3 + .../orchestrator/event_handlers_workflow.go | 21 +- .../orchestrator/executor/executor.go | 10 + .../orchestrator/executor/executor_execute.go | 42 +- .../executor/executor_interaction.go | 5 + .../orchestrator/executor/executor_resume.go | 5 + .../orchestrator/executor/executor_test.go | 6 +- .../orchestrator/scheduler/scheduler_test.go | 4 + .../internal/orchestrator/task_operations.go | 55 +- apps/backend/internal/sysprompt/sysprompt.go | 74 ++ .../internal/sysprompt/sysprompt_test.go | 206 ++++++ apps/backend/internal/task/dto/dto.go | 38 +- .../task/handlers/process_handlers_test.go | 2 +- .../internal/task/handlers/task_handlers.go | 3 + .../task/handlers/task_http_handlers.go | 150 +++- .../task/handlers/workspace_handlers.go | 98 +-- apps/backend/internal/task/models/models.go | 19 +- .../repository/archive_repository_test.go | 8 +- .../internal/task/repository/interface.go | 2 +- .../internal/task/repository/sqlite/base.go | 3 + .../internal/task/repository/sqlite/task.go | 13 +- .../task/repository/sqlite/workspace.go | 22 +- .../task/repository/task_repository_test.go | 16 +- .../internal/task/service/service_events.go | 19 +- .../internal/task/service/service_requests.go | 24 +- .../task/service/service_resources.go | 18 +- .../internal/task/service/service_tasks.go | 4 +- apps/backend/pkg/api/v1/workspace.go | 41 +- apps/backend/pkg/websocket/actions.go | 34 + apps/web/app/actions/workspaces.ts | 1 + apps/web/app/layout.tsx | 5 +- apps/web/app/page.tsx | 1 + apps/web/app/settings/agents/page.tsx | 73 +- apps/web/app/settings/layout.tsx | 8 +- .../config-chat/config-chat-panel.tsx | 330 +++++++++ .../config-chat/config-chat-provider.tsx | 41 ++ .../components/config-chat/use-config-chat.ts | 145 ++++ apps/web/components/global-commands.tsx | 44 +- .../quick-chat/quick-chat-content.tsx | 23 +- .../settings/settings-layout-client.tsx | 2 +- .../components/task/chat/chat-input-area.tsx | 21 +- .../components/task/chat/chat-input-body.tsx | 50 +- .../task/chat/chat-input-container.tsx | 2 + .../task/chat/chat-input-toolbar.tsx | 131 ++-- apps/web/e2e/fixtures/backend.ts | 2 +- apps/web/e2e/helpers/api-client.ts | 63 +- .../web/e2e/tests/config-chat-popover.spec.ts | 86 +++ apps/web/e2e/tests/config-management.spec.ts | 657 +++++++++++++++++ .../domains/session/use-session-messages.ts | 23 +- apps/web/lib/api/domains/workspace-api.ts | 25 +- apps/web/lib/state/slices/ui/types.ts | 20 + apps/web/lib/state/slices/ui/ui-slice.ts | 54 ++ apps/web/lib/state/slices/workspace/types.ts | 1 + apps/web/lib/state/store.ts | 7 + apps/web/lib/types/backend.ts | 21 +- apps/web/lib/types/http.ts | 1 + apps/web/lib/ws/handlers/workflows.ts | 44 ++ apps/web/lib/ws/handlers/workspaces.ts | 5 + 89 files changed, 5582 insertions(+), 329 deletions(-) create mode 100644 apps/backend/internal/agentctl/server/mcp/config_handlers.go create mode 100644 apps/backend/internal/agentctl/server/mcp/config_handlers_test.go create mode 100644 apps/backend/internal/agentctl/server/mcp/server_test.go create mode 100644 apps/backend/internal/mcp/handlers/config_agent_handlers.go create mode 100644 apps/backend/internal/mcp/handlers/config_executor_handlers.go create mode 100644 apps/backend/internal/mcp/handlers/config_handlers_test.go create mode 100644 apps/backend/internal/mcp/handlers/config_mcp_handlers.go create mode 100644 apps/backend/internal/mcp/handlers/config_task_handlers.go create mode 100644 apps/backend/internal/mcp/handlers/config_workflow_handlers.go create mode 100644 apps/backend/internal/sysprompt/sysprompt_test.go create mode 100644 apps/web/components/config-chat/config-chat-panel.tsx create mode 100644 apps/web/components/config-chat/config-chat-provider.tsx create mode 100644 apps/web/components/config-chat/use-config-chat.ts create mode 100644 apps/web/e2e/tests/config-chat-popover.spec.ts create mode 100644 apps/web/e2e/tests/config-management.spec.ts diff --git a/apps/backend/cmd/agentctl/main.go b/apps/backend/cmd/agentctl/main.go index 493d90649b..856b7cf754 100644 --- a/apps/backend/cmd/agentctl/main.go +++ b/apps/backend/cmd/agentctl/main.go @@ -92,7 +92,7 @@ func run(cfg *config.Config, log *logger.Logger) { mcpBackendClient := mcpserver.NewChannelBackendClient(instLog) // Create MCP server using the channel-based backend client - mcpSrv := mcpserver.New(mcpBackendClient, instCfg.SessionID, instCfg.Port, instLog, cfg.McpLogFile, instCfg.DisableAskQuestion) + mcpSrv := mcpserver.New(mcpBackendClient, instCfg.SessionID, instCfg.Port, instLog, cfg.McpLogFile, instCfg.DisableAskQuestion, instCfg.McpMode) instLog.Info("MCP server enabled (channel-based)", zap.String("session_id", instCfg.SessionID)) diff --git a/apps/backend/cmd/kandev/adapters.go b/apps/backend/cmd/kandev/adapters.go index 0e9c02c7b9..0fce379da6 100644 --- a/apps/backend/cmd/kandev/adapters.go +++ b/apps/backend/cmd/kandev/adapters.go @@ -82,6 +82,7 @@ func (a *lifecycleAdapter) LaunchAgent(ctx context.Context, req *executor.Launch ExecutorType: req.ExecutorType, ExecutorConfig: req.ExecutorConfig, PreviousExecutionID: req.PreviousExecutionID, + McpMode: req.McpMode, SetupScript: req.SetupScript, // Worktree configuration for concurrent agent execution UseWorktree: req.UseWorktree, @@ -129,6 +130,11 @@ func (a *lifecycleAdapter) SetExecutionDescription(ctx context.Context, agentExe return a.mgr.SetExecutionDescription(ctx, agentExecutionID, description) } +// SetMcpMode changes the MCP tool mode on an existing execution's agentctl instance. +func (a *lifecycleAdapter) SetMcpMode(ctx context.Context, executionID string, mode string) error { + return a.mgr.SetMcpMode(ctx, executionID, mode) +} + // StartAgentProcess starts the agent subprocess for an instance. // The command is built internally based on the instance's agent profile. func (a *lifecycleAdapter) StartAgentProcess(ctx context.Context, agentInstanceID string) error { diff --git a/apps/backend/cmd/kandev/helpers.go b/apps/backend/cmd/kandev/helpers.go index 806b92e7bf..0da1704728 100644 --- a/apps/backend/cmd/kandev/helpers.go +++ b/apps/backend/cmd/kandev/helpers.go @@ -14,6 +14,7 @@ import ( "github.com/kandev/kandev/internal/agent/docker" agenthandlers "github.com/kandev/kandev/internal/agent/handlers" "github.com/kandev/kandev/internal/agent/lifecycle" + "github.com/kandev/kandev/internal/agent/mcpconfig" agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller" agentsettingshandlers "github.com/kandev/kandev/internal/agent/settings/handlers" "github.com/kandev/kandev/internal/agentctl/tracing" @@ -431,6 +432,7 @@ type routeParams struct { msgCreator *messageCreatorAdapter secretsSvc *secrets.Service secretStore secrets.SecretStore + mcpConfigSvc *mcpconfig.Service webInternalURL string log *logger.Logger } @@ -580,6 +582,9 @@ func registerMCPAndDebugRoutes( p.taskSvc, wfCtrl, clarificationStore, p.msgCreator, p.taskRepo, p.taskRepo, p.eventBus, planService, p.log, ) + // Wire config-mode dependencies for agent-native configuration + mcpHandlers.SetConfigDeps(p.services.Workflow, p.agentSettingsController, p.mcpConfigSvc) + mcpHandlers.RegisterHandlers(p.gateway.Dispatcher) p.log.Debug("Registered MCP handlers (WebSocket)") diff --git a/apps/backend/cmd/kandev/main.go b/apps/backend/cmd/kandev/main.go index 28ca38d9af..9f34e11973 100644 --- a/apps/backend/cmd/kandev/main.go +++ b/apps/backend/cmd/kandev/main.go @@ -30,6 +30,7 @@ import ( // Agent infrastructure "github.com/kandev/kandev/internal/agent/lifecycle" + "github.com/kandev/kandev/internal/agent/mcpconfig" "github.com/kandev/kandev/internal/agent/registry" agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller" @@ -440,6 +441,7 @@ func buildHTTPServer( msgCreator: msgCreator, secretsSvc: secrets.NewService(repos.Secrets, log), secretStore: repos.Secrets, + mcpConfigSvc: mcpconfig.NewService(repos.AgentSettings), webInternalURL: cfg.Server.WebInternalURL, log: log, }) diff --git a/apps/backend/internal/agent/lifecycle/container.go b/apps/backend/internal/agent/lifecycle/container.go index 059f32d0c8..e1eacc2a0c 100644 --- a/apps/backend/internal/agent/lifecycle/container.go +++ b/apps/backend/internal/agent/lifecycle/container.go @@ -30,6 +30,7 @@ type ContainerConfig struct { InstanceID string MainRepoGitDir string // Path to main repo's .git directory (for worktrees) McpServers []McpServerConfig + McpMode string } // ContainerManager handles Docker container lifecycle operations @@ -113,6 +114,7 @@ func (cm *ContainerManager) LaunchContainer(ctx context.Context, config Containe SessionID: config.SessionID, DisableAskQuestion: disableAskQuestion, AssumeMcpSse: assumeMcpSse, + McpMode: config.McpMode, } resp, err := ctl.CreateInstance(ctx, createReq) diff --git a/apps/backend/internal/agent/lifecycle/executor_backend.go b/apps/backend/internal/agent/lifecycle/executor_backend.go index 83bc85d291..d8fe63093a 100644 --- a/apps/backend/internal/agent/lifecycle/executor_backend.go +++ b/apps/backend/internal/agent/lifecycle/executor_backend.go @@ -177,6 +177,7 @@ type ExecutorCreateRequest struct { McpServers []McpServerConfig AgentConfig agents.Agent // Agent type info needed by runtimes PreviousExecutionID string // Non-empty when reconnecting to a previous execution + McpMode string // MCP tool mode: "task" (default) or "config" // OnProgress is an optional callback for streaming preparation progress. // Executors that perform multi-step setup (e.g. Sprites, remote Docker) can diff --git a/apps/backend/internal/agent/lifecycle/executor_sprites_operations.go b/apps/backend/internal/agent/lifecycle/executor_sprites_operations.go index 1986a868db..ee86b0b5b9 100644 --- a/apps/backend/internal/agent/lifecycle/executor_sprites_operations.go +++ b/apps/backend/internal/agent/lifecycle/executor_sprites_operations.go @@ -229,6 +229,7 @@ func (r *SpritesExecutor) createAgentInstance( Protocol: req.Protocol, AgentType: agentTypeFromReq(req), McpServers: req.McpServers, + McpMode: req.McpMode, } reqJSON, err := json.Marshal(instanceReq) if err != nil { diff --git a/apps/backend/internal/agent/lifecycle/executor_standalone.go b/apps/backend/internal/agent/lifecycle/executor_standalone.go index cc13e408cc..f190469df5 100644 --- a/apps/backend/internal/agent/lifecycle/executor_standalone.go +++ b/apps/backend/internal/agent/lifecycle/executor_standalone.go @@ -108,6 +108,7 @@ func (r *StandaloneExecutor) CreateInstance(ctx context.Context, req *ExecutorCr SessionID: req.SessionID, DisableAskQuestion: disableAskQuestion, AssumeMcpSse: assumeMcpSse, + McpMode: req.McpMode, } r.logger.Info("CreateInstance: sending request to agentctl", diff --git a/apps/backend/internal/agent/lifecycle/manager_launch.go b/apps/backend/internal/agent/lifecycle/manager_launch.go index 268891e4f5..1f8cc32ac8 100644 --- a/apps/backend/internal/agent/lifecycle/manager_launch.go +++ b/apps/backend/internal/agent/lifecycle/manager_launch.go @@ -252,6 +252,7 @@ func (m *Manager) launchBuildExecutorRequest(ctx context.Context, executionID st AgentConfig: agentConfig, McpServers: mcpServers, PreviousExecutionID: reqWithWorktree.PreviousExecutionID, + McpMode: reqWithWorktree.McpMode, OnProgress: m.newProgressCallback(reqWithWorktree.TaskID, reqWithWorktree.SessionID), } @@ -479,6 +480,20 @@ func (m *Manager) SetExecutionDescription(_ context.Context, executionID string, return nil } +// SetMcpMode changes the MCP tool mode on an existing execution's agentctl instance. +// This is used when a session transitions to plan/config mode after the workspace was +// already prepared with the default (task) mode. +func (m *Manager) SetMcpMode(ctx context.Context, executionID string, mode string) error { + execution, exists := m.executionStore.Get(executionID) + if !exists { + return fmt.Errorf("execution %q not found", executionID) + } + if execution.agentctl == nil { + return fmt.Errorf("execution %q has no agentctl client", executionID) + } + return execution.agentctl.SetMcpMode(ctx, mode) +} + // resolveApprovalPolicyAndDisplayName resolves the approval policy and agent display name // from the execution's agent profile and registry. func (m *Manager) resolveApprovalPolicyAndDisplayName(ctx context.Context, execution *AgentExecution) (string, string) { diff --git a/apps/backend/internal/agent/lifecycle/types.go b/apps/backend/internal/agent/lifecycle/types.go index 48f04d3afe..ae9e121fd4 100644 --- a/apps/backend/internal/agent/lifecycle/types.go +++ b/apps/backend/internal/agent/lifecycle/types.go @@ -259,6 +259,7 @@ type LaunchRequest struct { ExecutorType string // Executor type (e.g., "local", "worktree", "local_docker") - determines runtime ExecutorConfig map[string]string // Executor config (docker_host, git_token, etc.) PreviousExecutionID string // Previous execution ID for runtime reconnect + McpMode string // MCP tool mode: "config" activates config-mode tools // Environment preparation SetupScript string // Setup script to run before agent starts diff --git a/apps/backend/internal/agentctl/client/client.go b/apps/backend/internal/agentctl/client/client.go index c4c1fc4e78..d33bbde49e 100644 --- a/apps/backend/internal/agentctl/client/client.go +++ b/apps/backend/internal/agentctl/client/client.go @@ -243,6 +243,45 @@ func (c *Client) ConfigureAgent(ctx context.Context, command string, env map[str return nil } +// SetMcpMode changes the MCP tool mode on the agentctl instance. +// This reconfigures which MCP tools are available to the agent. +func (c *Client) SetMcpMode(ctx context.Context, mode string) error { + ctx, span := tracing.TraceHTTPRequest(ctx, "PUT", "/api/v1/mcp/mode", c.executionID) + defer span.End() + + body, err := json.Marshal(struct { + Mode string `json:"mode"` + }{Mode: mode}) + if err != nil { + tracing.TraceHTTPResponse(span, 0, err) + return err + } + + req, err := http.NewRequestWithContext(ctx, "PUT", c.baseURL+"/api/v1/mcp/mode", bytes.NewReader(body)) + if err != nil { + tracing.TraceHTTPResponse(span, 0, err) + return err + } + req.Header.Set("Content-Type", "application/json") + + resp, err := c.httpClient.Do(req) + if err != nil { + tracing.TraceHTTPResponse(span, 0, err) + return err + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + respBody, _ := readResponseBody(resp) + httpErr := fmt.Errorf("set MCP mode failed with status %d: %s", resp.StatusCode, string(respBody)) + tracing.TraceHTTPResponse(span, resp.StatusCode, httpErr) + return httpErr + } + + tracing.TraceHTTPResponse(span, resp.StatusCode, nil) + return nil +} + // Start starts the agent process and returns the full command that was executed. func (c *Client) Start(ctx context.Context) (string, error) { ctx, span := tracing.TraceHTTPRequest(ctx, "POST", "/api/v1/start", c.executionID) diff --git a/apps/backend/internal/agentctl/client/control.go b/apps/backend/internal/agentctl/client/control.go index 8f54dae66e..b16bcd0f1f 100644 --- a/apps/backend/internal/agentctl/client/control.go +++ b/apps/backend/internal/agentctl/client/control.go @@ -46,6 +46,7 @@ type CreateInstanceRequest struct { SessionID string `json:"session_id,omitempty"` // Task session ID for MCP tool calls DisableAskQuestion bool `json:"disable_ask_question,omitempty"` // Disable ask_user_question MCP tool (TUI agents) AssumeMcpSse bool `json:"assume_mcp_sse,omitempty"` // Assume agent supports SSE MCP servers + McpMode string `json:"mcp_mode,omitempty"` // MCP tool mode: "task" (default) or "config" } // CreateInstanceResponse contains the result of creating a new agent instance. diff --git a/apps/backend/internal/agentctl/server/api/server.go b/apps/backend/internal/agentctl/server/api/server.go index fde87a3919..a5bd5f10de 100644 --- a/apps/backend/internal/agentctl/server/api/server.go +++ b/apps/backend/internal/agentctl/server/api/server.go @@ -153,6 +153,7 @@ func (s *Server) setupRoutes() { // MCP routes (if MCP server is configured) if s.mcpServer != nil { s.mcpServer.RegisterRoutes(s.router) + api.PUT("/mcp/mode", s.handleSetMcpMode) } } @@ -169,6 +170,23 @@ func (s *Server) handleHealth(c *gin.Context) { }) } +// handleSetMcpMode changes the MCP tool mode for this instance. +func (s *Server) handleSetMcpMode(c *gin.Context) { + var req struct { + Mode string `json:"mode"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + if req.Mode != "task" && req.Mode != "config" { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid mode: must be 'task' or 'config'"}) + return + } + s.mcpServer.SetMode(req.Mode) + c.JSON(http.StatusOK, gin.H{"mode": req.Mode}) +} + // Status response type StatusResponse struct { AgentStatus string `json:"agent_status"` diff --git a/apps/backend/internal/agentctl/server/config/config.go b/apps/backend/internal/agentctl/server/config/config.go index 1329a1c950..04bff30db0 100644 --- a/apps/backend/internal/agentctl/server/config/config.go +++ b/apps/backend/internal/agentctl/server/config/config.go @@ -158,6 +158,10 @@ type InstanceConfig struct { // AssumeMcpSse overrides MCP capability filtering to assume the agent supports SSE. AssumeMcpSse bool + + // McpMode controls which MCP tools are registered for this instance. + // "task" (default) registers kanban/plan tools; "config" registers config tools. + McpMode string } // Load loads the configuration from environment variables. @@ -200,6 +204,7 @@ func (c *Config) NewInstanceConfig(port int, overrides *InstanceOverrides) *Inst LogFormat: c.LogFormat, ProcessBufferMaxBytes: c.Defaults.ProcessBufferMaxBytes, VscodeCommand: c.VscodeCommand, + McpMode: "task", } applyOverrides(cfg, overrides) @@ -261,6 +266,9 @@ func applyOverrides(cfg *InstanceConfig, overrides *InstanceOverrides) { if overrides.AssumeMcpSse { cfg.AssumeMcpSse = true } + if overrides.McpMode != "" { + cfg.McpMode = overrides.McpMode + } } // InstanceOverrides allows overriding default values when creating an instance @@ -276,6 +284,7 @@ type InstanceOverrides struct { SessionID string DisableAskQuestion bool AssumeMcpSse bool + McpMode string } // ParseCommand splits a command string into arguments diff --git a/apps/backend/internal/agentctl/server/instance/instance.go b/apps/backend/internal/agentctl/server/instance/instance.go index 3b10c6e166..1b2cd64508 100644 --- a/apps/backend/internal/agentctl/server/instance/instance.go +++ b/apps/backend/internal/agentctl/server/instance/instance.go @@ -89,6 +89,9 @@ type CreateRequest struct { // AssumeMcpSse overrides MCP capability filtering to assume SSE support. AssumeMcpSse bool `json:"assume_mcp_sse,omitempty"` + + // McpMode controls which MCP tools are registered: "task" (default) or "config". + McpMode string `json:"mcp_mode,omitempty"` } // CreateResponse contains the result of creating a new agent instance. diff --git a/apps/backend/internal/agentctl/server/instance/manager.go b/apps/backend/internal/agentctl/server/instance/manager.go index e28b95e211..9859760445 100644 --- a/apps/backend/internal/agentctl/server/instance/manager.go +++ b/apps/backend/internal/agentctl/server/instance/manager.go @@ -91,6 +91,7 @@ func (m *Manager) CreateInstance(ctx context.Context, req *CreateRequest) (*Crea SessionID: req.SessionID, DisableAskQuestion: req.DisableAskQuestion, AssumeMcpSse: req.AssumeMcpSse, + McpMode: req.McpMode, } m.logger.Info("CreateInstance: applying overrides", diff --git a/apps/backend/internal/agentctl/server/mcp/config_handlers.go b/apps/backend/internal/agentctl/server/mcp/config_handlers.go new file mode 100644 index 0000000000..98f64619b7 --- /dev/null +++ b/apps/backend/internal/agentctl/server/mcp/config_handlers.go @@ -0,0 +1,697 @@ +package mcp + +import ( + "context" + "encoding/json" + + ws "github.com/kandev/kandev/pkg/websocket" + "github.com/mark3labs/mcp-go/mcp" + "github.com/mark3labs/mcp-go/server" +) + +// --- Workflow config tools --- + +func (s *Server) registerConfigWorkflowTools() { + s.mcpServer.AddTool( + mcp.NewToolWithRawSchema("list_workspaces", + "List all workspaces. Use this first to get workspace IDs.", + json.RawMessage(`{"type":"object","properties":{}}`), + ), + s.wrapHandler("list_workspaces", s.listWorkspacesHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("list_workflows", + mcp.WithDescription("List all workflows in a workspace."), + mcp.WithString("workspace_id", mcp.Required(), mcp.Description("The workspace ID")), + ), + s.wrapHandler("list_workflows", s.listWorkflowsHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("create_workflow", + mcp.WithDescription("Create a new workflow in a workspace."), + mcp.WithString("workspace_id", mcp.Required(), mcp.Description("The workspace ID")), + mcp.WithString("name", mcp.Required(), mcp.Description("Workflow name")), + mcp.WithString("description", mcp.Description("Workflow description")), + ), + s.wrapHandler("create_workflow", s.createWorkflowHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("update_workflow", + mcp.WithDescription("Update an existing workflow."), + mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")), + mcp.WithString("name", mcp.Description("New workflow name")), + mcp.WithString("description", mcp.Description("New workflow description")), + ), + s.wrapHandler("update_workflow", s.updateWorkflowHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("delete_workflow", + mcp.WithDescription("Delete a workflow and all its steps. This is destructive and cannot be undone."), + mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID to delete")), + ), + s.wrapHandler("delete_workflow", s.deleteWorkflowHandler()), + ) + s.registerConfigWorkflowStepTools() +} + +func (s *Server) registerConfigWorkflowStepTools() { + s.mcpServer.AddTool( + mcp.NewTool("list_workflow_steps", + mcp.WithDescription("List all workflow steps (columns) in a workflow."), + mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")), + ), + s.wrapHandler("list_workflow_steps", s.listWorkflowStepsHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("create_workflow_step", + mcp.WithDescription("Create a new workflow step (column) in a workflow."), + mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")), + mcp.WithString("name", mcp.Required(), mcp.Description("Step name")), + mcp.WithNumber("position", mcp.Description("Step position (0-based). Defaults to end.")), + mcp.WithString("color", mcp.Description("Step color hex code (e.g. '#3b82f6')")), + mcp.WithString("prompt", mcp.Description("System prompt for agents in this step")), + mcp.WithBoolean("is_start_step", mcp.Description("Whether this is the start step")), + mcp.WithBoolean("allow_manual_move", mcp.Description("Allow manual task moves into this step (default: false)")), + mcp.WithBoolean("show_in_command_panel", mcp.Description("Show this step in the command panel")), + mcp.WithObject("events", mcp.Description("Event-driven actions. Keys: on_enter, on_exit, on_turn_start, on_turn_complete. Each is an array of {type, config} objects.")), + ), + s.wrapHandler("create_workflow_step", s.createWorkflowStepHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("update_workflow_step", + mcp.WithDescription("Update an existing workflow step."), + mcp.WithString("step_id", mcp.Required(), mcp.Description("The workflow step ID")), + mcp.WithString("name", mcp.Description("New step name")), + mcp.WithString("color", mcp.Description("New color hex code")), + mcp.WithString("prompt", mcp.Description("New system prompt")), + mcp.WithBoolean("is_start_step", mcp.Description("Whether this is the start step")), + mcp.WithBoolean("allow_manual_move", mcp.Description("Allow manual task moves into this step")), + mcp.WithBoolean("show_in_command_panel", mcp.Description("Show this step in the command panel")), + mcp.WithNumber("auto_archive_after_hours", mcp.Description("Auto-archive tasks after N hours in this step (0 to disable)")), + mcp.WithObject("events", mcp.Description("Event-driven actions. Keys: on_enter, on_exit, on_turn_start, on_turn_complete.")), + ), + s.wrapHandler("update_workflow_step", s.updateWorkflowStepHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("delete_workflow_step", + mcp.WithDescription("Delete a workflow step. This is destructive and cannot be undone."), + mcp.WithString("step_id", mcp.Required(), mcp.Description("The workflow step ID to delete")), + ), + s.wrapHandler("delete_workflow_step", s.deleteWorkflowStepHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("reorder_workflow_steps", + mcp.WithDescription("Reorder workflow steps by providing the full ordered list of step IDs."), + mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")), + mcp.WithArray("step_ids", mcp.Required(), mcp.Description("Ordered list of step IDs defining the new order")), + ), + s.wrapHandler("reorder_workflow_steps", s.reorderWorkflowStepsHandler()), + ) +} + +// --- Agent config tools --- + +func (s *Server) registerConfigAgentTools() { + s.mcpServer.AddTool( + mcp.NewToolWithRawSchema("list_agents", + "List all configured agents with their profiles.", + json.RawMessage(`{"type":"object","properties":{}}`), + ), + s.wrapHandler("list_agents", s.listAgentsHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("update_agent", + mcp.WithDescription("Update an existing agent."), + mcp.WithString("agent_id", mcp.Required(), mcp.Description("The agent ID")), + mcp.WithBoolean("supports_mcp", mcp.Description("Whether the agent supports MCP")), + mcp.WithString("mcp_config_path", mcp.Description("Path to MCP config file")), + ), + s.wrapHandler("update_agent", s.updateAgentHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("create_agent_profile", + mcp.WithDescription("Create a new agent profile for an agent."), + mcp.WithString("agent_id", mcp.Required(), mcp.Description("The agent ID to create a profile for")), + mcp.WithString("name", mcp.Required(), mcp.Description("Profile name")), + mcp.WithString("model", mcp.Required(), mcp.Description("Model name (e.g. 'claude-sonnet-4-5-20250514')")), + mcp.WithBoolean("auto_approve", mcp.Description("Auto-approve permissions (default: false)")), + ), + s.wrapHandler("create_agent_profile", s.createAgentProfileHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("delete_agent_profile", + mcp.WithDescription("Delete an agent profile. Fails if the profile is used by an active session."), + mcp.WithString("profile_id", mcp.Required(), mcp.Description("The profile ID to delete")), + ), + s.wrapHandler("delete_agent_profile", s.deleteAgentProfileHandler()), + ) +} + +// --- MCP config tools --- + +func (s *Server) registerConfigMcpTools() { + s.mcpServer.AddTool( + mcp.NewTool("list_agent_profiles", + mcp.WithDescription("List all profiles for an agent."), + mcp.WithString("agent_id", mcp.Required(), mcp.Description("The agent ID")), + ), + s.wrapHandler("list_agent_profiles", s.listAgentProfilesHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("update_agent_profile", + mcp.WithDescription("Update an agent profile's settings."), + mcp.WithString("profile_id", mcp.Required(), mcp.Description("The profile ID")), + mcp.WithString("name", mcp.Description("New profile name")), + mcp.WithString("model", mcp.Description("New model name")), + mcp.WithBoolean("auto_approve", mcp.Description("Auto-approve permissions")), + ), + s.wrapHandler("update_agent_profile", s.updateAgentProfileHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("get_mcp_config", + mcp.WithDescription("Get MCP server configuration for an agent profile."), + mcp.WithString("profile_id", mcp.Required(), mcp.Description("The agent profile ID")), + ), + s.wrapHandler("get_mcp_config", s.getMcpConfigHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("update_mcp_config", + mcp.WithDescription("Update MCP server configuration for an agent profile. Pass the full servers map."), + mcp.WithString("profile_id", mcp.Required(), mcp.Description("The agent profile ID")), + mcp.WithBoolean("enabled", mcp.Description("Whether MCP is enabled for this profile")), + mcp.WithObject("servers", mcp.Description("Full MCP servers map to set. Each key is a server name, value is the server configuration object.")), + ), + s.wrapHandler("update_mcp_config", s.updateMcpConfigHandler()), + ) +} + +// --- Executor config tools --- + +func (s *Server) registerConfigExecutorTools() { + s.mcpServer.AddTool( + mcp.NewToolWithRawSchema("list_executors", + "List all executors.", + json.RawMessage(`{"type":"object","properties":{}}`), + ), + s.wrapHandler("list_executors", s.listExecutorsHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("list_executor_profiles", + mcp.WithDescription("List all profiles for an executor."), + mcp.WithString("executor_id", mcp.Required(), mcp.Description("The executor ID")), + ), + s.wrapHandler("list_executor_profiles", s.listExecutorProfilesHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("create_executor_profile", + mcp.WithDescription("Create a new executor profile."), + mcp.WithString("executor_id", mcp.Required(), mcp.Description("The executor ID")), + mcp.WithString("name", mcp.Required(), mcp.Description("Profile name")), + mcp.WithString("mcp_policy", mcp.Description("MCP policy for this profile")), + mcp.WithObject("config", mcp.Description("Key-value configuration map")), + mcp.WithString("prepare_script", mcp.Description("Script to run before agent starts")), + mcp.WithString("cleanup_script", mcp.Description("Script to run after agent stops")), + ), + s.wrapHandler("create_executor_profile", s.createExecutorProfileHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("update_executor_profile", + mcp.WithDescription("Update an existing executor profile."), + mcp.WithString("profile_id", mcp.Required(), mcp.Description("The executor profile ID")), + mcp.WithString("name", mcp.Description("New profile name")), + mcp.WithString("mcp_policy", mcp.Description("New MCP policy")), + mcp.WithObject("config", mcp.Description("New configuration map")), + mcp.WithString("prepare_script", mcp.Description("New prepare script")), + mcp.WithString("cleanup_script", mcp.Description("New cleanup script")), + ), + s.wrapHandler("update_executor_profile", s.updateExecutorProfileHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("delete_executor_profile", + mcp.WithDescription("Delete an executor profile."), + mcp.WithString("profile_id", mcp.Required(), mcp.Description("The executor profile ID to delete")), + ), + s.wrapHandler("delete_executor_profile", s.deleteExecutorProfileHandler()), + ) +} + +// --- Task config tools --- + +func (s *Server) registerConfigTaskTools() { + s.mcpServer.AddTool( + mcp.NewTool("list_tasks", + mcp.WithDescription("List all tasks in a workflow."), + mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")), + ), + s.wrapHandler("list_tasks", s.listTasksHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("move_task", + mcp.WithDescription("Move a task to a different workflow step."), + mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID")), + mcp.WithString("workflow_id", mcp.Required(), mcp.Description("Target workflow ID")), + mcp.WithString("workflow_step_id", mcp.Required(), mcp.Description("Target workflow step ID")), + mcp.WithNumber("position", mcp.Description("Position within the step (0-based)")), + ), + s.wrapHandler("move_task", s.moveTaskHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("delete_task", + mcp.WithDescription("Delete a task permanently."), + mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID to delete")), + ), + s.wrapHandler("delete_task", s.deleteTaskHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("archive_task", + mcp.WithDescription("Archive a task."), + mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID to archive")), + ), + s.wrapHandler("archive_task", s.archiveTaskHandler()), + ) + s.mcpServer.AddTool( + mcp.NewTool("update_task_state", + mcp.WithDescription("Update the state of a task."), + mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID")), + mcp.WithString("state", mcp.Required(), mcp.Description("New state: open, in_progress, complete, blocked, cancelled")), + ), + s.wrapHandler("update_task_state", s.updateTaskStateHandler()), + ) +} + +// --- Handler implementations --- + +func (s *Server) createWorkflowHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + workspaceID, err := req.RequireString("workspace_id") + if err != nil { + return mcp.NewToolResultError("workspace_id is required"), nil + } + name, err := req.RequireString("name") + if err != nil { + return mcp.NewToolResultError("name is required"), nil + } + payload := map[string]interface{}{ + "workspace_id": workspaceID, + "name": name, + } + if desc := req.GetString("description", ""); desc != "" { + payload["description"] = desc + } + return s.forwardToBackend(ctx, ws.ActionMCPCreateWorkflow, payload) + } +} + +func (s *Server) updateWorkflowHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + workflowID, err := req.RequireString("workflow_id") + if err != nil { + return mcp.NewToolResultError("workflow_id is required"), nil + } + payload := map[string]interface{}{"workflow_id": workflowID} + if name := req.GetString("name", ""); name != "" { + payload["name"] = name + } + if desc := req.GetString("description", ""); desc != "" { + payload["description"] = desc + } + return s.forwardToBackend(ctx, ws.ActionMCPUpdateWorkflow, payload) + } +} + +func (s *Server) deleteWorkflowHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + workflowID, err := req.RequireString("workflow_id") + if err != nil { + return mcp.NewToolResultError("workflow_id is required"), nil + } + return s.forwardToBackend(ctx, ws.ActionMCPDeleteWorkflow, map[string]string{"workflow_id": workflowID}) + } +} + +func (s *Server) createWorkflowStepHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + workflowID, err := req.RequireString("workflow_id") + if err != nil { + return mcp.NewToolResultError("workflow_id is required"), nil + } + name, err := req.RequireString("name") + if err != nil { + return mcp.NewToolResultError("name is required"), nil + } + payload := map[string]interface{}{ + "workflow_id": workflowID, + "name": name, + } + if color := req.GetString("color", ""); color != "" { + payload["color"] = color + } + if prompt := req.GetString("prompt", ""); prompt != "" { + payload["prompt"] = prompt + } + args := req.GetArguments() + for _, key := range []string{"position", "is_start_step", "allow_manual_move", "show_in_command_panel", "events"} { + if args[key] != nil { + payload[key] = args[key] + } + } + return s.forwardToBackend(ctx, ws.ActionMCPCreateWorkflowStep, payload) + } +} + +func (s *Server) updateWorkflowStepHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + stepID, err := req.RequireString("step_id") + if err != nil { + return mcp.NewToolResultError("step_id is required"), nil + } + payload := map[string]interface{}{"step_id": stepID} + if name := req.GetString("name", ""); name != "" { + payload["name"] = name + } + if color := req.GetString("color", ""); color != "" { + payload["color"] = color + } + if prompt := req.GetString("prompt", ""); prompt != "" { + payload["prompt"] = prompt + } + args := req.GetArguments() + for _, key := range []string{"is_start_step", "allow_manual_move", "show_in_command_panel", "auto_archive_after_hours", "events"} { + if args[key] != nil { + payload[key] = args[key] + } + } + return s.forwardToBackend(ctx, ws.ActionMCPUpdateWorkflowStep, payload) + } +} + +func (s *Server) listAgentsHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + return s.forwardToBackend(ctx, ws.ActionMCPListAgents, nil) + } +} + +func (s *Server) createAgentProfileHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + agentID, err := req.RequireString("agent_id") + if err != nil { + return mcp.NewToolResultError("agent_id is required"), nil + } + name, err := req.RequireString("name") + if err != nil { + return mcp.NewToolResultError("name is required"), nil + } + model, err := req.RequireString("model") + if err != nil { + return mcp.NewToolResultError("model is required"), nil + } + payload := map[string]interface{}{ + "agent_id": agentID, + "name": name, + "model": model, + } + if args := req.GetArguments(); args["auto_approve"] != nil { + payload["auto_approve"] = args["auto_approve"] + } + return s.forwardToBackend(ctx, ws.ActionMCPCreateAgentProfile, payload) + } +} + +func (s *Server) updateAgentHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + agentID, err := req.RequireString("agent_id") + if err != nil { + return mcp.NewToolResultError("agent_id is required"), nil + } + payload := map[string]interface{}{"agent_id": agentID} + if args := req.GetArguments(); args["supports_mcp"] != nil { + payload["supports_mcp"] = args["supports_mcp"] + } + if path := req.GetString("mcp_config_path", ""); path != "" { + payload["mcp_config_path"] = path + } + return s.forwardToBackend(ctx, ws.ActionMCPUpdateAgent, payload) + } +} + +func (s *Server) deleteAgentProfileHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + profileID, err := req.RequireString("profile_id") + if err != nil { + return mcp.NewToolResultError("profile_id is required"), nil + } + payload := map[string]string{"profile_id": profileID} + return s.forwardToBackend(ctx, ws.ActionMCPDeleteAgentProfile, payload) + } +} + +func (s *Server) listAgentProfilesHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + agentID, err := req.RequireString("agent_id") + if err != nil { + return mcp.NewToolResultError("agent_id is required"), nil + } + payload := map[string]string{"agent_id": agentID} + return s.forwardToBackend(ctx, ws.ActionMCPListAgentProfiles, payload) + } +} + +func (s *Server) updateAgentProfileHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + profileID, err := req.RequireString("profile_id") + if err != nil { + return mcp.NewToolResultError("profile_id is required"), nil + } + payload := map[string]interface{}{"profile_id": profileID} + if name := req.GetString("name", ""); name != "" { + payload["name"] = name + } + if model := req.GetString("model", ""); model != "" { + payload["model"] = model + } + if args := req.GetArguments(); args["auto_approve"] != nil { + payload["auto_approve"] = args["auto_approve"] + } + return s.forwardToBackend(ctx, ws.ActionMCPUpdateAgentProfile, payload) + } +} + +func (s *Server) getMcpConfigHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + profileID, err := req.RequireString("profile_id") + if err != nil { + return mcp.NewToolResultError("profile_id is required"), nil + } + payload := map[string]string{"profile_id": profileID} + return s.forwardToBackend(ctx, ws.ActionMCPGetMcpConfig, payload) + } +} + +func (s *Server) updateMcpConfigHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + profileID, err := req.RequireString("profile_id") + if err != nil { + return mcp.NewToolResultError("profile_id is required"), nil + } + payload := map[string]interface{}{"profile_id": profileID} + args := req.GetArguments() + if args["enabled"] != nil { + payload["enabled"] = args["enabled"] + } + if args["servers"] != nil { + payload["servers"] = args["servers"] + } + return s.forwardToBackend(ctx, ws.ActionMCPUpdateMcpConfig, payload) + } +} + +func (s *Server) moveTaskHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + taskID, err := req.RequireString("task_id") + if err != nil { + return mcp.NewToolResultError("task_id is required"), nil + } + workflowID, err := req.RequireString("workflow_id") + if err != nil { + return mcp.NewToolResultError("workflow_id is required"), nil + } + stepID, err := req.RequireString("workflow_step_id") + if err != nil { + return mcp.NewToolResultError("workflow_step_id is required"), nil + } + payload := map[string]interface{}{ + "task_id": taskID, + "workflow_id": workflowID, + "workflow_step_id": stepID, + } + if args := req.GetArguments(); args["position"] != nil { + payload["position"] = args["position"] + } + return s.forwardToBackend(ctx, ws.ActionMCPMoveTask, payload) + } +} + +func (s *Server) deleteTaskHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + taskID, err := req.RequireString("task_id") + if err != nil { + return mcp.NewToolResultError("task_id is required"), nil + } + payload := map[string]string{"task_id": taskID} + return s.forwardToBackend(ctx, ws.ActionMCPDeleteTask, payload) + } +} + +func (s *Server) updateTaskStateHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + taskID, err := req.RequireString("task_id") + if err != nil { + return mcp.NewToolResultError("task_id is required"), nil + } + state, err := req.RequireString("state") + if err != nil { + return mcp.NewToolResultError("state is required"), nil + } + payload := map[string]string{"task_id": taskID, "state": state} + return s.forwardToBackend(ctx, ws.ActionMCPUpdateTaskState, payload) + } +} + +func (s *Server) deleteWorkflowStepHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + stepID, err := req.RequireString("step_id") + if err != nil { + return mcp.NewToolResultError("step_id is required"), nil + } + return s.forwardToBackend(ctx, ws.ActionMCPDeleteWorkflowStep, map[string]string{"step_id": stepID}) + } +} + +func (s *Server) reorderWorkflowStepsHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + workflowID, err := req.RequireString("workflow_id") + if err != nil { + return mcp.NewToolResultError("workflow_id is required"), nil + } + args := req.GetArguments() + stepIDs := args["step_ids"] + if stepIDs == nil { + return mcp.NewToolResultError("step_ids is required"), nil + } + payload := map[string]interface{}{ + "workflow_id": workflowID, + "step_ids": stepIDs, + } + return s.forwardToBackend(ctx, ws.ActionMCPReorderWorkflowStep, payload) + } +} + +func (s *Server) archiveTaskHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + taskID, err := req.RequireString("task_id") + if err != nil { + return mcp.NewToolResultError("task_id is required"), nil + } + payload := map[string]string{"task_id": taskID} + return s.forwardToBackend(ctx, ws.ActionMCPArchiveTask, payload) + } +} + +// --- Executor handler implementations --- + +func (s *Server) listExecutorsHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + return s.forwardToBackend(ctx, ws.ActionMCPListExecutors, nil) + } +} + +func (s *Server) listExecutorProfilesHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + executorID, err := req.RequireString("executor_id") + if err != nil { + return mcp.NewToolResultError("executor_id is required"), nil + } + return s.forwardToBackend(ctx, ws.ActionMCPListExecutorProfiles, map[string]string{"executor_id": executorID}) + } +} + +func (s *Server) createExecutorProfileHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + executorID, err := req.RequireString("executor_id") + if err != nil { + return mcp.NewToolResultError("executor_id is required"), nil + } + name, err := req.RequireString("name") + if err != nil { + return mcp.NewToolResultError("name is required"), nil + } + payload := map[string]interface{}{ + "executor_id": executorID, + "name": name, + } + if mcpPolicy := req.GetString("mcp_policy", ""); mcpPolicy != "" { + payload["mcp_policy"] = mcpPolicy + } + if prepareScript := req.GetString("prepare_script", ""); prepareScript != "" { + payload["prepare_script"] = prepareScript + } + if cleanupScript := req.GetString("cleanup_script", ""); cleanupScript != "" { + payload["cleanup_script"] = cleanupScript + } + args := req.GetArguments() + if args["config"] != nil { + payload["config"] = args["config"] + } + return s.forwardToBackend(ctx, ws.ActionMCPCreateExecutorProfile, payload) + } +} + +func (s *Server) updateExecutorProfileHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + profileID, err := req.RequireString("profile_id") + if err != nil { + return mcp.NewToolResultError("profile_id is required"), nil + } + payload := map[string]interface{}{"profile_id": profileID} + if name := req.GetString("name", ""); name != "" { + payload["name"] = name + } + if mcpPolicy := req.GetString("mcp_policy", ""); mcpPolicy != "" { + payload["mcp_policy"] = mcpPolicy + } + if prepareScript := req.GetString("prepare_script", ""); prepareScript != "" { + payload["prepare_script"] = prepareScript + } + if cleanupScript := req.GetString("cleanup_script", ""); cleanupScript != "" { + payload["cleanup_script"] = cleanupScript + } + args := req.GetArguments() + if args["config"] != nil { + payload["config"] = args["config"] + } + return s.forwardToBackend(ctx, ws.ActionMCPUpdateExecutorProfile, payload) + } +} + +func (s *Server) deleteExecutorProfileHandler() server.ToolHandlerFunc { + return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + profileID, err := req.RequireString("profile_id") + if err != nil { + return mcp.NewToolResultError("profile_id is required"), nil + } + return s.forwardToBackend(ctx, ws.ActionMCPDeleteExecutorProfile, map[string]string{"profile_id": profileID}) + } +} + +// forwardToBackend sends a request to the backend and returns the result as JSON text. +func (s *Server) forwardToBackend(ctx context.Context, action string, payload interface{}) (*mcp.CallToolResult, error) { + var result map[string]interface{} + if err := s.backend.RequestPayload(ctx, action, payload, &result); err != nil { + return mcp.NewToolResultError(err.Error()), nil + } + data, err := json.MarshalIndent(result, "", " ") + if err != nil { + return mcp.NewToolResultError("failed to marshal response: " + err.Error()), nil + } + return mcp.NewToolResultText(string(data)), nil +} diff --git a/apps/backend/internal/agentctl/server/mcp/config_handlers_test.go b/apps/backend/internal/agentctl/server/mcp/config_handlers_test.go new file mode 100644 index 0000000000..27279f0437 --- /dev/null +++ b/apps/backend/internal/agentctl/server/mcp/config_handlers_test.go @@ -0,0 +1,674 @@ +package mcp + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + ws "github.com/kandev/kandev/pkg/websocket" + mcplib "github.com/mark3labs/mcp-go/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// testBackend implements BackendClient for testing handlers. +type testBackend struct { + lastAction string + lastPayload interface{} + response map[string]interface{} + err error +} + +func (tb *testBackend) RequestPayload(_ context.Context, action string, payload, result interface{}) error { + tb.lastAction = action + tb.lastPayload = payload + if tb.err != nil { + return tb.err + } + if tb.response != nil && result != nil { + data, _ := json.Marshal(tb.response) + return json.Unmarshal(data, result) + } + return nil +} + +func newTestServer(t *testing.T, backend BackendClient) *Server { + t.Helper() + log := newTestLogger(t) + return New(backend, "test-session", 10005, log, "", false, ModeConfig) +} + +func callTool(t *testing.T, s *Server, toolName string, args map[string]interface{}) *mcplib.CallToolResult { + t.Helper() + toolsMap := s.mcpServer.ListTools() + st, ok := toolsMap[toolName] + require.True(t, ok, "tool %q not registered", toolName) + + reqArgs, err := json.Marshal(args) + require.NoError(t, err) + + req := mcplib.CallToolRequest{} + req.Method = "tools/call" + req.Params.Name = toolName + req.Params.Arguments = make(map[string]interface{}) + if err := json.Unmarshal(reqArgs, &req.Params.Arguments); err != nil { + t.Fatal(err) + } + + result, err := st.Handler(context.Background(), req) + require.NoError(t, err) + return result +} + +// --- Action constant tests --- + +func TestActionConstants_MatchWebSocketActions(t *testing.T) { + // Verify canonical constants in pkg/websocket match the expected WS action strings. + assert.Equal(t, "mcp.create_workflow", ws.ActionMCPCreateWorkflow) + assert.Equal(t, "mcp.update_workflow", ws.ActionMCPUpdateWorkflow) + assert.Equal(t, "mcp.delete_workflow", ws.ActionMCPDeleteWorkflow) + assert.Equal(t, "mcp.create_workflow_step", ws.ActionMCPCreateWorkflowStep) + assert.Equal(t, "mcp.update_workflow_step", ws.ActionMCPUpdateWorkflowStep) + assert.Equal(t, "mcp.delete_workflow_step", ws.ActionMCPDeleteWorkflowStep) + assert.Equal(t, "mcp.reorder_workflow_steps", ws.ActionMCPReorderWorkflowStep) + assert.Equal(t, "mcp.list_agents", ws.ActionMCPListAgents) + assert.Equal(t, "mcp.update_agent", ws.ActionMCPUpdateAgent) + assert.Equal(t, "mcp.list_agent_profiles", ws.ActionMCPListAgentProfiles) + assert.Equal(t, "mcp.create_agent_profile", ws.ActionMCPCreateAgentProfile) + assert.Equal(t, "mcp.update_agent_profile", ws.ActionMCPUpdateAgentProfile) + assert.Equal(t, "mcp.delete_agent_profile", ws.ActionMCPDeleteAgentProfile) + assert.Equal(t, "mcp.get_mcp_config", ws.ActionMCPGetMcpConfig) + assert.Equal(t, "mcp.update_mcp_config", ws.ActionMCPUpdateMcpConfig) + assert.Equal(t, "mcp.list_executors", ws.ActionMCPListExecutors) + assert.Equal(t, "mcp.list_executor_profiles", ws.ActionMCPListExecutorProfiles) + assert.Equal(t, "mcp.create_executor_profile", ws.ActionMCPCreateExecutorProfile) + assert.Equal(t, "mcp.update_executor_profile", ws.ActionMCPUpdateExecutorProfile) + assert.Equal(t, "mcp.delete_executor_profile", ws.ActionMCPDeleteExecutorProfile) + assert.Equal(t, "mcp.move_task", ws.ActionMCPMoveTask) + assert.Equal(t, "mcp.delete_task", ws.ActionMCPDeleteTask) + assert.Equal(t, "mcp.archive_task", ws.ActionMCPArchiveTask) + assert.Equal(t, "mcp.update_task_state", ws.ActionMCPUpdateTaskState) +} + +// --- Workflow handler tests --- + +func TestCreateWorkflowHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"id": "wf-1", "name": "Sprint Board"}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "create_workflow", map[string]interface{}{ + "workspace_id": "ws-123", + "name": "Sprint Board", + "description": "A sprint workflow", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPCreateWorkflow, backend.lastAction) + payload, ok := backend.lastPayload.(map[string]interface{}) + require.True(t, ok) + assert.Equal(t, "ws-123", payload["workspace_id"]) + assert.Equal(t, "Sprint Board", payload["name"]) + assert.Equal(t, "A sprint workflow", payload["description"]) +} + +func TestCreateWorkflowHandler_MissingWorkspaceID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "create_workflow", map[string]interface{}{ + "name": "Sprint Board", + }) + + assert.True(t, result.IsError) +} + +func TestCreateWorkflowHandler_MissingName(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "create_workflow", map[string]interface{}{ + "workspace_id": "ws-123", + }) + + assert.True(t, result.IsError) +} + +func TestUpdateWorkflowHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"id": "wf-1", "name": "Updated"}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "update_workflow", map[string]interface{}{ + "workflow_id": "wf-1", + "name": "Updated", + "description": "New description", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPUpdateWorkflow, backend.lastAction) +} + +func TestUpdateWorkflowHandler_MissingWorkflowID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "update_workflow", map[string]interface{}{ + "name": "Updated", + }) + + assert.True(t, result.IsError) +} + +func TestDeleteWorkflowHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"success": true}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "delete_workflow", map[string]interface{}{ + "workflow_id": "wf-1", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPDeleteWorkflow, backend.lastAction) +} + +func TestDeleteWorkflowHandler_MissingWorkflowID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "delete_workflow", map[string]interface{}{}) + + assert.True(t, result.IsError) +} + +func TestCreateWorkflowStepHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"step": map[string]interface{}{"id": "step-1", "name": "Review"}}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "create_workflow_step", map[string]interface{}{ + "workflow_id": "wf-123", + "name": "Review", + "color": "#3b82f6", + "position": float64(2), + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPCreateWorkflowStep, backend.lastAction) +} + +func TestCreateWorkflowStepHandler_AllFields(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"step": map[string]interface{}{"id": "step-1"}}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "create_workflow_step", map[string]interface{}{ + "workflow_id": "wf-123", + "name": "Deploy", + "position": float64(0), + "color": "#22c55e", + "prompt": "Deploy prompt", + "is_start_step": true, + "allow_manual_move": true, + "show_in_command_panel": true, + "events": map[string]interface{}{ + "on_enter": []interface{}{map[string]interface{}{"type": "auto_start_agent"}}, + }, + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPCreateWorkflowStep, backend.lastAction) + // Verify optional fields are forwarded in the payload + payload, ok := backend.lastPayload.(map[string]interface{}) + require.True(t, ok) + assert.Equal(t, true, payload["allow_manual_move"]) + assert.Equal(t, true, payload["show_in_command_panel"]) + assert.NotNil(t, payload["events"]) +} + +func TestCreateWorkflowStepHandler_MissingWorkflowID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "create_workflow_step", map[string]interface{}{ + "name": "Review", + }) + + assert.True(t, result.IsError) +} + +func TestCreateWorkflowStepHandler_MissingName(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "create_workflow_step", map[string]interface{}{ + "workflow_id": "wf-123", + }) + + assert.True(t, result.IsError) +} + +func TestUpdateWorkflowStepHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"step": map[string]interface{}{"id": "step-1"}}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "update_workflow_step", map[string]interface{}{ + "step_id": "step-1", + "name": "Updated Name", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPUpdateWorkflowStep, backend.lastAction) +} + +func TestUpdateWorkflowStepHandler_AllFields(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"step": map[string]interface{}{"id": "step-1"}}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "update_workflow_step", map[string]interface{}{ + "step_id": "step-1", + "name": "In Review", + "color": "#3b82f6", + "allow_manual_move": true, + "show_in_command_panel": true, + "auto_archive_after_hours": float64(48), + "events": map[string]interface{}{ + "on_enter": []interface{}{map[string]interface{}{"type": "enable_plan_mode"}}, + }, + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPUpdateWorkflowStep, backend.lastAction) + payload, ok := backend.lastPayload.(map[string]interface{}) + require.True(t, ok) + assert.Equal(t, true, payload["allow_manual_move"]) + assert.Equal(t, true, payload["show_in_command_panel"]) + assert.Equal(t, float64(48), payload["auto_archive_after_hours"]) + assert.NotNil(t, payload["events"]) +} + +func TestUpdateWorkflowStepHandler_MissingStepID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "update_workflow_step", map[string]interface{}{ + "name": "Updated", + }) + + assert.True(t, result.IsError) +} + +// --- Agent handler tests --- + +func TestListAgentsHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"agents": []interface{}{}, "total": float64(0)}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "list_agents", map[string]interface{}{}) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPListAgents, backend.lastAction) +} + +func TestCreateAgentProfileHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"id": "profile-1", "name": "My Profile"}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "create_agent_profile", map[string]interface{}{ + "agent_id": "agent-1", + "name": "My Profile", + "model": "claude-sonnet-4-5-20250514", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPCreateAgentProfile, backend.lastAction) +} + +func TestCreateAgentProfileHandler_MissingAgentID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "create_agent_profile", map[string]interface{}{ + "name": "My Profile", + "model": "claude-sonnet-4-5-20250514", + }) + + assert.True(t, result.IsError) +} + +func TestCreateAgentProfileHandler_MissingModel(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "create_agent_profile", map[string]interface{}{ + "agent_id": "agent-1", + "name": "My Profile", + }) + + assert.True(t, result.IsError) +} + +func TestUpdateAgentHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"id": "agent-1"}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "update_agent", map[string]interface{}{ + "agent_id": "agent-1", + "supports_mcp": true, + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPUpdateAgent, backend.lastAction) +} + +func TestUpdateAgentHandler_MissingAgentID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "update_agent", map[string]interface{}{ + "supports_mcp": true, + }) + + assert.True(t, result.IsError) +} + +func TestDeleteAgentProfileHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"id": "profile-1"}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "delete_agent_profile", map[string]interface{}{ + "profile_id": "profile-1", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPDeleteAgentProfile, backend.lastAction) +} + +func TestDeleteAgentProfileHandler_MissingProfileID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "delete_agent_profile", map[string]interface{}{}) + + assert.True(t, result.IsError) +} + +// --- MCP config handler tests --- + +func TestListAgentProfilesHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"profiles": []interface{}{}, "total": float64(0)}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "list_agent_profiles", map[string]interface{}{ + "agent_id": "agent-1", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPListAgentProfiles, backend.lastAction) +} + +func TestListAgentProfilesHandler_MissingAgentID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "list_agent_profiles", map[string]interface{}{}) + + assert.True(t, result.IsError) +} + +func TestUpdateAgentProfileHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"id": "profile-1"}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "update_agent_profile", map[string]interface{}{ + "profile_id": "profile-1", + "name": "Updated Profile", + "model": "claude-3.5-sonnet", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPUpdateAgentProfile, backend.lastAction) +} + +func TestUpdateAgentProfileHandler_MissingProfileID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "update_agent_profile", map[string]interface{}{ + "name": "Updated", + }) + + assert.True(t, result.IsError) +} + +func TestGetMcpConfigHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"profile_id": "p-1", "enabled": true}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "get_mcp_config", map[string]interface{}{ + "profile_id": "p-1", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPGetMcpConfig, backend.lastAction) +} + +func TestGetMcpConfigHandler_MissingProfileID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "get_mcp_config", map[string]interface{}{}) + + assert.True(t, result.IsError) +} + +func TestUpdateMcpConfigHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"profile_id": "p-1"}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "update_mcp_config", map[string]interface{}{ + "profile_id": "p-1", + "enabled": true, + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPUpdateMcpConfig, backend.lastAction) +} + +func TestUpdateMcpConfigHandler_MissingProfileID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "update_mcp_config", map[string]interface{}{}) + + assert.True(t, result.IsError) +} + +// --- Executor handler tests --- + +func TestListExecutorsHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"executors": []interface{}{}, "total": float64(0)}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "list_executors", map[string]interface{}{}) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPListExecutors, backend.lastAction) +} + +func TestListExecutorProfilesHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"profiles": []interface{}{}, "total": float64(0)}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "list_executor_profiles", map[string]interface{}{ + "executor_id": "exec-1", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPListExecutorProfiles, backend.lastAction) +} + +func TestListExecutorProfilesHandler_MissingExecutorID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "list_executor_profiles", map[string]interface{}{}) + + assert.True(t, result.IsError) +} + +func TestCreateExecutorProfileHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"id": "prof-1", "name": "Default"}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "create_executor_profile", map[string]interface{}{ + "executor_id": "exec-1", + "name": "Default", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPCreateExecutorProfile, backend.lastAction) + payload, ok := backend.lastPayload.(map[string]interface{}) + require.True(t, ok) + assert.Equal(t, "exec-1", payload["executor_id"]) + assert.Equal(t, "Default", payload["name"]) +} + +func TestCreateExecutorProfileHandler_MissingExecutorID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "create_executor_profile", map[string]interface{}{ + "name": "Default", + }) + + assert.True(t, result.IsError) +} + +func TestCreateExecutorProfileHandler_MissingName(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "create_executor_profile", map[string]interface{}{ + "executor_id": "exec-1", + }) + + assert.True(t, result.IsError) +} + +func TestUpdateExecutorProfileHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"id": "prof-1"}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "update_executor_profile", map[string]interface{}{ + "profile_id": "prof-1", + "name": "Updated Profile", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPUpdateExecutorProfile, backend.lastAction) +} + +func TestUpdateExecutorProfileHandler_MissingProfileID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "update_executor_profile", map[string]interface{}{ + "name": "Updated", + }) + + assert.True(t, result.IsError) +} + +func TestDeleteExecutorProfileHandler_Success(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{"success": true}, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "delete_executor_profile", map[string]interface{}{ + "profile_id": "prof-1", + }) + + assert.False(t, result.IsError) + assert.Equal(t, ws.ActionMCPDeleteExecutorProfile, backend.lastAction) +} + +func TestDeleteExecutorProfileHandler_MissingProfileID(t *testing.T) { + backend := &testBackend{} + s := newTestServer(t, backend) + + result := callTool(t, s, "delete_executor_profile", map[string]interface{}{}) + + assert.True(t, result.IsError) +} + +// --- ForwardToBackend tests --- + +func TestForwardToBackend_BackendError(t *testing.T) { + backend := &testBackend{ + err: fmt.Errorf("connection refused"), + } + s := newTestServer(t, backend) + + result := callTool(t, s, "list_agents", map[string]interface{}{}) + + assert.True(t, result.IsError) +} + +func TestForwardToBackend_ResultContainsJSON(t *testing.T) { + backend := &testBackend{ + response: map[string]interface{}{ + "agents": []interface{}{ + map[string]interface{}{"id": "a1", "name": "claude-code"}, + }, + "total": float64(1), + }, + } + s := newTestServer(t, backend) + + result := callTool(t, s, "list_agents", map[string]interface{}{}) + + assert.False(t, result.IsError) + require.NotEmpty(t, result.Content) + + // The result should be JSON text content + tc, ok := result.Content[0].(mcplib.TextContent) + assert.True(t, ok, "expected TextContent") + assert.NotEmpty(t, tc.Text) +} diff --git a/apps/backend/internal/agentctl/server/mcp/handlers.go b/apps/backend/internal/agentctl/server/mcp/handlers.go index c81a67123b..29eeb1d971 100644 --- a/apps/backend/internal/agentctl/server/mcp/handlers.go +++ b/apps/backend/internal/agentctl/server/mcp/handlers.go @@ -5,33 +5,17 @@ import ( "encoding/json" "fmt" + ws "github.com/kandev/kandev/pkg/websocket" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" "go.uber.org/zap" ) -// MCP action constants for backend WS requests -// These must match the actions registered in pkg/websocket/actions.go -const ( - ActionMCPListWorkspaces = "mcp.list_workspaces" - ActionMCPListWorkflows = "mcp.list_workflows" - ActionMCPListWorkflowSteps = "mcp.list_workflow_steps" - ActionMCPListTasks = "mcp.list_tasks" - ActionMCPCreateTask = "mcp.create_task" - ActionMCPUpdateTask = "mcp.update_task" - ActionMCPAskUserQuestion = "mcp.ask_user_question" - ActionMCPClarificationTimeout = "mcp.clarification_timeout" - ActionMCPCreateTaskPlan = "mcp.create_task_plan" - ActionMCPGetTaskPlan = "mcp.get_task_plan" - ActionMCPUpdateTaskPlan = "mcp.update_task_plan" - ActionMCPDeleteTaskPlan = "mcp.delete_task_plan" -) - func (s *Server) listWorkspacesHandler() server.ToolHandlerFunc { return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { // Backend returns {workspaces: [...], total: N} var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPListWorkspaces, nil, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPListWorkspaces, nil, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } data, _ := json.MarshalIndent(result, "", " ") @@ -48,7 +32,7 @@ func (s *Server) listWorkflowsHandler() server.ToolHandlerFunc { payload := map[string]string{"workspace_id": workspaceID} // Backend returns {workflows: [...], total: N} var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPListWorkflows, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPListWorkflows, payload, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } data, _ := json.MarshalIndent(result, "", " ") @@ -65,7 +49,7 @@ func (s *Server) listWorkflowStepsHandler() server.ToolHandlerFunc { payload := map[string]string{"workflow_id": workflowID} // Backend returns {workflow_steps: [...], total: N} var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPListWorkflowSteps, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPListWorkflowSteps, payload, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } data, _ := json.MarshalIndent(result, "", " ") @@ -82,7 +66,7 @@ func (s *Server) listTasksHandler() server.ToolHandlerFunc { payload := map[string]string{"workflow_id": workflowID} // Backend returns {tasks: [...], total: N} var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPListTasks, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPListTasks, payload, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } data, _ := json.MarshalIndent(result, "", " ") @@ -118,7 +102,7 @@ func (s *Server) createTaskHandler() server.ToolHandlerFunc { "description": description, } var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPCreateTask, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPCreateTask, payload, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } data, _ := json.MarshalIndent(result, "", " ") @@ -143,7 +127,7 @@ func (s *Server) updateTaskHandler() server.ToolHandlerFunc { payload["state"] = state } var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPUpdateTask, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPUpdateTask, payload, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } data, _ := json.MarshalIndent(result, "", " ") @@ -179,7 +163,7 @@ func (s *Server) askUserQuestionHandler() server.ToolHandlerFunc { // Use the MCP request context from the agent. This ensures that if the agent's // MCP client times out, we'll detect it and not update the session state. var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPAskUserQuestion, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPAskUserQuestion, payload, &result); err != nil { if ctx.Err() != nil { // Agent's MCP client disconnected/timed out. Notify backend to cancel // pending clarifications so the user's answer goes through the event @@ -281,7 +265,7 @@ func extractAnswerMap(answer interface{}) *mcp.CallToolResult { // the event fallback path (new turn) instead of the primary path (same turn). func (s *Server) notifyClarificationTimeout() { payload := map[string]string{"session_id": s.sessionID} - if err := s.backend.RequestPayload(context.Background(), ActionMCPClarificationTimeout, payload, nil); err != nil { + if err := s.backend.RequestPayload(context.Background(), ws.ActionMCPClarificationTimeout, payload, nil); err != nil { s.logger.Warn("failed to notify backend of clarification timeout", zap.String("session_id", s.sessionID), zap.Error(err)) @@ -307,7 +291,7 @@ func (s *Server) createTaskPlanHandler() server.ToolHandlerFunc { "created_by": "agent", } var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPCreateTaskPlan, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPCreateTaskPlan, payload, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } data, _ := json.MarshalIndent(result, "", " ") @@ -324,7 +308,7 @@ func (s *Server) getTaskPlanHandler() server.ToolHandlerFunc { payload := map[string]string{"task_id": taskID} var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPGetTaskPlan, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPGetTaskPlan, payload, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } @@ -365,7 +349,7 @@ func (s *Server) updateTaskPlanHandler() server.ToolHandlerFunc { } var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPUpdateTaskPlan, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPUpdateTaskPlan, payload, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } data, _ := json.MarshalIndent(result, "", " ") @@ -382,7 +366,7 @@ func (s *Server) deleteTaskPlanHandler() server.ToolHandlerFunc { payload := map[string]string{"task_id": taskID} var result map[string]interface{} - if err := s.backend.RequestPayload(ctx, ActionMCPDeleteTaskPlan, payload, &result); err != nil { + if err := s.backend.RequestPayload(ctx, ws.ActionMCPDeleteTaskPlan, payload, &result); err != nil { return mcp.NewToolResultError(err.Error()), nil } return mcp.NewToolResultText("Plan deleted successfully."), nil diff --git a/apps/backend/internal/agentctl/server/mcp/server.go b/apps/backend/internal/agentctl/server/mcp/server.go index 6dd1fca65c..d788fd56a2 100644 --- a/apps/backend/internal/agentctl/server/mcp/server.go +++ b/apps/backend/internal/agentctl/server/mcp/server.go @@ -24,11 +24,28 @@ type BackendClient interface { RequestPayload(ctx context.Context, action string, payload, result interface{}) error } +// MCP mode constants control which tools are registered. +const ( + // ModeTask registers kanban, plan, and interaction tools (default for task-solving agents). + ModeTask = "task" + // ModeConfig registers configuration tools for workflows, agents, and MCP servers. + ModeConfig = "config" +) + +// normalizeMode returns a valid MCP mode, defaulting unknown values to ModeTask. +func normalizeMode(mode string) string { + if mode == ModeConfig { + return ModeConfig + } + return ModeTask +} + // Server wraps the MCP server with backend client for communication. type Server struct { backend BackendClient sessionID string disableAskQuestion bool + mode string // "task" (default) or "config" mcpServer *server.MCPServer sseServer *server.SSEServer httpServer *server.StreamableHTTPServer @@ -41,11 +58,13 @@ type Server struct { // New creates a new MCP server for agentctl. // port is the HTTP server port used to build the SSE base URL (http://localhost:). // mcpLogFile is an optional file path for MCP debug logging; pass "" to disable. -func New(backend BackendClient, sessionID string, port int, log *logger.Logger, mcpLogFile string, disableAskQuestion bool) *Server { +func New(backend BackendClient, sessionID string, port int, log *logger.Logger, mcpLogFile string, disableAskQuestion bool, mcpMode string) *Server { + mcpMode = normalizeMode(mcpMode) s := &Server{ backend: backend, sessionID: sessionID, disableAskQuestion: disableAskQuestion, + mode: mcpMode, logger: log.WithFields(zap.String("component", "mcp-server")), } @@ -187,18 +206,50 @@ func (s *Server) wrapHandler(toolName string, handler server.ToolHandlerFunc) se } } -// registerTools registers all MCP tools. +// SetMode changes the MCP server mode and re-registers tools accordingly. +// This allows reconfiguring the tool set after initial creation (e.g., when +// a session transitions to plan/config mode on a pre-existing workspace). +func (s *Server) SetMode(mode string) { + s.mu.Lock() + defer s.mu.Unlock() + + s.mode = normalizeMode(mode) + // Clear all existing tools and re-register for the new mode. + s.mcpServer.SetTools() // empty call clears all tools + s.registerTools() +} + +// registerTools registers MCP tools based on the server mode. func (s *Server) registerTools() { count := 0 - s.registerKanbanTools() - count += 6 - if !s.disableAskQuestion { - s.registerInteractionTools() - count++ + switch s.mode { + case ModeConfig: + s.registerConfigWorkflowTools() + count += 10 + s.registerConfigAgentTools() + count += 4 + s.registerConfigMcpTools() + count += 4 + s.registerConfigExecutorTools() + count += 5 + s.registerConfigTaskTools() + count += 5 + if !s.disableAskQuestion { + s.registerInteractionTools() + count++ + } + default: // ModeTask + s.registerKanbanTools() + count += 6 + if !s.disableAskQuestion { + s.registerInteractionTools() + count++ + } + s.registerPlanTools() + count += 4 } - s.registerPlanTools() - count += 4 s.logger.Info("registered MCP tools", + zap.String("mode", s.mode), zap.Int("count", count), zap.Bool("disable_ask_question", s.disableAskQuestion)) } diff --git a/apps/backend/internal/agentctl/server/mcp/server_test.go b/apps/backend/internal/agentctl/server/mcp/server_test.go new file mode 100644 index 0000000000..df866dd818 --- /dev/null +++ b/apps/backend/internal/agentctl/server/mcp/server_test.go @@ -0,0 +1,226 @@ +package mcp + +import ( + "testing" + + "github.com/kandev/kandev/internal/common/logger" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func newTestLogger(t *testing.T) *logger.Logger { + t.Helper() + log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"}) + require.NoError(t, err) + return log +} + +// getRegisteredToolNames returns the names of all tools registered on the MCP server. +func getRegisteredToolNames(s *Server) []string { + toolsMap := s.mcpServer.ListTools() + names := make([]string, 0, len(toolsMap)) + for name := range toolsMap { + names = append(names, name) + } + return names +} + +func TestServerModeTask_RegistersCorrectTools(t *testing.T) { + log := newTestLogger(t) + backend := NewChannelBackendClient(log) + defer backend.Close() + + s := New(backend, "test-session", 10005, log, "", false, ModeTask) + require.NotNil(t, s) + + tools := getRegisteredToolNames(s) + + // Task mode should have kanban tools + assert.Contains(t, tools, "list_workspaces") + assert.Contains(t, tools, "list_workflows") + assert.Contains(t, tools, "list_workflow_steps") + assert.Contains(t, tools, "list_tasks") + assert.Contains(t, tools, "create_task") + assert.Contains(t, tools, "update_task") + + // Task mode should have plan tools + assert.Contains(t, tools, "create_task_plan") + assert.Contains(t, tools, "get_task_plan") + assert.Contains(t, tools, "update_task_plan") + assert.Contains(t, tools, "delete_task_plan") + + // Task mode should have interaction tools + assert.Contains(t, tools, "ask_user_question") + + // Task mode should NOT have config tools + assert.NotContains(t, tools, "create_workflow") + assert.NotContains(t, tools, "update_workflow") + assert.NotContains(t, tools, "delete_workflow") + assert.NotContains(t, tools, "create_workflow_step") + assert.NotContains(t, tools, "update_workflow_step") + assert.NotContains(t, tools, "list_agents") + assert.NotContains(t, tools, "update_agent") + assert.NotContains(t, tools, "create_agent_profile") + assert.NotContains(t, tools, "delete_agent_profile") + assert.NotContains(t, tools, "list_agent_profiles") + assert.NotContains(t, tools, "update_agent_profile") + assert.NotContains(t, tools, "get_mcp_config") + assert.NotContains(t, tools, "update_mcp_config") + assert.NotContains(t, tools, "move_task") + assert.NotContains(t, tools, "delete_task") + assert.NotContains(t, tools, "archive_task") + assert.NotContains(t, tools, "list_executors") + assert.NotContains(t, tools, "list_executor_profiles") + assert.NotContains(t, tools, "create_executor_profile") + assert.NotContains(t, tools, "update_executor_profile") + assert.NotContains(t, tools, "delete_executor_profile") + assert.NotContains(t, tools, "update_task_state") + assert.NotContains(t, tools, "delete_workflow_step") + assert.NotContains(t, tools, "reorder_workflow_steps") +} + +func TestServerModeConfig_RegistersCorrectTools(t *testing.T) { + log := newTestLogger(t) + backend := NewChannelBackendClient(log) + defer backend.Close() + + s := New(backend, "test-session", 10005, log, "", false, ModeConfig) + require.NotNil(t, s) + + tools := getRegisteredToolNames(s) + + // Config mode should have workflow config tools + assert.Contains(t, tools, "list_workspaces") + assert.Contains(t, tools, "list_workflows") + assert.Contains(t, tools, "create_workflow") + assert.Contains(t, tools, "update_workflow") + assert.Contains(t, tools, "delete_workflow") + assert.Contains(t, tools, "list_workflow_steps") + assert.Contains(t, tools, "create_workflow_step") + assert.Contains(t, tools, "update_workflow_step") + assert.Contains(t, tools, "delete_workflow_step") + assert.Contains(t, tools, "reorder_workflow_steps") + + // Config mode should have agent tools + assert.Contains(t, tools, "list_agents") + assert.Contains(t, tools, "update_agent") + assert.Contains(t, tools, "create_agent_profile") + assert.Contains(t, tools, "delete_agent_profile") + + // Config mode should have MCP config tools + assert.Contains(t, tools, "list_agent_profiles") + assert.Contains(t, tools, "update_agent_profile") + assert.Contains(t, tools, "get_mcp_config") + assert.Contains(t, tools, "update_mcp_config") + + // Config mode should have executor profile tools + assert.Contains(t, tools, "list_executors") + assert.Contains(t, tools, "list_executor_profiles") + assert.Contains(t, tools, "create_executor_profile") + assert.Contains(t, tools, "update_executor_profile") + assert.Contains(t, tools, "delete_executor_profile") + + // Config mode should have task tools + assert.Contains(t, tools, "list_tasks") + assert.Contains(t, tools, "move_task") + assert.Contains(t, tools, "delete_task") + assert.Contains(t, tools, "archive_task") + assert.Contains(t, tools, "update_task_state") + + // Config mode should have interaction tools + assert.Contains(t, tools, "ask_user_question") + + // Config mode should NOT have plan tools + assert.NotContains(t, tools, "create_task_plan") + assert.NotContains(t, tools, "get_task_plan") + assert.NotContains(t, tools, "update_task_plan") + assert.NotContains(t, tools, "delete_task_plan") + + // Config mode should NOT have task-mode kanban create/update tools + assert.NotContains(t, tools, "create_task") + assert.NotContains(t, tools, "update_task") +} + +func TestServerModeDefault_DefaultsToTask(t *testing.T) { + log := newTestLogger(t) + backend := NewChannelBackendClient(log) + defer backend.Close() + + s := New(backend, "test-session", 10005, log, "", false, "") + require.NotNil(t, s) + assert.Equal(t, ModeTask, s.mode) + + tools := getRegisteredToolNames(s) + assert.Contains(t, tools, "create_task") + assert.Contains(t, tools, "create_task_plan") + assert.NotContains(t, tools, "create_workflow_step") +} + +func TestServerModeConfig_DisableAskQuestion(t *testing.T) { + log := newTestLogger(t) + backend := NewChannelBackendClient(log) + defer backend.Close() + + s := New(backend, "test-session", 10005, log, "", true, ModeConfig) + require.NotNil(t, s) + + tools := getRegisteredToolNames(s) + assert.NotContains(t, tools, "ask_user_question") + assert.Contains(t, tools, "list_agents") + assert.Contains(t, tools, "create_workflow_step") +} + +func TestServerModeTask_DisableAskQuestion(t *testing.T) { + log := newTestLogger(t) + backend := NewChannelBackendClient(log) + defer backend.Close() + + s := New(backend, "test-session", 10005, log, "", true, ModeTask) + require.NotNil(t, s) + + tools := getRegisteredToolNames(s) + assert.NotContains(t, tools, "ask_user_question") + assert.Contains(t, tools, "create_task") + assert.Contains(t, tools, "create_task_plan") +} + +func TestServerModeTask_ToolCount(t *testing.T) { + log := newTestLogger(t) + backend := NewChannelBackendClient(log) + defer backend.Close() + + s := New(backend, "test-session", 10005, log, "", false, ModeTask) + tools := getRegisteredToolNames(s) + // 6 kanban + 1 interaction + 4 plan = 11 + assert.Equal(t, 11, len(tools)) +} + +func TestServerModeConfig_ToolCount(t *testing.T) { + log := newTestLogger(t) + backend := NewChannelBackendClient(log) + defer backend.Close() + + s := New(backend, "test-session", 10005, log, "", false, ModeConfig) + tools := getRegisteredToolNames(s) + // 10 workflow + 4 agent + 4 mcp + 5 executor + 5 task + 1 interaction = 29 + assert.Equal(t, 29, len(tools)) +} + +func TestServerModeConfig_ToolDescriptions(t *testing.T) { + log := newTestLogger(t) + backend := NewChannelBackendClient(log) + defer backend.Close() + + s := New(backend, "test-session", 10005, log, "", false, ModeConfig) + + toolsMap := s.mcpServer.ListTools() + + assert.Contains(t, toolsMap["create_workflow_step"].Tool.Description, "Create a new workflow step") + assert.Contains(t, toolsMap["list_agents"].Tool.Description, "List all configured agents") + assert.Contains(t, toolsMap["get_mcp_config"].Tool.Description, "Get MCP server configuration") +} + +func TestServerModeConstants(t *testing.T) { + assert.Equal(t, "task", ModeTask) + assert.Equal(t, "config", ModeConfig) +} diff --git a/apps/backend/internal/events/types.go b/apps/backend/internal/events/types.go index 21624612ee..4437b1580c 100644 --- a/apps/backend/internal/events/types.go +++ b/apps/backend/internal/events/types.go @@ -24,6 +24,13 @@ const ( WorkflowDeleted = "workflow.deleted" ) +// Event types for workflow steps +const ( + WorkflowStepCreated = "workflow_step.created" + WorkflowStepUpdated = "workflow_step.updated" + WorkflowStepDeleted = "workflow_step.deleted" +) + // Event types for comments const ( MessageAdded = "message.added" @@ -99,6 +106,13 @@ const ( EnvironmentDeleted = "environment.deleted" ) +// Event types for agent profiles (settings) +const ( + AgentProfileCreated = "agent_profile.created" + AgentProfileUpdated = "agent_profile.updated" + AgentProfileDeleted = "agent_profile.deleted" +) + // Event types for agents const ( AgentStarted = "agent.started" diff --git a/apps/backend/internal/gateway/websocket/task_notifications.go b/apps/backend/internal/gateway/websocket/task_notifications.go index 75bcacc53c..ad4630cc1b 100644 --- a/apps/backend/internal/gateway/websocket/task_notifications.go +++ b/apps/backend/internal/gateway/websocket/task_notifications.go @@ -31,6 +31,12 @@ func RegisterTaskNotifications(ctx context.Context, eventBus bus.EventBus, hub * b.subscribe(eventBus, events.WorkflowCreated, ws.ActionWorkflowCreated) b.subscribe(eventBus, events.WorkflowUpdated, ws.ActionWorkflowUpdated) b.subscribe(eventBus, events.WorkflowDeleted, ws.ActionWorkflowDeleted) + b.subscribe(eventBus, events.WorkflowStepCreated, ws.ActionWorkflowStepCreated) + b.subscribe(eventBus, events.WorkflowStepUpdated, ws.ActionWorkflowStepUpdated) + b.subscribe(eventBus, events.WorkflowStepDeleted, ws.ActionWorkflowStepDeleted) + b.subscribe(eventBus, events.AgentProfileCreated, ws.ActionAgentProfileCreated) + b.subscribe(eventBus, events.AgentProfileUpdated, ws.ActionAgentProfileUpdated) + b.subscribe(eventBus, events.AgentProfileDeleted, ws.ActionAgentProfileDeleted) b.subscribe(eventBus, events.TaskCreated, ws.ActionTaskCreated) b.subscribe(eventBus, events.TaskUpdated, ws.ActionTaskUpdated) b.subscribe(eventBus, events.TaskDeleted, ws.ActionTaskDeleted) diff --git a/apps/backend/internal/integration/simulated_agent_manager_test.go b/apps/backend/internal/integration/simulated_agent_manager_test.go index 403a122779..9aff1fb793 100644 --- a/apps/backend/internal/integration/simulated_agent_manager_test.go +++ b/apps/backend/internal/integration/simulated_agent_manager_test.go @@ -127,6 +127,10 @@ func (s *SimulatedAgentManagerClient) SetExecutionDescription(ctx context.Contex return nil } +func (s *SimulatedAgentManagerClient) SetMcpMode(_ context.Context, _ string, _ string) error { + return nil +} + // StartAgentProcess simulates starting the agent subprocess func (s *SimulatedAgentManagerClient) StartAgentProcess(ctx context.Context, agentExecutionID string) error { s.logger.Info("simulated: starting agent process", diff --git a/apps/backend/internal/mcp/handlers/config_agent_handlers.go b/apps/backend/internal/mcp/handlers/config_agent_handlers.go new file mode 100644 index 0000000000..4b7c4342e2 --- /dev/null +++ b/apps/backend/internal/mcp/handlers/config_agent_handlers.go @@ -0,0 +1,167 @@ +package handlers + +import ( + "context" + "encoding/json" + "errors" + + agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller" + "github.com/kandev/kandev/internal/events" + "github.com/kandev/kandev/internal/events/bus" + ws "github.com/kandev/kandev/pkg/websocket" + "go.uber.org/zap" +) + +func (h *Handlers) handleListAgents(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + resp, err := h.agentSettingsCtrl.ListAgents(ctx) + if err != nil { + h.logger.Error("failed to list agents", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to list agents", nil) + } + return ws.NewResponse(msg.ID, msg.Action, resp) +} + +func (h *Handlers) handleUpdateAgent(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + AgentID string `json:"agent_id"` + SupportsMCP *bool `json:"supports_mcp"` + MCPConfigPath *string `json:"mcp_config_path"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.AgentID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "agent_id is required", nil) + } + + agent, err := h.agentSettingsCtrl.UpdateAgent(ctx, agentsettingscontroller.UpdateAgentRequest{ + ID: req.AgentID, + SupportsMCP: req.SupportsMCP, + MCPConfigPath: req.MCPConfigPath, + }) + if err != nil { + h.logger.Error("failed to update agent", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update agent", nil) + } + return ws.NewResponse(msg.ID, msg.Action, agent) +} + +func (h *Handlers) handleListAgentProfiles(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + agentID, err := unmarshalStringField(msg.Payload, "agent_id") + if err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if agentID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "agent_id is required", nil) + } + + agent, err := h.agentSettingsCtrl.GetAgent(ctx, agentID) + if err != nil { + h.logger.Error("failed to get agent profiles", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to get agent profiles", nil) + } + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{ + "profiles": agent.Profiles, + "total": len(agent.Profiles), + }) +} + +func (h *Handlers) handleCreateAgentProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + AgentID string `json:"agent_id"` + Name string `json:"name"` + Model string `json:"model"` + AutoApprove bool `json:"auto_approve"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.AgentID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "agent_id is required", nil) + } + if req.Name == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil) + } + if req.Model == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "model is required", nil) + } + + profile, err := h.agentSettingsCtrl.CreateProfile(ctx, agentsettingscontroller.CreateProfileRequest{ + AgentID: req.AgentID, + Name: req.Name, + Model: req.Model, + AutoApprove: req.AutoApprove, + }) + if err != nil { + h.logger.Error("failed to create agent profile", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create agent profile: "+err.Error(), nil) + } + h.publishAgentProfileEvent(ctx, events.AgentProfileCreated, profile) + return ws.NewResponse(msg.ID, msg.Action, profile) +} + +func (h *Handlers) handleDeleteAgentProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + profileID, err := unmarshalStringField(msg.Payload, "profile_id") + if err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if profileID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil) + } + + profile, err := h.agentSettingsCtrl.DeleteProfile(ctx, profileID) + if err != nil { + h.logger.Error("failed to delete agent profile", zap.Error(err)) + if errors.Is(err, agentsettingscontroller.ErrAgentProfileInUse) { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "Cannot delete: profile is used by an active agent session", nil) + } + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to delete agent profile: "+err.Error(), nil) + } + h.publishAgentProfileEvent(ctx, events.AgentProfileDeleted, profile) + return ws.NewResponse(msg.ID, msg.Action, profile) +} + +func (h *Handlers) handleUpdateAgentProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + ProfileID string `json:"profile_id"` + Name *string `json:"name"` + Model *string `json:"model"` + AutoApprove *bool `json:"auto_approve"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.ProfileID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil) + } + + profile, err := h.agentSettingsCtrl.UpdateProfile(ctx, agentsettingscontroller.UpdateProfileRequest{ + ID: req.ProfileID, + Name: req.Name, + Model: req.Model, + AutoApprove: req.AutoApprove, + }) + if err != nil { + h.logger.Error("failed to update agent profile", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update agent profile", nil) + } + h.publishAgentProfileEvent(ctx, events.AgentProfileUpdated, profile) + return ws.NewResponse(msg.ID, msg.Action, profile) +} + +// publishAgentProfileEvent publishes an agent profile event to the event bus. +// The payload wraps the profile in a "profile" key to match the format expected +// by existing frontend WS handlers (same format as HTTP agent settings handlers). +func (h *Handlers) publishAgentProfileEvent(ctx context.Context, eventType string, profile interface{}) { + if h.eventBus == nil || profile == nil { + return + } + data := map[string]interface{}{ + "profile": profile, + } + if err := h.eventBus.Publish(ctx, eventType, bus.NewEvent(eventType, "mcp-handlers", data)); err != nil { + h.logger.Error("failed to publish agent profile event", + zap.String("event_type", eventType), + zap.Error(err)) + } +} diff --git a/apps/backend/internal/mcp/handlers/config_executor_handlers.go b/apps/backend/internal/mcp/handlers/config_executor_handlers.go new file mode 100644 index 0000000000..ef05a6a8a0 --- /dev/null +++ b/apps/backend/internal/mcp/handlers/config_executor_handlers.go @@ -0,0 +1,113 @@ +package handlers + +import ( + "context" + "encoding/json" + + "github.com/kandev/kandev/internal/task/dto" + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/service" + ws "github.com/kandev/kandev/pkg/websocket" + "go.uber.org/zap" +) + +func (h *Handlers) handleListExecutors(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + executors, err := h.taskSvc.ListExecutors(ctx) + if err != nil { + h.logger.Error("failed to list executors", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to list executors", nil) + } + dtos := make([]dto.ExecutorDTO, 0, len(executors)) + for _, e := range executors { + dtos = append(dtos, dto.FromExecutor(e)) + } + return ws.NewResponse(msg.ID, msg.Action, dto.ListExecutorsResponse{Executors: dtos, Total: len(dtos)}) +} + +func (h *Handlers) handleListExecutorProfiles(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + return h.handleListByField(ctx, msg, "executor_id", "failed to list executor profiles", "Failed to list executor profiles", + func(ctx context.Context, executorID string) (any, error) { + profiles, err := h.taskSvc.ListExecutorProfiles(ctx, executorID) + if err != nil { + return nil, err + } + dtos := make([]dto.ExecutorProfileDTO, 0, len(profiles)) + for _, p := range profiles { + dtos = append(dtos, dto.FromExecutorProfile(p)) + } + return dto.ListExecutorProfilesResponse{Profiles: dtos, Total: len(dtos)}, nil + }) +} + +func (h *Handlers) handleCreateExecutorProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + ExecutorID string `json:"executor_id"` + Name string `json:"name"` + McpPolicy string `json:"mcp_policy"` + Config map[string]string `json:"config"` + PrepareScript string `json:"prepare_script"` + CleanupScript string `json:"cleanup_script"` + EnvVars []models.ProfileEnvVar `json:"env_vars"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.ExecutorID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "executor_id is required", nil) + } + if req.Name == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil) + } + + profile, err := h.taskSvc.CreateExecutorProfile(ctx, &service.CreateExecutorProfileRequest{ + ExecutorID: req.ExecutorID, + Name: req.Name, + McpPolicy: req.McpPolicy, + Config: req.Config, + PrepareScript: req.PrepareScript, + CleanupScript: req.CleanupScript, + EnvVars: req.EnvVars, + }) + if err != nil { + h.logger.Error("failed to create executor profile", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create executor profile: "+err.Error(), nil) + } + return ws.NewResponse(msg.ID, msg.Action, dto.FromExecutorProfile(profile)) +} + +func (h *Handlers) handleUpdateExecutorProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + ProfileID string `json:"profile_id"` + Name *string `json:"name"` + McpPolicy *string `json:"mcp_policy"` + Config map[string]string `json:"config"` + PrepareScript *string `json:"prepare_script"` + CleanupScript *string `json:"cleanup_script"` + EnvVars []models.ProfileEnvVar `json:"env_vars"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.ProfileID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil) + } + + profile, err := h.taskSvc.UpdateExecutorProfile(ctx, req.ProfileID, &service.UpdateExecutorProfileRequest{ + Name: req.Name, + McpPolicy: req.McpPolicy, + Config: req.Config, + PrepareScript: req.PrepareScript, + CleanupScript: req.CleanupScript, + EnvVars: req.EnvVars, + }) + if err != nil { + h.logger.Error("failed to update executor profile", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update executor profile: "+err.Error(), nil) + } + return ws.NewResponse(msg.ID, msg.Action, dto.FromExecutorProfile(profile)) +} + +func (h *Handlers) handleDeleteExecutorProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + return h.handleDeleteByField(ctx, msg, "profile_id", "failed to delete executor profile", "Failed to delete executor profile", + func(ctx context.Context, id string) error { return h.taskSvc.DeleteExecutorProfile(ctx, id) }) +} diff --git a/apps/backend/internal/mcp/handlers/config_handlers_test.go b/apps/backend/internal/mcp/handlers/config_handlers_test.go new file mode 100644 index 0000000000..5e8f126a08 --- /dev/null +++ b/apps/backend/internal/mcp/handlers/config_handlers_test.go @@ -0,0 +1,466 @@ +package handlers + +import ( + "context" + "encoding/json" + "testing" + + "github.com/kandev/kandev/internal/common/logger" + ws "github.com/kandev/kandev/pkg/websocket" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// --- Test helpers --- + +func testLogger(t *testing.T) *logger.Logger { + t.Helper() + log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"}) + require.NoError(t, err) + return log +} + +func makeWSMessage(t *testing.T, action string, payload interface{}) *ws.Message { + t.Helper() + data, err := json.Marshal(payload) + require.NoError(t, err) + return &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: action, + Payload: data, + } +} + +func assertWSError(t *testing.T, resp *ws.Message, expectedCode string) { + t.Helper() + require.NotNil(t, resp) + assert.Equal(t, ws.MessageTypeError, resp.Type) + var ep ws.ErrorPayload + require.NoError(t, json.Unmarshal(resp.Payload, &ep)) + assert.Equal(t, expectedCode, ep.Code) +} + +// --- Workflow handler tests --- + +func TestHandleCreateWorkflowStep_MissingWorkflowID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPCreateWorkflowStep, map[string]interface{}{ + "name": "Test Step", + }) + + resp, err := h.handleCreateWorkflowStep(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleCreateWorkflowStep_MissingName(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPCreateWorkflowStep, map[string]interface{}{ + "workflow_id": "wf-123", + }) + + resp, err := h.handleCreateWorkflowStep(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleCreateWorkflowStep_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPCreateWorkflowStep, + Payload: json.RawMessage(`{invalid`), + } + + resp, err := h.handleCreateWorkflowStep(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +func TestHandleUpdateWorkflowStep_MissingStepID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPUpdateWorkflowStep, map[string]interface{}{ + "name": "New Name", + }) + + resp, err := h.handleUpdateWorkflowStep(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleUpdateWorkflowStep_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPUpdateWorkflowStep, + Payload: json.RawMessage(`not json`), + } + + resp, err := h.handleUpdateWorkflowStep(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +func TestHandleDeleteWorkflowStep_MissingStepID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPDeleteWorkflowStep, map[string]string{}) + + resp, err := h.handleDeleteWorkflowStep(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleDeleteWorkflowStep_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPDeleteWorkflowStep, + Payload: json.RawMessage(`badjson`), + } + + resp, err := h.handleDeleteWorkflowStep(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +func TestHandleReorderWorkflowSteps_MissingWorkflowID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPReorderWorkflowStep, map[string]interface{}{ + "step_ids": []string{"s1", "s2"}, + }) + + resp, err := h.handleReorderWorkflowSteps(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleReorderWorkflowSteps_MissingStepIDs(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPReorderWorkflowStep, map[string]interface{}{ + "workflow_id": "wf-123", + "step_ids": []string{}, + }) + + resp, err := h.handleReorderWorkflowSteps(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleReorderWorkflowSteps_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPReorderWorkflowStep, + Payload: json.RawMessage(`{bad}`), + } + + resp, err := h.handleReorderWorkflowSteps(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +// --- Agent handler tests --- + +func TestHandleUpdateAgent_MissingAgentID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPUpdateAgent, map[string]interface{}{ + "supports_mcp": true, + }) + + resp, err := h.handleUpdateAgent(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleUpdateAgent_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPUpdateAgent, + Payload: json.RawMessage(`not json`), + } + + resp, err := h.handleUpdateAgent(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +func TestHandleListAgentProfiles_MissingAgentID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPListAgentProfiles, map[string]string{}) + + resp, err := h.handleListAgentProfiles(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleListAgentProfiles_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPListAgentProfiles, + Payload: json.RawMessage(`badpayload`), + } + + resp, err := h.handleListAgentProfiles(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +func TestHandleUpdateAgentProfile_MissingProfileID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPUpdateAgentProfile, map[string]interface{}{ + "name": "New Name", + }) + + resp, err := h.handleUpdateAgentProfile(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleUpdateAgentProfile_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPUpdateAgentProfile, + Payload: json.RawMessage(`not json`), + } + + resp, err := h.handleUpdateAgentProfile(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +// --- MCP Config handler tests --- + +func TestHandleGetMcpConfig_MissingProfileID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPGetMcpConfig, map[string]string{}) + + resp, err := h.handleGetMcpConfig(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleGetMcpConfig_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPGetMcpConfig, + Payload: json.RawMessage(`not json`), + } + + resp, err := h.handleGetMcpConfig(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +func TestHandleUpdateMcpConfig_MissingProfileID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPUpdateMcpConfig, map[string]interface{}{ + "enabled": true, + }) + + resp, err := h.handleUpdateMcpConfig(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleUpdateMcpConfig_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPUpdateMcpConfig, + Payload: json.RawMessage(`invalid`), + } + + resp, err := h.handleUpdateMcpConfig(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +// --- Task handler tests --- + +func TestHandleMoveTask_MissingTaskID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPMoveTask, map[string]interface{}{ + "workflow_id": "wf-123", + "workflow_step_id": "step-1", + }) + + resp, err := h.handleMoveTask(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleMoveTask_MissingWorkflowID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPMoveTask, map[string]interface{}{ + "task_id": "task-1", + "workflow_step_id": "step-1", + }) + + resp, err := h.handleMoveTask(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleMoveTask_MissingStepID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPMoveTask, map[string]interface{}{ + "task_id": "task-1", + "workflow_id": "wf-123", + }) + + resp, err := h.handleMoveTask(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleMoveTask_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPMoveTask, + Payload: json.RawMessage(`invalid`), + } + + resp, err := h.handleMoveTask(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +func TestHandleDeleteTask_MissingTaskID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPDeleteTask, map[string]string{}) + + resp, err := h.handleDeleteTask(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleDeleteTask_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPDeleteTask, + Payload: json.RawMessage(`not json`), + } + + resp, err := h.handleDeleteTask(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +func TestHandleArchiveTask_MissingTaskID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPArchiveTask, map[string]string{}) + + resp, err := h.handleArchiveTask(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleArchiveTask_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPArchiveTask, + Payload: json.RawMessage(`bad`), + } + + resp, err := h.handleArchiveTask(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +func TestHandleUpdateTaskState_MissingTaskID(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPUpdateTaskState, map[string]interface{}{ + "state": "in_progress", + }) + + resp, err := h.handleUpdateTaskState(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleUpdateTaskState_MissingState(t *testing.T) { + h := &Handlers{} + msg := makeWSMessage(t, ws.ActionMCPUpdateTaskState, map[string]interface{}{ + "task_id": "task-1", + }) + + resp, err := h.handleUpdateTaskState(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeValidation) +} + +func TestHandleUpdateTaskState_InvalidPayload(t *testing.T) { + h := &Handlers{} + msg := &ws.Message{ + ID: "test-id", + Type: ws.MessageTypeRequest, + Action: ws.ActionMCPUpdateTaskState, + Payload: json.RawMessage(`not json`), + } + + resp, err := h.handleUpdateTaskState(context.Background(), msg) + require.NoError(t, err) + assertWSError(t, resp, ws.ErrorCodeBadRequest) +} + +// --- Registration tests --- + +func TestRegisterHandlers_NilDeps_DoesNotPanic(t *testing.T) { + log := testLogger(t) + h := &Handlers{logger: log} + d := ws.NewDispatcher() + + // Should not panic with nil config/task deps — handlers simply not registered. + assert.NotPanics(t, func() { h.RegisterHandlers(d) }) +} + +// --- Helper function tests --- + +func TestUnmarshalStringField(t *testing.T) { + t.Run("valid field", func(t *testing.T) { + payload := json.RawMessage(`{"task_id":"abc-123"}`) + val, err := unmarshalStringField(payload, "task_id") + assert.NoError(t, err) + assert.Equal(t, "abc-123", val) + }) + + t.Run("missing field returns empty", func(t *testing.T) { + payload := json.RawMessage(`{"other":"value"}`) + val, err := unmarshalStringField(payload, "task_id") + assert.NoError(t, err) + assert.Equal(t, "", val) + }) + + t.Run("invalid json", func(t *testing.T) { + payload := json.RawMessage(`not json`) + _, err := unmarshalStringField(payload, "task_id") + assert.Error(t, err) + }) + + t.Run("empty payload", func(t *testing.T) { + payload := json.RawMessage(`{}`) + val, err := unmarshalStringField(payload, "task_id") + assert.NoError(t, err) + assert.Equal(t, "", val) + }) +} diff --git a/apps/backend/internal/mcp/handlers/config_mcp_handlers.go b/apps/backend/internal/mcp/handlers/config_mcp_handlers.go new file mode 100644 index 0000000000..d3385b10b8 --- /dev/null +++ b/apps/backend/internal/mcp/handlers/config_mcp_handlers.go @@ -0,0 +1,62 @@ +package handlers + +import ( + "context" + "encoding/json" + + "github.com/kandev/kandev/internal/agent/mcpconfig" + ws "github.com/kandev/kandev/pkg/websocket" + "go.uber.org/zap" +) + +func (h *Handlers) handleGetMcpConfig(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + profileID, err := unmarshalStringField(msg.Payload, "profile_id") + if err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if profileID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil) + } + + config, err := h.mcpConfigSvc.GetConfigByProfileID(ctx, profileID) + if err != nil { + h.logger.Error("failed to get MCP config", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to get MCP config", nil) + } + return ws.NewResponse(msg.ID, msg.Action, config) +} + +func (h *Handlers) handleUpdateMcpConfig(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + ProfileID string `json:"profile_id"` + Enabled *bool `json:"enabled"` + Servers map[string]mcpconfig.ServerDef `json:"servers"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.ProfileID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil) + } + + // Get existing config to merge with + existing, err := h.mcpConfigSvc.GetConfigByProfileID(ctx, req.ProfileID) + if err != nil { + h.logger.Error("failed to get existing MCP config", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to get existing MCP config", nil) + } + + if req.Enabled != nil { + existing.Enabled = *req.Enabled + } + if req.Servers != nil { + existing.Servers = req.Servers + } + + updated, err := h.mcpConfigSvc.UpsertConfigByProfileID(ctx, req.ProfileID, existing) + if err != nil { + h.logger.Error("failed to update MCP config", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update MCP config", nil) + } + return ws.NewResponse(msg.ID, msg.Action, updated) +} diff --git a/apps/backend/internal/mcp/handlers/config_task_handlers.go b/apps/backend/internal/mcp/handlers/config_task_handlers.go new file mode 100644 index 0000000000..4589e589fc --- /dev/null +++ b/apps/backend/internal/mcp/handlers/config_task_handlers.go @@ -0,0 +1,104 @@ +package handlers + +import ( + "context" + "encoding/json" + + "github.com/kandev/kandev/internal/task/dto" + v1 "github.com/kandev/kandev/pkg/api/v1" + ws "github.com/kandev/kandev/pkg/websocket" + "go.uber.org/zap" +) + +func (h *Handlers) handleMoveTask(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + TaskID string `json:"task_id"` + WorkflowID string `json:"workflow_id"` + WorkflowStepID string `json:"workflow_step_id"` + Position int `json:"position"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.TaskID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil) + } + if req.WorkflowID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil) + } + if req.WorkflowStepID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_step_id is required", nil) + } + + result, err := h.taskSvc.MoveTask(ctx, req.TaskID, req.WorkflowID, req.WorkflowStepID, req.Position) + if err != nil { + h.logger.Error("failed to move task", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to move task", nil) + } + return ws.NewResponse(msg.ID, msg.Action, dto.FromTask(result.Task)) +} + +func (h *Handlers) handleDeleteTask(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + taskID, err := unmarshalStringField(msg.Payload, "task_id") + if err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if taskID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil) + } + + if err := h.taskSvc.DeleteTask(ctx, taskID); err != nil { + h.logger.Error("failed to delete task", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to delete task", nil) + } + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true}) +} + +func (h *Handlers) handleArchiveTask(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + taskID, err := unmarshalStringField(msg.Payload, "task_id") + if err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if taskID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil) + } + + if err := h.taskSvc.ArchiveTask(ctx, taskID); err != nil { + h.logger.Error("failed to archive task", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to archive task", nil) + } + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true}) +} + +func (h *Handlers) handleUpdateTaskState(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + TaskID string `json:"task_id"` + State string `json:"state"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.TaskID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil) + } + if req.State == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "state is required", nil) + } + state := v1.TaskState(req.State) + switch state { + case v1.TaskStateTODO, v1.TaskStateCreated, v1.TaskStateScheduling, + v1.TaskStateInProgress, v1.TaskStateReview, v1.TaskStateBlocked, + v1.TaskStateWaitingForInput, v1.TaskStateCompleted, + v1.TaskStateFailed, v1.TaskStateCancelled: + // valid + default: + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "invalid task state: "+req.State, nil) + } + + task, err := h.taskSvc.UpdateTaskState(ctx, req.TaskID, state) + if err != nil { + h.logger.Error("failed to update task state", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update task state", nil) + } + return ws.NewResponse(msg.ID, msg.Action, dto.FromTask(task)) +} diff --git a/apps/backend/internal/mcp/handlers/config_workflow_handlers.go b/apps/backend/internal/mcp/handlers/config_workflow_handlers.go new file mode 100644 index 0000000000..3cc554972c --- /dev/null +++ b/apps/backend/internal/mcp/handlers/config_workflow_handlers.go @@ -0,0 +1,242 @@ +package handlers + +import ( + "context" + "encoding/json" + + "github.com/kandev/kandev/internal/events" + "github.com/kandev/kandev/internal/events/bus" + "github.com/kandev/kandev/internal/task/service" + workflowctrl "github.com/kandev/kandev/internal/workflow/controller" + wfmodels "github.com/kandev/kandev/internal/workflow/models" + ws "github.com/kandev/kandev/pkg/websocket" + "go.uber.org/zap" +) + +func (h *Handlers) handleCreateWorkflow(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + WorkspaceID string `json:"workspace_id"` + Name string `json:"name"` + Description string `json:"description"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.WorkspaceID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workspace_id is required", nil) + } + if req.Name == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil) + } + + workflow, err := h.taskSvc.CreateWorkflow(ctx, &service.CreateWorkflowRequest{ + WorkspaceID: req.WorkspaceID, + Name: req.Name, + Description: req.Description, + }) + if err != nil { + h.logger.Error("failed to create workflow", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create workflow", nil) + } + return ws.NewResponse(msg.ID, msg.Action, workflow) +} + +func (h *Handlers) handleUpdateWorkflow(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + WorkflowID string `json:"workflow_id"` + Name *string `json:"name"` + Description *string `json:"description"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.WorkflowID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil) + } + + workflow, err := h.taskSvc.UpdateWorkflow(ctx, req.WorkflowID, &service.UpdateWorkflowRequest{ + Name: req.Name, + Description: req.Description, + }) + if err != nil { + h.logger.Error("failed to update workflow", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update workflow", nil) + } + return ws.NewResponse(msg.ID, msg.Action, workflow) +} + +func (h *Handlers) handleDeleteWorkflow(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + workflowID, err := unmarshalStringField(msg.Payload, "workflow_id") + if err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if workflowID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil) + } + + if err := h.taskSvc.DeleteWorkflow(ctx, workflowID); err != nil { + h.logger.Error("failed to delete workflow", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to delete workflow", nil) + } + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true}) +} + +func (h *Handlers) handleCreateWorkflowStep(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + WorkflowID string `json:"workflow_id"` + Name string `json:"name"` + Position int `json:"position"` + Color string `json:"color"` + Prompt string `json:"prompt"` + IsStartStep *bool `json:"is_start_step"` + AllowManualMove *bool `json:"allow_manual_move"` + ShowInCommandPanel *bool `json:"show_in_command_panel"` + Events *wfmodels.StepEvents `json:"events"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.WorkflowID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil) + } + if req.Name == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil) + } + + createReq := workflowctrl.CreateStepRequest{ + WorkflowID: req.WorkflowID, + Name: req.Name, + Position: req.Position, + Color: req.Color, + Prompt: req.Prompt, + IsStartStep: req.IsStartStep, + ShowInCommandPanel: req.ShowInCommandPanel, + Events: req.Events, + } + if req.AllowManualMove != nil { + createReq.AllowManualMove = *req.AllowManualMove + } + + resp, err := h.workflowCtrl.CreateStep(ctx, createReq) + if err != nil { + h.logger.Error("failed to create workflow step", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create workflow step", nil) + } + h.publishWorkflowStepEvent(ctx, events.WorkflowStepCreated, resp.Step) + return ws.NewResponse(msg.ID, msg.Action, resp) +} + +func (h *Handlers) handleUpdateWorkflowStep(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + StepID string `json:"step_id"` + Name *string `json:"name"` + Color *string `json:"color"` + Prompt *string `json:"prompt"` + IsStartStep *bool `json:"is_start_step"` + AllowManualMove *bool `json:"allow_manual_move"` + ShowInCommandPanel *bool `json:"show_in_command_panel"` + AutoArchiveAfterHours *int `json:"auto_archive_after_hours"` + Events *wfmodels.StepEvents `json:"events"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.StepID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "step_id is required", nil) + } + + updateReq := workflowctrl.UpdateStepRequest{ + ID: req.StepID, + Name: req.Name, + Color: req.Color, + Prompt: req.Prompt, + IsStartStep: req.IsStartStep, + AllowManualMove: req.AllowManualMove, + ShowInCommandPanel: req.ShowInCommandPanel, + AutoArchiveAfterHours: req.AutoArchiveAfterHours, + Events: req.Events, + } + + resp, err := h.workflowCtrl.UpdateStep(ctx, updateReq) + if err != nil { + h.logger.Error("failed to update workflow step", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update workflow step", nil) + } + h.publishWorkflowStepEvent(ctx, events.WorkflowStepUpdated, resp.Step) + return ws.NewResponse(msg.ID, msg.Action, resp) +} + +func (h *Handlers) handleDeleteWorkflowStep(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + stepID, err := unmarshalStringField(msg.Payload, "step_id") + if err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if stepID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "step_id is required", nil) + } + + // Fetch step before deleting to get workflow_id for the event + stepResp, _ := h.workflowCtrl.GetStep(ctx, stepID) + + if err := h.workflowCtrl.DeleteStep(ctx, stepID); err != nil { + h.logger.Error("failed to delete workflow step", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to delete workflow step", nil) + } + if stepResp != nil { + h.publishWorkflowStepEvent(ctx, events.WorkflowStepDeleted, stepResp.Step) + } + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true}) +} + +func (h *Handlers) handleReorderWorkflowSteps(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req struct { + WorkflowID string `json:"workflow_id"` + StepIDs []string `json:"step_ids"` + } + if err := json.Unmarshal(msg.Payload, &req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.WorkflowID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil) + } + if len(req.StepIDs) == 0 { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "step_ids is required", nil) + } + + if err := h.workflowCtrl.ReorderSteps(ctx, workflowctrl.ReorderStepsRequest{ + WorkflowID: req.WorkflowID, + StepIDs: req.StepIDs, + }); err != nil { + h.logger.Error("failed to reorder workflow steps", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to reorder workflow steps", nil) + } + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true}) +} + +// publishWorkflowStepEvent publishes a workflow step event to the event bus. +func (h *Handlers) publishWorkflowStepEvent(ctx context.Context, eventType string, step *wfmodels.WorkflowStep) { + if h.eventBus == nil || step == nil { + return + } + data := map[string]interface{}{ + "step": map[string]interface{}{ + "id": step.ID, + "workflow_id": step.WorkflowID, + "name": step.Name, + "position": step.Position, + "color": step.Color, + "prompt": step.Prompt, + "events": step.Events, + "show_in_command_panel": step.ShowInCommandPanel, + "allow_manual_move": step.AllowManualMove, + "is_start_step": step.IsStartStep, + "auto_archive_after_hours": step.AutoArchiveAfterHours, + }, + } + if err := h.eventBus.Publish(ctx, eventType, bus.NewEvent(eventType, "mcp-handlers", data)); err != nil { + h.logger.Error("failed to publish workflow step event", + zap.String("event_type", eventType), + zap.String("step_id", step.ID), + zap.Error(err)) + } +} diff --git a/apps/backend/internal/mcp/handlers/handlers.go b/apps/backend/internal/mcp/handlers/handlers.go index 2815d125c7..1375b9cdea 100644 --- a/apps/backend/internal/mcp/handlers/handlers.go +++ b/apps/backend/internal/mcp/handlers/handlers.go @@ -9,6 +9,8 @@ import ( "errors" "fmt" + "github.com/kandev/kandev/internal/agent/mcpconfig" + agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller" "github.com/kandev/kandev/internal/clarification" "github.com/kandev/kandev/internal/common/logger" "github.com/kandev/kandev/internal/events" @@ -17,6 +19,7 @@ import ( "github.com/kandev/kandev/internal/task/models" "github.com/kandev/kandev/internal/task/service" workflowctrl "github.com/kandev/kandev/internal/workflow/controller" + workflowsvc "github.com/kandev/kandev/internal/workflow/service" v1 "github.com/kandev/kandev/pkg/api/v1" ws "github.com/kandev/kandev/pkg/websocket" "go.uber.org/zap" @@ -61,6 +64,11 @@ type Handlers struct { eventBus EventBus planService *service.PlanService logger *logger.Logger + + // Config-mode dependencies (optional, set via SetConfigDeps) + workflowSvc *workflowsvc.Service + agentSettingsCtrl *agentsettingscontroller.Controller + mcpConfigSvc *mcpconfig.Service } // NewHandlers creates new MCP handlers. @@ -88,8 +96,21 @@ func NewHandlers( } } +// SetConfigDeps sets the config-mode dependencies for agent-native configuration handlers. +// These are optional and only needed when config-mode MCP sessions are used. +func (h *Handlers) SetConfigDeps( + workflowSvc *workflowsvc.Service, + agentSettingsCtrl *agentsettingscontroller.Controller, + mcpConfigSvc *mcpconfig.Service, +) { + h.workflowSvc = workflowSvc + h.agentSettingsCtrl = agentSettingsCtrl + h.mcpConfigSvc = mcpConfigSvc +} + // RegisterHandlers registers all MCP handlers with the dispatcher. func (h *Handlers) RegisterHandlers(d *ws.Dispatcher) { + // Task-mode handlers (always registered) d.RegisterFunc(ws.ActionMCPListWorkspaces, h.handleListWorkspaces) d.RegisterFunc(ws.ActionMCPListWorkflows, h.handleListWorkflows) d.RegisterFunc(ws.ActionMCPListWorkflowSteps, h.handleListWorkflowSteps) @@ -102,8 +123,52 @@ func (h *Handlers) RegisterHandlers(d *ws.Dispatcher) { d.RegisterFunc(ws.ActionMCPUpdateTaskPlan, h.handleUpdateTaskPlan) d.RegisterFunc(ws.ActionMCPDeleteTaskPlan, h.handleDeleteTaskPlan) d.RegisterFunc(ws.ActionMCPClarificationTimeout, h.handleClarificationTimeout) + count := 12 - h.logger.Info("registered MCP handlers", zap.Int("count", 12)) + // Config-mode handlers (registered when config deps are set) + if h.workflowSvc != nil { + d.RegisterFunc(ws.ActionMCPCreateWorkflow, h.handleCreateWorkflow) + d.RegisterFunc(ws.ActionMCPUpdateWorkflow, h.handleUpdateWorkflow) + d.RegisterFunc(ws.ActionMCPDeleteWorkflow, h.handleDeleteWorkflow) + d.RegisterFunc(ws.ActionMCPCreateWorkflowStep, h.handleCreateWorkflowStep) + d.RegisterFunc(ws.ActionMCPUpdateWorkflowStep, h.handleUpdateWorkflowStep) + d.RegisterFunc(ws.ActionMCPDeleteWorkflowStep, h.handleDeleteWorkflowStep) + d.RegisterFunc(ws.ActionMCPReorderWorkflowStep, h.handleReorderWorkflowSteps) + count += 7 + } + if h.agentSettingsCtrl != nil { + d.RegisterFunc(ws.ActionMCPListAgents, h.handleListAgents) + d.RegisterFunc(ws.ActionMCPUpdateAgent, h.handleUpdateAgent) + d.RegisterFunc(ws.ActionMCPListAgentProfiles, h.handleListAgentProfiles) + d.RegisterFunc(ws.ActionMCPCreateAgentProfile, h.handleCreateAgentProfile) + d.RegisterFunc(ws.ActionMCPUpdateAgentProfile, h.handleUpdateAgentProfile) + d.RegisterFunc(ws.ActionMCPDeleteAgentProfile, h.handleDeleteAgentProfile) + count += 6 + } + if h.mcpConfigSvc != nil { + d.RegisterFunc(ws.ActionMCPGetMcpConfig, h.handleGetMcpConfig) + d.RegisterFunc(ws.ActionMCPUpdateMcpConfig, h.handleUpdateMcpConfig) + count += 2 + } + if h.taskSvc != nil { + d.RegisterFunc(ws.ActionMCPMoveTask, h.handleMoveTask) + d.RegisterFunc(ws.ActionMCPDeleteTask, h.handleDeleteTask) + d.RegisterFunc(ws.ActionMCPArchiveTask, h.handleArchiveTask) + d.RegisterFunc(ws.ActionMCPUpdateTaskState, h.handleUpdateTaskState) + count += 4 + + // Executor config handlers (gated on config-mode via workflowSvc) + if h.workflowSvc != nil { + d.RegisterFunc(ws.ActionMCPListExecutors, h.handleListExecutors) + d.RegisterFunc(ws.ActionMCPListExecutorProfiles, h.handleListExecutorProfiles) + d.RegisterFunc(ws.ActionMCPCreateExecutorProfile, h.handleCreateExecutorProfile) + d.RegisterFunc(ws.ActionMCPUpdateExecutorProfile, h.handleUpdateExecutorProfile) + d.RegisterFunc(ws.ActionMCPDeleteExecutorProfile, h.handleDeleteExecutorProfile) + count += 5 + } + } + + h.logger.Info("registered MCP handlers", zap.Int("count", count)) } // handleListWorkspaces lists all workspaces. @@ -150,6 +215,26 @@ func (h *Handlers) handleListByField( return ws.NewResponse(msg.ID, msg.Action, resp) } +// handleDeleteByField is a generic handler for deleting a resource identified by a single string field. +func (h *Handlers) handleDeleteByField( + ctx context.Context, msg *ws.Message, + fieldName, logErrMsg, clientErrMsg string, + fn func(context.Context, string) error, +) (*ws.Message, error) { + value, err := unmarshalStringField(msg.Payload, fieldName) + if err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if value == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, fieldName+" is required", nil) + } + if err := fn(ctx, value); err != nil { + h.logger.Error(logErrMsg, zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, clientErrMsg+": "+err.Error(), nil) + } + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true}) +} + // handleListWorkflows lists workflows for a workspace. func (h *Handlers) handleListWorkflows(ctx context.Context, msg *ws.Message) (*ws.Message, error) { return h.handleListByField(ctx, msg, "workspace_id", "failed to list workflows", "Failed to list workflows", diff --git a/apps/backend/internal/orchestrator/event_handlers_test.go b/apps/backend/internal/orchestrator/event_handlers_test.go index 152255f817..c303dd9e48 100644 --- a/apps/backend/internal/orchestrator/event_handlers_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_test.go @@ -175,6 +175,9 @@ func (m *mockAgentManager) SetExecutionDescription(_ context.Context, _, _ strin func (m *mockAgentManager) SetSessionModelBySessionID(_ context.Context, _, _ string) error { return fmt.Errorf("not supported") } +func (m *mockAgentManager) SetMcpMode(_ context.Context, _ string, _ string) error { + return nil +} func (m *mockAgentManager) WasSessionInitialized(_ string) bool { return false } func (m *mockAgentManager) GetSessionAuthMethods(_ string) []streams.AuthMethodInfo { return nil diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow.go b/apps/backend/internal/orchestrator/event_handlers_workflow.go index 0ce1c15305..bbc78172d1 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow.go @@ -299,7 +299,16 @@ func (s *Service) handleTaskMoved(ctx context.Context, data watcher.TaskMovedEve // If the target step has auto_start_agent, it creates a session and starts the agent // using agent/executor profile IDs from the task's metadata. func (s *Service) handleTaskMovedNoSession(ctx context.Context, data watcher.TaskMovedEventData) { - if !s.shouldAutoStartStep(ctx, data.ToStepID) { + // Load the target step to check auto-start and plan mode flags + step, err := s.workflowStepGetter.GetStep(ctx, data.ToStepID) + if err != nil { + s.logger.Warn("task.moved: failed to load target step", + zap.String("task_id", data.TaskID), + zap.String("to_step_id", data.ToStepID), + zap.Error(err)) + return + } + if step == nil || !step.HasOnEnterAction(wfmodels.OnEnterAutoStartAgent) { s.logger.Debug("task.moved: no session and target step has no auto-start", zap.String("task_id", data.TaskID), zap.String("to_step_id", data.ToStepID)) @@ -316,14 +325,16 @@ func (s *Service) handleTaskMovedNoSession(ctx context.Context, data watcher.Tas agentProfileID, _ := task.Metadata["agent_profile_id"].(string) executorProfileID, _ := task.Metadata["executor_profile_id"].(string) + planMode := step.HasOnEnterAction(wfmodels.OnEnterEnablePlanMode) s.logger.Info("task.moved: starting task (no session, auto-start step)", zap.String("task_id", data.TaskID), zap.String("to_step_id", data.ToStepID), zap.String("agent_profile_id", agentProfileID), - zap.String("executor_profile_id", executorProfileID)) + zap.String("executor_profile_id", executorProfileID), + zap.Bool("plan_mode", planMode)) - _, err = s.StartTask(ctx, task.ID, agentProfileID, "", executorProfileID, 0, task.Description, data.ToStepID, false) + _, err = s.StartTask(ctx, task.ID, agentProfileID, "", executorProfileID, 0, task.Description, data.ToStepID, planMode) if err != nil { s.logger.Error("task.moved: failed to auto-start task", zap.String("task_id", data.TaskID), @@ -455,7 +466,7 @@ func (s *Service) processOnEnter(ctx context.Context, taskID string, session *mo // Passthrough path: write prompt directly to PTY stdin. // By the time processOnEnter runs (from an on_turn_complete transition), // the agent has finished its previous turn and the PTY is waiting for input. - effectivePrompt := s.buildWorkflowPrompt(taskDescription, step, taskID) + effectivePrompt := s.buildWorkflowPrompt(taskDescription, step, taskID, sessionID) if err := s.autoStartPassthroughPrompt(ctx, taskID, session, step.Name, effectivePrompt); err != nil { s.logger.Error("failed to auto-start passthrough agent for step", zap.String("task_id", taskID), @@ -470,7 +481,7 @@ func (s *Service) processOnEnter(ctx context.Context, taskID string, session *mo // ACP path: build prompt from step configuration. // Run auto-start inline so queue state is visible before handleAgentReady // checks for queued messages. - effectivePrompt := s.buildWorkflowPrompt(taskDescription, step, taskID) + effectivePrompt := s.buildWorkflowPrompt(taskDescription, step, taskID, sessionID) planMode := hasPlanMode err := s.autoStartStepPrompt(ctx, taskID, session, step.Name, effectivePrompt, planMode, true) if err != nil { diff --git a/apps/backend/internal/orchestrator/executor/executor.go b/apps/backend/internal/orchestrator/executor/executor.go index 79e1847635..91e4ee78db 100644 --- a/apps/backend/internal/orchestrator/executor/executor.go +++ b/apps/backend/internal/orchestrator/executor/executor.go @@ -97,6 +97,10 @@ type AgentManagerClient interface { // Used when starting an agent on a session whose workspace was already launched. SetExecutionDescription(ctx context.Context, agentExecutionID string, description string) error + // SetMcpMode changes the MCP tool mode on an existing execution's agentctl instance. + // Used when a session transitions to config mode after the workspace was prepared with default mode. + SetMcpMode(ctx context.Context, executionID string, mode string) error + // RestartAgentProcess stops the agent subprocess and starts a fresh one with a new ACP session, // clearing the agent's conversation context. The execution environment (container/agentctl) is preserved. RestartAgentProcess(ctx context.Context, agentExecutionID string) error @@ -213,6 +217,7 @@ type LaunchAgentRequest struct { ExecutorType string // Executor type (e.g., "local", "worktree", "local_docker") - determines runtime ExecutorConfig map[string]string // Executor config (docker_host, git_token, etc.) PreviousExecutionID string // Previous execution ID for runtime reconnect + McpMode string // MCP tool mode: "config" activates config-mode tools // Setup script from executor profile (runs in execution environment before agent starts) SetupScript string @@ -227,6 +232,10 @@ type LaunchAgentRequest struct { PullBeforeWorktree bool // Whether to pull from remote before creating the worktree } +// McpModeConfig activates config-mode MCP tools (workflow steps, agents, MCP +// config, tasks). Used when plan_mode is enabled on a session. +const McpModeConfig = "config" + // LaunchOptions contains optional parameters for LaunchPreparedSession. type LaunchOptions struct { AgentProfileID string @@ -234,6 +243,7 @@ type LaunchOptions struct { Prompt string WorkflowStepID string StartAgent bool + McpMode string // MCP tool mode: McpModeConfig activates config-mode tools } // LaunchAgentResponse contains the result of launching an agent diff --git a/apps/backend/internal/orchestrator/executor/executor_execute.go b/apps/backend/internal/orchestrator/executor/executor_execute.go index eb05b41b75..5f9bba944b 100644 --- a/apps/backend/internal/orchestrator/executor/executor_execute.go +++ b/apps/backend/internal/orchestrator/executor/executor_execute.go @@ -14,6 +14,16 @@ import ( "go.uber.org/zap" ) +// isConfigModeSession returns true if the session has config_mode: true in its metadata. +// Config-mode sessions are dedicated settings-chat sessions that get config MCP tools. +func isConfigModeSession(session *models.TaskSession) bool { + if session == nil || session.Metadata == nil { + return false + } + cm, ok := session.Metadata["config_mode"].(bool) + return ok && cm +} + // runAgentProcessAsync starts the agent subprocess in a background goroutine. // On error it marks both the session and task as FAILED. // On success it calls onSuccess with a non-cancellable context derived from ctx. @@ -221,6 +231,7 @@ func (e *Executor) PrepareSession(ctx context.Context, task *v1.Task, agentProfi AgentProfileSnapshot: agentProfileSnapshot, IsPrimary: true, IsPassthrough: isPassthrough, + Metadata: metadata, } if workflowStepID != "" { session.WorkflowStepID = &workflowStepID @@ -311,7 +322,7 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses // Fast path: workspace already launched (e.g., from PrepareSession with workspace). // Only start the agent subprocess if requested; otherwise return early. if session.AgentExecutionID != "" { - return e.startAgentOnExistingWorkspace(ctx, task, session, prompt, startAgent) + return e.startAgentOnExistingWorkspace(ctx, task, session, prompt, startAgent, opts.McpMode) } repoInfo, err := e.resolvePrimaryRepoInfo(ctx, task.ID) @@ -324,6 +335,11 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses return nil, err } + // Apply McpMode from options (takes precedence over session metadata check in buildLaunchAgentRequest) + if opts.McpMode != "" { + req.McpMode = opts.McpMode + } + e.logger.Info("launching agent for prepared session", zap.String("task_id", task.ID), zap.String("session_id", sessionID), @@ -466,6 +482,11 @@ func (e *Executor) buildLaunchAgentRequest(ctx context.Context, task *v1.Task, s req.RepositoryURL = cloneURL } + // Activate config-mode MCP tools when config_mode is set in session metadata. + if isConfigModeSession(session) { + req.McpMode = McpModeConfig + } + if len(metadata) > 0 { req.Metadata = metadata } @@ -475,7 +496,7 @@ func (e *Executor) buildLaunchAgentRequest(ctx context.Context, task *v1.Task, s // startAgentOnExistingWorkspace handles the case where LaunchPreparedSession is called on a session // whose workspace (agentctl) was already launched. It optionally starts just the agent subprocess. -func (e *Executor) startAgentOnExistingWorkspace(ctx context.Context, task *v1.Task, session *models.TaskSession, prompt string, startAgent bool) (*TaskExecution, error) { +func (e *Executor) startAgentOnExistingWorkspace(ctx context.Context, task *v1.Task, session *models.TaskSession, prompt string, startAgent bool, mcpMode string) (*TaskExecution, error) { if !startAgent { // Workspace already launched, nothing else to do now := time.Now().UTC() @@ -501,6 +522,23 @@ func (e *Executor) startAgentOnExistingWorkspace(ctx context.Context, task *v1.T } } + // If config MCP mode is needed, reconfigure the MCP server before starting the agent. + // The workspace may have been prepared before config_mode was set on the session. + effectiveMcpMode := mcpMode + if effectiveMcpMode == "" && isConfigModeSession(session) { + effectiveMcpMode = McpModeConfig + } + if effectiveMcpMode != "" { + if err := e.agentManager.SetMcpMode(ctx, session.AgentExecutionID, effectiveMcpMode); err != nil { + e.logger.Error("failed to set MCP mode for existing workspace", + zap.String("session_id", session.ID), + zap.String("agent_execution_id", session.AgentExecutionID), + zap.String("mcp_mode", effectiveMcpMode), + zap.Error(err)) + return nil, fmt.Errorf("set MCP mode %q: %w", effectiveMcpMode, err) + } + } + // Transition session to STARTING now := time.Now().UTC() session.State = models.TaskSessionStateStarting diff --git a/apps/backend/internal/orchestrator/executor/executor_interaction.go b/apps/backend/internal/orchestrator/executor/executor_interaction.go index 4b4f0fbe4f..e29e3667ac 100644 --- a/apps/backend/internal/orchestrator/executor/executor_interaction.go +++ b/apps/backend/internal/orchestrator/executor/executor_interaction.go @@ -283,6 +283,11 @@ func (e *Executor) buildSwitchModelRequest(ctx context.Context, task *models.Tas Metadata: execConfig.Metadata, } + // Activate config-mode MCP tools when config_mode is set in session metadata. + if isConfigModeSession(session) { + req.McpMode = McpModeConfig + } + repositoryPath, err := e.applyRepositoryToSwitchRequest(ctx, req, session, execConfig) if err != nil { return nil, err diff --git a/apps/backend/internal/orchestrator/executor/executor_resume.go b/apps/backend/internal/orchestrator/executor/executor_resume.go index ea630468ad..d2defd8d59 100644 --- a/apps/backend/internal/orchestrator/executor/executor_resume.go +++ b/apps/backend/internal/orchestrator/executor/executor_resume.go @@ -364,6 +364,11 @@ func (e *Executor) buildResumeRequest(ctx context.Context, task *v1.Task, sessio return nil, "", execConfig, nil, err } + // Activate config-mode MCP tools when config_mode is set in session metadata. + if isConfigModeSession(session) { + req.McpMode = McpModeConfig + } + existingRunning := e.applyRunningRecordToResumeRequest(ctx, req, task, session, startAgent) return req, repositoryID, execConfig, existingRunning, nil diff --git a/apps/backend/internal/orchestrator/executor/executor_test.go b/apps/backend/internal/orchestrator/executor/executor_test.go index 3a4c6bd1df..eb86bd2939 100644 --- a/apps/backend/internal/orchestrator/executor/executor_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_test.go @@ -42,6 +42,10 @@ func (m *mockAgentManager) SetExecutionDescription(ctx context.Context, agentExe return nil } +func (m *mockAgentManager) SetMcpMode(_ context.Context, _ string, _ string) error { + return nil +} + func (m *mockAgentManager) StartAgentProcess(ctx context.Context, agentExecutionID string) error { if m.startAgentProcessFunc != nil { return m.startAgentProcessFunc(ctx, agentExecutionID) @@ -292,7 +296,7 @@ func (m *mockRepository) DeleteTask(ctx context.Context, id string) error func (m *mockRepository) ListTasks(ctx context.Context, workflowID string) ([]*models.Task, error) { return nil, nil } -func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) { +func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) { return nil, 0, nil } func (m *mockRepository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) { diff --git a/apps/backend/internal/orchestrator/scheduler/scheduler_test.go b/apps/backend/internal/orchestrator/scheduler/scheduler_test.go index 5c51329159..db9cd2352c 100644 --- a/apps/backend/internal/orchestrator/scheduler/scheduler_test.go +++ b/apps/backend/internal/orchestrator/scheduler/scheduler_test.go @@ -51,6 +51,10 @@ func (m *mockAgentManager) SetExecutionDescription(ctx context.Context, agentExe return nil } +func (m *mockAgentManager) SetMcpMode(_ context.Context, _ string, _ string) error { + return nil +} + func (m *mockAgentManager) StartAgentProcess(ctx context.Context, agentExecutionID string) error { return nil } diff --git a/apps/backend/internal/orchestrator/task_operations.go b/apps/backend/internal/orchestrator/task_operations.go index 00cc1b358f..0174799914 100644 --- a/apps/backend/internal/orchestrator/task_operations.go +++ b/apps/backend/internal/orchestrator/task_operations.go @@ -189,7 +189,7 @@ func (s *Service) StartTaskWithSession(ctx context.Context, taskID string, sessi effectivePrompt = task.Description } - effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, workflowStepID, planMode) + effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, sessionID, workflowStepID, planMode) execution, err := s.executor.LaunchPreparedSession(ctx, task, sessionID, executor.LaunchOptions{AgentProfileID: agentProfileID, ExecutorID: executorID, Prompt: effectivePrompt, WorkflowStepID: workflowStepID, StartAgent: true}) if err != nil { @@ -282,7 +282,12 @@ func (s *Service) StartCreatedSession(ctx context.Context, taskID, sessionID, ag if session.WorkflowStepID != nil { stepID = *session.WorkflowStepID } - effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, taskID, stepID, planMode) + effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, taskID, sessionID, stepID, planMode) + + // Inject config context for config-mode sessions (dedicated settings chat) + if cm, ok := session.Metadata["config_mode"].(bool); ok && cm { + effectivePrompt = sysprompt.InjectConfigContext(sessionID, effectivePrompt) + } executorID := session.ExecutorID @@ -379,15 +384,34 @@ func (s *Service) StartTask(ctx context.Context, taskID string, agentProfileID s effectivePrompt = task.Description } - effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, workflowStepID, planMode) + // Prepare session first so we have the sessionID for config context injection + sessionID, err := s.executor.PrepareSession(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) + if err != nil { + return nil, err + } - execution, err := s.executor.ExecuteWithFullProfile(ctx, task, agentProfileID, executorID, executorProfileID, effectivePrompt, workflowStepID) + effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, sessionID, workflowStepID, planMode) + + // Inject config context for config-mode sessions (dedicated settings chat) + configMode := false + if cm, ok := task.Metadata["config_mode"].(bool); ok && cm { + configMode = true + effectivePrompt = sysprompt.InjectConfigContext(sessionID, effectivePrompt) + } + + execution, err := s.executor.LaunchPreparedSession(ctx, task, sessionID, executor.LaunchOptions{ + AgentProfileID: agentProfileID, + ExecutorID: executorID, + Prompt: effectivePrompt, + WorkflowStepID: workflowStepID, + StartAgent: true, + }) if err != nil { return nil, err } if execution.SessionID != "" { - s.recordInitialMessage(ctx, taskID, execution.SessionID, effectivePrompt, planModeActive) + s.recordInitialMessage(ctx, taskID, execution.SessionID, effectivePrompt, planModeActive || configMode) // Set plan mode in session metadata so the frontend can detect it. // applyWorkflowAndPlanMode only injects plan mode into the prompt text; @@ -411,7 +435,7 @@ func (s *Service) StartTask(ctx context.Context, taskID string, agentProfileID s // applyWorkflowAndPlanMode applies workflow step configuration and plan mode injection to a prompt. // Returns the effective prompt and whether plan mode is active (from either the step or the caller). -func (s *Service) applyWorkflowAndPlanMode(ctx context.Context, prompt string, taskID string, workflowStepID string, planMode bool) (string, bool) { +func (s *Service) applyWorkflowAndPlanMode(ctx context.Context, prompt string, taskID string, sessionID string, workflowStepID string, planMode bool) (string, bool) { effectivePrompt := prompt stepHasPlanMode := false @@ -423,13 +447,12 @@ func (s *Service) applyWorkflowAndPlanMode(ctx context.Context, prompt string, t zap.Error(err)) } else { stepHasPlanMode = step.HasOnEnterAction(wfmodels.OnEnterEnablePlanMode) - effectivePrompt = s.buildWorkflowPrompt(effectivePrompt, step, taskID) + effectivePrompt = s.buildWorkflowPrompt(effectivePrompt, step, taskID, sessionID) } } if planMode && !stepHasPlanMode { var parts []string - parts = append(parts, sysprompt.Wrap(sysprompt.PlanMode)) parts = append(parts, sysprompt.Wrap(sysprompt.InterpolatePlaceholders(sysprompt.DefaultPlanPrefix, taskID))) parts = append(parts, effectivePrompt) effectivePrompt = strings.Join(parts, "\n\n") @@ -453,16 +476,10 @@ func (s *Service) recordInitialMessage(ctx context.Context, taskID, sessionID, p // buildWorkflowPrompt constructs the effective prompt using workflow step configuration. // If step.Prompt contains {{task_prompt}}, it is replaced with the base prompt. // Otherwise, step.Prompt is prepended to the base prompt. -// If the step has enable_plan_mode in on_enter events, plan mode prefix is also prepended. // System-injected content is wrapped in tags so it can be stripped when displaying to users. -func (s *Service) buildWorkflowPrompt(basePrompt string, step *wfmodels.WorkflowStep, taskID string) string { +func (s *Service) buildWorkflowPrompt(basePrompt string, step *wfmodels.WorkflowStep, taskID string, sessionID string) string { var parts []string - // Apply plan mode prefix if enabled (wrapped in system tags) - if step.HasOnEnterAction(wfmodels.OnEnterEnablePlanMode) { - parts = append(parts, sysprompt.Wrap(sysprompt.PlanMode)) - } - // Build the prompt from step.Prompt template and base prompt if step.Prompt != "" { interpolatedPrompt := sysprompt.InterpolatePlaceholders(step.Prompt, taskID) @@ -585,7 +602,7 @@ func (s *Service) StartSessionForWorkflowStep(ctx context.Context, taskID, sessi s.advanceSessionWorkflowStep(ctx, sessionID, workflowStepID, session) - effectivePrompt := s.buildWorkflowPrompt(task.Description, step, taskID) + effectivePrompt := s.buildWorkflowPrompt(task.Description, step, taskID, sessionID) if err := s.ensureSessionRunning(ctx, sessionID, session); err != nil { return err @@ -1184,10 +1201,10 @@ func (s *Service) PromptTask(ctx context.Context, taskID, sessionID string, prom return nil, fmt.Errorf("failed to ensure session is running: %w", err) } - // Apply plan mode prefix if enabled + // Inject config context for config-mode sessions (dedicated settings chat, not plan mode) effectivePrompt := prompt - if planMode { - effectivePrompt = sysprompt.InjectPlanMode(prompt) + if cm, ok := session.Metadata["config_mode"].(bool); ok && cm { + effectivePrompt = sysprompt.InjectConfigContext(sessionID, prompt) } // Check if model switching is requested diff --git a/apps/backend/internal/sysprompt/sysprompt.go b/apps/backend/internal/sysprompt/sysprompt.go index 87b24f131a..a1f9347407 100644 --- a/apps/backend/internal/sysprompt/sysprompt.go +++ b/apps/backend/internal/sysprompt/sysprompt.go @@ -85,6 +85,80 @@ func FormatKandevContext(taskID, sessionID string) string { return fmt.Sprintf(KandevContext, taskID, sessionID) } +// ConfigContext is the system prompt for config-mode MCP sessions. +// It provides instructions for agents performing configuration operations +// via the dedicated config chat on the settings page. +const ConfigContext = `KANDEV CONFIG MCP TOOLS — You are a configuration assistant for the Kandev platform. +You have access to the following MCP tools from the "kandev" server. +Always use the exact tool names shown below (they include the _kandev suffix). + +Session ID: %s + +WORKFLOW TOOLS: +- list_workspaces_kandev: List all workspaces to get workspace IDs. +- list_workflows_kandev: List workflows in a workspace. Required: workspace_id. +- create_workflow_kandev: Create a new workflow. Required: workspace_id, name. Optional: description. +- update_workflow_kandev: Update a workflow. Required: workflow_id. Optional: name, description. +- delete_workflow_kandev: Delete a workflow and all its steps (destructive). Required: workflow_id. +- list_workflow_steps_kandev: List workflow steps (columns) in a workflow. Required: workflow_id. +- create_workflow_step_kandev: Create a new workflow step. Required: workflow_id, name. Optional: position, color, prompt, is_start_step, allow_manual_move, show_in_command_panel, events. +- update_workflow_step_kandev: Update a workflow step. Required: step_id. Optional: name, color, prompt, is_start_step, allow_manual_move, show_in_command_panel, auto_archive_after_hours, events. +- delete_workflow_step_kandev: Delete a workflow step (destructive). Required: step_id. +- reorder_workflow_steps_kandev: Reorder workflow steps. Required: workflow_id, step_ids (ordered array of step IDs). + +AGENT TOOLS: +- list_agents_kandev: List all configured agents and their profiles. +- update_agent_kandev: Update agent settings. Required: agent_id. Optional: supports_mcp, mcp_config_path. +- create_agent_profile_kandev: Create a new agent profile. Required: agent_id, name, model. Optional: auto_approve. +- delete_agent_profile_kandev: Delete an agent profile. Required: profile_id. + +EXECUTOR PROFILE TOOLS: +Executors (local, worktree, local_docker, sprites) are pre-defined. Use list_executors to find executor IDs, then manage profiles. +- list_executors_kandev: List all executors with their IDs and types. +- list_executor_profiles_kandev: List profiles for an executor. Required: executor_id. +- create_executor_profile_kandev: Create an executor profile. Required: executor_id, name. Optional: mcp_policy, config, prepare_script, cleanup_script. +- update_executor_profile_kandev: Update an executor profile. Required: profile_id. Optional: name, mcp_policy, config, prepare_script, cleanup_script. +- delete_executor_profile_kandev: Delete an executor profile. Required: profile_id. + +MCP CONFIG TOOLS: +- list_agent_profiles_kandev: List profiles for an agent. Required: agent_id. +- update_agent_profile_kandev: Update a profile. Required: profile_id. Optional: name, model, auto_approve. +- get_mcp_config_kandev: Get MCP server config for a profile. Required: profile_id. +- update_mcp_config_kandev: Update MCP config for a profile. Required: profile_id. Optional: enabled, servers. + +TASK TOOLS: +- list_tasks_kandev: List all tasks in a workflow. Required: workflow_id. +- move_task_kandev: Move a task to a different workflow step. Required: task_id, workflow_step_id. +- delete_task_kandev: Delete a task. Required: task_id. +- archive_task_kandev: Archive a task. Required: task_id. +- update_task_state_kandev: Update task state. Required: task_id, state (TODO, CREATED, SCHEDULING, IN_PROGRESS, REVIEW, BLOCKED, WAITING_FOR_INPUT, COMPLETED, FAILED, CANCELLED). + +INTERACTION: +- ask_user_question_kandev: Ask the user a clarifying question with multiple-choice options. Required: prompt, options. + +EXAMPLE REQUESTS the user might ask: +- "Create a new workflow called 'Feature Development'" +- "Add a 'Code Review' step to my workflow" +- "Create a new agent profile for Claude with auto-approve enabled" +- "Show me the current workflow steps" +- "Update the MCP servers for the default agent profile" +- "Create a new executor profile for Docker with a prepare script" +- "Move all completed tasks to the 'Done' column" +- "Archive old tasks from last month" + +IMPORTANT: Always list existing resources before creating or modifying. Confirm destructive operations (delete, archive) with the user first using ask_user_question_kandev.` + +// FormatConfigContext returns the config context prompt with the session ID injected. +func FormatConfigContext(sessionID string) string { + return fmt.Sprintf(ConfigContext, sessionID) +} + +// InjectConfigContext prepends the config system prompt to a user's prompt. +// The system content is wrapped in tags. +func InjectConfigContext(sessionID, prompt string) string { + return Wrap(FormatConfigContext(sessionID)) + "\n\n" + prompt +} + // InjectKandevContext prepends the Kandev system prompt and session context to a user's prompt. // The system content is wrapped in tags. func InjectKandevContext(taskID, sessionID, prompt string) string { diff --git a/apps/backend/internal/sysprompt/sysprompt_test.go b/apps/backend/internal/sysprompt/sysprompt_test.go new file mode 100644 index 0000000000..f6bac840a9 --- /dev/null +++ b/apps/backend/internal/sysprompt/sysprompt_test.go @@ -0,0 +1,206 @@ +package sysprompt + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// Test constants to avoid repeated string literals. +const ( + testConfigPrompt = "Configure my workflow" + testPlanPrompt = "Plan this task" + testTaskID = "task-123" + testSessionID = "session-123" +) + +// --- ConfigContext tests --- + +func TestConfigContext_ContainsAllTools(t *testing.T) { + expectedTools := []string{ + "list_workspaces_kandev", + "list_workflows_kandev", + "create_workflow_kandev", + "update_workflow_kandev", + "delete_workflow_kandev", + "list_workflow_steps_kandev", + "create_workflow_step_kandev", + "update_workflow_step_kandev", + "delete_workflow_step_kandev", + "reorder_workflow_steps_kandev", + "list_agents_kandev", + "update_agent_kandev", + "create_agent_profile_kandev", + "delete_agent_profile_kandev", + "list_executors_kandev", + "list_executor_profiles_kandev", + "create_executor_profile_kandev", + "update_executor_profile_kandev", + "delete_executor_profile_kandev", + "list_agent_profiles_kandev", + "update_agent_profile_kandev", + "get_mcp_config_kandev", + "update_mcp_config_kandev", + "list_tasks_kandev", + "move_task_kandev", + "delete_task_kandev", + "archive_task_kandev", + "update_task_state_kandev", + "ask_user_question_kandev", + } + + for _, tool := range expectedTools { + assert.Contains(t, ConfigContext, tool, "ConfigContext should contain tool: %s", tool) + } +} + +func TestConfigContext_ContainsSections(t *testing.T) { + assert.Contains(t, ConfigContext, "WORKFLOW TOOLS:") + assert.Contains(t, ConfigContext, "AGENT TOOLS:") + assert.Contains(t, ConfigContext, "EXECUTOR PROFILE TOOLS:") + assert.Contains(t, ConfigContext, "MCP CONFIG TOOLS:") + assert.Contains(t, ConfigContext, "TASK TOOLS:") + assert.Contains(t, ConfigContext, "INTERACTION:") + assert.Contains(t, ConfigContext, "EXAMPLE REQUESTS") +} + +func TestConfigContext_HasExactlyOneSessionIDPlaceholder(t *testing.T) { + count := strings.Count(ConfigContext, "%s") + assert.Equal(t, 1, count, "ConfigContext should have exactly 1 %%s placeholder") +} + +func TestFormatConfigContext_InjectsSessionID(t *testing.T) { + result := FormatConfigContext("session-abc-123") + assert.Contains(t, result, "Session ID: session-abc-123") + assert.NotContains(t, result, "%s") + assert.NotContains(t, result, "%!") +} + +func TestInjectConfigContext_WrapsInSystemTags(t *testing.T) { + result := InjectConfigContext(testSessionID, testConfigPrompt) + assert.True(t, strings.HasPrefix(result, TagStart)) + assert.Contains(t, result, TagEnd) + assert.Contains(t, result, testConfigPrompt) + assert.Contains(t, result, testSessionID) +} + +func TestInjectConfigContext_SystemContentStrippable(t *testing.T) { + result := InjectConfigContext(testSessionID, testConfigPrompt) + stripped := StripSystemContent(result) + assert.Equal(t, testConfigPrompt, stripped) + assert.NotContains(t, stripped, "KANDEV CONFIG MCP TOOLS") +} + +// --- KandevContext tests (existing, verify not broken) --- + +func TestKandevContext_HasExactlyTwoPlaceholders(t *testing.T) { + count := strings.Count(KandevContext, "%s") + assert.Equal(t, 2, count, "KandevContext should have exactly 2 %%s placeholders") +} + +func TestFormatKandevContext_InjectsIDs(t *testing.T) { + result := FormatKandevContext("task-abc", "session-xyz") + assert.Contains(t, result, "Kandev Task ID: task-abc") + assert.Contains(t, result, "Session ID: session-xyz") + assert.NotContains(t, result, "%!") +} + +func TestInjectKandevContext_WrapsInSystemTags(t *testing.T) { + result := InjectKandevContext("task-abc", "session-xyz", "Do something") + assert.True(t, strings.HasPrefix(result, TagStart)) + assert.Contains(t, result, "Do something") +} + +func TestInjectKandevContext_SystemContentStrippable(t *testing.T) { + result := InjectKandevContext("task-abc", "session-xyz", "Do something") + stripped := StripSystemContent(result) + assert.Equal(t, "Do something", stripped) +} + +// --- StripSystemContent tests --- + +func TestStripSystemContent_NoTags(t *testing.T) { + assert.Equal(t, "Hello world", StripSystemContent("Hello world")) +} + +func TestStripSystemContent_OnlyTags(t *testing.T) { + input := Wrap("system content only") + assert.Equal(t, "", StripSystemContent(input)) +} + +func TestStripSystemContent_MixedContent(t *testing.T) { + input := Wrap("hidden") + "\n\nvisible text" + result := StripSystemContent(input) + assert.Equal(t, "visible text", result) +} + +func TestStripSystemContent_MultipleTags(t *testing.T) { + input := Wrap("first") + " middle " + Wrap("second") + " end" + result := StripSystemContent(input) + // The regex replaces tags + trailing whitespace, so check both parts are present + assert.Contains(t, result, "middle") + assert.Contains(t, result, "end") + assert.NotContains(t, result, "first") + assert.NotContains(t, result, "second") +} + +// --- Wrap and HasSystemContent tests --- + +func TestWrap(t *testing.T) { + result := Wrap("test content") + assert.Equal(t, TagStart+"test content"+TagEnd, result) +} + +func TestHasSystemContent(t *testing.T) { + assert.True(t, HasSystemContent(Wrap("content"))) + assert.False(t, HasSystemContent("no tags")) +} + +// --- PlanMode tests --- + +func TestInjectPlanMode_WrapsInTags(t *testing.T) { + result := InjectPlanMode(testPlanPrompt) + assert.True(t, strings.HasPrefix(result, TagStart)) + assert.Contains(t, result, "PLAN MODE ACTIVE") + assert.Contains(t, result, testPlanPrompt) +} + +func TestInjectPlanMode_SystemContentStrippable(t *testing.T) { + result := InjectPlanMode(testPlanPrompt) + stripped := StripSystemContent(result) + assert.Equal(t, testPlanPrompt, stripped) +} + +// --- InterpolatePlaceholders tests --- + +func TestInterpolatePlaceholders_TaskID(t *testing.T) { + result := InterpolatePlaceholders("Check {task_id} status", testTaskID) + assert.Equal(t, "Check task-123 status", result) +} + +func TestInterpolatePlaceholders_NoPlaceholders(t *testing.T) { + result := InterpolatePlaceholders("No placeholders here", testTaskID) + assert.Equal(t, "No placeholders here", result) +} + +func TestInterpolatePlaceholders_MultiplePlaceholders(t *testing.T) { + result := InterpolatePlaceholders("{task_id} and {task_id}", testTaskID) + assert.Equal(t, "task-123 and task-123", result) +} + +// --- ConfigContext vs KandevContext distinction --- + +func TestConfigContext_DoesNotContainPlanTools(t *testing.T) { + assert.NotContains(t, ConfigContext, "create_task_plan_kandev") + assert.NotContains(t, ConfigContext, "get_task_plan_kandev") + assert.NotContains(t, ConfigContext, "update_task_plan_kandev") + assert.NotContains(t, ConfigContext, "delete_task_plan_kandev") +} + +func TestKandevContext_DoesNotContainConfigTools(t *testing.T) { + assert.NotContains(t, KandevContext, "create_workflow_step_kandev") + assert.NotContains(t, KandevContext, "update_workflow_step_kandev") + assert.NotContains(t, KandevContext, "list_agents_kandev") + assert.NotContains(t, KandevContext, "create_agent_kandev") +} diff --git a/apps/backend/internal/task/dto/dto.go b/apps/backend/internal/task/dto/dto.go index 9af9b70fd3..a1f2c4bc70 100644 --- a/apps/backend/internal/task/dto/dto.go +++ b/apps/backend/internal/task/dto/dto.go @@ -18,15 +18,16 @@ type WorkflowDTO struct { } type WorkspaceDTO struct { - ID string `json:"id"` - Name string `json:"name"` - Description *string `json:"description,omitempty"` - OwnerID string `json:"owner_id"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `json:"id"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + OwnerID string `json:"owner_id"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } type RepositoryDTO struct { @@ -341,15 +342,16 @@ func FromWorkspace(workspace *models.Workspace) WorkspaceDTO { } return WorkspaceDTO{ - ID: workspace.ID, - Name: workspace.Name, - Description: description, - OwnerID: workspace.OwnerID, - DefaultExecutorID: workspace.DefaultExecutorID, - DefaultEnvironmentID: workspace.DefaultEnvironmentID, - DefaultAgentProfileID: workspace.DefaultAgentProfileID, - CreatedAt: workspace.CreatedAt, - UpdatedAt: workspace.UpdatedAt, + ID: workspace.ID, + Name: workspace.Name, + Description: description, + OwnerID: workspace.OwnerID, + DefaultExecutorID: workspace.DefaultExecutorID, + DefaultEnvironmentID: workspace.DefaultEnvironmentID, + DefaultAgentProfileID: workspace.DefaultAgentProfileID, + DefaultConfigAgentProfileID: workspace.DefaultConfigAgentProfileID, + CreatedAt: workspace.CreatedAt, + UpdatedAt: workspace.UpdatedAt, } } diff --git a/apps/backend/internal/task/handlers/process_handlers_test.go b/apps/backend/internal/task/handlers/process_handlers_test.go index b29380f935..98d5abf89c 100644 --- a/apps/backend/internal/task/handlers/process_handlers_test.go +++ b/apps/backend/internal/task/handlers/process_handlers_test.go @@ -60,7 +60,7 @@ func (m *mockRepository) DeleteTask(ctx context.Context, id string) error { func (m *mockRepository) ListTasks(ctx context.Context, workflowID string) ([]*models.Task, error) { return nil, nil } -func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) { +func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) { return nil, 0, nil } func (m *mockRepository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) { diff --git a/apps/backend/internal/task/handlers/task_handlers.go b/apps/backend/internal/task/handlers/task_handlers.go index 8781b49480..33173c2212 100644 --- a/apps/backend/internal/task/handlers/task_handlers.go +++ b/apps/backend/internal/task/handlers/task_handlers.go @@ -74,6 +74,9 @@ func (h *TaskHandlers) registerHTTP(router *gin.Engine) { // Quick chat endpoint - creates ephemeral task with prepared session api.POST("/workspaces/:id/quick-chat", h.httpStartQuickChat) + + // Config chat endpoint - creates ephemeral task with config-mode MCP tools + api.POST("/workspaces/:id/config-chat", h.httpStartConfigChat) } func (h *TaskHandlers) registerWS(dispatcher *ws.Dispatcher) { diff --git a/apps/backend/internal/task/handlers/task_http_handlers.go b/apps/backend/internal/task/handlers/task_http_handlers.go index f2732249b6..de4dbc7505 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers.go +++ b/apps/backend/internal/task/handlers/task_http_handlers.go @@ -52,9 +52,10 @@ func (h *TaskHandlers) httpListTasksByWorkspace(c *gin.Context) { includeArchived := c.Query("include_archived") == queryValueTrue includeEphemeral := c.Query("include_ephemeral") == queryValueTrue onlyEphemeral := c.Query("only_ephemeral") == queryValueTrue + excludeConfig := c.Query("exclude_config") == queryValueTrue tasks, total, err := h.service.ListTasksByWorkspace( - c.Request.Context(), c.Param("id"), query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral, + c.Request.Context(), c.Param("id"), query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig, ) if err != nil { handleNotFound(c, h.logger, err, "tasks not found") @@ -761,3 +762,150 @@ func (h *TaskHandlers) httpStartQuickChat(c *gin.Context) { SessionID: resp.SessionID, }) } + +// httpStartConfigChatRequest is the request body for starting a config chat session. +type httpStartConfigChatRequest struct { + AgentProfileID string `json:"agent_profile_id,omitempty"` + ExecutorID string `json:"executor_id,omitempty"` + Prompt string `json:"prompt,omitempty"` +} + +// httpStartConfigChat creates an ephemeral task with config_mode and prepares a session. +// The session will have config MCP tools (workflow, agent, MCP management) instead of +// the normal kanban/plan tools used for task-solving agents. +// resolveConfigChatDefaults resolves the agent profile ID, executor ID, and task +// metadata for a config chat session. Profile priority: request → workspace config → workspace default. +func resolveConfigChatDefaults(body httpStartConfigChatRequest, ws *models.Workspace) (agentProfileID, executorID string, metadata map[string]interface{}) { + agentProfileID = body.AgentProfileID + if agentProfileID == "" && ws.DefaultConfigAgentProfileID != nil { + agentProfileID = *ws.DefaultConfigAgentProfileID + } + if agentProfileID == "" && ws.DefaultAgentProfileID != nil { + agentProfileID = *ws.DefaultAgentProfileID + } + executorID = body.ExecutorID + if executorID == "" && ws.DefaultExecutorID != nil { + executorID = *ws.DefaultExecutorID + } + metadata = map[string]interface{}{ + "config_mode": true, + "agent_profile_id": agentProfileID, + } + if executorID != "" { + metadata["executor_id"] = executorID + } + return agentProfileID, executorID, metadata +} + +func (h *TaskHandlers) httpStartConfigChat(c *gin.Context) { + workspaceID := c.Param("id") + var body httpStartConfigChatRequest + if err := c.ShouldBindJSON(&body); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + return + } + + ctx := c.Request.Context() + + workspace, err := h.service.GetWorkspace(ctx, workspaceID) + if err != nil { + handleNotFound(c, h.logger, err, "workspace not found") + return + } + + workflows, err := h.service.ListWorkflows(ctx, workspaceID) + if err != nil { + h.logger.Error("failed to list workflows", zap.Error(err), zap.String("workspace_id", workspaceID)) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list workflows"}) + return + } + if len(workflows) == 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "workspace has no workflows"}) + return + } + + agentProfileID, executorID, metadata := resolveConfigChatDefaults(body, workspace) + if agentProfileID == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "no agent profile configured — set a default agent profile in workspace settings"}) + return + } + + task, err := h.service.CreateTask(ctx, &service.CreateTaskRequest{ + WorkspaceID: workspaceID, + WorkflowID: workflows[0].ID, + Title: "Config Chat", + Description: body.Prompt, + IsEphemeral: true, + Metadata: metadata, + }) + if err != nil { + h.logger.Error("failed to create config chat task", zap.Error(err)) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create config chat"}) + return + } + + resp, err := h.orchestrator.LaunchSession(ctx, &orchestrator.LaunchSessionRequest{ + TaskID: task.ID, + Intent: orchestrator.IntentPrepare, + AgentProfileID: agentProfileID, + ExecutorID: executorID, + }) + if err != nil { + h.deleteTaskOnError(task.ID, "config chat", err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare session"}) + return + } + + sessionID := resp.SessionID + + // If a prompt was provided, launch the agent asynchronously so it starts + // processing immediately. The frontend receives WS updates when it starts. + if body.Prompt != "" { + go h.launchConfigChatAgent(task.ID, sessionID, agentProfileID, body.Prompt) + } + + h.logger.Info("config chat session created", + zap.String("task_id", task.ID), + zap.String("session_id", sessionID), + zap.String("workspace_id", workspaceID)) + + c.JSON(http.StatusOK, httpStartQuickChatResponse{ + TaskID: task.ID, + SessionID: sessionID, + }) +} + +func (h *TaskHandlers) deleteTaskOnError(taskID, label string, err error) { + if deleteErr := h.service.DeleteTask(context.Background(), taskID); deleteErr != nil { + h.logger.Error("failed to rollback "+label+" task", + zap.String("task_id", taskID), zap.Error(deleteErr)) + } + h.logger.Error("failed to prepare "+label+" session", + zap.Error(err), zap.String("task_id", taskID)) +} + +func (h *TaskHandlers) launchConfigChatAgent( + taskID, sessionID, agentProfileID, prompt string, +) { + startCtx, cancel := context.WithTimeout( + context.Background(), constants.AgentLaunchTimeout, + ) + defer cancel() + launchResp, err := h.orchestrator.LaunchSession(startCtx, &orchestrator.LaunchSessionRequest{ + TaskID: taskID, + Intent: orchestrator.IntentStartCreated, + SessionID: sessionID, + AgentProfileID: agentProfileID, + Prompt: prompt, + }) + if err != nil { + h.logger.Error("failed to start config chat agent", + zap.Error(err), zap.String("task_id", taskID), + zap.String("session_id", sessionID)) + return + } + h.logger.Info("config chat agent started", + zap.String("task_id", taskID), + zap.String("session_id", launchResp.SessionID), + zap.String("execution_id", launchResp.AgentExecutionID)) +} diff --git a/apps/backend/internal/task/handlers/workspace_handlers.go b/apps/backend/internal/task/handlers/workspace_handlers.go index f9409362cd..e643ebcba0 100644 --- a/apps/backend/internal/task/handlers/workspace_handlers.go +++ b/apps/backend/internal/task/handlers/workspace_handlers.go @@ -73,12 +73,13 @@ func (h *WorkspaceHandlers) httpListWorkspaces(c *gin.Context) { } type httpCreateWorkspaceRequest struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - OwnerID string `json:"owner_id,omitempty"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + OwnerID string `json:"owner_id,omitempty"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` } func (h *WorkspaceHandlers) httpCreateWorkspace(c *gin.Context) { @@ -92,12 +93,13 @@ func (h *WorkspaceHandlers) httpCreateWorkspace(c *gin.Context) { return } workspace, err := h.service.CreateWorkspace(c.Request.Context(), &service.CreateWorkspaceRequest{ - Name: body.Name, - Description: body.Description, - OwnerID: body.OwnerID, - DefaultExecutorID: body.DefaultExecutorID, - DefaultEnvironmentID: body.DefaultEnvironmentID, - DefaultAgentProfileID: body.DefaultAgentProfileID, + Name: body.Name, + Description: body.Description, + OwnerID: body.OwnerID, + DefaultExecutorID: body.DefaultExecutorID, + DefaultEnvironmentID: body.DefaultEnvironmentID, + DefaultAgentProfileID: body.DefaultAgentProfileID, + DefaultConfigAgentProfileID: body.DefaultConfigAgentProfileID, }) if err != nil { handleNotFound(c, h.logger, err, "workspace not created") @@ -116,11 +118,12 @@ func (h *WorkspaceHandlers) httpGetWorkspace(c *gin.Context) { } type httpUpdateWorkspaceRequest struct { - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` } func (h *WorkspaceHandlers) httpUpdateWorkspace(c *gin.Context) { @@ -130,11 +133,12 @@ func (h *WorkspaceHandlers) httpUpdateWorkspace(c *gin.Context) { return } workspace, err := h.service.UpdateWorkspace(c.Request.Context(), c.Param("id"), &service.UpdateWorkspaceRequest{ - Name: body.Name, - Description: body.Description, - DefaultExecutorID: body.DefaultExecutorID, - DefaultEnvironmentID: body.DefaultEnvironmentID, - DefaultAgentProfileID: body.DefaultAgentProfileID, + Name: body.Name, + Description: body.Description, + DefaultExecutorID: body.DefaultExecutorID, + DefaultEnvironmentID: body.DefaultEnvironmentID, + DefaultAgentProfileID: body.DefaultAgentProfileID, + DefaultConfigAgentProfileID: body.DefaultConfigAgentProfileID, }) if err != nil { handleNotFound(c, h.logger, err, "workspace not updated") @@ -163,12 +167,13 @@ func (h *WorkspaceHandlers) wsListWorkspaces(ctx context.Context, msg *ws.Messag } type wsCreateWorkspaceRequest struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - OwnerID string `json:"owner_id,omitempty"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + OwnerID string `json:"owner_id,omitempty"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` } func (h *WorkspaceHandlers) wsCreateWorkspace(ctx context.Context, msg *ws.Message) (*ws.Message, error) { @@ -180,12 +185,13 @@ func (h *WorkspaceHandlers) wsCreateWorkspace(ctx context.Context, msg *ws.Messa return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil) } workspace, err := h.service.CreateWorkspace(ctx, &service.CreateWorkspaceRequest{ - Name: req.Name, - Description: req.Description, - OwnerID: req.OwnerID, - DefaultExecutorID: req.DefaultExecutorID, - DefaultEnvironmentID: req.DefaultEnvironmentID, - DefaultAgentProfileID: req.DefaultAgentProfileID, + Name: req.Name, + Description: req.Description, + OwnerID: req.OwnerID, + DefaultExecutorID: req.DefaultExecutorID, + DefaultEnvironmentID: req.DefaultEnvironmentID, + DefaultAgentProfileID: req.DefaultAgentProfileID, + DefaultConfigAgentProfileID: req.DefaultConfigAgentProfileID, }) if err != nil { h.logger.Error("failed to create workspace", zap.Error(err)) @@ -215,12 +221,13 @@ func (h *WorkspaceHandlers) wsGetWorkspace(ctx context.Context, msg *ws.Message) } type wsUpdateWorkspaceRequest struct { - ID string `json:"id"` - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + ID string `json:"id"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` } func (h *WorkspaceHandlers) wsUpdateWorkspace(ctx context.Context, msg *ws.Message) (*ws.Message, error) { @@ -233,11 +240,12 @@ func (h *WorkspaceHandlers) wsUpdateWorkspace(ctx context.Context, msg *ws.Messa } workspace, err := h.service.UpdateWorkspace(ctx, req.ID, &service.UpdateWorkspaceRequest{ - Name: req.Name, - Description: req.Description, - DefaultExecutorID: req.DefaultExecutorID, - DefaultEnvironmentID: req.DefaultEnvironmentID, - DefaultAgentProfileID: req.DefaultAgentProfileID, + Name: req.Name, + Description: req.Description, + DefaultExecutorID: req.DefaultExecutorID, + DefaultEnvironmentID: req.DefaultEnvironmentID, + DefaultAgentProfileID: req.DefaultAgentProfileID, + DefaultConfigAgentProfileID: req.DefaultConfigAgentProfileID, }) if err != nil { h.logger.Error("failed to update workspace", zap.Error(err)) diff --git a/apps/backend/internal/task/models/models.go b/apps/backend/internal/task/models/models.go index c3ba05bb72..0b963725d7 100644 --- a/apps/backend/internal/task/models/models.go +++ b/apps/backend/internal/task/models/models.go @@ -52,15 +52,16 @@ type Workflow struct { // Workspace represents a workspace type Workspace struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - OwnerID string `json:"owner_id"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + OwnerID string `json:"owner_id"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } // TaskRepository represents a repository associated with a task diff --git a/apps/backend/internal/task/repository/archive_repository_test.go b/apps/backend/internal/task/repository/archive_repository_test.go index 34b70d3004..96eeb78360 100644 --- a/apps/backend/internal/task/repository/archive_repository_test.go +++ b/apps/backend/internal/task/repository/archive_repository_test.go @@ -114,7 +114,7 @@ func TestSQLiteRepository_ListTasksByWorkspace_IncludeArchived(t *testing.T) { _ = repo.ArchiveTask(ctx, "task-2") // Without includeArchived: should return only active task - tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false, false, false) + tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false, false, false, false) if err != nil { t.Fatalf("failed to list tasks: %v", err) } @@ -126,7 +126,7 @@ func TestSQLiteRepository_ListTasksByWorkspace_IncludeArchived(t *testing.T) { } // With includeArchived: should return both tasks - tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, true, false, false) + tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, true, false, false, false) if err != nil { t.Fatalf("failed to list tasks with archived: %v", err) } @@ -138,7 +138,7 @@ func TestSQLiteRepository_ListTasksByWorkspace_IncludeArchived(t *testing.T) { } // Search with includeArchived=false should filter archived - _, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, false, false, false) + _, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, false, false, false, false) if err != nil { t.Fatalf("failed to search tasks: %v", err) } @@ -147,7 +147,7 @@ func TestSQLiteRepository_ListTasksByWorkspace_IncludeArchived(t *testing.T) { } // Search with includeArchived=true should include archived - _, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, true, false, false) + _, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, true, false, false, false) if err != nil { t.Fatalf("failed to search tasks with archived: %v", err) } diff --git a/apps/backend/internal/task/repository/interface.go b/apps/backend/internal/task/repository/interface.go index 5a12617e24..8483c5f9fe 100644 --- a/apps/backend/internal/task/repository/interface.go +++ b/apps/backend/internal/task/repository/interface.go @@ -24,7 +24,7 @@ type TaskRepository interface { UpdateTask(ctx context.Context, task *models.Task) error DeleteTask(ctx context.Context, id string) error ListTasks(ctx context.Context, workflowID string) ([]*models.Task, error) - ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) + ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) ArchiveTask(ctx context.Context, id string) error ListTasksForAutoArchive(ctx context.Context) ([]*models.Task, error) diff --git a/apps/backend/internal/task/repository/sqlite/base.go b/apps/backend/internal/task/repository/sqlite/base.go index 7bcf8a8680..ffb8b4821c 100644 --- a/apps/backend/internal/task/repository/sqlite/base.go +++ b/apps/backend/internal/task/repository/sqlite/base.go @@ -136,6 +136,8 @@ func (r *Repository) runMigrations() error { _, _ = r.db.Exec(`ALTER TABLE task_repositories ADD COLUMN checkout_branch TEXT DEFAULT ''`) // Add base_commit_sha column to task_sessions for tracking session start commit (ignore error if already exists) _, _ = r.db.Exec(`ALTER TABLE task_sessions ADD COLUMN base_commit_sha TEXT DEFAULT ''`) + // Add default_config_agent_profile_id column to workspaces (ignore error if already exists) + _, _ = r.db.Exec(`ALTER TABLE workspaces ADD COLUMN default_config_agent_profile_id TEXT DEFAULT ''`) return nil } @@ -159,6 +161,7 @@ func (r *Repository) initInfraSchema() error { default_executor_id TEXT DEFAULT '', default_environment_id TEXT DEFAULT '', default_agent_profile_id TEXT DEFAULT '', + default_config_agent_profile_id TEXT DEFAULT '', created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL ); diff --git a/apps/backend/internal/task/repository/sqlite/task.go b/apps/backend/internal/task/repository/sqlite/task.go index 609b0a9deb..93782f2d4b 100644 --- a/apps/backend/internal/task/repository/sqlite/task.go +++ b/apps/backend/internal/task/repository/sqlite/task.go @@ -179,7 +179,7 @@ func (r *Repository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID // If includeArchived is false, archived tasks are excluded // If includeEphemeral is false, ephemeral tasks are excluded // If onlyEphemeral is true, only ephemeral tasks are returned -func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) { +func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) { ctx, span := tracing.Tracer("kandev-db").Start(ctx, "db.ListTasksByWorkspace") defer span.End() // Calculate offset @@ -203,6 +203,10 @@ func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID strin filter += " AND archived_at IS NULL" } + if excludeConfig { + filter += " AND (metadata IS NULL OR json_extract(metadata, '$.config_mode') IS NOT 1)" + } + var rows *sql.Rows var total int var err error @@ -210,7 +214,7 @@ func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID strin if query == "" { rows, total, err = r.queryAllTasks(ctx, workspaceID, filter, pageSize, offset) } else { - rows, total, err = r.searchTasks(ctx, workspaceID, query, filter, pageSize, offset, includeArchived, includeEphemeral, onlyEphemeral) + rows, total, err = r.searchTasks(ctx, workspaceID, query, filter, pageSize, offset, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig) } if err != nil { @@ -244,7 +248,7 @@ func (r *Repository) queryAllTasks(ctx context.Context, workspaceID, archiveFilt } // searchTasks fetches tasks matching a search query for a workspace with pagination. -func (r *Repository) searchTasks(ctx context.Context, workspaceID, query, filter string, pageSize, offset int, includeArchived, includeEphemeral, onlyEphemeral bool) (*sql.Rows, int, error) { +func (r *Repository) searchTasks(ctx context.Context, workspaceID, query, filter string, pageSize, offset int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) (*sql.Rows, int, error) { searchPattern := "%" + query + "%" like := dialect.Like(r.ro.DriverName()) @@ -258,6 +262,9 @@ func (r *Repository) searchTasks(ctx context.Context, workspaceID, query, filter if !includeArchived { tFilter += " AND t.archived_at IS NULL" } + if excludeConfig { + tFilter += " AND (t.metadata IS NULL OR json_extract(t.metadata, '$.config_mode') IS NOT 1)" + } countQuery := fmt.Sprintf(` SELECT COUNT(DISTINCT t.id) FROM tasks t diff --git a/apps/backend/internal/task/repository/sqlite/workspace.go b/apps/backend/internal/task/repository/sqlite/workspace.go index 9b29f72b92..23eddd0e45 100644 --- a/apps/backend/internal/task/repository/sqlite/workspace.go +++ b/apps/backend/internal/task/repository/sqlite/workspace.go @@ -29,11 +29,12 @@ func (r *Repository) CreateWorkspace(ctx context.Context, workspace *models.Work default_executor_id, default_environment_id, default_agent_profile_id, + default_config_agent_profile_id, created_at, updated_at ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - `), workspace.ID, workspace.Name, workspace.Description, workspace.OwnerID, workspace.DefaultExecutorID, workspace.DefaultEnvironmentID, workspace.DefaultAgentProfileID, workspace.CreatedAt, workspace.UpdatedAt) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `), workspace.ID, workspace.Name, workspace.Description, workspace.OwnerID, workspace.DefaultExecutorID, workspace.DefaultEnvironmentID, workspace.DefaultAgentProfileID, workspace.DefaultConfigAgentProfileID, workspace.CreatedAt, workspace.UpdatedAt) return err } @@ -44,9 +45,10 @@ func (r *Repository) GetWorkspace(ctx context.Context, id string) (*models.Works var defaultExecutorID sql.NullString var defaultEnvironmentID sql.NullString var defaultAgentProfileID sql.NullString + var defaultConfigAgentProfileID sql.NullString err := r.ro.QueryRowContext(ctx, r.ro.Rebind(` - SELECT id, name, description, owner_id, default_executor_id, default_environment_id, default_agent_profile_id, created_at, updated_at + SELECT id, name, description, owner_id, default_executor_id, default_environment_id, default_agent_profile_id, default_config_agent_profile_id, created_at, updated_at FROM workspaces WHERE id = ? `), id).Scan( &workspace.ID, @@ -56,6 +58,7 @@ func (r *Repository) GetWorkspace(ctx context.Context, id string) (*models.Works &defaultExecutorID, &defaultEnvironmentID, &defaultAgentProfileID, + &defaultConfigAgentProfileID, &workspace.CreatedAt, &workspace.UpdatedAt, ) @@ -68,6 +71,9 @@ func (r *Repository) GetWorkspace(ctx context.Context, id string) (*models.Works if defaultAgentProfileID.Valid && defaultAgentProfileID.String != "" { workspace.DefaultAgentProfileID = &defaultAgentProfileID.String } + if defaultConfigAgentProfileID.Valid && defaultConfigAgentProfileID.String != "" { + workspace.DefaultConfigAgentProfileID = &defaultConfigAgentProfileID.String + } if err == sql.ErrNoRows { return nil, fmt.Errorf("workspace not found: %s", id) @@ -86,9 +92,10 @@ func (r *Repository) UpdateWorkspace(ctx context.Context, workspace *models.Work default_executor_id = ?, default_environment_id = ?, default_agent_profile_id = ?, + default_config_agent_profile_id = ?, updated_at = ? WHERE id = ? - `), workspace.Name, workspace.Description, workspace.DefaultExecutorID, workspace.DefaultEnvironmentID, workspace.DefaultAgentProfileID, workspace.UpdatedAt, workspace.ID) + `), workspace.Name, workspace.Description, workspace.DefaultExecutorID, workspace.DefaultEnvironmentID, workspace.DefaultAgentProfileID, workspace.DefaultConfigAgentProfileID, workspace.UpdatedAt, workspace.ID) if err != nil { return err } @@ -117,7 +124,7 @@ func (r *Repository) DeleteWorkspace(ctx context.Context, id string) error { // ListWorkspaces returns all workspaces func (r *Repository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, error) { rows, err := r.ro.QueryContext(ctx, ` - SELECT id, name, description, owner_id, default_executor_id, default_environment_id, default_agent_profile_id, created_at, updated_at + SELECT id, name, description, owner_id, default_executor_id, default_environment_id, default_agent_profile_id, default_config_agent_profile_id, created_at, updated_at FROM workspaces ORDER BY created_at DESC `) if err != nil { @@ -131,6 +138,7 @@ func (r *Repository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, e var defaultExecutorID sql.NullString var defaultEnvironmentID sql.NullString var defaultAgentProfileID sql.NullString + var defaultConfigAgentProfileID sql.NullString if err := rows.Scan( &workspace.ID, &workspace.Name, @@ -139,6 +147,7 @@ func (r *Repository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, e &defaultExecutorID, &defaultEnvironmentID, &defaultAgentProfileID, + &defaultConfigAgentProfileID, &workspace.CreatedAt, &workspace.UpdatedAt, ); err != nil { @@ -153,6 +162,9 @@ func (r *Repository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, e if defaultAgentProfileID.Valid && defaultAgentProfileID.String != "" { workspace.DefaultAgentProfileID = &defaultAgentProfileID.String } + if defaultConfigAgentProfileID.Valid && defaultConfigAgentProfileID.String != "" { + workspace.DefaultConfigAgentProfileID = &defaultConfigAgentProfileID.String + } result = append(result, workspace) } return result, rows.Err() diff --git a/apps/backend/internal/task/repository/task_repository_test.go b/apps/backend/internal/task/repository/task_repository_test.go index a218d28060..fbb0c4ae0e 100644 --- a/apps/backend/internal/task/repository/task_repository_test.go +++ b/apps/backend/internal/task/repository/task_repository_test.go @@ -196,7 +196,7 @@ func TestSQLiteRepository_ListTasksByWorkspace(t *testing.T) { _ = repo.CreateTask(ctx, &models.Task{ID: "task-4", WorkspaceID: "ws-2", WorkflowID: "wf-456", WorkflowStepID: "step-2", Title: "Task Four"}) // Test basic listing without search - tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false, false, false) + tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false, false, false, false) if err != nil { t.Fatalf("failed to list tasks by workspace: %v", err) } @@ -208,7 +208,7 @@ func TestSQLiteRepository_ListTasksByWorkspace(t *testing.T) { } // Test pagination - tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 2, false, false, false) + tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 2, false, false, false, false) if err != nil { t.Fatalf("failed to list tasks with pagination: %v", err) } @@ -220,7 +220,7 @@ func TestSQLiteRepository_ListTasksByWorkspace(t *testing.T) { } // Test page 2 - tasksPage2, _, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 2, 2, false, false, false) + tasksPage2, _, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 2, 2, false, false, false, false) if err != nil { t.Fatalf("failed to list tasks page 2: %v", err) } @@ -250,7 +250,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { _ = repo.CreateTaskRepository(ctx, &models.TaskRepository{ID: "tr-1", TaskID: "task-1", RepositoryID: "repo-1", BaseBranch: "main"}) // Test search by title - _, totalAuth, err := repo.ListTasksByWorkspace(ctx, "ws-1", "authentication", 1, 10, false, false, false) + _, totalAuth, err := repo.ListTasksByWorkspace(ctx, "ws-1", "authentication", 1, 10, false, false, false, false) if err != nil { t.Fatalf("failed to search tasks by title: %v", err) } @@ -259,7 +259,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { } // Test search by description - tasksDarkMode, totalDarkMode, err := repo.ListTasksByWorkspace(ctx, "ws-1", "dark mode", 1, 10, false, false, false) + tasksDarkMode, totalDarkMode, err := repo.ListTasksByWorkspace(ctx, "ws-1", "dark mode", 1, 10, false, false, false, false) if err != nil { t.Fatalf("failed to search tasks by description: %v", err) } @@ -271,7 +271,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { } // Test search by repository name - tasksRepo, totalRepo, err := repo.ListTasksByWorkspace(ctx, "ws-1", "MyProject", 1, 10, false, false, false) + tasksRepo, totalRepo, err := repo.ListTasksByWorkspace(ctx, "ws-1", "MyProject", 1, 10, false, false, false, false) if err != nil { t.Fatalf("failed to search tasks by repository name: %v", err) } @@ -283,7 +283,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { } // Test search by repository local_path - _, totalPath, err := repo.ListTasksByWorkspace(ctx, "ws-1", "myproject", 1, 10, false, false, false) + _, totalPath, err := repo.ListTasksByWorkspace(ctx, "ws-1", "myproject", 1, 10, false, false, false, false) if err != nil { t.Fatalf("failed to search tasks by repository path: %v", err) } @@ -292,7 +292,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { } // Test search with no results - tasksNone, totalNone, err := repo.ListTasksByWorkspace(ctx, "ws-1", "nonexistent", 1, 10, false, false, false) + tasksNone, totalNone, err := repo.ListTasksByWorkspace(ctx, "ws-1", "nonexistent", 1, 10, false, false, false, false) if err != nil { t.Fatalf("failed to search tasks with no results: %v", err) } diff --git a/apps/backend/internal/task/service/service_events.go b/apps/backend/internal/task/service/service_events.go index abdbfeab6c..818bebe87c 100644 --- a/apps/backend/internal/task/service/service_events.go +++ b/apps/backend/internal/task/service/service_events.go @@ -122,15 +122,16 @@ func (s *Service) publishWorkspaceEvent(ctx context.Context, eventType string, w } data := map[string]interface{}{ - "id": workspace.ID, - "name": workspace.Name, - "description": workspace.Description, - "owner_id": workspace.OwnerID, - "default_executor_id": workspace.DefaultExecutorID, - "default_environment_id": workspace.DefaultEnvironmentID, - "default_agent_profile_id": workspace.DefaultAgentProfileID, - "created_at": workspace.CreatedAt.Format(time.RFC3339), - "updated_at": workspace.UpdatedAt.Format(time.RFC3339), + "id": workspace.ID, + "name": workspace.Name, + "description": workspace.Description, + "owner_id": workspace.OwnerID, + "default_executor_id": workspace.DefaultExecutorID, + "default_environment_id": workspace.DefaultEnvironmentID, + "default_agent_profile_id": workspace.DefaultAgentProfileID, + "default_config_agent_profile_id": workspace.DefaultConfigAgentProfileID, + "created_at": workspace.CreatedAt.Format(time.RFC3339), + "updated_at": workspace.UpdatedAt.Format(time.RFC3339), } s.publishEventToBus(ctx, eventType, "workspace", workspace.ID, data) diff --git a/apps/backend/internal/task/service/service_requests.go b/apps/backend/internal/task/service/service_requests.go index df0585cbdf..34444218f8 100644 --- a/apps/backend/internal/task/service/service_requests.go +++ b/apps/backend/internal/task/service/service_requests.go @@ -62,21 +62,23 @@ type UpdateWorkflowRequest struct { // CreateWorkspaceRequest contains the data for creating a new workspace type CreateWorkspaceRequest struct { - Name string `json:"name"` - Description string `json:"description"` - OwnerID string `json:"owner_id"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + Name string `json:"name"` + Description string `json:"description"` + OwnerID string `json:"owner_id"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` } // UpdateWorkspaceRequest contains the data for updating a workspace type UpdateWorkspaceRequest struct { - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` } // FindOrCreateRepositoryRequest contains the data for finding or creating a repository by provider info. diff --git a/apps/backend/internal/task/service/service_resources.go b/apps/backend/internal/task/service/service_resources.go index 7efb4377af..1a1a13f5c3 100644 --- a/apps/backend/internal/task/service/service_resources.go +++ b/apps/backend/internal/task/service/service_resources.go @@ -21,13 +21,14 @@ const spritesTokenEnvKey = "SPRITES_API_TOKEN" // CreateWorkspace creates a new workspace func (s *Service) CreateWorkspace(ctx context.Context, req *CreateWorkspaceRequest) (*models.Workspace, error) { workspace := &models.Workspace{ - ID: uuid.New().String(), - Name: req.Name, - Description: req.Description, - OwnerID: req.OwnerID, - DefaultExecutorID: normalizeOptionalID(req.DefaultExecutorID), - DefaultEnvironmentID: normalizeOptionalID(req.DefaultEnvironmentID), - DefaultAgentProfileID: normalizeOptionalID(req.DefaultAgentProfileID), + ID: uuid.New().String(), + Name: req.Name, + Description: req.Description, + OwnerID: req.OwnerID, + DefaultExecutorID: normalizeOptionalID(req.DefaultExecutorID), + DefaultEnvironmentID: normalizeOptionalID(req.DefaultEnvironmentID), + DefaultAgentProfileID: normalizeOptionalID(req.DefaultAgentProfileID), + DefaultConfigAgentProfileID: normalizeOptionalID(req.DefaultConfigAgentProfileID), } if err := s.workspaces.CreateWorkspace(ctx, workspace); err != nil { @@ -67,6 +68,9 @@ func (s *Service) UpdateWorkspace(ctx context.Context, id string, req *UpdateWor if req.DefaultAgentProfileID != nil { workspace.DefaultAgentProfileID = normalizeOptionalID(req.DefaultAgentProfileID) } + if req.DefaultConfigAgentProfileID != nil { + workspace.DefaultConfigAgentProfileID = normalizeOptionalID(req.DefaultConfigAgentProfileID) + } workspace.UpdatedAt = time.Now().UTC() if err := s.workspaces.UpdateWorkspace(ctx, workspace); err != nil { diff --git a/apps/backend/internal/task/service/service_tasks.go b/apps/backend/internal/task/service/service_tasks.go index 7a6e16b552..6a012bf39c 100644 --- a/apps/backend/internal/task/service/service_tasks.go +++ b/apps/backend/internal/task/service/service_tasks.go @@ -656,8 +656,8 @@ func (s *Service) ListTasks(ctx context.Context, workflowID string) ([]*models.T // ListTasksByWorkspace returns paginated tasks for a workspace with task repositories loaded. // If query is non-empty, filters by task title, description, repository name, or repository path. -func (s *Service) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) { - tasks, total, err := s.tasks.ListTasksByWorkspace(ctx, workspaceID, query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral) +func (s *Service) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) { + tasks, total, err := s.tasks.ListTasksByWorkspace(ctx, workspaceID, query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig) if err != nil { return nil, 0, err } diff --git a/apps/backend/pkg/api/v1/workspace.go b/apps/backend/pkg/api/v1/workspace.go index ac01385a7a..5939b1c7d0 100644 --- a/apps/backend/pkg/api/v1/workspace.go +++ b/apps/backend/pkg/api/v1/workspace.go @@ -4,31 +4,34 @@ import "time" // Workspace represents a workspace type Workspace struct { - ID string `json:"id"` - Name string `json:"name"` - Description *string `json:"description,omitempty"` - OwnerID string `json:"owner_id"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `json:"id"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + OwnerID string `json:"owner_id"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } // CreateWorkspaceRequest for creating a new workspace type CreateWorkspaceRequest struct { - Name string `json:"name" binding:"required,max=255"` - Description *string `json:"description,omitempty"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + Name string `json:"name" binding:"required,max=255"` + Description *string `json:"description,omitempty"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` } // UpdateWorkspaceRequest for updating an existing workspace type UpdateWorkspaceRequest struct { - Name *string `json:"name,omitempty" binding:"omitempty,max=255"` - Description *string `json:"description,omitempty"` - DefaultExecutorID *string `json:"default_executor_id,omitempty"` - DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` - DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + Name *string `json:"name,omitempty" binding:"omitempty,max=255"` + Description *string `json:"description,omitempty"` + DefaultExecutorID *string `json:"default_executor_id,omitempty"` + DefaultEnvironmentID *string `json:"default_environment_id,omitempty"` + DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"` + DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"` } diff --git a/apps/backend/pkg/websocket/actions.go b/apps/backend/pkg/websocket/actions.go index 543b7dc8a2..15d0d01c6c 100644 --- a/apps/backend/pkg/websocket/actions.go +++ b/apps/backend/pkg/websocket/actions.go @@ -156,6 +156,9 @@ const ( ActionWorkflowCreated = "workflow.created" ActionWorkflowUpdated = "workflow.updated" ActionWorkflowDeleted = "workflow.deleted" + ActionWorkflowStepCreated = "workflow.step.created" + ActionWorkflowStepUpdated = "workflow.step.updated" + ActionWorkflowStepDeleted = "workflow.step.deleted" ActionSessionMessageAdded = "session.message.added" ActionSessionMessageUpdated = "session.message.updated" ActionSessionStateChanged = "session.state_changed" @@ -299,6 +302,37 @@ const ( ActionMCPUpdateTaskPlan = "mcp.update_task_plan" ActionMCPDeleteTaskPlan = "mcp.delete_task_plan" ActionMCPClarificationTimeout = "mcp.clarification_timeout" + + // Config-mode MCP actions (agent-native configuration) + ActionMCPCreateWorkflow = "mcp.create_workflow" + ActionMCPUpdateWorkflow = "mcp.update_workflow" + ActionMCPDeleteWorkflow = "mcp.delete_workflow" + + ActionMCPCreateWorkflowStep = "mcp.create_workflow_step" + ActionMCPUpdateWorkflowStep = "mcp.update_workflow_step" + ActionMCPDeleteWorkflowStep = "mcp.delete_workflow_step" + ActionMCPReorderWorkflowStep = "mcp.reorder_workflow_steps" + + ActionMCPListAgents = "mcp.list_agents" + ActionMCPUpdateAgent = "mcp.update_agent" + + ActionMCPListAgentProfiles = "mcp.list_agent_profiles" + ActionMCPCreateAgentProfile = "mcp.create_agent_profile" + ActionMCPUpdateAgentProfile = "mcp.update_agent_profile" + ActionMCPDeleteAgentProfile = "mcp.delete_agent_profile" + ActionMCPGetMcpConfig = "mcp.get_mcp_config" + ActionMCPUpdateMcpConfig = "mcp.update_mcp_config" + + ActionMCPListExecutors = "mcp.list_executors" + ActionMCPListExecutorProfiles = "mcp.list_executor_profiles" + ActionMCPCreateExecutorProfile = "mcp.create_executor_profile" + ActionMCPUpdateExecutorProfile = "mcp.update_executor_profile" + ActionMCPDeleteExecutorProfile = "mcp.delete_executor_profile" + + ActionMCPMoveTask = "mcp.move_task" + ActionMCPDeleteTask = "mcp.delete_task" + ActionMCPArchiveTask = "mcp.archive_task" + ActionMCPUpdateTaskState = "mcp.update_task_state" ) // GitHub integration actions diff --git a/apps/web/app/actions/workspaces.ts b/apps/web/app/actions/workspaces.ts index 706099bf22..692ded194d 100644 --- a/apps/web/app/actions/workspaces.ts +++ b/apps/web/app/actions/workspaces.ts @@ -78,6 +78,7 @@ export async function updateWorkspaceAction( default_executor_id?: string; default_environment_id?: string; default_agent_profile_id?: string; + default_config_agent_profile_id?: string; }, ) { return fetchJson(`${apiBaseUrl}/api/v1/workspaces/${id}`, { diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index b505b4e498..bcbc4e4c00 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -10,6 +10,7 @@ import { CommandPanel } from "@/components/command-panel"; import { GlobalCommands } from "@/components/global-commands"; import { DiffWorkerPoolProvider } from "@/components/diff-worker-pool-provider"; import { QuickChatProvider } from "@/components/quick-chat/quick-chat-provider"; +import { ConfigChatProvider } from "@/components/config-chat/config-chat-provider"; import { SessionFailureToastBridge } from "@/components/session-failure-toast-bridge"; export const metadata: Metadata = { @@ -64,7 +65,9 @@ export default function RootLayout({ - {children} + + {children} + diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index c9d307645d..b2c1e4769e 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -33,6 +33,7 @@ function mapWorkspaceItem(ws: WorkspaceItem) { default_executor_id: ws.default_executor_id ?? null, default_environment_id: ws.default_environment_id ?? null, default_agent_profile_id: ws.default_agent_profile_id ?? null, + default_config_agent_profile_id: ws.default_config_agent_profile_id ?? null, created_at: ws.created_at, updated_at: ws.updated_at, }; diff --git a/apps/web/app/settings/agents/page.tsx b/apps/web/app/settings/agents/page.tsx index 4b93d7f221..0adeda507e 100644 --- a/apps/web/app/settings/agents/page.tsx +++ b/apps/web/app/settings/agents/page.tsx @@ -14,8 +14,11 @@ import { import { Badge } from "@kandev/ui/badge"; import { Button } from "@kandev/ui/button"; import { Card, CardContent } from "@kandev/ui/card"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; import { Separator } from "@kandev/ui/separator"; -import { useAppStore } from "@/components/state-provider"; +import { useAppStore, useAppStoreApi } from "@/components/state-provider"; +import { useToast } from "@/components/toast-provider"; +import { updateWorkspaceAction } from "@/app/actions/workspaces"; import { createCustomTUIAgent, listAgentDiscovery, @@ -369,6 +372,72 @@ function AgentProfilesSection({ savedAgents }: AgentProfilesSectionProps) { ); } +function ConfigChatAgentSection() { + const workspace = useAppStore( + (s) => s.workspaces.items.find((w) => w.id === s.workspaces.activeId) ?? null, + ); + const profiles = useAppStore((s) => s.agentProfiles.items ?? []); + const currentProfileId = workspace?.default_config_agent_profile_id ?? ""; + const [saving, setSaving] = useState(false); + const { toast } = useToast(); + + const storeApi = useAppStoreApi(); + + const handleChange = async (value: string) => { + const effectiveValue = value === "none" ? "" : value; + if (!workspace) return; + setSaving(true); + try { + await updateWorkspaceAction(workspace.id, { + default_config_agent_profile_id: effectiveValue, + }); + const { workspaces, setWorkspaces } = storeApi.getState(); + setWorkspaces( + workspaces.items.map((w) => + w.id === workspace.id ? { ...w, default_config_agent_profile_id: effectiveValue } : w, + ), + ); + toast({ title: "Configuration agent updated", variant: "success" }); + } catch (error) { + toast({ + title: "Failed to update", + description: error instanceof Error ? error.message : "Unknown error", + variant: "error", + }); + } finally { + setSaving(false); + } + }; + + if (!workspace) return null; + + return ( +
+ +
+

Configuration Chat Agent

+

+ Choose which agent profile to use for the Configuration Chat. This agent can manage your + workflows, agent profiles, and MCP configuration. +

+
+ +
+ ); +} + function useAgentPageState() { const { items: discoveryAgents, loading: discoveryLoading } = useAgentDiscovery(); const savedAgents = useAppStore((state) => state.settingsAgents.items); @@ -494,6 +563,8 @@ export default function AgentsSettingsPage() { + + + <> + {children} - + ); } diff --git a/apps/web/components/config-chat/config-chat-panel.tsx b/apps/web/components/config-chat/config-chat-panel.tsx new file mode 100644 index 0000000000..3388c8c209 --- /dev/null +++ b/apps/web/components/config-chat/config-chat-panel.tsx @@ -0,0 +1,330 @@ +"use client"; + +import { memo, useEffect, useRef, useState } from "react"; +import { + IconLoader2, + IconMessageCircle, + IconPlus, + IconSend2, + IconSparkles, + IconX, +} from "@tabler/icons-react"; +import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover"; +import { Button } from "@kandev/ui/button"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; +import { Textarea } from "@kandev/ui/textarea"; +import { QuickChatContent } from "@/components/quick-chat/quick-chat-content"; +import { useAppStore } from "@/components/state-provider"; +import { useConfigChat } from "./use-config-chat"; +import type { ConfigChatSession } from "@/lib/state/slices/ui/types"; + +const SUGGESTION_PROMPTS = [ + "Add a 'Code Review' step to my workflow", + "Create a new agent profile with auto-approve enabled", + "Show me the current workflow configuration", + "Update the MCP servers for the default agent profile", +]; + +function SuggestionList() { + return ( +
+

Try asking

+ {SUGGESTION_PROMPTS.map((prompt) => ( +

+ {prompt} +

+ ))} +
+ ); +} + +function ProfileSelector({ onSelect }: { onSelect: (id: string) => void }) { + const profiles = useAppStore((s) => s.agentProfiles.items ?? []); + return ( +
+

Select an agent profile

+
+ {profiles.map((profile) => ( + + ))} +
+

+ This will be saved as your default. Change it in Agent settings. +

+
+ ); +} + +function ConfigChatTabs({ + sessions, + activeSessionId, + onTabChange, + onTabClose, + onNewChat, +}: { + sessions: ConfigChatSession[]; + activeSessionId: string | null; + onTabChange: (sessionId: string) => void; + onTabClose: (sessionId: string) => void; + onNewChat: () => void; +}) { + if (sessions.length === 0) return null; + + return ( +
+
+ {sessions.map((s, index) => { + const isActive = s.sessionId === activeSessionId; + const tabName = s.name || `Chat ${index + 1}`; + return ( +
+ + +
+ ); + })} +
+ +
+ ); +} + +function LoadingState() { + return ( +
+ +

Starting config chat...

+
+ ); +} + +function ConfigChatEmptyState({ + defaultProfileId, + onSelectPrompt, + isStarting, + error, +}: { + defaultProfileId: string | undefined; + onSelectPrompt: (prompt: string, profileId: string) => void; + isStarting: boolean; + error: string | null; +}) { + const profileCount = useAppStore((s) => s.agentProfiles.items?.length ?? 0); + const [selectedProfileId, setSelectedProfileId] = useState(defaultProfileId ?? ""); + const [inputValue, setInputValue] = useState(""); + + const textareaRef = useRef(null); + const needsProfileSelection = !selectedProfileId && !defaultProfileId && profileCount > 0; + const effectiveProfileId = selectedProfileId || defaultProfileId || ""; + const canSubmit = inputValue.trim().length > 0 && !!effectiveProfileId && !isStarting; + + useEffect(() => { + if (!needsProfileSelection && !isStarting && textareaRef.current) { + textareaRef.current.focus(); + } + }, [needsProfileSelection, isStarting]); + + const handleSubmit = () => { + const trimmed = inputValue.trim(); + if (!trimmed || !effectiveProfileId) return; + onSelectPrompt(trimmed, effectiveProfileId); + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + handleSubmit(); + } + }; + + if (isStarting) return ; + + return ( +
+
+
+
+ +
+
+

Configure Kandev with AI

+

+ Manage workflows, agent profiles, and MCP configuration. +

+
+ + {needsProfileSelection ? ( + + ) : ( + <> + {inputValue.length === 0 ? :
} + +
+