Skip to main content
guidesSource-backed

Subagents in Claude Agent SDK Applications

A practical walkthrough of subagents in the Claude Agent SDK: defining them programmatically with the agents option and AgentDefinition, context isolation, parallelization, tool restrictions, invocation, and resuming.

by JPette1783·added 2026-06-05·
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/agent-sdk/subagents, https://github.com/JSONbored/awesome-claude/blob/main/content/guides/subagents-in-claude-agent-sdk-applications.mdx
Safety notes
Restrict each subagent's tools via the tools field (for example read-only Read, Grep, Glob) so it cannot take unintended actions., When the parent uses bypassPermissions, acceptEdits, or auto, subagents inherit that mode and it cannot be overridden per subagent; subagents may be less constrained, so inheriting bypassPermissions grants full autonomous access., Subagents cannot spawn their own subagents; do not include Agent in a subagent's tools array.
Privacy notes
A subagent's context starts fresh; the only channel from parent is the Agent tool prompt, so pass only the context it needs and avoid leaking unrelated data., The parent receives the subagent's final message; intermediate tool results stay in the subagent, which helps keep sensitive detail out of the main conversation., Subagent transcripts persist within the session and are cleaned up per cleanupPeriodDays.
Author
JPette1783
Submitted by
JPette1783
Claim status
unclaimed
Last verified
2026-06-05

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

63

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Needs review

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    No reviewed flag detected in metadata.

    Pending

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Adoption plan

Balanced adoption plan

Current risk score 24/100. Use staged verification before broader rollout.

Risk 24

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    No review metadata found; increase manual validation.

    Pending
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Missing required evidence: Metadata review. Risk score 31.

Risk 31

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Missing

Review metadata is missing.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required gaps: Metadata review

Decision timeline

Decision timeline · balanced

Blocking gaps: Check metadata review status. Risk 28.

Risk 28

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is missing.

Pending

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

Blockers: Check metadata review status

Prerequisite readiness

Prerequisite readiness

3 prerequisites to line up before setup. Includes a review or approval gate.

0/3 ready
Install & runtime1Review & approval1General1

Safety & privacy surface

Safety & privacy surface

3 safety and 3 privacy notes across 4 risk areas. Review closely: credentials & tokens, permissions & scopes.

4 areas
  • SafetyGeneralRestrict each subagent's tools via the tools field (for example read-only Read, Grep, Glob) so it cannot take unintended actions.
  • SafetyPermissions & scopesWhen the parent uses bypassPermissions, acceptEdits, or auto, subagents inherit that mode and it cannot be overridden per subagent; subagents may be less constrained, so inheriting bypassPermissions grants full autonomous access.
  • SafetyExecution & processesSubagents cannot spawn their own subagents; do not include Agent in a subagent's tools array.
  • PrivacyGeneralA subagent's context starts fresh; the only channel from parent is the Agent tool prompt, so pass only the context it needs and avoid leaking unrelated data.
  • PrivacyGeneralThe parent receives the subagent's final message; intermediate tool results stay in the subagent, which helps keep sensitive detail out of the main conversation.
  • PrivacyCredentials & tokensSubagent transcripts persist within the session and are cleaned up per cleanupPeriodDays.

Safety notes

  • Restrict each subagent's tools via the tools field (for example read-only Read, Grep, Glob) so it cannot take unintended actions.
  • When the parent uses bypassPermissions, acceptEdits, or auto, subagents inherit that mode and it cannot be overridden per subagent; subagents may be less constrained, so inheriting bypassPermissions grants full autonomous access.
  • Subagents cannot spawn their own subagents; do not include Agent in a subagent's tools array.

Privacy notes

  • A subagent's context starts fresh; the only channel from parent is the Agent tool prompt, so pass only the context it needs and avoid leaking unrelated data.
  • The parent receives the subagent's final message; intermediate tool results stay in the subagent, which helps keep sensitive detail out of the main conversation.
  • Subagent transcripts persist within the session and are cleaned up per cleanupPeriodDays.

Prerequisites

  • The Claude Agent SDK installed for Python or TypeScript.
  • Include Agent in allowedTools so subagent invocations are auto-approved.
  • Clear descriptions per subagent so Claude can match tasks to the right one.

Schema details

Install type
copy
Troubleshooting
No
Full copyable content
## Overview

Subagents are separate agent instances your main agent can spawn for focused
subtasks. Use them to isolate context, run analyses in parallel, and apply
specialized instructions without bloating the main prompt. The Agent SDK
recommends defining them programmatically with the `agents` option.

## Define subagents programmatically

Each subagent is an `AgentDefinition` with a `description` (when to use it),
`prompt` (its behavior), optional `tools`, and optional `model`. Include `Agent`
in `allowedTools` so invocations auto-approve.

```typescript
for await (const message of query({
  prompt: "Review the authentication module for security issues",
  options: {
    allowedTools: ["Read", "Grep", "Glob", "Agent"],
    agents: {
      "code-reviewer": {
        description: "Expert code review specialist. Use for quality and security reviews.",
        prompt: "You are a code review specialist...",
        tools: ["Read", "Grep", "Glob"],
        model: "sonnet",
      },
    },
  },
})) {
  if ("result" in message) console.log(message.result);
}
```

`AgentDefinition` also supports `disallowedTools`, `skills`, `mcpServers`,
`maxTurns`, `effort`, `background`, and `permissionMode`.

## Why subagents

- **Context isolation**: each subagent runs in a fresh conversation; only its
  final message returns to the parent.
- **Parallelization**: independent subagents run concurrently.
- **Specialization**: tailored system prompts and knowledge per subagent.
- **Tool restriction**: limit a subagent to specific tools to reduce risk.

## What a subagent inherits

A subagent receives its own system prompt, the Agent tool's prompt string,
project CLAUDE.md (via settingSources), and inherited tool definitions. It does
**not** receive the parent's conversation history, system prompt, or preloaded
skills (unless listed in `skills`). Put any file paths or context it needs into
the prompt.

## Invoke and detect

Claude invokes subagents automatically based on `description`, or you can name one
explicitly ("Use the code-reviewer agent to..."). Subagents run via the Agent
tool; detect them by `tool_use` blocks named `Agent` (older SDKs used `Task`), and
messages from inside a subagent carry `parent_tool_use_id`.

## Resume

When a subagent completes, the Agent tool result includes `agentId: <id>`.
Capture the `session_id` and `agentId`, then resume with `resume: sessionId` and
reference the agent id in the prompt to continue with full context.

## Scale up

For runs coordinating dozens to hundreds of agents, use the `Workflow` tool
(TypeScript SDK), which moves orchestration into a script outside the conversation
context.

## Source

- Subagents in the SDK: https://code.claude.com/docs/en/agent-sdk/subagents

About this resource

Overview

Subagents are separate agent instances your main agent can spawn for focused subtasks. Use them to isolate context, run analyses in parallel, and apply specialized instructions without bloating the main prompt. The Agent SDK recommends defining them programmatically with the agents option.

Define subagents programmatically

Each subagent is an AgentDefinition with a description (when to use it), prompt (its behavior), optional tools, and optional model. Include Agent in allowedTools so invocations auto-approve.

for await (const message of query({
  prompt: "Review the authentication module for security issues",
  options: {
    allowedTools: ["Read", "Grep", "Glob", "Agent"],
    agents: {
      "code-reviewer": {
        description: "Expert code review specialist. Use for quality and security reviews.",
        prompt: "You are a code review specialist...",
        tools: ["Read", "Grep", "Glob"],
        model: "sonnet",
      },
    },
  },
})) {
  if ("result" in message) console.log(message.result);
}

AgentDefinition also supports disallowedTools, skills, mcpServers, maxTurns, effort, background, and permissionMode.

Why subagents

  • Context isolation: each subagent runs in a fresh conversation; only its final message returns to the parent.
  • Parallelization: independent subagents run concurrently.
  • Specialization: tailored system prompts and knowledge per subagent.
  • Tool restriction: limit a subagent to specific tools to reduce risk.

What a subagent inherits

A subagent receives its own system prompt, the Agent tool's prompt string, project CLAUDE.md (via settingSources), and inherited tool definitions. It does not receive the parent's conversation history, system prompt, or preloaded skills (unless listed in skills). Put any file paths or context it needs into the prompt.

Invoke and detect

Claude invokes subagents automatically based on description, or you can name one explicitly ("Use the code-reviewer agent to..."). Subagents run via the Agent tool; detect them by tool_use blocks named Agent (older SDKs used Task), and messages from inside a subagent carry parent_tool_use_id.

Resume

When a subagent completes, the Agent tool result includes agentId: <id>. Capture the session_id and agentId, then resume with resume: sessionId and reference the agent id in the prompt to continue with full context.

Scale up

For runs coordinating dozens to hundreds of agents, use the Workflow tool (TypeScript SDK), which moves orchestration into a script outside the conversation context.

Source

Source citations

Add this badge to your README

Show that Subagents in Claude Agent SDK Applications is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/guides/subagents-in-claude-agent-sdk-applications.svg)](https://heyclau.de/entry/guides/subagents-in-claude-agent-sdk-applications)

How it compares

Subagents in Claude Agent SDK Applications side by side with 2 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Field

A practical walkthrough of subagents in the Claude Agent SDK: defining them programmatically with the agents option and AgentDefinition, context isolation, parallelization, tool restrictions, invocation, and resuming.

Open dossier

A practical walkthrough of using Agent Skills in the Claude Agent SDK: how skills are discovered from the filesystem via settingSources, the skills option to enable or filter them, tool access, and troubleshooting discovery.

Open dossier

A practical walkthrough of token and spend accounting in the Claude Agent SDK. Read total_cost_usd from the result message, deduplicate parallel tool calls that share an assistant id, break spend down per model with modelUsage, sum cost across query() calls yourself, and read cache_creation/cache_read tokens.

Open dossier
Next steps
Trust
Review statusNot reviewedNot reviewedNot reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backed
SubmitterJPette1783JPette1783JPette1783
Install riskReview firstReview firstReview first
Notes Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓
Brand
Categoryguidesguidesguides
SourceSource-backedSource-backedSource-backed
AuthorJPette1783JPette1783JPette1783
Added2026-06-052026-06-052026-06-05
Platforms
Harness
Source repo
Safety notesRestrict each subagent's tools via the tools field (for example read-only Read, Grep, Glob) so it cannot take unintended actions. When the parent uses bypassPermissions, acceptEdits, or auto, subagents inherit that mode and it cannot be overridden per subagent; subagents may be less constrained, so inheriting bypassPermissions grants full autonomous access. Subagents cannot spawn their own subagents; do not include Agent in a subagent's tools array.The skills option is a context filter, not a sandbox: unlisted skills are hidden from the model but their files remain on disk and are reachable via Read and Bash. Skills are model-invoked; pair them with a tight allowedTools list (and dontAsk where appropriate) so an invoked skill cannot use more tools than intended. The allowed-tools frontmatter in SKILL.md does not apply through the SDK; control tool access with the main allowedTools option.total_cost_usd / costUSD are client-side estimates from a bundled price table, not authoritative billing; do not bill end users or trigger financial decisions from them. Estimates can drift when pricing changes or the SDK version does not recognize a model; use the Usage and Cost API or Console for real billing. Both success and error result messages include usage and cost; read cost regardless of subtype so failed runs are still accounted for.
Privacy notesA subagent's context starts fresh; the only channel from parent is the Agent tool prompt, so pass only the context it needs and avoid leaking unrelated data. The parent receives the subagent's final message; intermediate tool results stay in the subagent, which helps keep sensitive detail out of the main conversation. Subagent transcripts persist within the session and are cleaned up per cleanupPeriodDays.Skill descriptions are loaded so the model can decide when to use them; keep sensitive workflow detail and secrets out of descriptions. Skills sourced from outside your project run their instructions in your sessions; review them before enabling. Skill content is sent to the model provider when a skill is invoked; treat it like any other prompt content.Usage data is token counts and cost, not content; it is safe to log, though it can reveal activity volume. Per-model and end-user attribution may be sent to an observability backend if you also enable telemetry; govern that data accordingly. The SDK uses prompt caching automatically; cache token fields reveal reuse patterns but not content.
Prerequisites
  • The Claude Agent SDK installed for Python or TypeScript.
  • Include Agent in allowedTools so subagent invocations are auto-approved.
  • Clear descriptions per subagent so Claude can match tasks to the right one.
  • The Claude Agent SDK installed for Python or TypeScript.
  • SKILL.md files in .claude/skills/ (project) or ~/.claude/skills/ (user).
  • A cwd that points at or below the directory containing .claude/skills/, within the same repository.
  • The Claude Agent SDK installed for Python or TypeScript.
  • An async loop over query() results so you can read assistant and result messages.
  • For authoritative billing, access to the Usage and Cost API or the Console.
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimed
Open 3 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.