Lee-W commented on code in PR #74026:
URL: https://github.com/apache/airflow/pull/74026#discussion_r4257877769


##########
providers/common/ai/src/airflow/providers/common/ai/tools/claude_agent_sdk.py:
##########
@@ -0,0 +1,215 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Give Airflow tools to an agent loop run by the Claude Agent SDK.
+
+.. note:: Experimental; see :mod:`airflow.providers.common.ai.tools`.
+"""
+
+from __future__ import annotations
+
+try:
+    from claude_agent_sdk import (
+        ClaudeAgentOptions,
+        McpSdkServerConfig,
+        Message,
+        ResultMessage,
+        create_sdk_mcp_server,
+        tool,
+    )
+except ImportError as e:
+    from airflow.providers.common.compat.sdk import 
AirflowOptionalProviderFeatureException
+
+    raise AirflowOptionalProviderFeatureException(e)
+
+import copy
+import logging
+from typing import TYPE_CHECKING, Any
+
+from airflow.providers.common.ai.tools import AirflowTool, ToolCallError, 
collect_tools
+from airflow.providers.common.ai.tools._from_toolset import tool_call_scope
+from airflow.providers.common.ai.utils.tool_definition import serialize_for_llm
+from airflow.providers.common.ai.utils.tool_metrics import calling_framework
+
+if TYPE_CHECKING:
+    from collections.abc import AsyncIterable, Awaitable, Callable
+
+    from airflow.providers.common.ai.tools import ToolProvider
+
+log = logging.getLogger(__name__)
+
+__all__ = ["AirflowTools"]
+
+
+class _Run:
+    """One run of :meth:`AirflowTools.run`: identifies its calls and collects 
their failures."""
+
+    def __init__(self) -> None:
+        self.failures: list[ToolCallError] = []
+
+
+class AirflowTools:
+    """
+    Airflow's tools for an agent loop run by the Claude Agent SDK.
+
+    Pass toolsets that implement
+    :class:`~airflow.providers.common.ai.tools.ToolProvider`, such as 
``SQLToolset``
+    and ``HookToolset``, or individual
+    :class:`~airflow.providers.common.ai.tools.AirflowTool` objects. They are 
served
+    through an in-process MCP server; add it and :attr:`allowed_tools` to
+    ``ClaudeAgentOptions``, or build them with :meth:`build_options`, and 
drive the SDK's
+    ``query()`` with :meth:`run`:
+
+    .. code-block:: python
+
+        from claude_agent_sdk import query
+
+        from airflow.providers.common.ai.tools.claude_agent_sdk import 
AirflowTools
+        from airflow.providers.common.ai.toolsets.sql import SQLToolset
+
+        tools = AirflowTools(SQLToolset(db_conn_id="warehouse", 
allowed_tables=["orders"]))
+        options = tools.build_options(model="claude-sonnet-5", max_turns=10)
+        result = await tools.run(query(prompt="...", options=options))
+
+    Each tool keeps the source tool's name, description and argument schema, 
and every
+    result passes through Airflow's secret masker first. A failure the model 
can
+    correct, such as a query naming a missing column, reaches it as an 
``is_error``
+    tool result. A failure the model cannot fix, such as a hook raising, makes
+    :meth:`run` raise 
:class:`~airflow.providers.common.ai.tools.ToolCallError`, so the
+    task fails and Airflow retries it. The SDK's own tool dispatch catches 
every
+    exception a handler raises and turns it into an ``is_error`` result the 
model
+    reads, so drive the query with :meth:`run` rather than iterating it 
yourself.
+
+    An instance runs one query at a time: build a new ``AirflowTools`` per 
task, or
+    call :meth:`run` again once the previous run has finished.
+
+    :param sources: Toolsets and tools to serve, in order.
+    :param server_name: The MCP server name the tools are served under. Also 
the
+        prefix of each tool's name in :attr:`allowed_tools`
+        (``mcp__<server_name>__<tool name>``).
+    """
+
+    def __init__(self, *sources: ToolProvider | AirflowTool, server_name: str 
= "airflow") -> None:
+        self.server_name = server_name
+        airflow_tools = collect_tools(sources)
+        self.allowed_tools: list[str] = [f"mcp__{server_name}__{t.name}" for t 
in airflow_tools]
+        self._run: _Run | None = None
+        sdk_tools = [
+            tool(t.name, t.description, 
copy.deepcopy(t.parameters))(self._build_handler(t))

Review Comment:
   - Every MCP tool now carries `ToolAnnotations(maxResultSizeChars=...)` set 
to `SQLToolset`'s 64 KiB result cap, so the SDK keeps results inline.
   - A hand-built `AirflowTool` with `{"type": "object"}` gets an empty 
`properties` on the copy, so it no longer takes a required `type` argument.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to