Skip to content

Let Claude Agent SDK agent loops use common.ai toolsets through a new AirflowTools adapter - #74026

Merged
Lee-W merged 23 commits into
apache:mainfrom
astronomer:common-ai-native-harness
Oct 28, 2026
Merged

Lee-W merged 23 commits into
apache:mainfrom
astronomer:common-ai-native-harness

Conversation

@Lee-W

@Lee-W Lee-W commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Why

Agents whose loop is the Claude Agent SDK's query() could not use common.ai's connection-backed toolsets without being rebuilt as an AgentOperator.

What

Add airflow.providers.common.ai.tools.claude_agent_sdk.AirflowTools, which serves common.ai's connection-backed toolsets (SQLToolset, HookToolset, ...) to the Claude Agent SDK through an in-process MCP server. The Dag author keeps the loop. common.ai owns the tool layer, as in the existing Strands and ADK adapters.

  • New opt-in extra: pip install "apache-airflow-providers-common-ai[claude-agent-sdk]" (claude-agent-sdk>=0.2.160). Nothing changes for existing installs. Importing the adapter without the SDK raises AirflowOptionalProviderFeatureException.
  • Usage is AirflowTools(SQLToolset(...)), then tools.options(...), then await tools.run(query(prompt=..., options=options)). An example Dag (example_claude_agent_sdk.py) and a guide (docs/frameworks/claude_agent_sdk.rst) are included.
  • The adapter keeps the same promises as the other framework adapters:
    • Each tool keeps its source name, description and argument schema.
    • Results go through the secret masker before the model sees them. The test covers the case where mask_secrets cannot descend into an opaque object, so masking happens after rendering to text.
    • Failures the model can correct reach it as an is_error tool result.
    • Failures the model cannot fix (for example a hook raising) make run raise ToolCallError, so the task fails and Airflow's retry applies.
    • Tool calls are counted in common_ai.tool_calls with the new tag value framework=claude_agent_sdk. Framework in tool_metrics.py, observability.rst and metrics_template.yaml are updated to match.
  • AirflowTools.options() defaults the SDK options to tools=[], setting_sources=[] and strict_mcp_config=True. A bare ClaudeAgentOptions() loads ~/.claude, project settings and .mcp.json on the worker, and leaves a worker-host Bash tool on. This is stated in the docs and the options() docstring. Anyone who builds ClaudeAgentOptions by hand has to set these fields themselves, and the guide says so.
  • uv.lock adds claude-agent-sdk 0.2.163 and the extra. docs/index.rst adds the extra to the extras table, and the table columns are re-padded.

Was generative AI tooling used to co-author this PR?
  • Yes (please specify the tool below)

Generated-by: [Claude] following the guidelines


  • Read the Pull Request Guidelines for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
  • For fundamental code changes, an Airflow Improvement Proposal (AIP) is needed.
  • When adding dependency, check compliance with the ASF 3rd Party License Policy.
  • For significant user-facing changes create newsfragment: {pr_number}.significant.rst, in airflow-core/newsfragments. You can add this file in a follow-up commit after the PR is created so you know the PR number.

@Lee-W
Lee-W force-pushed the common-ai-native-harness branch 2 times, most recently from 21e14dd to 0d34121 Compare October 4, 2026 13:59
@Lee-W
Lee-W marked this pull request as ready for review October 4, 2026 14:16
@Lee-W
Lee-W force-pushed the common-ai-native-harness branch 2 times, most recently from 5b78271 to 30d9f99 Compare October 5, 2026 08:28
@Lee-W
Lee-W marked this pull request as draft October 6, 2026 03:04
@Lee-W Lee-W changed the title Add HarnessOperator to run Claude Agent SDK loops in common.ai Add Claude Agent SDK adapter for common.ai toolsets Oct 7, 2026
@Lee-W
Lee-W force-pushed the common-ai-native-harness branch 2 times, most recently from ac42689 to af35e21 Compare October 8, 2026 05:21
@Lee-W Lee-W changed the title Add Claude Agent SDK adapter for common.ai toolsets Let Claude Agent SDK agent loops use common.ai toolsets through a new AirflowTools adapter Oct 8, 2026
@Lee-W
Lee-W force-pushed the common-ai-native-harness branch from af35e21 to e085227 Compare October 8, 2026 08:44
@Lee-W
Lee-W marked this pull request as ready for review October 8, 2026 09:17
@Lee-W
Lee-W force-pushed the common-ai-native-harness branch 5 times, most recently from 8450fe3 to b5ac727 Compare October 13, 2026 13:06
@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

uv.lock on main just moved via #75689 ("Allow FastAPI 0.137+ by requiring cadwyn 8.1"), commit b70a439 and this PR currently conflicts.

Quickest fix:

git fetch upstream main && git rebase upstream/main
rm uv.lock && uv lock
git add uv.lock && git rebase --continue
git push --force-with-lease

Automated nudge — ignore if you're not ready to rebase. This comment is updated in place on future uv.lock bumps.

@Lee-W
Lee-W force-pushed the common-ai-native-harness branch from b5ac727 to 915c76d Compare October 14, 2026 08:12
Lee-W added 21 commits October 28, 2026 16:39
… a success

`ClaudeSDKClient.receive_response()` stops right after the `ResultMessage`, so an
error result (`max_turns` reached, API failure) came back from `run()` as a
success and the task passed with an empty result. `run()` now raises
`RuntimeError` when `ResultMessage.is_error` is set, after any `ToolCallError`.
The message lists the result's subtype, text and errors, bounded in length.

The docstring now says `receive_messages()` is not supported.

Tests cover the error result, a failure stopping the stream before the next turn
starts, and the `isError` mapping against a real SDK MCP server.
…d-built tools

Every tool `AirflowTools` registers now carries
`ToolAnnotations(maxResultSizeChars=DEFAULT_MAX_RESULT_BYTES)`, the cap
`SQLToolset` applies to its results. The Claude Agent SDK writes a result over
its inline limit to a file and shows the model a preview; with `tools=[]` the
model has no `Read` tool to open that file.

A hand-built `AirflowTool` whose schema is `{"type": "object"}` no longer gets a
required `type` argument from the SDK: the copy handed to the SDK now has an
empty `properties`.
…rences

Label the sample tool log and is_error result as illustrative, show the
SQLToolset tool names, link every AirflowTools.run reference, say that
build_options() keeps the caller's mcp_servers, and describe the RuntimeError
raised for an error result and the raised inline result ceiling.
`build_options()` now defaults `verbatim_prompts=True`. Without it the
Claude Code CLI expands `@path` mentions in the prompt, so a Dag that takes
the question as a parameter could send any file the worker can read to the
model without passing through the secrets masker. `verbatim_prompts` also
turns off slash commands and the turn-start attachment pass, and needs
Claude Code CLI 2.1.248 or later.

When the caller passes `can_use_tool`, the Airflow tools are no longer added
to `allowed_tools`, which made the CLI auto-approve them and skip the
callback, and `permission_mode` defaults to `"default"` so the callback is
consulted. An explicit `permission_mode` still wins.

`maxResultSizeChars` is now 500,000, the ceiling the bundled CLI applies
(observed with CLI 2.1.286; a larger value is clamped), and a tool result
over that size is truncated with a notice after masking, so it stays inline
and cannot overrun the SDK's 1 MiB message buffer.
…nt one failure per model turn

`AirflowTools.run` now closes the `messages` stream before it clears its run
state. Previously, when `run` raised, the Claude Code CLI kept going: it sent
further `tools/call` requests after the run state was cleared, so the "not run"
guard was skipped and the tool executed, and `asyncio.run` shutdown logged
`aclose(): asynchronous generator is already running`. For `query()`, closing
the stream ends the CLI session; a `ClaudeSDKClient` stays connected until it is
disconnected. A failure to close the stream is logged when the run already
failed, and raised otherwise.

The retry budget now receives the `message_id` of the latest `AssistantMessage`
as the turn, so several failed calls in one model turn count as one failure, as
in the Anthropic and Strands adapters. Without a `message_id`, failures still
count per call. The bundled CLI delivers a turn's `AssistantMessage` before its
first tool call, but the SDK does not document that order.
…extras table

`query()` raises the SDK's `ResultError` for an error result, because the
Claude Code CLI exits non-zero right after it and the SDK raises from the
stream before `AirflowTools.run` reaches its own check. Only
`ClaudeSDKClient.receive_response()` reaches the `RuntimeError`. The guide and
the `run` docstring now say which stream raises which.

The guide now describes the framework-neutral tool interface as stable and only
`AirflowTools` as experimental, as the other framework guides do.

The extras table in the provider index had a leftover `=======` line and the old
table above the new one, so the section rendered as a paragraph. Only the new
table is kept, with the `skills` extra's `<2` upper bound restored to match
`pyproject.toml`.
…s the CLI lists

The example imported the SDK and the adapter at module level, so the guide's
`exampleinclude` showed `query`, `AirflowTools` and `SQLToolset` without their
imports, and parsing the file without the extra failed with
`ModuleNotFoundError`. The imports now sit inside the task, as in the other
framework examples.

A new test reads `tools/list` from the real MCP server and checks each tool's
name, description, input schema and result-size limit, which no test read back
before. The test module also imports `AirflowOptionalProviderFeatureException`
at the top, and its remaining `AsyncMock` now has a spec.
…xamples

The guide's task log and `is_error` examples were illustrative and the log
listed only `list_tables`. Both now come from a real run of the example
against a temporary SQLite database: the task log shows the model calling
`list_tables`, `get_schema` and `query`, and the error example is the
`tool_result` the model read when `SQLToolset` rejected a `DELETE` statement.
`uv sync --frozen` failed with "Found duplicate package pyvespa==1.2.9", so
every `uv run` and the mypy hooks that sync a virtualenv could not run. Re-lock
with the repo-pinned uv 0.13.1 so `pyvespa` has a single entry again.
…nd check the stream really closes

- The failing-`aclose` test patches `log` with `autospec` instead of asserting
  on `caplog`, which only supports `in` from Airflow 3.1.
- The cancelled-run test uses a class-based stream whose `aclose` is recorded,
  so it fails when `_close_stream` is removed.
… `asyncio` inside the example task

- The stability entry attributed the handler-exception-to-error-result
  conversion to the Claude Code CLI; it is the SDK's in-process MCP server.
- `asyncio` moves into the task so the guide's `exampleinclude` shows every
  import the example needs.
…line cap do not kill it

- `build_options()` sets `max_buffer_size` to 16 MiB unless the caller passes one.
  The CLI writes each tool result to stdout twice, JSON-escaped, and the SDK
  fails the stream on any line over 1 MiB, which a result well under the
  500,000 character inline cap can exceed.
- The guide no longer says only a result of about a million characters fails.
…n` has ended

`run()` cleared its state before the SDK's own teardown finished, so a
`tools/call` landing in that gap saw no run and executed the tool.

- The handler now keeps the most recent run visible and refuses calls once it
  has ended, with a message that tells an ended run from a failed one.
- A call that arrives after the next run has started cannot be told apart and
  is served by that run; the class docstring says so.
- The gap is modelled with a fake stream; the tests do not reproduce the SDK's
  real teardown timing.
…results are not spilled to a file

- Tool results are compared with the 500,000 ceiling in UTF-16 code units, the way the bundled CLI counts them, instead of code points.
- A truncated result is cut on a code point boundary, so a surrogate pair is never split, and the notice still counts toward the ceiling.
- The guide notes that the CLI counts UTF-16 code units.
… result

- `run` keeps the first `is_error` result and raises on it after the stream
  ends, so an error turn followed by a successful turn is no longer
  reported as a success.
- Link the module's experimental note to `howto/stability`, as the sibling
  adapters do.
…servers` key

- The framework index intro, the "Bring your own agent" paragraph and table
  in the features guide, and the toolsets bridge list now name the Claude
  Agent SDK.
- The Claude Agent SDK guide says a hand-built `mcp_servers` entry must use
  `tools.server_name` as its key, or `allowed_tools` will not match.
Comparing the whole ~250k-character string made pytest diff it on failure,
so a regression took minutes to surface instead of failing fast.
…or declaration

- `uv.lock` is `main`'s lock with only `claude-agent-sdk` (0.2.168) added by a
  plain `uv lock`; the 52 unrelated version changes and the removed
  `pyvespa` Python-version split entries are gone.
- With the lock back on pydantic-ai-slim 2.56, the Meta vendor entry and the
  2.57.0 gate in `test_provider_metadata.py` are no longer needed, so
  `provider.yaml`, `get_provider_info.py` and the test return to `main`.
The framework index and the Claude Agent SDK guide said the adapter was
tested with 0.2.163, while `uv.lock` resolves 0.2.168.
A second error result with different text now fails the test if `run()` keeps the last error instead of the first.
…note the streamed-prompt error rule

The guide named three of the four tools `SQLToolset` serves, and its error-result section described only a single prompt. It now lists `check_query` and says that with a streamed prompt `run()` raises `RuntimeError` when any turn ended in an error result, even if a later turn succeeds.
@Lee-W
Lee-W force-pushed the common-ai-native-harness branch from f3ed363 to 0aa5b4b Compare October 28, 2026 08:39
@Lee-W
Lee-W disabled auto-merge October 28, 2026 13:38
@Lee-W
Lee-W enabled auto-merge (squash) October 28, 2026 13:43
@Lee-W
Lee-W merged commit 320b0c5 into apache:main Oct 28, 2026
89 checks passed
@Lee-W
Lee-W deleted the common-ai-native-harness branch October 28, 2026 14:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants