---
title: "把 Connector 用作 tool"
description: "Agent 可以把官方 Connector 的 operation 当作 tool 调用。每次调用都在自己的 tool Step 中运行一个 operation，使用 Connector 的 credential，以及与 Connector Step 相同的稳定 Call ID。Mutation 从这个 Call ID 派生发给 provider 的幂等键，所以这次调用的每次尝试都发送同一个 key。"
canonical_url: "https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/agent-frameworks/connectors-as-tools.mdx"
locale: "zh-Hans"
framework: "claude-agent-sdk"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# 把 Connector 用作 tool

本文件为 Claude Agent SDK 版本。其他框架：[Eino](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.eino.md) · [Google ADK](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.google-adk.md) · [LangGraph](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.langchain-langgraph.md) · [Mastra](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.mastra.md) · [OpenAI Agents SDK](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.openai-agents-sdk.md) · [Pi](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.pi.md) · [Pydantic AI](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.pydantic-ai.md) · [Vercel AI SDK](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.vercel-ai-sdk.md) · [Dex Agent Framework](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.built-in-agent-loop.md)

本页代码为 Python。其他语言：[TypeScript](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.typescript.md)

Agent 可以把官方 [Connector](https://docs.superdurable.io/zh-Hans/concepts/connector.md) 的 operation 当作 tool 调用。每次调用都在自己的 tool Step 中运行一个 operation，使用 Connector 的 credential，以及与 Connector Step 相同的稳定 Call ID。Mutation 从这个 Call ID 派生发给 provider 的幂等键，所以这次调用的每次尝试都发送同一个 key。

<a id="connectors-as-tools"></a>

## 工作方式

`ConnectorToolSource` 提供你指定的 operation。Agent 把它作为 tool source 接收：Python 中是 `tool_sources`，TypeScript 中是 `toolSources`，Go 中是 `WithToolSources` 选项。Manifest 允许 Agent 使用哪些 operation，见 [Name the tools](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#connector-tools-offered)（英文）。

Dex 先按 operation 的 input schema 检查模型给出的参数。字段错误或缺失时，调用在 operation 运行之前就会失败，并返回一条模型可以据此修正的消息。

<a id="connector-tools-effects"></a>

### Effect class

Operation 的 [effect class](https://docs.superdurable.io/zh-Hans/concepts/connector.md#effect-classes) 就是 tool 的 effect class，并由此决定哪个 Step 运行调用：

| Operation                                           | Effect class           | 运行于                                                                                                                                     |
| --------------------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| Query                                               | **read**               | `CallTool`，会重试                                                                                                                          |
| Manifest 标记为可安全重试（**agent.retry: safe**）的 Mutation  | `idempotent_write`     | `CallTool`，会重试                                                                                                                          |
| 有限次重发（**agent.repeatOnUnknown: limited**）的 Mutation | `non_idempotent_write` | `CallSingleAttemptTool`；结果未知后可以在发送上限内[重发](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#bounded-resends)（英文） |
| 其他 Mutation                                         | `non_idempotent_write` | `CallSingleAttemptTool`，这次调用只有[一次尝试](https://docs.superdurable.io/zh-Hans/reference/agents/failures.md#tool-runs-twice)                 |

有限次重发适合偶尔重复也能接受的写操作，例如聊天消息或电子邮件。Session 的 tool policy 改变不了 Connector tool 的 effect class；见 [Step options](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#step-options)（英文）。

<a id="connector-tools-approval"></a>

### 审批

Manifest 建议审批（**agent.approval: recommended**）的 Connector tool 会等待审批，例如退款。其他 Mutation 默认直接运行。应用可以为每个 tool 覆盖这个设置，或者传入一个 predicate，根据参数逐次决定，例如超过某个金额的退款。Predicate 抛出异常时，调用会请求审批。Session 的 tool policy 优先于这两者，见 [Step options](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#step-options)（英文）。

<a id="connector-tools-outcomes"></a>

### 结果

Operation 的分支决定 Tool Call 的记录：**succeeded**、**failed**，或者在写操作可能已经生效时记录为 `outcome_unknown`。[Outcomes](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#outcomes)（英文）列出了每个分支。`outcome_unknown` 的核对方式 [与其他 tool 相同](https://docs.superdurable.io/zh-Hans/reference/agents/failures.md#reconcile-outcome-unknown)。

Worker 崩溃后，Connector 调用遵循[崩溃后什么会再运行](https://docs.superdurable.io/zh-Hans/reference/agents/failures.md#what-runs-again)，[新的调用](https://docs.superdurable.io/zh-Hans/reference/agents/failures.md#tool-runs-twice)可能重复它的效果。有限次重发的 Mutation 只在结果未知、且 read-back 无法确认时才再次发送，次数不超过一个计入每次发送的上限。[Crashes](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#crashes)（英文）逐一列出了每种情况。

<a id="connector-tools-write-order"></a>

### 写操作顺序

同一个模型响应中的 Connector 写操作按模型给出的顺序逐个运行。读操作和其他 tool 的调用并行运行。需要审批的写操作要等轮到它时才请求审批。

当一个写操作失败、以 `outcome_unknown` 结束或被拒绝时，同一响应中后面的 Connector 写操作都会被跳过。每个被跳过的写操作记录为 **failed** 并设置 **skipped**，错误信息以“the tool did not run, so it is safe to call again”开头。Claude Agent SDK 则在它的分段内直接拒绝这样的写操作；见 [Connector tools: Framework adapters](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#framework-adapters)（英文）。

<a id="connect-connectors"></a>

## 连接 Connector

配置好 Slack connection **support-slack** 后，每个示例 Agent 都会得到 tool `slack_post_thread_reply`，它运行 Slack operation `postThreadReply`，在 thread 中回复。没有这个 connection 时，示例记录一行日志，不带这个 tool 照常运行。每个示例都设置了 `requires_approval=True`（TypeScript 中是 **requiresApproval: true**，Go 中是 `connectortools.WithRequiresApproval(true)`），所以每次发帖都先等待人审批，然后在 `CallSingleAttemptTool` 中运行。Go 示例使用的 Slack Connector 版本带有限次重发；每个示例的发帖可能怎样重复，见 [The Slack tool in the examples](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#slack-example)（英文）。

<a id="offer-connector-tools"></a>

### 提供 tool

**Python**

安装 `dex-agents` 的 `connectors` extra，以及 Connector 包，例如 `dex-connector-slack`（[安装命令](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#install)，英文）。`connector_tool` 把 operation 变成 tool。

```python
def build_slack_tool_sources(connection: slack.Connection | None) -> list[ToolSource]:
    """Returns the Slack tool source, or no source when Slack is not configured."""
    if connection is None:
        return []
    return [
        ConnectorToolSource([
            # The manifest does not ask for approval; this agent asks before every post.
            connector_tool(
                connection.post_thread_reply(), connection.reference, requires_approval=True
            ),
        ]),
    ]

# ...

async def open_slack_project_connection(
    environment: Mapping[str, str] = os.environ,
) -> SlackProjectConnection | None:
    # ...
    # An incomplete or invalid configuration raises here, so the Worker fails at startup.
    try:
        project = await load_from_environment(environment)
    except FileNotFoundError:
        _log_slack_not_set_up("the connector configuration file does not exist")
        return None
    # ...
    try:
        connection = slack.new_project_connection(project, SLACK_CONNECTION_NAME)
    except BaseException:
        await project.close()
        raise
    return SlackProjectConnection(project, connection)
```

例子: [examples/python/agent-harnesses/agent_harness_examples/slack_connector_tools.py](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses/agent_harness_examples/slack_connector_tools.py)

Worker 在启动时打开一次 connection，每个 Agent 都使用它：

**Python**

```python
async def main() -> None:
    config = AgentHarnessExamplesConfig.from_env()
    slack_setup = await open_slack_project_connection()
    try:
        app_state = AgentHarnessExamplesApp(config, slack_setup.connection if slack_setup else None)
        # ...
    finally:
        if slack_setup is not None:
            await slack_setup.aclose()
```

例子: [examples/python/agent-harnesses/agent_harness_examples/\_\_main\_\_.py](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses/agent_harness_examples/__main__.py)

Agent 把这个 tool source 和它自己的 tool 一起传入：

**Python**

```python
    return claude_agent_session_flow(
        build_options,
        [look_up_order, cancel_order],
        flow_type=CLAUDE_AGENT_SDK_ORDER_SUPPORT_FLOW_TYPE,
        tool_sources=build_slack_tool_sources(slack_connection),
        # ...
    )
```

例子: [examples/python/agent-harnesses/agent_harness_examples/claude_agent_sdk_order_support.py](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses/agent_harness_examples/claude_agent_sdk_order_support.py)

<a id="try-the-slack-tool"></a>

### 试用 Slack tool

先设置 `DEX_CONNECTOR_CONFIG_FILE` 再启动示例；Worker 从哪里找到 **support-slack**，见 [Connections](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md#connector-tools-connection)（英文）。然后让 Agent 在某个 Slack thread 中回复，并给出 channel ID 和 thread timestamp：

```text
Reply in Slack thread C0123456789 1710000000.000100: Order 1002 ships on Thursday.
```

这次发帖和 `cancel_order` 一样，会等待审批。

<a id="next"></a>

## 下一步

- [Dex Agent Framework](https://docs.superdurable.io/zh-Hans/build-ai-agents/dex-agent-framework.md)：不用其他 agent SDK 的 Agent。
- [Connector tools reference](https://docs.superdurable.io/zh-Hans/reference/agents/connector-tools.md)（英文）：package、tool 名称、结果大小、connection，以及各 agent SDK 怎样把调用交给它的 tool Step。
- [Connector Triggers](https://docs.superdurable.io/zh-Hans/reference/agents/connector-triggers.md)（英文）：从 Connector 事件启动 Session 并给它发送消息。
