harness-sdk / strands-py
AGENTS.md8.7k starsChanged 59 days agoApache-2.0View on GitHub
This document provides context, patterns, and guidelines for AI coding assistants working on the Strands Python SDK (strands-py/). For human contributors, see CONTRIBUTING.md. Cross-SDK rules live in the root AGENTS.md. Plugin naming, cross-SDK parity, public/internal API marking, the structured-logging format, and the evergreen-comment rule apply to both SDKs and are stated once there — this file shows only the Python-idiomatic form and the rules unique to Python. When a rule applies to both SDKs, edit the root, not this file.
Trending
More talk lately.about the whole repository
Who's talking about strands-agents/harness-sdk
- @fluid.sublimer.me“GitHub - strands-agents/harness-sdk: Build an agent harness and control it end-to-end. Open-source SDK for …”Bluesky · Sep 30, 2026 · 2 likes
- @github-trending.bsky.social“📦 strands-agents / harness-sdk ⭐ 7,621 (+96) 🗒 Python Build an agent harness and control it end-to-end. …”Bluesky · Sep 24, 2026 · 2 likes
- aws/bedrock-agentcore-sdk-typescript“feat: implement SessionManager for Strands TS integration”GitHub · Jul 16, 2026 · 2 reactions
- aws/bedrock-agentcore-sdk-typescript“An AgentCoreMemoryStore that works with the Strands native memory management system (`MemoryManager`)”GitHub · Jun 5, 2026 · 2 reactions
- @dailygithubtrends.bsky.social“今日のGitHubトレンド strands-agents/harness-sdk”Bluesky · Sep 23, 2026 · 1 likes
The biggest 5 of 51 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 51
Talked about on GitHub and Bluesky (51 times).
On GitHub · 47
- Jul 16, 2026feat: implement SessionManager for Strands TS integration — aws/bedrock-agentcore-sdk-typescript2 reactions
- Jun 5, 2026An AgentCoreMemoryStore that works with the Strands native memory management system (`MemoryManager`) — aws/bedrock-agentcore-sdk-typescript2 reactions
- Aug 16, 2026Chore(deps): bump strands-agents[openai] from 1.51.0 to 1.52.0 in /v1 — rhprasad0/nova-toll-budget-agent1 reaction · 1 comment
- Aug 11, 2026Chore(deps): bump strands-agents[openai] from 1.50.2 to 1.51.0 — rhprasad0/nova-toll-budget-agent1 reaction
- Jun 22, 2026chore(deps): bump the lambda-dependencies group across 1 directory with 6 updates — thechrisgrey/thechrisgrey1 reaction · 3 comments
42 more on GitHub
- Oct 5, 2026build(deps): bump strands-agents from 1.45.0 to 1.57.1 — diagridio/python-ai0 reactions
- Oct 5, 2026chore(deps): update strands-agents requirement from >=1.42.0 to >=1.57.2 in /tutor — aws-samples/amazon-bedrock-workshop0 reactions
- Oct 5, 2026chore(deps): bump the agent-framework group across 1 directory with 3 updates — suranimayur/banking-data-agents0 reactions · 1 comment
- Oct 3, 2026Update strands-agents requirement from >=1.0.0 to >=1.57.1 in /harness — sholtomaud/desktop-uat0 reactions
- Oct 3, 2026Update strands-agents requirement from <2,>=1.47.0 to >=1.57.1,<2 in /src — ikenley/email-ai-agent0 reactions
- Oct 2, 2026rc5 a2a template has incompatible dependencies — aws/agentcore-cli0 reactions · 1 comment
- Oct 1, 2026Bump strands-agents from 1.45.0 to 1.57.1 in /functions/most_popular_repo_strands — nexcode240/prompt-chaining-sls0 reactions
- Oct 1, 2026Bump strands-agents from 1.54.0 to 1.57.1 in /functions/most_popular_repo_strands — aws-samples/amazon-bedrock-serverless-prompt-chaining0 reactions · 1 comment
- Oct 1, 2026chore(deps): update strands-agents requirement from <2.0,>=1.0 to >=1.57.1,<2.0 — MariamJangveladze/conversational-banking-agent-demo0 reactions
- Oct 1, 2026Bump strands-agents from 1.50.2 to 1.57.1 in /functions/most_popular_repo_strands — probelabs/amazon-bedrock-serverless-prompt-chaining-audit0 reactions
- Oct 1, 2026Bump the python-deps group with 2 updates — mauc-agentic/spec-to-runtime-aws0 reactions
- Oct 1, 2026build(deps): bump the python group with 2 updates — vishalsg42/munim0 reactions
- Sep 30, 2026chore(deps): bump the python-minor-patch group across 6 directories with 3 updates — aws-samples/amazon-transcribe-live-meeting-assistant0 reactions
- Sep 29, 2026build(deps): bump strands-agents from 1.55.1 to 1.57.1 — AjaneeI/homeops-agent0 reactions · 1 comment
- Sep 29, 2026chore(deps): bump strands-harness from 0.1.1 to 0.1.2 in /app/ops_investigator — iracic82/strands-harness-on-aws0 reactions
- Sep 29, 2026chore(deps): bump strands-agents from 1.56.0 to 1.57.1 in /app/ops_investigator — iracic82/strands-harness-on-aws0 reactions
- Sep 28, 2026chore(deps): bump @strands-agents/sdk from 1.12.0 to 1.19.0 — 4suke-sun/connpass-scout-agent0 reactions · 1 comment
- Sep 28, 2026chore(deps): bump strands-agents from 1.56.0 to 1.57.0 — iguinea/mongodb-session-manager0 reactions
- Sep 27, 2026Bump strands-agents from 1.56.0 to 1.57.0 — Prashant-thakur77/Beacon0 reactions
- Sep 26, 2026build(deps): Update strands-agents requirement from >=1.0 to >=1.57.0 in /agents — minho5889/gen-ai-pro0 reactions
- Sep 23, 2026Add LangGraph migration examples (Python and TypeScript) — strands-agents/samples0 reactions · 1 comment
- Sep 22, 2026chore(deps): bump the python group across 1 directory with 3 updates — aws-samples/sample-strands-agent-with-agentcore0 reactions
- Sep 21, 2026chore(deps): bump strands-agents from 1.55.1 to 1.56.0 — fakhriaunur/genie-fleet0 reactions
- Sep 18, 2026Bump strands-agents from 1.55.0 to 1.55.1 — harveybellini/glide0 reactions
- Sep 16, 2026Bump the aws-agent-toolchain group across 1 directory with 2 updates — ag-ke-nakamura/form-echo-agent0 reactions
- Sep 12, 2026Bump strands-agents from 1.54.0 to 1.55.0 — AmirmLotfy/incaseof0 reactions
- Sep 4, 2026Bump the all group with 6 updates — rogervinas/strands-agents-langfuse-evaluations0 reactions
- Sep 2, 2026Bump the aws-agent-toolchain group in /app/FormEchoAgent with 2 updates — ag-ke-nakamura/form-echo-agent0 reactions
- Sep 2, 2026build(deps): bump the agent-dependencies group across 1 directory with 6 updates — nightandweather/lifelens-agent0 reactions
- Sep 2, 2026Bump strands-agents from 1.53.0 to 1.54.0 — mli-cyber/ada0 reactions
- Sep 1, 2026chore(deps): bump the python-e2e group in /e2e_tests/python with 5 updates — awslabs/run-model-context-protocol-servers-with-aws-lambda0 reactions
- Sep 1, 2026chore(deps): bump the python-chatbots group in /examples/chatbots/python with 4 updates — awslabs/run-model-context-protocol-servers-with-aws-lambda0 reactions
- Aug 29, 2026chore(deps): update strands-agents requirement from >=1.52.0 to >=1.53.0 in /apps/agent — yuyumama/AWS-MON0 reactions
- Aug 10, 2026chore(deps): update strands-agents requirement from >=1.26.0 to >=1.52.0 in /backend — SxBxcoder/Avoir0 reactions
- Aug 5, 2026[BUG] filter_restored_tool_context is incompatible with extended thinking — aws/bedrock-agentcore-sdk-python0 reactions · 1 comment
- Aug 3, 2026build(deps): Update strands-agents[anthropic,gemini,openai] requirement from >=1.50 to >=1.50.2 — khalaharvi/FDE-Agent-Platform0 reactions
- Aug 2, 2026deps(deps): update strands-agents requirement from >=0.1.0 to >=1.50.2 in /backend — camiloavilacm/camiloavila.dev0 reactions · 3 comments
- Jul 22, 2026Bump strands-agents from 1.39.0 to 1.48.0 — huisun/conversation-ai0 reactions
- Jul 1, 2026chore(deps): bump @strands-agents/sdk from 1.6.0 to 1.7.0 — arnoldsimha/skillspell0 reactions · 1 comment
- Jun 24, 2026[design] Determine whether parallel-invocation protection should apply to BiDiAgent — chaynabors/harness-sdk0 reactions
- Jun 18, 2026chore(deps): Update strands-agents[ollama] requirement from >=1.43.0 to >=1.44.0 — Iwaschkin/weather-agent0 reactions
- Jun 15, 2026build(deps): update strands-agents requirement from <2.0,>=1.42.0 to >=1.43.0,<2.0 in /agent-runtime — christiantobin/tobot-agent0 reactions
On Bluesky · 4
- Sep 30, 2026GitHub - strands-agents/harness-sdk: Build an agent harness and control it end-to-end. Open-source SDK for production AI agents in Python &… — @fluid.sublimer.me2 likes and reposts · 1 reply
- Sep 24, 2026📦 strands-agents / harness-sdk ⭐ 7,621 (+96) 🗒 Python Build an agent harness and control it end-to-end. Open-source SDK for production AI… — @github-trending.bsky.social2 likes and reposts
- Sep 23, 2026今日のGitHubトレンド strands-agents/harness-sdk — @dailygithubtrends.bsky.social1 likes and repost
- Aug 3, 2026harness-sdk from strands-agents hands you the agent loop itself, in Python or TypeScript, running against any model on any cloud. For… — @agentwire.thecompound.tech1 likes and repost
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository25 other files it gives its agents.
- AGENTS.mdAGENTS.md
- harness-py/AGENTS.mdAGENTS.md
- harness-ts/AGENTS.mdAGENTS.md
- site/AGENTS.mdAGENTS.md
- strands-cli/AGENTS.mdAGENTS.md
- strands-ts/AGENTS.mdAGENTS.md
- test-infra/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- harness-py/CLAUDE.mdCLAUDE.md
- harness-ts/CLAUDE.mdCLAUDE.md
- site/CLAUDE.mdCLAUDE.md
- strands-cli/CLAUDE.mdCLAUDE.md
- strands-py/CLAUDE.mdCLAUDE.md
- strands-ts/CLAUDE.mdCLAUDE.md
- test-infra/CLAUDE.mdCLAUDE.md
- docs-auditSkill
- docs-plannerSkill
- docs-reviewerSkill
- docs-writerSkill
- pr-createSkill
- pre-pushSkill
- pr-feedbackSkill
- pr-writerSkill
- strands-reviewSkill
- strandsSkill
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
16 rules. About 0 are common, 5 are distinctive, and 11 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
11
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 54
Run quality checks before committing
- Very specific: line 55
Commit with conventional commits (feat:, fix:, docs:, refactor:, test:, chore:)
- Distinctive: line 60
When creating pull requests, you MUST follow the guidelines and template in PR.md.
- Very specific: line 82
If you catch yourself building a process-global "warn once" set over the logger, you almost certainly want warnings.warn instead.
- Very specific: line 86
All code is fully type-annotated (mypy strict enforces parameter/return types and rejects implicit optionals).
- Very specific: line 88
Spell optionals as PEP 604 unions, not
Optional[...]: Write X | None and X | Y, never Optional[X] / Union[X, Y] — including for forward … - Very specific: line 150
Test files prefixed with test_
- Very specific: line 161
Use custom exceptions from strands.types.exceptions.
- Very specific: line 214
The floor is Python 3.10: Do not use asyncio.TaskGroup or asyncio.timeout (3.11+) without a sys.version_info gate and a 3.10 fallback (see …
- Very specific: line 279
Document a Raises: section when a public function raises as part of its contract
- Very specific: line 281
Use a Protocol with kwargs (not Callable) for extensible interfaces.
- Very specific: line 290
Keep a model-provider config as a plain dict + cast — store the TypedDict
- Very specific: line 292
Use invocation_state for SDK-internal state — it is user-only (see the root AGENTS.md)
- Distinctive: line 325
Prefer simple, clean, maintainable solutions over clever ones
- Distinctive: line 338
Update documentation if behavior changes
- Distinctive: line 340
Follow conventional commit format for fix commits
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Agent Development Guide - Python SDK
This document provides context, patterns, and guidelines for AI coding assistants working on the Strands Python SDK (strands-py/). For human contributors, see CONTRIBUTING.md.
Cross-SDK rules live in the root AGENTS.md. Plugin naming, cross-SDK parity, public/internal API marking, the structured-logging format, and the evergreen-comment rule apply to both SDKs and are stated once there — this file shows only the Python-idiomatic form and the rules unique to Python. When a rule applies to both SDKs, edit the root, not this file.
Product Overview
Strands Agents is an open-source Python SDK for building AI agents with a model-driven approach. It provides a lightweight, flexible framework that scales from simple conversational assistants to complex autonomous workflows.
Core Features:
- Model Agnostic: Multiple model providers (Amazon Bedrock, Anthropic, OpenAI, Gemini, Ollama, etc.)
- Python-Based Tools: Simple
@tooldecorator with hot reloading - MCP Integration: Native Model Context Protocol support
- Multi-Agent Systems: Agent-to-agent, swarms, and graph patterns
- Streaming Support: Real-time response streaming
- Hooks: Event-driven extensibility for agent lifecycle
- Session Management: Pluggable session managers (file, S3, custom)
- Observability: OpenTelemetry tracing and metrics
Directory Structure
strands-py/
├── src/strands/ # All production source code
│ ├── agent/ # Core agent loop, state, conversation management
│ ├── models/ # Model provider implementations (Bedrock, OpenAI, etc.)
│ ├── tools/ # Tool system (registry, execution, MCP client)
│ ├── event_loop/ # Event loop and streaming
│ ├── multiagent/ # Multi-agent orchestration (A2A, graphs, swarm)
│ ├── session/ # Session persistence
│ ├── telemetry/ # Tracing and metrics
│ ├── types/ # Shared type definitions
│ └── … # Key subsystems shown; run `ls src/strands/` for the full list
├── tests/ # Unit tests (mirrors src/ structure)
├── tests_integ/ # Integration tests with real providers
├── docs/ # Developer documentation
└── pyproject.toml # Build config, dependencies, tool settingsDevelopment Workflow
1. Environment Setup
hatch shell # Enter dev environment
pre-commit install -t pre-commit -t commit-msg # Install hooks2. Making Changes
- Create feature branch
- Implement changes following the patterns below
- Run quality checks before committing
- Commit with conventional commits (
feat:,fix:,docs:,refactor:,test:,chore:) - Push and open PR
3. Pull Request Guidelines
When creating pull requests, you MUST follow the guidelines and template in PR.md.
4. Quality Gates
Pre-commit hooks run automatically on commit and must all pass: formatting (ruff), linting (ruff + mypy strict), tests (pytest), and commit-message validation (commitizen). Run them yourself with hatch fmt --formatter and hatch fmt --linter before committing.
ruff, isort, mypy, and pydocstyle already enforce import order, line length (120), logging format, docstring presence, and type-annotation coverage. This guide does not re-list those — it covers the conventions a linter cannot check. When a rule below says "enforced by review," it means exactly that: no tool catches it, so it is on you and the reviewer.
Coding Patterns and Best Practices
Logging
Structured logging is a cross-SDK rule — see the format in the root AGENTS.md. The Python-idiomatic form uses %s interpolation (never f-strings; ruff G enforces this) so interpolation is skipped when the log level is disabled:
logger.debug("user_id=<%s>, action=<%s> | user performed action", user_id, action)warnings.warn vs logger.warning — pick by audience, not severity. The two are not interchangeable; the split runs throughout the codebase:
warnings.warn(...)for developer-facing notices about how the SDK is being used — an ignored/invalid config field, a deprecated argument, an unsupported option that will be dropped. These target the developer writing the code, are controllable via-W/PYTHONWARNINGS/pytest.warns, and the standard library already dedupes them once per call site under the default filter — so do not hand-roll a warn-once helper for this. Pass an explicitstacklevelso the warning points at the caller, not the SDK internals (seemodels/_validation.py, the reference:validate_config_keysandwarn_on_tool_choice_not_supportedboth usewarnings.warn(..., stacklevel=4)).logger.warning(...)for runtime/operational diagnostics — something went wrong while the SDK was running that an operator would want in their logs (an MCP server failed to start, a tool failed to load, a store write failed). These are for log aggregation, not the developer's console.
If you catch yourself building a process-global "warn once" set over the logger, you almost certainly want warnings.warn instead.
Type Annotations
All code is fully type-annotated (mypy strict enforces parameter/return types and rejects implicit optionals). Use typing / typing_extensions for complex types. Beyond what the type checker catches:
- Spell optionals as PEP 604 unions, not
Optional[...]. WriteX | NoneandX | Y, neverOptional[X]/Union[X, Y]— including for forward references, where ruff'sUP045will not auto-fix it for you. The codebase is ~99%X | Nonealready; don't reintroduceOptional. - Scope every type suppression to a code. Use
# type: ignore[code](no bare# type: ignore, no space before the bracket —# type: ignore [assignment]silently degrades to a bare ignore). mypy runs withwarn_unused_ignores, so a coded ignore stays narrow and self-cleans when the underlying error goes away. When narrowing an overridden signature (e.g.update_config), the code is[override]. - Avoid
Anywithout a good reason. Reach for a precise type or aProtocolfirst.
def process_message(content: str, max_tokens: int | None = None) -> AgentResult:
...Data Structures
Choose the construct by the role the data plays — don't model the same kind of thing two ways:
TypedDictfor wire / message / config shapes and**kwargsoption bags — anything that is fundamentally a JSON-serializable dict or a keyword-option payload (the Bedrock-API-modeledcontent/streaming/toolstypes, and every model-provider*Config). Usetotal=Falsefor option/config bags and mark the few mandatory keys withtyping_extensions.Required; for required wire shapes keep the defaulttotal=Trueand mark optional keys withtyping_extensions.NotRequired.@dataclassfor runtime objects that own behavior, defaults, or serialization helpers — results, contexts, events, state, persistence models (e.g.agent/agent_result.py).pydantic BaseModelonly for schemas the model reads or writes — structured output and tool-input validation (e.g.vended_plugins/goal/judge.py). Do not reach for pydantic to model internal data.- Do not introduce
NamedTuplefor new data structures.
Canonical examples: types/content.py (TypedDict), agent/agent_result.py (dataclass), vended_plugins/goal/judge.py (BaseModel).
Naming Conventions
- Variables/Functions:
snake_case - Classes:
PascalCase - Constants:
UPPER_SNAKE_CASE - Private members, functions, and modules: prefix with
_(e.g._helper(),_internal.py) - Name every variable for its content, including short-lived loop/catch bindings —
event,index,error, nevere/i/x.
Docstrings
Use Google-style docstrings for all public functions, classes, and modules. ruff's pydocstyle (D) enforces that a docstring exists and is well-formed, but not that its sections are complete — so the judgment rule is: include a Raises: section whenever a public function raises as part of its contract (a missing one passes lint and is caught only in review).
def example_function(param1: str, param2: int) -> bool:
"""Brief description of function.
Longer description if needed. This docstring is used by LLMs
to understand the function's purpose when used as a tool.
Args:
param1: Description of param1
param2: Description of param2
Returns:
Description of return value
Raises:
ValueError: When invalid input is provided
"""
passImport Organization
Imports go at the top of the file; ruff/isort orders them (stdlib → third-party → local). Use absolute imports for cross-package references, relative imports within a package.
File Organization
- Each major feature in its own directory
- Base classes and interfaces defined first
- Implementation-specific code in separate files
- Private modules prefixed with
_ - Test files prefixed with
test_
Public API Surface
Public/internal marking is a cross-SDK rule — see the root AGENTS.md. The Python-idiomatic form:
- Every public package declares its surface with an explicit
__all__in its__init__.py. Internal (_-prefixed) and namespace-only packages may omit it. Don't lean on the redundantimport X as Xre-export alias in place of__all__for a public package. - Optional or heavy model providers stay out of
__all__and are lazy-loaded via a module-level__getattr__(seemodels/__init__.py) so importing the package doesn't pull every provider's third-party dependency.
Error Handling
- Use custom exceptions from
strands.types.exceptions; provide clear, context-rich messages; never swallow exceptions silently. - Reserve a bare
raise Exception(...)for nothing — pick the specific type. A malformed model response is aValueError(the convention across every provider); a timeout is aTimeoutError. When you re-raise, preserve the cause withraise NewError(...) from original. - Model providers translate vendor errors into the SDK's typed exceptions. A vendor SDK's context-window / token-overflow error becomes
ContextWindowOverflowException; rate-limiting / throttling (HTTP 429) becomesModelThrottledException. Preserve the original withraise ... from error; never let a raw vendor exception escape the provider boundary. Most providers already do this (seeopenai.py,bedrock.py,anthropic.py); match them when adding or touching one.
Extensible Interfaces (Protocol vs ABC)
Before adding or changing a public interface, read docs/STYLE_GUIDE.md. It carries two rules a linter cannot enforce, summarized here so you don't miss them:
- Use a
Protocolwith**kwargs, not aCallable, for extensible interfaces. AProtocollets you add optional keyword arguments later without breaking implementors; a bareCallablesignature can't evolve. Example:def __call__(self, state: GraphState, **kwargs: Any) -> bool: .... - Reference a tool by its
tool_nameproperty, never a hardcoded string.tool.tool_namestays correct when a tool is renamed; a string literal silently rots.
Hook Events
Before adding a hook event, read docs/HOOKS.md. Event names take an
Eventsuffix, paired events followBefore{Action}Event/After{Action}Event(the action word comes after the lifecycle word), and everyBeforehas a matchingAfterinvoked in reverse registration order. Hook event names are shared with the TypeScript SDK — see the cross-SDK parity rule in the root AGENTS.md.
Adding a Model Provider
A model provider is the single most-repeated pattern in the SDK. Follow the existing skeleton — models/anthropic.py is the cleanest reference.
- One flat file
models/<name>.pydefiningclass XModel(Model). (models/model.pyis the abstract base;models/_validation.pyandmodels/_defaults.pyhold the shared helpers.) - Config is a nested
TypedDictclass XConfig(BaseModelConfig, total=False)declared inside the class, with mandatory keys markedtyping_extensions.Required(e.g.model_id: Required[str]). __init__(self, *, <client args>, **model_config: Unpack[XConfig])callsvalidate_config_keys(model_config, self.XConfig)before storing, then stores the typed config (self.config = XModel.XConfig(**model_config)— store theTypedDict, don't keep a plaindictandcastlater).- Implement the abstract contract from
Model:update_config(re-validate, thenself.config.update(...); decorate@overrideand suppress with# type: ignore[override]because it narrows**kwargs),get_config(returnresolve_config_metadata(self.config, self.config["model_id"])),stream, andstructured_output. - Conversion helpers are conventional, not abstract:
format_request(...)builds the vendor request andformat_chunk(event) -> StreamEventmaps a vendor chunk to aStreamEvent. - Map vendor errors to typed SDK exceptions and chain the cause (see Error Handling above).
class XModel(Model):
class XConfig(BaseModelConfig, total=False):
model_id: Required[str]
params: dict[str, Any] | None
def __init__(self, *, client_args: dict[str, Any] | None = None, **model_config: Unpack[XConfig]) -> None:
validate_config_keys(model_config, self.XConfig)
self.config = XModel.XConfig(**model_config)
self.client = vendor.AsyncClient(**(client_args or {}))
@override
def update_config(self, **model_config: Unpack[XConfig]) -> None: # type: ignore[override]
validate_config_keys(model_config, self.XConfig)
self.config.update(model_config)
@override
def get_config(self) -> XConfig:
return resolve_config_metadata(self.config, self.config["model_id"])Async & Streaming
streamis an async generator. Annotate provider overrides-> AsyncGenerator[StreamEvent, None](the abstract base widens the return toAsyncIterable); annotatestructured_output-> AsyncGenerator[dict[str, T | Any], None].- Everything after
system_promptin astreamoverride is keyword-only — place a bare*beforetool_choice. Every provider does this; it keeps the orchestrator's keyword call site stable as new options are added. - Never buffer a stream into a list before yielding. Consume upstream async iterables with
async forand yield as you go. - Async-first with thin sync facades. Public APIs come in async form (
invoke_async,stream_async) plus thin sync wrappers (__call__,invoke) that delegate via_async.run_async. Never block the event loop — wrap blocking or third-party-sync calls inasyncio.to_thread(seebedrock.py). - The floor is Python 3.10. Do not use
asyncio.TaskGrouporasyncio.timeout(3.11+) without asys.version_infogate and a 3.10 fallback (seemultiagent/swarm.py); for concurrent work useasyncio.create_taskand clean up infinallywithtask.cancel()thenawait asyncio.gather(*tasks, return_exceptions=True). - Cancellation is cooperative. Long-running integrations must propagate and observe the agent cancellation signal rather than blocking the event loop. (The TypeScript SDK uses
AbortSignalinstead — see its AGENTS.md.)
MCP Tasks (Experimental)
The SDK supports MCP task-augmented execution for long-running tools. This feature is experimental and subject to change. Which task protocol runs depends on the installed mcp line:
- mcp 2.x: finalized SEP-2663 Tasks (protocol
2026-07-28) —tools/callreturns a direct result or a task handle, followed bytasks/get/tasks/update/tasks/cancel. - mcp 1.x: the legacy 2025-11-25 flow —
call_tool_as_task,poll_task,get_task_result.
Configuration
Enable tasks by passing a TasksConfig to MCPClient:
from datetime import timedelta
from strands.tools.mcp import MCPClient, TasksConfig
# Enable with defaults
client = MCPClient(transport, tasks_config={})
# Or configure explicitly
client = MCPClient(
transport,
tasks_config=TasksConfig(
poll_timeout=timedelta(minutes=10), # Overall task deadline (default 5min)
request_timeout=timedelta(minutes=1), # Per lifecycle request (default 1min)
poll_interval=timedelta(seconds=1), # Fallback when the server omits pollIntervalMs
ttl=timedelta(minutes=2), # Legacy 1.x task time-to-live (default 1min)
),
)Decision Logic
Task-augmented execution is used when ALL conditions are met:
- Client opts in via
tasks_config(not None) - Server advertises task capability (on 1.x,
tasks.requests.tools.call; on 2.x, theio.modelcontextprotocol/tasksextension) - On the mcp 1.x line only: tool's
execution.taskSupportisrequiredoroptional(the finalized extension has no tool-level setting)
Key Files
src/strands/tools/mcp/mcp_tasks.py-TasksConfig, task result models, and defaultssrc/strands/tools/mcp/mcp_client.py- Task execution logic (2.x:_call_tool_with_task_and_poll_async; 1.x:_call_tool_as_task_and_poll_async) and the public task lifecycle methods (submit_tool_*,get_task_*,update_task_*,cancel_task_*)tests/strands/tools/mcp/test_mcp_client_tasks.py- Unit tests (1.x flow; runs in the MCP 1.x Compat CI job)tests/strands/tools/mcp/test_mcp_client_tasks_v2.py- Unit tests (2.x flow)tests_integ/mcp/test_mcp_client_tasks.py- Integration teststests_integ/mcp/task_echo_server.py- Test server with task support
Testing
Before writing tests, read docs/TESTING.md. It is the authoritative reference for the shared fixtures (reuse them — don't hand-roll mock models/hooks), the
tru_/exp_assertion-pair naming, whole-object assertions, and test organization. The summary below is just the entry point.
- Unit tests in
tests/mirror thesrc/strands/structure exactly (tests/strands/agent/test_agent.py↔src/strands/agent/agent.py); use mocking for external dependencies and fixtures fromtests/fixtures/. - Integration tests in
tests_integ/exercise real providers end to end, require credentials, and are organized by feature area. - File naming:
test_{module}.pyintests/strands/{path}/;test_{feature}.pyintests_integ/. - Writing tests: pytest fixtures for setup/teardown,
motofor AWS,@pytest.mark.asyncioon every async test (strict mode), keep tests focused and independent, import packages at the top of the file.
Quick Rules
The un-lintable rules an agent most often misses — every one is enforced by review, not tooling (formatting, import order, line length, docstring presence, and type-annotation coverage are already handled by ruff/mypy; run hatch fmt). Cross-SDK rules (plugin naming, parity, public/internal marking, logging format, evergreen comments) are in the root AGENTS.md.
Do:
- Spell optionals
X | None(neverOptional[X]); scope suppressions# type: ignore[code] - Choose the data construct by role (TypedDict / dataclass / pydantic) — see Data Structures
- Document a
Raises:section when a public function raises as part of its contract - Declare a public package's surface with an explicit
__all__ - Use a
Protocolwith**kwargs(notCallable) for extensible interfaces; compare tools bytool_name, not a string literal - Name hook events
…EventwithBefore{Action}Event/After{Action}Eventpairing (readdocs/HOOKS.mdfirst) - In a
streamoverride, put a bare*beforetool_choice; type itAsyncGenerator[StreamEvent, None] - Wrap blocking/sync work in
asyncio.to_thread; gate any 3.11+ asyncio API behindsys.version_info - Name every variable for its content, even short-lived loop/catch bindings (
event/index/error, nevere/i/x)
Don't:
raise Exception(...)— raise a specific type and chain the cause withfrom- Let a raw vendor error escape a provider boundary — translate to a typed SDK exception
- Keep a model-provider config as a plain
dict+cast— store theTypedDict - Buffer a stream into a list before yielding
- Use
invocation_statefor SDK-internal state — it is user-only (see the root AGENTS.md)
Development Commands
# Environment
hatch shell # Enter dev environment
# Formatting & Linting
hatch fmt --formatter # Format code
hatch fmt --linter # Run linters (ruff + mypy)
# Testing
hatch test # Run unit tests
hatch test -c # Run with coverage
hatch run test-integ # Run integration tests
hatch test --all # Test all Python versions
# Pre-commit
pre-commit run --all-files # Run all hooks manually
# Readiness Check
hatch run prepare # Run all checks (format, lint, test)
# Build
hatch build # Build packageAgent-Specific Notes
Writing Code
- Make the SMALLEST reasonable changes to achieve the desired outcome
- Prefer simple, clean, maintainable solutions over clever ones
- Reduce code duplication, even if refactoring takes extra effort
- Match the style and formatting of surrounding code
- Fix broken things immediately when you find them
Code Comments
Comments are to-the-point, state only what cannot be inferred from the code, and stay evergreen. The full rule (including how it applies to tests, and the deprecated/legacy nuance) is in the root AGENTS.md.
Code Review Considerations
- Address all review comments
- Test changes thoroughly
- Update documentation if behavior changes
- Maintain test coverage
- Follow conventional commit format for fix commits
Additional Resources
- Strands Agents Documentation
- CONTRIBUTING.md - Human contributor guidelines
- docs/ - Developer documentation
- STYLE_GUIDE.md - Code style conventions
- TESTING.md - Testing reference
- HOOKS.md - Hooks system guide
- MCP_CLIENT_ARCHITECTURE.md - MCP threading design
- MCP_VERSIONS.md - MCP 1.x/2.x support and migration
- PR.md - PR description guidelines
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

