From 353e6c252dbcbf13210b07cf26c4958ac6bd327c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Mon, 17 Aug 2026 11:19:19 +0000 Subject: [PATCH] chore: clarify native subagent delegation (#2716) --- apps/backend/config/prompts/kandev-context.md | 32 +- .../backend/internal/mcp/handlers/handlers.go | 2 +- .../internal/mcp/server/config_handlers.go | 8 + apps/backend/internal/mcp/server/handlers.go | 4 +- .../internal/mcp/server/handlers_test.go | 24 +- .../internal/mcp/server/handoff_handlers.go | 11 +- apps/backend/internal/mcp/server/server.go | 289 ++++-------------- .../internal/mcp/server/server_test.go | 16 +- .../mcp/server/spawn_session_tool_test.go | 7 +- .../mcp/server/sysprompt_sync_test.go | 35 +-- .../internal/mcp/server/tool_metadata_test.go | 144 +++++++++ apps/backend/internal/sysprompt/sysprompt.go | 13 +- .../internal/sysprompt/sysprompt_test.go | 13 +- .../use-workspace-content-search.test.ts | 24 ++ 14 files changed, 311 insertions(+), 311 deletions(-) create mode 100644 apps/backend/internal/mcp/server/tool_metadata_test.go diff --git a/apps/backend/config/prompts/kandev-context.md b/apps/backend/config/prompts/kandev-context.md index 300a681c56..ed3bb34ca0 100644 --- a/apps/backend/config/prompts/kandev-context.md +++ b/apps/backend/config/prompts/kandev-context.md @@ -5,24 +5,28 @@ Kandev Task ID: {task_id} Kandev Session ID: {session_id} Use these IDs when calling tools that require task_id or session_id. +DELEGATION POLICY: +For ordinary coding, research, review, or parallel work, use your host agent's native subagent mechanism (for example Codex's native subagent tool, Claude Code's Agent tool, Cursor custom subagents, or OpenCode's Task tool) only when the user has explicitly authorized delegation for this task. Otherwise continue in this session or ask the user. Do NOT use Kandev task or session tools as a generic worker mechanism. +Use create_task_kandev only when the user explicitly wants a persistent Kandev task or subtask, workflow tracking, or Kandev task lifecycle. Use spawn_session_kandev only when the user explicitly wants another Kandev session/tab. If no native subagent tool is available, continue in this session or ask the user; do not silently create a Kandev task or session. + {autopilot_section} Available tools: {question_tool_section} -{step_complete_section}{task_title_section}- create_task_plan_kandev: Save an implementation plan for the current task. Required params: task_id, content (markdown). Optional: title. -- get_task_plan_kandev: Retrieve the current plan for a task (includes any user edits). Required params: task_id. -- update_task_plan_kandev: Update an existing plan. Required params: task_id, content (markdown). Optional: title. -- delete_task_plan_kandev: Delete a task plan. Required params: task_id. -- show_walkthrough_kandev: Show and store a code walkthrough for the current task. Required param: `steps` (ordered array; every step requires `file`, `line`, and `text`). Optional: task_id, title; each step may include repo, title, and line_end. -- get_walkthrough_kandev: Retrieve the stored walkthrough for a task. Optional: task_id (defaults to the current task). -- delete_walkthrough_kandev: Delete the stored walkthrough for a task. Optional: task_id (defaults to the current task). +{step_complete_section}{task_title_section}- create_task_plan_kandev: Save an implementation plan for a task. +- get_task_plan_kandev: Read a task plan, including user edits. +- update_task_plan_kandev: Update an existing task plan. +- delete_task_plan_kandev: Delete a task plan. +- show_walkthrough_kandev: Store an ordered, file-anchored code walkthrough. +- get_walkthrough_kandev: Read a task's stored walkthrough. +- delete_walkthrough_kandev: Delete a task's walkthrough. - list_workspaces_kandev: List all workspaces. -- list_workflows_kandev: List workflows in a workspace. Required params: workspace_id. -- list_tasks_kandev: List tasks in a workflow. Required params: workflow_id. -- create_task_kandev: Create a new task or subtask. Required params: title (keep it concise, a few words, and no more than 60 characters; put detailed context in description). For subtasks, set parent_id to the literal string "self" (the MCP server expands it to your current task ID) and omit workspace_id/workflow_id/workflow_step_id; they inherit from the parent. Pass workspace_id/workflow_id on a subtask only when deliberately targeting another task workspace/workflow; any supplied workflow_id must belong to the effective workspace_id. MCP subtasks reuse the parent's materialized workspace by default; set workspace_mode to "new_workspace" only when the subtask should launch in its own worktree/materialized workspace. For top-level tasks, provide workspace_id/workflow_id unless each can be auto-resolved uniquely. workflow_step_id is optional. -- update_task_kandev: Update a task. Required params: task_id. Optional: title, description, state, deferred_launch_prompt (rewrite the prompt a not-yet-started task created with blocked_by will launch with; rejected once the task has started). -- spawn_session_kandev: Spawn an ADDITIONAL agent session on your current task (no new task is created — it runs alongside your session in the same workspace). Required params: prompt (the new session's ONLY initial context). Optional: agent_profile_id (defaults to your profile; specify a different one to spawn a different agent), name (session tab label, e.g. "reviewer"), task_id (defaults to your task). Returns the new session_id. -- message_task_kandev: Message another task's agent, or a specific session via optional session_id — including a sibling session on your OWN task. Required params: task_id, prompt.{coordinator_task_control_section} -- list_task_sessions_kandev: List every agent session on a task, most recently started first. Use it to find the session_id for message_task_kandev or get_task_conversation_kandev when a task has more than one session; both of those default to the primary session, so siblings are only reachable by ID. Required params: task_id. Each entry reports session_id, name, state, is_primary, is_current (your own session), agent_profile_id, and timestamps. +- list_workflows_kandev: List workflows in a workspace. +- list_tasks_kandev: List tasks in a workflow. +- create_task_kandev: Create user-requested persistent Kandev-tracked work. Use parent_id="self" for a current-task subtask; its context is inherited unless explicitly overridden. +- update_task_kandev: Update a task, including a deferred launch prompt for blocked work that has not started. +- spawn_session_kandev: Start an additional Kandev session/tab without creating a task. Use only when the user explicitly requests one. +- message_task_kandev: Send a prompt to an existing Kandev task session.{coordinator_task_control_section} +- list_task_sessions_kandev: List a task's sessions and their IDs. IMPORTANT: You MUST use these MCP tools when instructed to create plans, ask questions, or interact with the Kandev platform. Do not skip them. diff --git a/apps/backend/internal/mcp/handlers/handlers.go b/apps/backend/internal/mcp/handlers/handlers.go index 3d48e7443d..5cedfa9208 100644 --- a/apps/backend/internal/mcp/handlers/handlers.go +++ b/apps/backend/internal/mcp/handlers/handlers.go @@ -613,7 +613,7 @@ func (h *Handlers) handleCreateTask(ctx context.Context, msg *ws.Message) (*ws.M // Only require description for subtasks if we're starting an agent if req.ParentID != "" && req.Description == "" && startAgent { - return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "description is required for subtasks: it is the sub-agent's initial prompt and the only context it receives to start working", nil) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "description is required for subtasks: it is the task agent's initial prompt and the only context it receives to start working", nil) } // Resolve repositories and default workspace/workflow from parent if needed. diff --git a/apps/backend/internal/mcp/server/config_handlers.go b/apps/backend/internal/mcp/server/config_handlers.go index 8a0e130659..c601a6a8ec 100644 --- a/apps/backend/internal/mcp/server/config_handlers.go +++ b/apps/backend/internal/mcp/server/config_handlers.go @@ -284,6 +284,10 @@ func (s *Server) registerConfigTaskTools() { s.mcpServer.AddTool( mcp.NewTool("delete_task_kandev", mcp.WithDescription("Delete a task permanently."), + mcp.WithReadOnlyHintAnnotation(false), + mcp.WithDestructiveHintAnnotation(true), + mcp.WithIdempotentHintAnnotation(false), + mcp.WithOpenWorldHintAnnotation(false), mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID to delete")), ), s.wrapHandler("delete_task_kandev", s.deleteTaskHandler()), @@ -291,6 +295,10 @@ func (s *Server) registerConfigTaskTools() { s.mcpServer.AddTool( mcp.NewTool("archive_task_kandev", mcp.WithDescription("Archive a task."), + mcp.WithReadOnlyHintAnnotation(false), + mcp.WithDestructiveHintAnnotation(false), + mcp.WithIdempotentHintAnnotation(true), + mcp.WithOpenWorldHintAnnotation(false), mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID to archive")), ), s.wrapHandler("archive_task_kandev", s.archiveTaskHandler()), diff --git a/apps/backend/internal/mcp/server/handlers.go b/apps/backend/internal/mcp/server/handlers.go index d5c26771b0..33218fb9db 100644 --- a/apps/backend/internal/mcp/server/handlers.go +++ b/apps/backend/internal/mcp/server/handlers.go @@ -830,11 +830,11 @@ func extractQuestionAnswers(result map[string]interface{}, questions []map[strin if len(out) == 0 { // Nothing matched by id — surface the raw payload so the agent can still inspect it. data, _ := json.MarshalIndent(result, "", " ") - return mcp.NewToolResultText(string(data)) + return mcp.NewToolResultStructured(result, string(data)) } data, _ := json.MarshalIndent(out, "", " ") - return mcp.NewToolResultText(string(data)) + return mcp.NewToolResultStructured(out, string(data)) } // simplifyAnswer normalizes the answer map. Single-choice per question, but diff --git a/apps/backend/internal/mcp/server/handlers_test.go b/apps/backend/internal/mcp/server/handlers_test.go index 24331fd41e..dc1aeb39ea 100644 --- a/apps/backend/internal/mcp/server/handlers_test.go +++ b/apps/backend/internal/mcp/server/handlers_test.go @@ -71,22 +71,24 @@ func TestCreateTask_ToolSchema_HasParentID(t *testing.T) { "blocked_by", "start_when_unblocked", }, propertyNames(props), "unexpected change to the advertised create_task_kandev schema") assert.NotContains(t, props, "description", "legacy alias must not increase the advertised schema") - assert.Contains(t, tool.Tool.Description, "'prompt' is the sub-agent's initial prompt") - assert.NotContains(t, tool.Tool.Description, "'description' is the sub-agent's initial prompt") + assert.Contains(t, tool.Tool.Description, "persistent Kandev task or subtask") + assert.Contains(t, tool.Tool.Description, "native subagent mechanism") + assert.Contains(t, tool.Tool.Description, `parent_id="self"`) + assert.Contains(t, tool.Tool.Description, "external_id") + assert.NotContains(t, tool.Tool.Description, "DELEGATION POLICY") + parentProperty, ok := props["parent_id"].(map[string]interface{}) + require.True(t, ok, "parent_id schema should be an object") + parentDescription, ok := parentProperty["description"].(string) + require.True(t, ok, "parent_id should have a description") + assert.NotContains(t, parentDescription, "delegated work") promptProp, ok := props["prompt"].(map[string]interface{}) require.True(t, ok, "prompt schema should be an object") promptDesc, ok := promptProp["description"].(string) require.True(t, ok, "prompt should have a description") + assert.Contains(t, promptDesc, "task agent") + assert.NotContains(t, promptDesc, "sub-agent") assert.Contains(t, promptDesc, "For auto-started subtasks") assert.NotContains(t, promptDesc, "REQUIRED") - assert.Contains(t, tool.Tool.Description, "outranks an explicit agent_profile_id") - assert.Contains(t, tool.Tool.Description, "current_task") - assert.Contains(t, tool.Tool.Description, "workspace_default") - assert.Contains(t, tool.Tool.Description, "workflow") - assert.Contains(t, tool.Tool.Description, "verified creating session") - assert.Contains(t, tool.Tool.Description, "effective model, mode, and dynamic options") - assert.Contains(t, tool.Tool.Description, "An explicit agent_profile_id prevents creator-session runtime inheritance") - assert.Contains(t, tool.Tool.Description, "workspace_mode='new_workspace'") assert.NotContains(t, props, "mcp_task_agent_profile_default", "saved policy must not change the tool input schema") agentProfileProp, ok := props["agent_profile_id"].(map[string]interface{}) @@ -759,7 +761,7 @@ func TestMessageTask_DescriptionExplainsQueueInterruptAndStop(t *testing.T) { assert.Contains(t, description, `delivery_mode="queued"`) assert.Contains(t, description, `delivery_mode="interrupt"`) assert.Contains(t, description, "stop_task_kandev") - assert.Contains(t, description, `safely falls back to "queued"`) + assert.Contains(t, description, "prompt remains queued") assert.Contains(t, description, "reply_to_question_id") // Terminal sessions and the session_id-less defaulting rule are both // documented, so a caller does not have to discover either by trial. diff --git a/apps/backend/internal/mcp/server/handoff_handlers.go b/apps/backend/internal/mcp/server/handoff_handlers.go index 16938692c7..e598738948 100644 --- a/apps/backend/internal/mcp/server/handoff_handlers.go +++ b/apps/backend/internal/mcp/server/handoff_handlers.go @@ -16,16 +16,7 @@ import ( func (s *Server) registerRelatedTasksTool() { s.mcpServer.AddTool( mcp.NewTool("list_related_tasks_kandev", - mcp.WithDescription( - `List parent, children, siblings, blockers, and blocked tasks for the current task. -Use this to discover task IDs you can reach via message_task_kandev. Each related task includes its id, -identifier, title and state. Each related task also includes its associated GitHub pull requests -(number, url, title, state) under the "prs" field when any exist. In office mode, document keys are -also included so you can fetch documents with get_task_document_kandev. Task descriptions are omitted -by default because they dominate the response size; pass verbose=true to include them, e.g. to read -dependency metadata (a "Depends on:" line) from a sibling that has not started yet. Pass task_id to -inspect a different task in the same workspace.`, - ), + mcp.WithDescription(`List a task's parent, children, siblings, blockers, and blocked tasks. Entries include identity, state, and linked pull requests; Office entries also include document keys. Descriptions are omitted unless verbose=true. task_id defaults to the current task and may inspect another task in the same workspace.`), mcp.WithString("task_id", mcp.Description("Defaults to the current task.")), mcp.WithBoolean("verbose", mcp.Description( "Include each related task's full description. Defaults to false, which returns the compact projection.")), diff --git a/apps/backend/internal/mcp/server/server.go b/apps/backend/internal/mcp/server/server.go index 006df2f424..0051260648 100644 --- a/apps/backend/internal/mcp/server/server.go +++ b/apps/backend/internal/mcp/server/server.go @@ -952,6 +952,10 @@ func (s *Server) registerKanbanTools() { s.mcpServer.AddTool( mcp.NewTool("delete_task_kandev", mcp.WithDescription("Delete a task permanently. Use to clean up orphaned, duplicate, or test tasks you no longer need. This cannot be undone — prefer archive_task_kandev when the task may still be wanted. Restoring an archived task is a user action done from the UI, not via MCP."), + mcp.WithReadOnlyHintAnnotation(false), + mcp.WithDestructiveHintAnnotation(true), + mcp.WithIdempotentHintAnnotation(false), + mcp.WithOpenWorldHintAnnotation(false), mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID to delete")), ), s.wrapHandler("delete_task_kandev", s.deleteTaskHandler()), @@ -959,34 +963,17 @@ func (s *Server) registerKanbanTools() { s.mcpServer.AddTool( mcp.NewTool("archive_task_kandev", mcp.WithDescription("Archive a task. The task is hidden from active board views but kept in the database. Use to tidy up finished or abandoned tasks. Archiving an already-archived task is a no-op that succeeds with already_archived: true. Unarchiving is a user action done from the UI, not via MCP."), + mcp.WithReadOnlyHintAnnotation(false), + mcp.WithDestructiveHintAnnotation(false), + mcp.WithIdempotentHintAnnotation(true), + mcp.WithOpenWorldHintAnnotation(false), mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID to archive")), ), s.wrapHandler("archive_task_kandev", s.archiveTaskHandler()), ) s.mcpServer.AddTool( mcp.NewTool("message_task_kandev", - mcp.WithDescription(`Send a follow-up prompt (message) to an existing task's primary session, or to a specific session via session_id. - -Use this to communicate with a sibling task, a parent task, or any task you know the ID of — for example to ask a delegated subtask for clarification, hand it new context, or nudge a paused task forward. Pass session_id to target a specific session — including a sibling session on your OWN task (e.g. one you spawned with spawn_session_kandev). - -Choose the control by intent: -- Information that can wait: use delivery_mode="queued" (the default). The current turn continues and the message waits FIFO. -- Urgent replacement work for a running/starting direct child: use delivery_mode="interrupt". This requests immediate cancel-and-redispatch. Only the target task's direct parent may request it; non-parent requests fail. If immediate cancellation and dispatch cannot be confirmed safely, the message safely falls back to "queued". -- Halt-only work with no replacement prompt: use stop_task_kandev instead. - -Behaviour by session state: -- Running/starting: queued delivery waits for turn-end; interrupt delivery follows the direct-parent behavior and safe fallback above. -- Idle (waiting for input or completed): the message is sent immediately as a new turn (delivery_mode has no effect). -- Created (not yet started): the agent is started with this message as its first prompt (delivery_mode has no effect). -- Failed/cancelled: an error is returned. Those states are terminal and cannot be resumed — use spawn_session_kandev to start a new session on the task. - -Session defaulting when session_id is omitted: the task's primary session is used. If the primary is terminal (cancelled/failed) the newest session that can still take a message is used instead, so a task with a live session stays reachable. If every session is terminal, the error says so and names spawn_session_kandev. - -For an autopilot child question, pass reply_to_question_id with the question_id -from the child message. The direct parent answer is recorded against that -question and retries are idempotent. - -Returns the dispatch status: "queued", "sent", or "started".`), + mcp.WithDescription(`Send a prompt to an existing Kandev task session, not a native subagent. Use delivery_mode="queued" (default) for information that can wait, or delivery_mode="interrupt" for urgent replacement work on a running direct child; non-parent interrupts fail and if cancellation is unsafe, the prompt remains queued. Halt-only work uses stop_task_kandev. The primary session is used by default; if it is terminal, Kandev tries the newest session that can accept messages, or names spawn_session_kandev when none can. Pass reply_to_question_id for an autopilot child question. Returns "queued", "sent", or "started".`), mcp.WithString("task_id", mcp.Required(), mcp.Description("The target task's full UUID (not a truncated prefix)")), mcp.WithString("session_id", mcp.Description("Optional target session ID (must belong to task_id). Omit to message the task's primary session. Required when messaging a sibling session on your OWN task (task_id may then be your own task ID) — e.g. a session you spawned with spawn_session_kandev.")), mcp.WithString("prompt", mcp.Required(), mcp.Description("The message to deliver to the task's agent")), @@ -1001,15 +988,11 @@ Returns the dispatch status: "queued", "sent", or "started".`), ) s.mcpServer.AddTool( mcp.NewTool("stop_task_kandev", - mcp.WithDescription(`Stop all live sessions Kandev observes for a direct child task. Only the target task's direct parent may use this tool; self, sibling, child-to-parent, grandparent, unrelated, and cross-workspace requests are rejected. The operation has no session-specific option. - -This is halt-only: it does not send a prompt or start a replacement turn. For urgent stop-and-steer work, use message_task_kandev with delivery_mode="interrupt". For ordinary information that can wait, use message_task_kandev with delivery_mode="queued" or omit delivery_mode. - -For every accepted live execution, Kandev first marks its session CANCELLED, then schedules graceful runtime teardown. An eligible active, unarchived, non-Office task is also moved to REVIEW through the normal guarded transition; other task states are preserved. Runtime teardown continues asynchronously, so status="stopped" confirms logical cancellation and scheduled teardown, not process exit. - -If the child has no live execution, the call succeeds idempotently with status="not_running" and changes no task or session state. Worktrees, environments, commits, task records, descendants, and queued messages are preserved. - -Recovery: a CANCELLED session is terminal and cannot be resumed, so message_task_kandev against it fails. To put the task back to work after stopping it, call spawn_session_kandev with the new prompt — it starts a fresh session in the same workspace, keeping the worktree and history. (Its sessions are otherwise unaffected: use list_task_sessions_kandev if you need to check what is still live.)`), + mcp.WithDescription(`Stop all live sessions on a direct child task. Only its direct parent may call this halt-only tool; self, sibling, parent, grandparent, unrelated, and cross-workspace requests fail. It does not send a prompt or start a replacement turn; use message_task_kandev with delivery_mode="interrupt" to stop and steer. Accepted sessions become CANCELLED and teardown runs asynchronously; an eligible active task moves to REVIEW. If nothing is running, returns status="not_running" without changing state. Worktrees, commits, records, descendants, and queued messages are preserved. CANCELLED sessions cannot be resumed; use spawn_session_kandev with a new prompt to restart in the same workspace.`), + mcp.WithReadOnlyHintAnnotation(false), + mcp.WithDestructiveHintAnnotation(true), + mcp.WithIdempotentHintAnnotation(true), + mcp.WithOpenWorldHintAnnotation(false), mcp.WithString(mcpKeyTaskID, mcp.Required(), mcp.Description("The direct child task's full UUID (not a truncated prefix)")), ), s.wrapHandler("stop_task_kandev", s.stopTaskHandler()), @@ -1089,58 +1072,12 @@ func (s *Server) registerMRAutomationTools() { // guidance differ by mode: in external mode there is no current task, so the // 'self' shorthand is omitted. func (s *Server) registerCreateTaskTool() { - toolDesc := `Create a new task or subtask and auto-start an agent on it. - -WHEN TO USE parent_id='self': -- Breaking down your current task into phases/steps → use parent_id='self' -- Creating tasks from a plan → use parent_id='self' (inherits repo, task workspace, workflow, and materialized workspace by default) -- Delegating work to another agent → use parent_id='self' -- Delegating work that lives in a sibling repo → use parent_id='self' AND pass repository_url / repository_id / local_path to point the subtask at that repo - -WHEN TO OMIT parent_id (top-level task): -- Creating an unrelated, standalone task -- Provide a repository via repository_url, repository_id, or local_path -- workspace_id and workflow_id are auto-resolved if only one exists; provide explicitly if ambiguous - -IMPORTANT: -- Subtasks inherit task workspace, workflow, agent profile, executor, and materialized workspace from the parent by default. Pass workspace_id/workflow_id only when deliberately targeting a different task workspace/workflow; any supplied workflow_id must belong to the effective workspace_id. Pass workspace_mode='new_workspace' when the subtask needs its own materialized workspace/worktree. -- A workflow step's launch profile outranks an explicit agent_profile_id when the task is on a step: that is the step's pinned profile, or the workflow default when the step has none. That profile is what launches, and it is the one reported back in the created task's metadata. Off a step, or when the step and workflow resolve no profile, an explicit agent_profile_id wins. When no workflow profile wins and agent_profile_id is omitted, the saved user policy applies: current_task uses the verified creating session's profile and effective model, mode, and dynamic options for a session-bound call. Without verified session context, it falls back to the current/source task or parent profile, then workflow and target-workspace defaults. workspace_default skips the creating session, current/source task, and parent profiles, honors workflow profiles first, then uses the target workspace default. An explicit agent_profile_id prevents creator-session runtime inheritance. -- Creator-session runtime values are copied only when current_task selects that verified session profile. Executor and executor-profile inheritance from the current/source task or parent is unchanged by either saved agent-profile policy. -- Every created task must have a resolvable agent profile. start_agent=false still records the profile for a later manual start. -- Subtasks inherit the parent's repository unless you supply repository_url, repository_id, or local_path — in which case the subtask targets that repo instead -- base_branch behaviour: - - Same repo as parent (no repo args): subtask inherits the parent's base_branch (sibling branches off the same starting point — useful for PR stacks) - - Different repo (you passed repository_url / repository_id / local_path): subtask defaults to that repo's default_branch - - Pass base_branch explicitly to override either default. Use list_repositories_kandev to see each repo's default_branch. -- Top-level tasks need a repository via repository_url, repository_id, or local_path -- 'prompt' is the sub-agent's initial prompt — be specific and detailed -- start_agent defaults to true and is what you want in nearly every case — the new task auto-launches an agent that immediately works on the prompt. Pass start_agent=false ONLY for an explicit placeholder (e.g. queuing work the user will start later, or creating a tracking task with no immediate work), and still pass agent_profile_id unless it can be inherited. When in doubt, leave it true. -- Kanban subtasks cannot have their own subtasks (max nesting depth is 1). To break work down further, create a sibling under the same parent. (Office task trees are exempt.) - -IDEMPOTENCY (external_id): -- Passing external_id makes this call create-if-absent, not a lookup: it creates the task when nothing holds that identity yet, and it DOES create something the first time you call it. Do not call it just to check whether an identity exists. -- deduplicated:true in the result means a task already held that identity and nothing new was created — do not report having created a task in that case. -- deduplicated:true together with creation_complete:false means another create claimed the identity and had not finished when observed; it may still be running. Proceed with the returned task_id or escalate to a human — never release the identity and create again, which can produce a duplicate task and a duplicate agent.` - parentDesc := "Parent task ID for subtasks. Use 'self' to create a subtask of your current task (RECOMMENDED for plan phases, delegated work). Omit only for unrelated top-level tasks." + toolDesc := `Create a persistent Kandev task or subtask and optionally start its agent. Use only for user-requested Kandev-tracked work; use the host's native subagent mechanism for ordinary delegation. Set parent_id="self" for a subtask of the current task and omit it for an unrelated top-level task. Subtasks inherit the parent's workspace, workflow, repository, profiles, executor, and materialized workspace unless the matching input overrides them. external_id provides create-if-absent idempotency and is not a lookup.` + parentDesc := "Parent task ID for subtasks. Use 'self' for a user-requested Kandev subtask or plan phase. Omit only for unrelated top-level tasks." agentProfileDesc := "Agent profile ID to use. On a workflow step, the step's launch profile (its pinned profile, or the workflow default when unpinned) outranks it; otherwise an explicit agent_profile_id wins. When both are absent, current_task uses the verified creating session's profile and effective model, mode, and dynamic options for a session-bound call, then falls back to the current/source or parent profile without verified session context. workspace_default skips those task profiles and the creating session, then uses workflow profiles before the target workspace default. Explicit profiles do not copy creator-session runtime values. start_agent=false still needs a resolvable profile for later manual start." if s.mode == ModeExternal { - toolDesc = `Create a new top-level task and auto-start an agent on it. - -IMPORTANT: -- Provide a repository via repository_url, repository_id, or local_path -- workspace_id and workflow_id are auto-resolved if only one exists; provide explicitly if ambiguous -- A workflow step's launch profile outranks an explicit agent_profile_id when the task is on a step: that is the step's pinned profile, or the workflow default when the step has none. That profile is what launches, and it is the one reported back in the created task's metadata. Off a step, or when the step and workflow resolve no profile, an explicit agent_profile_id wins. When both are absent, the saved user policy applies: current_task uses the parent task profile because external mode has no creating session or current/source task context, then checks workflow and target-workspace defaults. workspace_default skips the parent profile, honors workflow profiles first, then uses the target workspace default. External mode has no creating session, so it never copies creator-session runtime values. -- Executor and executor-profile inheritance from a parent is unchanged by either saved agent-profile policy. -- Every created task must have a resolvable agent profile. start_agent=false still records the profile for a later manual start. -- 'prompt' is the agent's initial prompt — be specific and detailed -- start_agent defaults to true and is what you want in nearly every case — the new task auto-launches an agent that immediately works on the prompt. Pass start_agent=false ONLY for an explicit placeholder (e.g. queuing work the user will start later), and still pass agent_profile_id unless a default exists. When in doubt, leave it true. -- Use parent_id only when delegating to a known existing task by its ID - -IDEMPOTENCY (external_id): -- Passing external_id makes this call create-if-absent, not a lookup: it creates the task when nothing holds that identity yet, and it DOES create something the first time you call it. Do not call it just to check whether an identity exists. -- deduplicated:true in the result means a task already held that identity and nothing new was created — do not report having created a task in that case. -- deduplicated:true together with creation_complete:false means another create claimed the identity and had not finished when observed; it may still be running. Proceed with the returned task_id or escalate to a human — never release the identity and create again, which can produce a duplicate task and a duplicate agent.` + toolDesc = `Create a persistent Kandev task and optionally start its agent from an external client. Use only for user-requested Kandev-tracked work; use the host's native subagent mechanism for ordinary delegation. Provide a repository for a top-level task; parent_id may target a known task when the user requested a subtask. external_id provides create-if-absent idempotency and is not a lookup.` parentDesc = "Optional parent task ID. Omit for top-level tasks; provide an existing task ID only to create a subtask of that task." agentProfileDesc = "Agent profile ID to use. On a workflow step, the step's launch profile (its pinned profile, or the workflow default when unpinned) outranks it; otherwise an explicit agent_profile_id wins. When both are absent, current_task uses the parent task profile because external mode has no creating session or current/source task context; workspace_default skips the parent profile, then uses workflow profiles before the target workspace default. External mode never copies creator-session runtime values. start_agent=false still needs a resolvable profile for later manual start." } @@ -1154,7 +1091,7 @@ IDEMPOTENCY (external_id): mcp.WithString("workflow_step_id", mcp.Description("The workflow step ID (optional, auto-resolved if omitted; for subtasks, pass only with an explicit workflow_id)")), mcp.WithString("workspace_mode", mcp.Description("Subtask materialized-workspace mode: inherit_parent reuses the parent's worktree/materialized workspace (default for subtasks); new_workspace launches the subtask in its own workspace/worktree.")), mcp.WithString("title", mcp.Required(), mcp.MaxLength(service.TaskTitleMaxLength), mcp.Description("A concise, few-word task title (maximum 60 characters).")), - mcp.WithString("prompt", mcp.Description("The initial prompt for the sub-agent. This is the ONLY context the agent receives when it starts — treat it as the agent's first user message. For auto-started subtasks, provide a specific and detailed prompt; omitting it starts the sub-agent without task-specific context.")), + mcp.WithString("prompt", mcp.Description("The initial prompt for the task agent. This is the ONLY context the agent receives when it starts — treat it as the agent's first user message. For auto-started subtasks, provide a specific and detailed prompt; omitting it starts the task agent without task-specific context.")), mcp.WithBoolean("autopilot", mcp.Description("Start this task in autopilot mode. Default: false. The value is fixed at creation and is not inherited by subtasks. The agent does not ask the user directly; it asks its direct parent only for critical decisions.")), mcp.WithString("agent_profile_id", mcp.Description(agentProfileDesc)), mcp.WithString("executor_profile_id", mcp.Description("Executor profile ID to use (determines the runtime environment: local, worktree, docker, etc.). For subtasks, inherited from the parent session. For top-level tasks, ask the user which executor profile they want if not already known.")), @@ -1196,11 +1133,7 @@ const ( func (s *Server) registerTaskDependencyTools() { s.mcpServer.AddTool( mcp.NewTool("add_task_dependency_kandev", - mcp.WithDescription(`Declare that a task is blocked by another task: it will not start until that one completes successfully. - -`+blockedByParamDesc+` - -task_id defaults to your CURRENT task. Rejected when the edge would create a cycle (the error names the cycle path), when both IDs are the same, or when the two tasks are in different workspaces. Returns the task's resulting depends_on list.`), + mcp.WithDescription(`Block a task until another task completes successfully. Use dependencies for execution order and parent_id for hierarchy. task_id defaults to the current task. Self-dependencies, cross-workspace dependencies, and cycles are rejected. A failed or cancelled predecessor leaves the task blocked for human action. Returns the resulting depends_on list.`), mcp.WithString(mcpKeyTaskID, mcp.Description("The blocked task. Defaults to your current task when omitted.")), mcp.WithString("depends_on_task_id", mcp.Required(), mcp.Description("The task that must complete first (the predecessor).")), ), @@ -1225,16 +1158,8 @@ Removing the last edge unblocks the task but does NOT start it: an automatic sta func (s *Server) registerSpawnSessionTool() { s.mcpServer.AddTool( mcp.NewTool("spawn_session_kandev", - mcp.WithDescription(`Spawn an ADDITIONAL agent session on an existing task (defaults to your current task) and start it with the given prompt. - -Unlike create_task_kandev this does NOT create a new task — the new session runs alongside the task's existing sessions in the same workspace, as a separate session tab. Use it to bring in another agent (or another instance of yourself) on the work you're already doing: a reviewer, a pair of hands for a parallelizable piece, or a different agent profile better suited to a subproblem. - -The spawned session knows it was spawned by you and can reply via message_task_kandev using your task_id + session_id. You can message it the same way using the session_id returned by this tool. - -The returned agent_profile_id is the effective agent profile used by the new session. On a workflow step, the step's launch profile wins: a pinned step profile outranks the requested agent_profile_id, and an unpinned step uses the workflow default. Without a workflow launch profile, an explicit agent_profile_id wins; when omitted, the existing inheritance rules apply. - -Returns {task_id, session_id, state, agent_profile_id}.`), - mcp.WithString("prompt", mcp.Required(), mcp.Description("The spawned session's initial prompt. This is the ONLY context the new agent receives — be specific and detailed.")), + mcp.WithDescription(`Start an additional Kandev session on an existing task. This creates a persistent Kandev session/tab, not a native subagent; call it only when the user explicitly requests another Kandev session or a Kandev workflow requires session coordination. It does not create a task. Returns {task_id, session_id, state, agent_profile_id}; a workflow step may override the requested profile.`), + mcp.WithString("prompt", mcp.Required(), mcp.Description("The Kandev session's initial prompt. This is the ONLY context the new agent receives — be specific and detailed.")), mcp.WithString("agent_profile_id", mcp.Description("Requested agent profile for the new session. Omit to inherit your session's profile; a workflow launch profile may override it.")), mcp.WithString("name", mcp.Description("Optional session name shown on the session tab (e.g. 'reviewer'). Helps the user tell concurrent sessions apart.")), mcp.WithString("task_id", mcp.Description("Task to spawn the session on. Omit to use your current task.")), @@ -1252,11 +1177,11 @@ Returns {task_id, session_id, state, agent_profile_id}.`), func (s *Server) registerListTaskSessionsTool() { s.mcpServer.AddTool( mcp.NewTool("list_task_sessions_kandev", - mcp.WithDescription(`List every agent session attached to a task, most recently started first. - -Use it to find the session_id to pass to get_task_conversation_kandev or message_task_kandev when a task has more than one session — for example after spawn_session_kandev, or to read a sibling session on your own task. Both of those tools default to the task's primary session when session_id is omitted, so other sessions are only reachable by ID. - -Each entry reports session_id, name (the session tab label, if set), state, is_primary (the session the other tools default to), is_current (true for your own session), agent_profile_id, and started/updated/completed timestamps.`), + mcp.WithDescription(`List a task's sessions, newest first. Use the returned session_id with get_task_conversation_kandev or message_task_kandev; those tools otherwise use the primary session. Entries include name, state, is_primary, is_current, agent_profile_id, and timestamps.`), + mcp.WithReadOnlyHintAnnotation(true), + mcp.WithDestructiveHintAnnotation(false), + mcp.WithIdempotentHintAnnotation(true), + mcp.WithOpenWorldHintAnnotation(false), mcp.WithString(mcpKeyTaskID, mcp.Required(), mcp.Description("The task ID whose sessions to list")), ), s.wrapHandler("list_task_sessions_kandev", s.listTaskSessionsHandler()), @@ -1270,17 +1195,7 @@ Each entry reports session_id, name (the session tab label, if set), state, is_p func (s *Server) registerAddBranchToTaskTool() { s.mcpServer.AddTool( mcp.NewTool("add_branch_to_task_kandev", - mcp.WithDescription(`Attach an additional (repository, branch) worktree to an existing task. - -Use this when the task should open more than one PR — same repo with different branches, or a second repository entirely. The new branch gets its own sibling worktree under the task directory and behaves like any other multi-repo entry for changes, PRs, and review surfaces. The running agent and terminals keep their current working directory; use the returned worktree_path for the exact new location. task_workspace_path is the promoted task root used by the Files tree. - -IMPORTANT: -- Only works on tasks running the WORKTREE executor. Tasks on docker / sprites / local-pc / SSH / remote_docker reject this tool because sibling worktrees are a git-worktree-specific layout — other executors bind one workspace path per task and the new branch would silently never appear on disk. -- task_id defaults to your CURRENT task when omitted and must match that task when provided. -- Repository selection (matches create_task_kandev): pass exactly one of repository_id / repository_url / local_path. For single-repo tasks all three are optional — the service auto-resolves to the task's only repository. Multi-repo tasks must identify the target repo explicitly. -- checkout_branch is the branch the new worktree will check out. Leave empty to create a fresh feature branch from base_branch. -- base_branch is optional; defaults to the repository's default_branch. -- The (task_id, repository_id, base_branch, checkout_branch) tuple must be unique on the task — re-adding the same combination is an error, not a no-op.`), + mcp.WithDescription(`Attach another repository branch worktree to the current task for an additional PR or repository. This works only with the worktree executor. Single-repository tasks can omit the repository locator; multi-repository tasks must pass exactly one of repository_id, repository_url, or local_path. checkout_branch selects an existing branch; omit it to create a feature branch from base_branch. Returns worktree_path and task_workspace_path.`), mcp.WithString("task_id", mcp.Description("The current task. Defaults to the current task when omitted.")), mcp.WithString("repository_id", mcp.Description("Repository UUID. Optional for single-repo tasks (auto-resolved). Required for multi-repo tasks unless repository_url or local_path is supplied.")), mcp.WithString("repository_url", mcp.Description("GitHub repository URL (e.g. 'https://github.com/owner/repo'). Alternative to repository_id when you don't have the UUID handy. The repository is found-or-created in the task's workspace.")), @@ -1395,13 +1310,7 @@ func (s *Server) addBranchToTaskHandler() server.ToolHandlerFunc { func (s *Server) registerUpdateRepositoryBaseBranchTool() { s.mcpServer.AddTool( mcp.NewTool("update_repository_base_branch_kandev", - mcp.WithDescription(`Change the base branch used by a task repository for diff stats and the Changes panel. - -Use when a task was created against the wrong base (e.g. picked up `+"`main`"+` when the work was forked from a release / QA / staging branch). The Changes panel and per-task +/- counts compare HEAD against this branch. - -Scope: this updates the value the WorkspaceTracker uses for diff comparison (BaseCommit / Ahead / Behind / cumulative diff). It does NOT auto-set the PR target on push; the PR target is whatever value the caller passes to the create-PR endpoint at push time. Callers that want both to move together should pass the new base_branch on the next PR-create call. - -The agentctl tracker is updated live: a successful call refreshes BaseCommit / Ahead / Behind without needing a session restart.`), + mcp.WithDescription(`Change the base branch used for task diff statistics and the Changes panel. This updates BaseCommit, Ahead, Behind, and cumulative diff immediately without restarting the session. It does not change a pull request's target branch; pass the same base_branch when creating the PR if both must change.`), mcp.WithString("task_id", mcp.Description("The task whose repository to update. Defaults to the current task when omitted.")), mcp.WithString("task_repository_id", mcp.Description("UUID of the task_repositories row to update. Required — disambiguates multi-repo tasks. Find it via list_tasks_kandev's repositories[] field.")), mcp.WithString("base_branch", mcp.Description("New base branch name (e.g. 'staging', 'release/v2.4'). Required.")), @@ -1450,24 +1359,7 @@ func (s *Server) updateRepositoryBaseBranchHandler() server.ToolHandlerFunc { func (s *Server) registerStepCompleteTool() { s.mcpServer.AddTool( mcp.NewTool("step_complete_kandev", - mcp.WithDescription(`Signal that every user-stated requirement for the CURRENT workflow step is satisfied. - -WHEN TO CALL: -- All work for the current step is finished and the task is ready to move forward in the workflow. -- This is the LAST thing you do in the step — call it after the final tool call / commit / answer that completes the requested work. - -WHEN NOT TO CALL: -- You are about to ask the user a question (use ask_user_question_kandev instead and wait). -- The work is partially done or you ran into a blocker you couldn't resolve. -- You are mid-conversation and expect the user to reply with more direction. - -BEHAVIOUR: -- The call is idempotent within a step: subsequent calls return accepted=false with reason="already_signaled" and have no other effect. -- The call returns immediately. The workflow transition (if the step is configured to auto-advance) is driven asynchronously by the orchestrator on turn-end. -- If the user sends another message before the transition fires, the signal is cancelled and the conversation continues on the current step. Call again at the end of the new turn if appropriate. -- For steps that do NOT have auto-advance enabled, the call succeeds (accepted=true) but the workflow does not move automatically. The signal is discarded on the next turn start; there is no separate audit history to query later. - -The summary you provide is shown to the user in chat and may be forwarded to the next step's agent as a hand-off note.`), + mcp.WithDescription(`Signal that every requirement for the current workflow step is complete. Call this as the step's final action; do not call before asking the user, during partial work, or with an unresolved blocker. The signal is idempotent within a step, and any configured transition runs asynchronously at turn end. A new user message cancels a pending signal. The summary is shown to the user and may be forwarded to the next step.`), mcp.WithString("summary", mcp.Required(), mcp.Description("One-paragraph plain-text summary of what was done in this step. Shown to the user.")), mcp.WithString("handoff", mcp.Description("Optional context the next step's agent will need to pick up where you left off (decisions, open files, follow-ups).")), mcp.WithString("blockers", mcp.Description("Optional list of known unresolved issues. Use sparingly — only when the step is complete in the sense that you cannot make further progress without input, not for normal partial work.")), @@ -1482,20 +1374,7 @@ The summary you provide is shown to the user in chat and may be forwarded to the func (s *Server) registerSetTaskTitleTool() { s.mcpServer.AddTool( mcp.NewTool("set_task_title_kandev", - mcp.WithDescription(`Set the user-facing title for the CURRENT task. - -Call this as your first action in the session, before planning, inspecting files, -or doing any other work. The task currently has a provisional title derived from -the prompt; call this tool even when that provisional title looks usable. - -Use a concise title targeting about 6 words. -Write a short title phrase, not a sentence or a progress update. Your title should -summarize the requested outcome and will replace the provisional title. For tasks created -without a title, Kandev also uses this final title when naming Kandev-generated branches; -branches checked out from a remote link (such as a GitHub PR) and local-executor branches -are intentionally preserved. Use sentence case: -capitalize only the first word and proper nouns (for example, "Improve task title casing", not -"Improve Task Title Casing").`), + mcp.WithDescription(`Replace the current task's provisional title. Call this as the session's first action, even when the provisional title looks usable. Use a short title phrase in sentence case, targeting about 6 words and summarizing the requested outcome. Do not use a sentence or progress update (for example, "Improve task title casing"). Kandev may also use it for generated branch names.`), mcp.WithString(titleArg, mcp.Required(), mcp.Description("Short sentence-case task title targeting about 6 words.")), ), s.wrapHandler("set_task_title_kandev", s.setTaskTitleHandler()), @@ -1550,66 +1429,31 @@ func (s *Server) stepCompleteHandler() server.ToolHandlerFunc { } } +const askUserQuestionOutputSchema = `{ + "type": "object", + "properties": { + "rejected": {"type": "boolean", "description": "True when the user rejected the question bundle."}, + "reject_reason": {"type": "string", "description": "Optional reason supplied when the bundle was rejected."} + }, + "additionalProperties": { + "type": "object", + "description": "Answer keyed by question id.", + "properties": { + "selected_option": {"type": "string"}, + "custom_text": {"type": "string"}, + "answered": {"type": "boolean"}, + "rejected": {"type": "boolean"} + }, + "additionalProperties": false + } +}` + func (s *Server) registerInteractionTools() { s.mcpServer.AddTool( mcp.NewTool("ask_user_question_kandev", - mcp.WithDescription(`Ask the user one or more clarifying questions in a single tool call. - -Use this tool when you need user input to proceed. Bundle related questions -together in one call so the user answers them all in one back-and-forth instead -of sequential round-trips. Each question is rendered as its own card; the user -selects an option or provides a custom text response per question, and the -agent receives a map keyed by question id once every question has been answered. - -IMPORTANT: -- Provide 1 to 4 questions per call. -- Each question must have 2 to 6 concrete, actionable options. -- Each option must have a short "label" (1-5 words) and a "description" - explaining what selecting it means. NEVER use meta-text like "Answer below". -- Only call this tool when you genuinely need information you cannot infer. - -Example usage: -{ - "questions": [ - { - "id": "db", - "prompt": "Which database should I use for this project?", - "options": [ - {"label": "PostgreSQL", "description": "Relational, good for complex queries"}, - {"label": "MongoDB", "description": "Document database, flexible schema"}, - {"label": "SQLite", "description": "Embedded, simple setup"} - ] - }, - { - "id": "migration", - "prompt": "How should I handle the existing user data during migration?", - "options": [ - {"label": "Migrate all", "description": "Keep all existing records"}, - {"label": "Archive old", "description": "Archive records older than 1 year"}, - {"label": "Fresh start", "description": "Delete existing data and start fresh"} - ] - } - ], - "context": "Backend redesign — picking the persistence layer and migration policy together." -} - -The response is a JSON object keyed by each question id. Each entry may include -"selected_option" (the option_id the user picked), "custom_text" (the user's -free-form answer; can co-exist with a selected option), or "answered": false -when the user did not respond to that question. When the user skipped the entire -bundle, the envelope also carries "rejected": true and an optional -"reject_reason". Example success response: -{ - "db": {"selected_option": "q1_opt1"}, - "migration": {"custom_text": "Migrate all but flag rows older than 2 years"} -} -Example rejection: -{ - "rejected": true, - "reject_reason": "User skipped", - "db": {"answered": false, "rejected": true}, - "migration": {"answered": false, "rejected": true} -}`), + mcp.WithDescription(`Ask the user 1-4 related questions and wait for all answers. Each question requires a prompt and 2-6 concrete options with short labels and descriptions; use a stable id when response keys matter. Call only when required input cannot be inferred, and bundle related questions in one call. Returns answers keyed by question id; a rejected bundle includes rejected=true and may include reject_reason.`), + mcp.WithDestructiveHintAnnotation(false), + mcp.WithRawOutputSchema(json.RawMessage(askUserQuestionOutputSchema)), mcp.WithArray(questionsArg, mcp.Required(), mcp.Description(`Array of 1-4 question objects. Each question must have a "prompt" (the question text) and an "options" array (2-6 entries with label + description). Optional fields: "id" (stable identifier in the response map; auto-generated if omitted), "title" (≤12 chars short label).`), mcp.MinItems(1), @@ -1682,20 +1526,7 @@ func (s *Server) registerPlanTools() { func (s *Server) registerWalkthroughTools() { s.mcpServer.AddTool( mcp.NewTool("show_walkthrough_kandev", - mcp.WithDescription( - "Show and store a guided code walkthrough for this task. Accepts an ordered list of "+ - "steps; each step anchors a short markdown explanation to a specific file line or "+ - "line range, and renders as a popover over the review diff/editor. The user cycles "+ - "through steps with Previous and Next. The walkthrough is saved to the task and "+ - "replaces any prior one. Only reference files that exist in the task's local worktree "+ - "or current review diff; for PR-only files, do not assume the PR head is checked out "+ - "locally. Use line_end when a logical explanation spans multiple lines. "+ - "Use this after producing a change to narrate the diff (what each hunk does and why), "+ - "or to explain how a part of the codebase works. Order steps to follow the reader's "+ - "natural path through the code (entry point first, then the call chain). Keep text "+ - "concise and do not add a 'Justification:' preamble. task_id defaults to your current "+ - "task; pass another task's ID to target it directly, allowed only within your reach "+ - "(same workspace / task tree)."), + mcp.WithDescription("Store an ordered, file-anchored code walkthrough that replaces any prior walkthrough on the task. Use it to narrate a completed diff or explain a code path; order steps from the entry point through the call chain. Reference only files in the local worktree or current review diff, and use line_end for a range. task_id defaults to the current task and may target another task within your reach."), mcp.WithString("task_id", mcp.Description("The task ID to attach the walkthrough to. Defaults to your current task when omitted; pass another task's ID (within your reach — same workspace / task tree) to target it directly.")), mcp.WithString("title", mcp.Description("Optional title for the walkthrough (default: 'Walkthrough')")), mcp.WithArray("steps", mcp.Required(), @@ -1728,19 +1559,7 @@ func (s *Server) registerWalkthroughTools() { func (s *Server) registerReviewTools() { s.mcpServer.AddTool( mcp.NewTool("publish_review_findings_kandev", - mcp.WithDescription( - "Publish code-review findings for this task. Each finding anchors a markdown explanation "+ - "to a file and line range in the task's current changes, and renders as an inline "+ - "review comment the user can resolve, dismiss, or send back to an agent. Findings are "+ - "advisory: nothing is applied automatically. Only anchor to files that appear in the "+ - "task's current changes, and use line numbers from the new version of the file. "+ - "Report real defects — correctness, security, concurrency, error handling, resource "+ - "leaks, contract breaks, missing tests — not style or formatting a linter owns. "+ - "Be honest with severity; marking everything a blocker makes the review useless. "+ - "Publishing adds to the task's findings; it does not replace earlier ones, except "+ - "that an unresolved finding with the same file, line range, and title is refreshed. "+ - "task_id defaults to your current task; pass another task's ID to target it directly, "+ - "allowed only within your reach (same workspace / task tree)."), + mcp.WithDescription("Publish actionable code-review findings as comments anchored to the task's current changes. Use changed files and line numbers from the new version. Report correctness, security, concurrency, error handling, resource, contract, or test defects rather than linter-owned style. Findings are advisory and additive; an unresolved finding with the same anchor and title is refreshed. task_id defaults to the current task and may target another task within your reach."), mcp.WithString("task_id", mcp.Description("The task ID to attach the findings to. Defaults to your current task when omitted; pass another task's ID (within your reach — same workspace / task tree) to target it directly.")), mcp.WithString("summary", mcp.Description("Optional one-paragraph summary of the review")), mcp.WithArray("findings", mcp.Required(), diff --git a/apps/backend/internal/mcp/server/server_test.go b/apps/backend/internal/mcp/server/server_test.go index 84226a0511..60d049077c 100644 --- a/apps/backend/internal/mcp/server/server_test.go +++ b/apps/backend/internal/mcp/server/server_test.go @@ -983,12 +983,16 @@ func TestServerModeExternal_RegistersCorrectTools(t *testing.T) { // External mode includes create_task_kandev so external agents can spawn tasks assert.Contains(t, tools, "create_task_kandev") createTask := s.mcpServer.ListTools()["create_task_kandev"] - assert.Contains(t, createTask.Tool.Description, "outranks an explicit agent_profile_id") - assert.Contains(t, createTask.Tool.Description, "current_task") - assert.Contains(t, createTask.Tool.Description, "workspace_default") - assert.Contains(t, createTask.Tool.Description, "workflow profiles first") - assert.Contains(t, createTask.Tool.Description, "no creating session") - assert.Contains(t, createTask.Tool.Description, "parent task profile") + assert.Contains(t, createTask.Tool.Description, "external client") + assert.Contains(t, createTask.Tool.Description, "native subagent mechanism") + assert.Contains(t, createTask.Tool.Description, "external_id") + agentProfile := toolInputProperties(t, s, "create_task_kandev")["agent_profile_id"].(map[string]interface{}) + agentProfileDescription := agentProfile["description"].(string) + assert.Contains(t, agentProfileDescription, "current_task") + assert.Contains(t, agentProfileDescription, "workspace_default") + assert.Contains(t, agentProfileDescription, "workflow profiles") + assert.Contains(t, agentProfileDescription, "parent task profile") + assert.Contains(t, agentProfileDescription, "External mode never copies creator-session runtime values") // External mode does NOT include session-scoped tools assert.NotContains(t, tools, "ask_user_question_kandev") diff --git a/apps/backend/internal/mcp/server/spawn_session_tool_test.go b/apps/backend/internal/mcp/server/spawn_session_tool_test.go index 73dcbf69f7..e8c62b9307 100644 --- a/apps/backend/internal/mcp/server/spawn_session_tool_test.go +++ b/apps/backend/internal/mcp/server/spawn_session_tool_test.go @@ -14,8 +14,13 @@ func TestSpawnSessionToolDescribesEffectiveAgentProfile(t *testing.T) { require.True(t, ok, "spawn_session_kandev must be registered in task mode") description := tool.Tool.Description + assert.Contains(t, description, "not a native subagent") + assert.Contains(t, description, "only when the user explicitly requests another Kandev session") + assert.Contains(t, description, "does not create a task") + assert.NotContains(t, description, "pair of hands") + assert.NotContains(t, description, "parallelizable piece") assert.Contains(t, description, "agent_profile_id") - assert.Contains(t, description, "effective agent profile") + assert.Contains(t, description, "workflow step may override") assert.Contains(t, description, "Returns {task_id, session_id, state, agent_profile_id}") profileProperty, ok := toolInputProperties(t, s, "spawn_session_kandev")["agent_profile_id"].(map[string]interface{}) diff --git a/apps/backend/internal/mcp/server/sysprompt_sync_test.go b/apps/backend/internal/mcp/server/sysprompt_sync_test.go index 4a9a61f7fc..ec744ac26a 100644 --- a/apps/backend/internal/mcp/server/sysprompt_sync_test.go +++ b/apps/backend/internal/mcp/server/sysprompt_sync_test.go @@ -114,9 +114,9 @@ func TestSyspromptToolNames_MatchMCPTaskMode(t *testing.T) { } // TestTaskControlDocs_MatchMessageSchemaAndStopChoice keeps the short injected -// context aligned with the task-control choices exposed by task-mode MCP. The -// full tool descriptions remain authoritative for lifecycle detail, but the -// first-turn context must make the queue/interrupt/stop decision discoverable. +// context aligned with the task-control choices exposed by task-mode MCP. Tool +// descriptions carry tool-specific behavior, while the first-turn context makes +// the queue/interrupt/stop relationship discoverable. func TestTaskControlDocs_MatchMessageSchemaAndStopChoice(t *testing.T) { log := newTestLogger(t) backend := NewChannelBackendClient(log) @@ -408,9 +408,8 @@ func TestAskUserQuestionDocs_MatchSchema(t *testing.T) { facts := taskFacts bounds := fmt.Sprintf("%d-%d", facts.minItems, facts.maxItems) - // Each prompt must mention the array param name, the bounds, and every - // required sub-field name. We assert phrases (not exact wording) so authors - // can rewrite the prose freely as long as the load-bearing facts survive. + // The shared contexts advertise the tool and bundle size. The input schema is + // authoritative for per-question fields so that prompt text does not repeat it. cases := map[string]string{ "KandevContext": sysprompt.KandevContext(), "ConfigContext": sysprompt.ConfigContext(), @@ -420,10 +419,6 @@ func TestAskUserQuestionDocs_MatchSchema(t *testing.T) { "%s must mention ask_user_question param name %q", name, facts.paramName) assert.Contains(t, prompt, bounds, "%s must mention the question-count bounds %q from the schema", name, bounds) - for _, field := range facts.requiredFields { - assert.Contains(t, prompt, field, - "%s must mention required question sub-field %q", name, field) - } } } @@ -480,17 +475,13 @@ func TestWalkthroughDocs_MatchSchema(t *testing.T) { "KandevContext must advertise task-mode walkthrough tool %q", toolName) } - for name, prompt := range map[string]string{ - "KandevContext": context, - "ChangesWalkthrough": promptcfg.Get("changes-walkthrough"), - } { - assert.Contains(t, prompt, "`steps`", - "%s must identify the walkthrough steps parameter", name) - assert.Contains(t, prompt, "ordered array", - "%s must say walkthrough steps preserve order", name) - for _, field := range requiredFields { - assert.Contains(t, prompt, fmt.Sprintf("`%s`", field), - "%s must identify required walkthrough step field %q", name, field) - } + prompt := promptcfg.Get("changes-walkthrough") + assert.Contains(t, prompt, "`steps`", + "ChangesWalkthrough must identify the walkthrough steps parameter") + assert.Contains(t, prompt, "ordered array", + "ChangesWalkthrough must say walkthrough steps preserve order") + for _, field := range requiredFields { + assert.Contains(t, prompt, fmt.Sprintf("`%s`", field), + "ChangesWalkthrough must identify required walkthrough step field %q", field) } } diff --git a/apps/backend/internal/mcp/server/tool_metadata_test.go b/apps/backend/internal/mcp/server/tool_metadata_test.go new file mode 100644 index 0000000000..9e6fc9d0ac --- /dev/null +++ b/apps/backend/internal/mcp/server/tool_metadata_test.go @@ -0,0 +1,144 @@ +package mcp + +import ( + "encoding/json" + "testing" + "unicode/utf8" + + mcplib "github.com/mark3labs/mcp-go/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCoreToolDescriptionsStayFocused(t *testing.T) { + s := newTaskModeServer(t, &testBackend{}, "task-current") + + limits := map[string]int{ + "create_task_kandev": 700, + "message_task_kandev": 650, + "stop_task_kandev": 700, + "spawn_session_kandev": 600, + "add_branch_to_task_kandev": 650, + "step_complete_kandev": 650, + "ask_user_question_kandev": 600, + "show_walkthrough_kandev": 650, + "publish_review_findings_kandev": 650, + "update_repository_base_branch_kandev": 500, + "add_task_dependency_kandev": 500, + "list_related_tasks_kandev": 500, + } + for name, limit := range limits { + t.Run(name, func(t *testing.T) { + tool, ok := s.mcpServer.ListTools()[name] + require.True(t, ok) + assert.LessOrEqual(t, utf8.RuneCountInString(tool.Tool.Description), limit) + }) + } +} + +func TestTaskTitleDescriptionStaysFocused(t *testing.T) { + s := New(&testBackend{}, "test-session", "task-current", 10005, newTestLogger(t), "", false, ModeTaskTitlePending) + tool, ok := s.mcpServer.ListTools()["set_task_title_kandev"] + require.True(t, ok) + assert.LessOrEqual(t, utf8.RuneCountInString(tool.Tool.Description), 500) +} + +func TestDelegationPolicyLivesInSharedContext(t *testing.T) { + s := newTaskModeServer(t, &testBackend{}, "task-current") + + for _, name := range []string{"create_task_kandev", "message_task_kandev", "spawn_session_kandev"} { + tool, ok := s.mcpServer.ListTools()[name] + require.True(t, ok) + assert.NotContains(t, tool.Tool.Description, "DELEGATION POLICY") + } +} + +func TestCoreToolRiskAnnotations(t *testing.T) { + s := newTaskModeServer(t, &testBackend{}, "task-current") + + tests := []struct { + name string + readOnly bool + destructive bool + idempotent bool + openWorld bool + }{ + {name: "list_task_sessions_kandev", readOnly: true, destructive: false, idempotent: true, openWorld: false}, + {name: "archive_task_kandev", readOnly: false, destructive: false, idempotent: true, openWorld: false}, + {name: "delete_task_kandev", readOnly: false, destructive: true, idempotent: false, openWorld: false}, + {name: "stop_task_kandev", readOnly: false, destructive: true, idempotent: true, openWorld: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tool, ok := s.mcpServer.ListTools()[tt.name] + require.True(t, ok) + annotations := tool.Tool.Annotations + require.NotNil(t, annotations.ReadOnlyHint) + require.NotNil(t, annotations.DestructiveHint) + require.NotNil(t, annotations.IdempotentHint) + require.NotNil(t, annotations.OpenWorldHint) + assert.Equal(t, tt.readOnly, *annotations.ReadOnlyHint) + assert.Equal(t, tt.destructive, *annotations.DestructiveHint) + assert.Equal(t, tt.idempotent, *annotations.IdempotentHint) + assert.Equal(t, tt.openWorld, *annotations.OpenWorldHint) + }) + } +} + +func TestConfigTaskRiskAnnotationsMatchTaskMode(t *testing.T) { + s := New(&testBackend{}, "test-session", "", 10005, newTestLogger(t), "", false, ModeConfig) + + archive := s.mcpServer.ListTools()["archive_task_kandev"].Tool.Annotations + require.NotNil(t, archive.DestructiveHint) + require.NotNil(t, archive.IdempotentHint) + require.NotNil(t, archive.OpenWorldHint) + assert.False(t, *archive.DestructiveHint) + assert.True(t, *archive.IdempotentHint) + assert.False(t, *archive.OpenWorldHint) + + deleteTool := s.mcpServer.ListTools()["delete_task_kandev"].Tool.Annotations + require.NotNil(t, deleteTool.DestructiveHint) + require.NotNil(t, deleteTool.OpenWorldHint) + assert.True(t, *deleteTool.DestructiveHint) + assert.False(t, *deleteTool.OpenWorldHint) +} + +func TestAskUserQuestionPublishesAndReturnsStructuredOutput(t *testing.T) { + backend := &testBackend{response: map[string]interface{}{ + "answers": []interface{}{map[string]interface{}{ + "question_id": "q1", + "selected_options": []interface{}{"q1_opt1"}, + }}, + }} + s := newTaskModeServer(t, backend, "task-current") + + tool, ok := s.mcpServer.ListTools()["ask_user_question_kandev"] + require.True(t, ok) + require.NotEmpty(t, tool.Tool.RawOutputSchema) + var schema map[string]interface{} + require.NoError(t, json.Unmarshal(tool.Tool.RawOutputSchema, &schema)) + assert.Equal(t, "object", schema["type"]) + assert.Contains(t, schema["properties"], "rejected") + assert.Contains(t, schema["properties"], "reject_reason") + assert.NotNil(t, schema["additionalProperties"]) + + result := callTool(t, s, "ask_user_question_kandev", map[string]interface{}{ + "questions": []map[string]interface{}{{ + "id": "q1", + "prompt": "Which database?", + "options": []map[string]interface{}{ + {"label": "Postgres", "description": "Relational"}, + {"label": "SQLite", "description": "Embedded"}, + }, + }}, + }) + require.False(t, result.IsError) + structured, ok := result.StructuredContent.(map[string]interface{}) + require.True(t, ok) + answer, ok := structured["q1"].(map[string]interface{}) + require.True(t, ok) + assert.Equal(t, "q1_opt1", answer["selected_option"]) + content, ok := result.Content[0].(mcplib.TextContent) + require.True(t, ok) + assert.JSONEq(t, `{"q1":{"selected_option":"q1_opt1"}}`, content.Text) +} diff --git a/apps/backend/internal/sysprompt/sysprompt.go b/apps/backend/internal/sysprompt/sysprompt.go index 47c45fe268..c42bd2d64a 100644 --- a/apps/backend/internal/sysprompt/sysprompt.go +++ b/apps/backend/internal/sysprompt/sysprompt.go @@ -132,7 +132,7 @@ func KandevContext() string { }) } -const userQuestionSection = `- ask_user_question_kandev: Ask the user one or more clarifying questions in a single tool call. Use this whenever you need user input to proceed. Required params: questions (array of 1-4 question objects; each object has prompt (string) and options (array of 2-6 {label, description})). Optional: context (string). +const userQuestionSection = `- ask_user_question_kandev: Ask the user 1-4 related questions and wait for all answers. Use this whenever you need user input to proceed. ` const parentQuestionSection = `- ask_parent_question_kandev: Ask the direct parent task one or more critical questions. Use this only when you cannot continue safely without a parent decision. The question is sent to the parent task, and this call MUST end your turn; do not use an operator-question tool. @@ -153,13 +153,10 @@ This task runs in autopilot mode. Continue independently and make reasonable dec // without forcing the template to add its own. Dropping the "\n" silently // merges the two bullets onto one line; the omit path (empty string) is // unaffected since the next line in the template already starts the bullet. -const stepCompleteSection = "- step_complete_kandev: Signal that every user-stated requirement for the CURRENT workflow step is satisfied. " + - "This is the canonical MCP protocol name; a client registry may display the client-specific alias mcp__kandev__step_complete_kandev for the same tool. " + - "If the tool is not already visible, use the client's tool search/discovery with the canonical name. " + - "Call this as the LAST action of the step (after the final tool call / commit / answer). " + - "Idempotent — a second call within the same step is a no-op. " + - "Do NOT call when asking a question, mid-conversation, or on partial progress. " + - "Required params: summary (one-paragraph plain text). Optional: handoff, blockers.\n" +const stepCompleteSection = "- step_complete_kandev: Signal that every requirement for the CURRENT workflow step is satisfied. " + + "Call it as the LAST action, never before a question or during partial progress. " + + "If it is not visible, use the client's tool search/discovery with the canonical name; some clients display mcp__kandev__step_complete_kandev. " + + "Required param: summary.\n" // coordinatorTaskControlSection documents task-mode-only parent/child controls. // Restricted MCP modes omit the section because neither message_task_kandev nor diff --git a/apps/backend/internal/sysprompt/sysprompt_test.go b/apps/backend/internal/sysprompt/sysprompt_test.go index 54114667be..8fdd625034 100644 --- a/apps/backend/internal/sysprompt/sysprompt_test.go +++ b/apps/backend/internal/sysprompt/sysprompt_test.go @@ -117,6 +117,17 @@ func TestFormatKandevContext_OmitsStepCompleteToolByDefault(t *testing.T) { assert.NotContains(t, result, "{step_complete_section}") } +func TestKandevContext_PrefersNativeSubagentsForOrdinaryDelegation(t *testing.T) { + context := FormatKandevContext("task-abc", "session-xyz", false) + + assert.Contains(t, context, "DELEGATION POLICY") + assert.Contains(t, context, "native subagent mechanism") + assert.Contains(t, context, "only when the user has explicitly authorized delegation") + assert.Contains(t, context, "user explicitly wants a persistent Kandev task or subtask") + assert.Contains(t, context, "user explicitly wants another Kandev session/tab") + assert.Contains(t, context, "do not silently create a Kandev task or session") +} + func TestFormatKandevContext_TitleToolFollowsCapability(t *testing.T) { withoutTitle := FormatKandevContextWithOptions("task-abc", "session-xyz", KandevContextOptions{}) assert.NotContains(t, withoutTitle, "set_task_title_kandev") @@ -568,7 +579,7 @@ func TestContexts_DocumentCurrentAskUserQuestionSchema(t *testing.T) { "KandevContext": KandevContext(), } { assert.Contains(t, ctx, "questions", "%s should mention the questions array param", name) - assert.Contains(t, ctx, "1-4 question objects", "%s should document the 1-4 question limit", name) + assert.Contains(t, ctx, "1-4", "%s should document the question limit", name) assert.NotContains(t, ctx, "Required params: prompt (string), options", "%s leaks the legacy ask_user_question schema", name) assert.NotContains(t, ctx, "Required: prompt, options", "%s leaks the legacy ask_user_question schema", name) } diff --git a/apps/web/hooks/domains/session/use-workspace-content-search.test.ts b/apps/web/hooks/domains/session/use-workspace-content-search.test.ts index ecea8f2896..f9a42bec32 100644 --- a/apps/web/hooks/domains/session/use-workspace-content-search.test.ts +++ b/apps/web/hooks/domains/session/use-workspace-content-search.test.ts @@ -234,6 +234,30 @@ describe("useWorkspaceContentSearch validation and failures", () => { expect(result.current.results).toEqual([primary, extra]); }); + + it("publishes matches before retry polling completes", async () => { + const match = { + repository_name: "primary", + path: "src/match.ts", + line: 1, + column: 1, + preview: "needle", + match_ranges: [], + }; + mockSearchWorkspaceContent.mockResolvedValue({ results: [match] }); + const { result } = renderHook(() => + useWorkspaceContentSearch({ + enabled: true, + query: "needle", + sessionId: "session-1", + }), + ); + + await act(async () => vi.advanceTimersByTimeAsync(250)); + + expect(result.current.results).toEqual([match]); + expect(result.current.isSearching).toBe(true); + }); }); describe("useWorkspaceContentSearch stale responses", () => {