Setting Up Claude Agent SDK Subagents With Tool Restrictions and a Concurrency Cap

A conductor leading an orchestra through a rehearsal

A subagent in the Claude Agent SDK is a separate agent instance your main agent can spawn to handle a focused subtask in its own conversation, with its own system prompt and its own restricted set of tools. The benefit isn’t just organization: a subagent’s intermediate tool calls and results stay inside its own context, so the parent conversation only receives a final summary instead of every file a research subagent happened to read. This walkthrough covers the three ways to define one, which AgentDefinition fields actually matter in practice, and the depth, concurrency, and spend limits worth setting before you let Claude delegate on its own.

Three ways to create a subagent

ApproachHowWhen it’s the right fit
ProgrammaticThe agents parameter in your query() options, as an AgentDefinition object per nameSDK applications where the set of agents is known at build time or constructed from runtime conditions
Filesystem-basedMarkdown files under .claude/agents/ (project or user level)Claude Code sessions where you want an agent defined once and reused across projects or picked up live without a restart
Built-in general-purposeNothing to configure — Claude calls the Agent tool with no subagent_typeAny ad hoc delegation where you haven’t defined a specialized agent for the task

Programmatically defined agents take precedence over a filesystem agent that shares the same name, and setting CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS=1 removes the built-in general-purpose fallback entirely — after that, an Agent tool call with no matching subagent_type fails outright instead of falling back to a default.

A minimal tool-restricted subagent

from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Grep", "Glob", "Agent"],
    agents={
        "code-reviewer": AgentDefinition(
            description="Expert code review specialist. Use for quality, security, and maintainability reviews.",
            prompt="You are a code review specialist. Identify security vulnerabilities, "
                   "check for performance issues, and suggest specific improvements.",
            tools=["Read", "Grep", "Glob"],  # no Edit, Write, or Bash
            model="sonnet",
        ),
    },
)

Leaving tools off an AgentDefinition gives the subagent every tool available to subagents in general; listing it, as above, means a tool left out isn’t in that subagent’s session at all — Claude works without it, with no permission prompt and no error. A read-only reviewer that should never touch a file directly is one line away from a reviewer that can. The same tool-restriction instinct applies to anything you’d otherwise lock down with a PreToolUse hook that blocks dangerous Bash commands: here, you just don’t give the subagent Bash in the first place.

The AgentDefinition fields worth knowing beyond description and prompt

FieldTypeWhat it does
toolsstring[]Restricts the subagent’s tool access. Omit it to inherit everything available to subagents.
disallowedToolsstring[]Removes specific tools from an otherwise-inherited set. Accepts MCP patterns like mcp__server__* to drop a whole server’s tools at once.
modelstringOverrides the model for this agent: an alias ('opus', 'sonnet', 'haiku', 'fable'), 'inherit', or a full model ID.
skillsstring[]Preloads named skills into the agent’s context at startup — at most the first 32 distinct names in the list.
memory'user' | 'project' | 'local'Which memory source this agent reads from.
maxTurnsnumberStops the agent after this many turns, marking its output partial so you know the run was cut off rather than finished.
backgroundbooleanRuns this agent as a non-blocking background task when invoked, instead of the default foreground wait.
effort'low' | 'medium' | 'high' | 'xhigh' | 'max' | numberReasoning effort level for this specific agent.

The memory field is worth pausing on if you’re also using the memory tool (memory_20250818): it controls which memory source — user, project, or local — a given subagent reads from, not whether memory is available at all. A write-restricted reviewer agent and a persistent research agent can point at different memory scopes without either one seeing the other’s files.

What a subagent inherits, and what it doesn’t

  • Inherits: its own system prompt and the Agent tool’s prompt string, project CLAUDE.md (unless omitClaudeMd is set), and tool definitions — either inherited from the parent or the subset in tools.
  • Doesn’t inherit: the parent’s conversation history or tool results, the parent’s system prompt, and any preloaded skill content not listed in that agent’s own skills field.
  • The exception: a fork (a subagent started with subagent_type: "fork") copies the conversation so far instead of starting fresh, which is the right choice when the subtask genuinely needs everything discussed up to that point.

That isolation is also why writing a specific, unambiguous description matters more than it looks like it should. Claude decides when to invoke a subagent automatically based on the task and that description field — the same discipline covered in our checklist for writing tool descriptions Claude won’t misread applies just as directly here. A vague description gets skipped in favor of Claude doing the work directly; a precise one gets matched reliably and consistently, run after run.

Capping depth, concurrency, and spend before you ship this

LimitSet it withDefaultAt the limit
DepthCLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH (env var)3 layers below the main agentA subagent at the bottom layer can’t spawn further; it does the delegated work itself.
ConcurrencyCLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS (env var)20 running at onceRefuses to spawn more, returning “Concurrent subagent limit reached,” until the count drops.
SpendmaxBudgetUsd (TypeScript) / max_budget_usd (Python), a query optionNo limitStops spawning new subagents, ends background ones still running, and the query ends with error_max_budget_usd.

Claude decides on its own when to spawn a subagent and how many, and each one’s API requests count toward the query’s total cost — a subagent can spawn subagents of its own, so one prompt can grow into a tree of agents if nothing bounds it. Claude Opus 5 in particular delegates to subagents more readily than earlier models, which is exactly when these three limits matter most; Anthropic’s own prompting guide for Opus 5 includes a delegation instruction worth adding to your prompt specifically because of that tendency.

If Claude isn’t delegating to your subagent

Two fixes cover almost every case: mention the subagent by name directly in your prompt (“Use the code-reviewer agent to check the authentication module”) to bypass automatic matching entirely, or rewrite the description field to state exactly when the agent should be used rather than describing it in general terms. If you’ve defined a subagent as a file and it never shows up at all, check whether its directory existed before the session started — the filesystem watcher only covers directories that were already there, so the first file in a brand-new .claude/agents/ folder needs a session restart to be picked up.

For a handful of delegated tasks per turn, the pattern above is the right level of control. Coordinating dozens or hundreds of agents at once is a different problem with its own tool, outside the scope of a single conversation’s turn-by-turn delegation — reach for that only once you’ve confirmed, with one or two subagents working well in a real session, that the delegation and tool-restriction choices above actually hold up before scaling the pattern any further.

Resuming a subagent instead of starting over

A subagent doesn’t have to be one-shot. When it finishes, the Agent tool’s result includes a text block containing agentId: <id>; capture that alongside the session_id from the query’s messages, and a later call can pass resume: sessionId with the agent ID mentioned in the follow-up prompt to continue exactly where that subagent left off, full tool-call history and all. The built-in Explore and Plan agents are one-shot and never return an agentId, so resuming only works with a custom agent definition or the built-in general-purpose one. This matters most when a subagent hits its maxTurns ceiling mid-task: instead of re-running the whole investigation from scratch, you resume the same agent and ask it to continue, and it picks up with everything it had already found.

A security detail worth knowing before a subagent’s output reaches the user

Because a subagent’s final message can get summarized rather than shown verbatim, and because that message might contain text the subagent picked up from a file, a web page, or any other untrusted source it read, Claude Code scans a subagent’s final message for instruction-shaped patterns before the parent reads it. Three kinds of pattern are handled differently: an imitation of a harness-only control tag (like a fake <system-reminder> block) gets a backslash inserted right after its opening angle bracket, neutralizing it in place; a line starting with Human: or Assistant: gets a backslash before the colon so it can’t impersonate a conversation-turn boundary; and references to permission configuration, such as .claude/settings.json or --dangerously-skip-permissions, are left untouched and flagged with a [harness: ...] marker line instead. None of this rewrites or deletes the subagent’s actual content — it’s specifically there to stop a subagent’s output from being mistaken for a new instruction, which is the exact failure mode worth watching for any time an agent ingests content it didn’t write itself — a subagent that summarized a scraped web page is exactly the kind of source that content could have come from.

Photo: orchestra rehearsal in the Musikschule, Munich, by Jorge Royan, CC BY-SA 3.0, via Wikimedia Commons.

Treat the three limits above as the first thing you set, not the last — a tree of unbounded subagents is the most common way a first working prototype turns into a surprising bill.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top