Thanks to visit codestin.com
Credit goes to docs.qoder.com

Skip to main content
Tools & Extensions

Subagents

Subagents are specialized roles that the main session can delegate to temporarily. The Qoder Agent SDK supports two kinds of subagents:
  • Built-in subagents: Provided by qodercli, such as general search, code exploration, planning, and related roles.
  • Custom subagents: Defined by SDK users through options.agents, suitable for business review, test execution, security analysis, and other specialized roles.
This guide focuses on using built-in subagents from the SDK and defining custom subagents when needed. You can read it from top to bottom or jump to a specific configuration item. For complete type definitions, see Agents Reference. Unless stated otherwise, "Agent" in this page means a subagent the main session can delegate to; options.agent is the special usage that runs a subagent definition as the main-session role.

Built-in Subagents

When using a built-in subagent, you do not need to write the subagent definition yourself. You only need to know its name and reference it from the SDK. Common built-in subagents currently provided by qodercli:
NamePurpose
general-purposeGeneral-purpose subagent, suitable for searching code, researching complex problems, and executing multi-step tasks
ExploreRead-only code exploration subagent, suitable for quickly finding files, searching keywords, and understanding code structure
PlanRead-only planning subagent, suitable for designing implementation plans, identifying key files, and analyzing architectural tradeoffs
The built-in subagent list can change with the qodercli version and current configuration. In the interactive CLI, enter /agents to view the currently discovered subagents. From the command line, you can also run:
qodercli agents list
After the SDK session initializes, you can read the subagents actually available in the current session:
import { query } from '@qoder-ai/qoder-agent-sdk';

const q = query({ prompt: 'List available agents.' });
const agents = await q.supportedAgents();
The returned list includes subagents registered via options.agents as well as built-in, user, project, and plugin subagents the CLI has discovered that apply to SDK scenarios. general-purpose, Explore, and Plan can appear in SDK sessions by default; the interactive-CLI helpers qoder-guide and statusline-setup are not supported in SDK sessions and won't appear in the results. See AgentInfo for the structure.

Using Built-in Subagents

Run as the Main Session Role

If you want the whole session to run under a built-in subagent role, pass the built-in subagent name directly to options.agent. You do not need to redefine it in options.agents.
import { query } from '@qoder-ai/qoder-agent-sdk';

const q = query({
  prompt: 'Summarize this project architecture and identify the most important modules.',
  options: {
    agent: 'general-purpose',
  },
});
options.agent can reference a subagent registered by the SDK, or a built-in, user, project, or plugin subagent discovered by the current CLI and suitable for SDK sessions.

Delegate as a Subagent

Subagent delegation happens through the built-in Agent tool. The main session's available tool set must include Agent; otherwise the model has no entry point for delegation. In SDK usage, a common pattern is to pre-authorize that tool call path and name the desired subagent in the prompt.
const q = query({
  prompt: 'Use the Explore agent to find where authentication is implemented.',
  options: {
    // Pre-authorize Agent tool calls. If options.tools restricts the tool set, include 'Agent' there too.
    allowedTools: ['Agent'],
  },
});
allowedTools: ['Agent'] / allowed_tools=["Agent"] pre-approves this class of tool calls; if you also narrow the main session's tool set with options.tools, include Agent there too. Never put Agent in the denylist. Subagent names must match the current discovery results, including case. Current built-in names include Explore, Plan, and general-purpose. When unsure, read the supported subagent list first.

Custom Subagents

When built-in subagents do not fit your business or project constraints, define custom subagents with options.agents. For example:
  • Read-only code review subagent: can only read files and search, and cannot modify code.
  • Test execution subagent: can run test commands and analyze failure reasons.
  • Security review subagent: focuses only on authentication, authorization, injection, sensitive information leakage, and related risks.
  • Business support subagent: can only call specific MCP tools, such as order lookup, ticket search, or internal knowledge base search.
Custom subagents usually involve three steps:
  1. Define the subagent name, usage description, and system prompt in options.agents.
  2. Narrow the tools it can use with tools or disallowedTools.
  3. Let the main session delegate to it through the Agent tool, or use options.agent to let it drive the main session directly.
The Agent tool is required: custom subagents are delegated to via the built-in Agent tool, so the tool allowlist must include Agent.

Defining Custom Subagents with options.agents

Minimal example: register a read-only code review subagent.
import { query } from '@qoder-ai/qoder-agent-sdk';

const q = query({
  prompt: 'Use the code-reviewer agent to review the authentication module.',
  options: {
    // Pre-authorize Agent tool calls. If options.tools restricts the tool set, include 'Agent' there too.
    allowedTools: ['Agent'],
    agents: {
      'code-reviewer': {
        description:
          'Reviews code for correctness, security issues, and maintainability problems.',
        prompt: `You are a code review specialist.
Review the requested code and report concrete findings.
Sort findings by severity and include file paths when possible.`,
        tools: ['Read', 'Grep', 'Glob'],
      },
    },
  },
});

for await (const message of q) {
  // Consume streamed messages according to your application needs.
}
There are three key points in this example:
  • options.agents registers the custom subagent available to this session.
  • Subagent delegation happens through the Agent tool; that call path must be pre-approved here.
  • The subagent's own tools only allow reading and searching, so it cannot edit files or execute commands.

options.agents Input

options.agents maps subagent names to subagent definitions. Full type in AgentDefinition.
FieldTypeRequiredHow to set itDescription
descriptionstringYesOne sentence describing when to use this subagentRouting description for the model; affects whether it is invoked
promptstringYesThe subagent's role, boundaries, and output requirementsSystem prompt for this subagent
toolsstring[]NoFor example ['Read', 'Grep', 'Glob']Tool allowlist; when set, only listed tools can be used
disallowedToolsstring[]NoFor example ['Bash', 'Write']Tool blocklist, useful when excluding only a few tools
modelstringNoFor example 'inherit', 'auto', 'performance'Model configuration for the subagent
maxTurnsnumberNoFor example 8Limits how many turns the subagent may execute
effortEffortLevelNoFor example 'low', 'medium', 'high', 'max'Controls reasoning effort
permissionModePermissionModeNoFor example 'default', 'acceptEdits', 'plan'Controls the permission mode for tool calls inside the subagent
skillsstring[]NoFor example ['review']Skills preloaded into the subagent context
mcpServersAgentMcpServerSpec[]NoMCP server names or configurationsLimits or adds MCP servers for the subagent
initialPromptstringNoFirst-turn automatic inputOnly takes effect when this subagent becomes the main session role through options.agent
Python note: AgentDefinition field names use protocol-style camelCase—disallowedTools, maxTurns, initialPrompt, permissionMode—not disallowed_tools, max_turns.

Configuring the Subagent Role

description and prompt are the two most important fields for a custom subagent.

description

description says "when this subagent should be used". The model uses it to decide whether to delegate.
description: 'Runs project tests, analyzes failing output, and suggests fixes.'
A good description should state the task boundary clearly. Avoid generic descriptions such as A helpful agent or Helper.

prompt

prompt defines the subagent's role, boundaries, and output style. TypeScript type-checking fails without prompt; Python's AgentDefinition constructor requires it as well.
prompt: `You are a code review specialist.
Only review the requested code; do not edit files.
Return findings sorted by severity, with file paths and suggested fixes.`
If prompt is just a generic "you are a helpful assistant", the model may still call the subagent, but it will behave like an ordinary assistant: unclear on what to check first, what to avoid, and how to return results. At minimum, prompt should explain three things:
What to explainExample
What task it ownsReview code for security and maintainability issues.
What it should not doDo not edit files. Do not run commands.
How to return resultsReturn findings sorted by severity with file paths.

Configuring Model and Reasoning

First make description and prompt clear, then consider model, effort, and maxTurns. The former decides whether the subagent is invoked correctly and whether it understands its boundaries. The latter mainly tunes quality, speed, and cost after the role is clear.
OptionControlsWhen to adjust first
modelSelects the subagent's model tierThe subagent handles a fixed task type long-term and needs stable control over capability and cost
effortHow much reasoning budget to spend under the same modelThe same subagent occasionally receives a more complex task that needs more careful reasoning
maxTurnsThe maximum number of turnsThe task may explore too deeply or run too long, or you want a hard cost limit
Use this order of judgment:
  1. Start with no setting, or set model: 'inherit', so the subagent follows the main session model.
  2. For frequent, simple, low-risk tasks, use model: 'efficient' or model: 'lite' to reduce cost.
  3. For architecture design, complex refactors, cross-module reviews, and other high-risk tasks, use model: 'performance' or model: 'ultimate'.
  4. If the model tier stays the same but you want the subagent to think more on the current task, increase effort.
  5. If you are worried about runaway exploration, combine it with maxTurns.
Common combinations:
ScenarioRecommended configurationDescription
Quick Q&A, format conversion, simple locatingmodel: 'efficient', effort: 'low', maxTurns: 3Cheap and fast, suitable for low-risk tasks
Read-only code exploration and module mappingmodel: 'auto' or 'inherit', effort: 'medium'Let routing or the main session model decide the capability tier
Code review, security review, migration planmodel: 'performance', effort: 'high'Better for tasks that require careful tradeoffs and issue discovery
Complex system design and difficult analysismodel: 'ultimate', effort: 'high' or 'max'Higher cost; recommended only for critical complex tasks
Batch helper subtasksmodel: 'efficient', effort: 'low', smaller maxTurnsHelps control total cost in multi-subagent collaboration
Example: give different subagents different strategies.
agents: {
  explorer: {
    description: 'Quickly searches code and summarizes relevant files.',
    prompt: 'Find relevant files and return a concise summary. Do not edit.',
    tools: ['Read', 'Grep', 'Glob'],
    model: 'efficient',
    effort: 'low',
    maxTurns: 5,
  },
  architect: {
    description: 'Designs complex implementation plans across modules.',
    prompt: 'Analyze tradeoffs carefully and return an implementation plan with risks.',
    tools: ['Read', 'Grep', 'Glob'],
    model: 'performance',
    effort: 'high',
    maxTurns: 10,
  },
}
See model, maxTurns, and effort in the Agents Reference for the full values.

Controlling Subagent Tools

Custom subagents and the main session use the same tool names. Built-in tool names include Read, Grep, Glob, and Bash; custom MCP tools use the full format mcp__{serverName}__{toolName}. These settings decide which tools the subagent can see and call.

The Main Session's Agent Tool

options.agents only registers subagents—it doesn't call them for the model. To delegate, the main session's tool set must contain Agent. The default tool set usually registers it; if you restrict tools with options.tools, remember to include Agent; putting Agent in the denylist disables delegation.

Tool Allowlist: tools

tools is the subagent's tool allowlist. Once set, the subagent can only use listed tools.
tools: ['Read', 'Grep', 'Glob']
Common tool combinations:
ScenarioRecommended toolsDescription
Read-only analysisRead, Grep, GlobCan inspect code; cannot modify files or run commands
Run testsBash, Read, GrepCan execute test commands and analyze output
Write codeRead, Edit, Write, Grep, GlobCan read and write files but cannot run commands directly
Call business toolsmcp__server__toolOnly allows specific custom tools

Tool Blocklist: disallowedTools

disallowedTools fits "allow most tools, exclude a few".
disallowedTools: ['Bash', 'Write']
Usually avoid setting both tools and disallowedTools unless you are certain of the final tool set.

Relationship to Main Session Tool Configuration

A subagent's tools and disallowedTools only apply to that subagent. They do not inherit the main session's tool allowlist or blocklist trimming. Even if the main session only pre-authorizes the Agent delegation path, the subagent can still use its own configured Read, Grep, and related tools.
query({
  prompt: 'Use the analyst agent to inspect the repository.',
  options: {
    // Pre-authorize the main session to call the Agent tool.
    allowedTools: ['Agent'],
    agents: {
      analyst: {
        description: 'Reads and summarizes code structure.',
        prompt: 'Inspect relevant files and return a concise summary. Do not edit files.',
        tools: ['Read', 'Grep', 'Glob'],
      },
    },
  },
});

Controlling Subagent Permissions

The tool set decides which tools a subagent can call; permission config decides how those calls are approved or blocked. permissionMode can be set per subagent to control the permission behavior of its internal tool execution.
agents: {
  planner: {
    description: 'Plans implementation work without making changes.',
    prompt: 'Read relevant files and return an implementation plan. Do not edit files.',
    tools: ['Read', 'Grep', 'Glob'],
    permissionMode: 'plan',
  },
}
See the Agents Reference for the full set of permissionMode values and their meanings. If a tool needs user approval, use the session-level canUseTool / can_use_tool callback. The subagent ID is context.agentID in TypeScript and context.agent_id in Python. See Approval and User Input for the callback rules.

Loading Skills for Subagents

skills preloads specialized skills for a subagent. It is useful when you want to bind a specific workflow, team convention, or tool usage pattern to one subagent instead of putting it in every prompt.
agents: {
  reviewer: {
    description: 'Reviews pull requests using the team review workflow.',
    prompt: 'Review the requested changes and return actionable findings.',
    tools: ['Read', 'Grep', 'Glob'],
    skills: ['review'],
  },
}
Recommendations:
ScenarioHow to configure
The subagent always follows a specialized workflowPut the corresponding skill in the subagent's skills
Only the main session needs a skillUse session-level options.skills; do not put it in the subagent
A plugin-provided skillUse the plugin-qualified name, for example sdk-test-plugin:sdk-echo
Subagent skills only affect that subagent's context. They are not the same as main-session options.skills. For session-level skill behavior, see Skills.

Configuring Subagent mcpServers

mcpServers limits or adds MCP servers for a subagent. It is suitable for exposing business tools only to the subagents that need them, such as order lookup, ticket search, or internal knowledge base search. You can reference an MCP server already configured at the session level:
const q = query({
  prompt: 'Use the support agent to check the latest order status.',
  options: {
    mcpServers: {
      orders: {
        type: 'stdio',
        command: 'node',
        args: ['servers/orders.js'],
      },
    },
    allowedTools: ['Agent'],
    agents: {
      support: {
        description: 'Answers customer support questions using order tools.',
        prompt: 'Use order tools when needed and return a concise answer.',
        mcpServers: ['orders'],
        tools: ['mcp__orders__get_order'],
      },
    },
  },
});
You can also configure a dedicated MCP server for a specific subagent:
agents: {
  knowledge: {
    description: 'Searches the internal knowledge base.',
    prompt: 'Search the knowledge base and cite the relevant entries.',
    mcpServers: [
      {
        kb: {
          type: 'stdio',
          command: 'node',
          args: ['servers/kb.js'],
        },
      },
    ],
    tools: ['mcp__kb__search'],
  },
}
Recommendations:
ScenarioHow to configure
Multiple subagents share one MCP serverConfigure the server at session level in the MCP servers option, then reference its name in each subagent's mcpServers
Only one subagent needs a business toolPut the server in that subagent's mcpServers, and use tools to limit callable tools
You only want to call a specific MCP toolAlso set tools: ['mcp__server__tool'] to avoid exposing every tool from the server
MCP server config structure: see MCP and the Agents Reference.

Invoking Subagents

Subagents have three common invocation modes.

Automatic Invocation

The model decides whether to call a subagent based on the task and each subagent's description. Clear descriptions improve routing accuracy.
agents: {
  tester: {
    description: 'Runs tests and analyzes test failures.',
    prompt: 'Run relevant tests and explain any failures clearly.',
    tools: ['Bash', 'Read', 'Grep'],
  },
}

Explicit Invocation

If you want the model to use a specific subagent, name it in the prompt.
const q = query({
  prompt: 'Use the tester agent to run the unit tests and summarize failures.',
  options: {
    // Pre-authorize Agent tool calls. If options.tools restricts the tool set, include 'Agent' there too.
    allowedTools: ['Agent'],
    agents: {
      tester: {
        description: 'Runs tests and analyzes failures.',
        prompt: 'Run the requested tests and explain failures clearly.',
        tools: ['Bash', 'Read', 'Grep'],
      },
    },
  },
});

Run as the Main Session Role

options.agent makes the main session run directly as a subagent identity.
const q = query({
  prompt: 'Plan the refactor for the payment module.',
  options: {
    agents: {
      planner: {
        description: 'Plans implementation work before code changes.',
        prompt: 'Break the task into clear steps, risks, and validation checks.',
        tools: ['Read', 'Grep', 'Glob'],
        model: 'inherit',
      },
    },
    agent: 'planner',
  },
});
options.agent can reference a custom subagent in options.agents, or a built-in, user, project, or plugin subagent discovered by the current CLI.

Subagent Context and Results

A subagent runs in an independent context. It receives its own system prompt and delegation prompt, but it does not directly inherit the parent session's full history.
Subagent can seeSubagent cannot see
Its own promptFull parent-session conversation history
The task prompt passed by the main session through the Agent toolIntermediate tool results from the parent session
Its own available tool definitionsParent session private reasoning that was not passed to it
Skills preloaded by configurationIntermediate context from other Agents
The main channel for passing information from the parent session to a subagent is the task prompt passed when calling the Agent tool. If a subagent needs specific file paths, error messages, or business context, make the main session pass them explicitly during delegation. When a subagent completes, the parent session receives its final response, not the full context of every internal tool call. This is one of the main benefits of using subagents to isolate context.

Combined Examples

Multi-role Collaboration

Register multiple subagents with different roles. The main session decides whether and when to call them based on the task.
const q = query({
  prompt: 'Add input validation to the user registration endpoint.',
  options: {
    // Pre-authorize Agent tool calls. If options.tools restricts the tool set, include 'Agent' there too.
    allowedTools: ['Agent'],
    agents: {
      researcher: {
        description: 'Reads existing code to understand patterns and constraints.',
        prompt: 'Research relevant files and report implementation constraints. Do not edit.',
        tools: ['Read', 'Grep', 'Glob'],
        maxTurns: 8,
      },
      implementer: {
        description: 'Implements code changes following existing project conventions.',
        prompt: 'Implement the requested change with minimal, idiomatic edits.',
        tools: ['Read', 'Edit', 'Write', 'Grep', 'Glob'],
        maxTurns: 12,
      },
      tester: {
        description: 'Runs tests and explains failures.',
        prompt: 'Run relevant tests, summarize results, and identify failing cases.',
        tools: ['Bash', 'Read', 'Grep'],
        maxTurns: 6,
      },
    },
  },
});

Automatically Run the First Task After Startup

initialPrompt only takes effect when that subagent becomes the main session role through options.agent:
const q = query({
  prompt: '',
  options: {
    agents: {
      auditor: {
        description: 'Audits code for security risks.',
        prompt: 'Scan code for security risks and produce a concise report.',
        initialPrompt: 'Start with the authentication and session management code.',
        tools: ['Read', 'Grep', 'Glob'],
        effort: 'high',
      },
    },
    agent: 'auditor',
  },
});
If auditor is called as a subagent through the main session's Agent tool, initialPrompt is ignored.

Common Pitfalls

  • When directly using a built-in subagent, do not redefine a subagent with the same name in options.agents unless you intentionally want to override it.
  • Calling subagents relies on the main session's Agent tool. Agent in the allowlist is the pre-approval; when restricting with options.tools, include Agent as well.
  • Subagent names are case-sensitive and must match the discovered result, such as Explore and Plan with capitalized first letters.
  • description tells the model when to call the subagent; prompt tells the subagent what to do after it is called.
  • Subagents cannot spawn their own subagents. Do not put Agent in a subagent's tools.
  • initialPrompt only takes effect for the main session role specified by options.agent; it is ignored when the agent is delegated to as a subagent.
  • Dedicated MCP servers for subagents can be configured through mcpServers; see MCP for MCP connection methods.
  • In Python, AgentDefinition field names are camelCase, not snake_case.

Continue Reading

  • Agents Reference: Complete reference for AgentDefinition, AgentInfo, options.agent, and options.agents.
  • Tools: Built-in tools, custom tools, and tool permissions.
  • Permissions: permission modes, tool allowlists, and permission callbacks.
  • Skills: Session-level and subagent-level skill configuration.