把 Connector 用作 tool
查看 MarkdownAgent 可以把官方 Connector 的 operation 当作 tool 调用。每次调用都在自己的 tool Step 中运行一个 operation,使用 Connector 的 credential,以及与 Connector Step 相同的稳定 Call ID。Mutation 从这个 Call ID 派生发给 provider 的幂等键,所以这次调用的每次尝试都发送同一个 key。
工作方式
ConnectorToolSource 提供你指定的 operation。Agent 把它作为 tool source 接收:Python 中是 tool_sources,TypeScript 中是 toolSources,Go 中是 WithToolSources 选项。Manifest 允许 Agent 使用哪些 operation,见 Name the tools(英文)。
Dex 先按 operation 的 input schema 检查模型给出的参数。字段错误或缺失时,调用在 operation 运行之前就会失败,并返回一条模型可以据此修正的消息。
Effect class
Operation 的 effect class 就是 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;结果未知后可以在发送上限内重发(英文) |
| 其他 Mutation | non_idempotent_write | CallSingleAttemptTool,这次调用只有一次尝试 |
有限次重发适合偶尔重复也能接受的写操作,例如聊天消息或电子邮件。Session 的 tool policy 改变不了 Connector tool 的 effect class;见 Step options(英文)。
审批
Manifest 建议审批(agent.approval: recommended)的 Connector tool 会等待审批,例如退款。其他 Mutation 默认直接运行。应用可以为每个 tool 覆盖这个设置,或者传入一个 predicate,根据参数逐次决定,例如超过某个金额的退款。Predicate 抛出异常时,调用会请求审批。Session 的 tool policy 优先于这两者,见 Step options(英文)。
结果
Operation 的分支决定 Tool Call 的记录:succeeded、failed,或者在写操作可能已经生效时记录为 outcome_unknown。Outcomes(英文)列出了每个分支。outcome_unknown 的核对方式 与其他 tool 相同。
Worker 崩溃后,Connector 调用遵循崩溃后什么会再运行,新的调用可能重复它的效果。有限次重发的 Mutation 只在结果未知、且 read-back 无法确认时才再次发送,次数不超过一个计入每次发送的上限。Crashes(英文)逐一列出了每种情况。
写操作顺序
同一个模型响应中的 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(英文)。
连接 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(英文)。
提供 tool
安装 dex-agents 的 connectors extra,以及 Connector 包,例如 dex-connector-slack(安装命令,英文)。connector_tool 把 operation 变成 tool。
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
添加 Slack Connector 模块 github.com/superdurable/dex-connectors-library/connectors/slack/go;connectortools 包是 Go core 的一部分。connectortools.NewConnectorTool 把 operation 的 agent tool 变成 tool。
// NewSlackToolSources returns the Slack tool source, or no source when connection is nil.
//
// The source offers one tool, slack_post_thread_reply. Each call runs in its
// own tool Step with the Connector's Call ID, after a person approves it. It
// returns an error when the Connector's agent tools cannot be built.
func NewSlackToolSources(connection *slack.Connection) ([]dexagents.ToolSource, error) {
if connection == nil {
return nil, nil
}
agentTools, err := connection.AgentTools()
if err != nil {
return nil, err
}
tools := []*connectortools.ConnectorTool{}
for _, agentTool := range agentTools {
if agentTool.Metadata().ToolName != SlackPostThreadReplyToolName {
continue
}
// Every post waits for a person, whatever the manifest recommends.
tool, err := connectortools.NewConnectorTool(agentTool, connectortools.WithRequiresApproval(true))
if err != nil {
return nil, err
}
tools = append(tools, tool)
}
source, err := connectortools.NewConnectorToolSource(tools)
if err != nil {
return nil, err
}
return []dexagents.ToolSource{source}, nil
}
例子: examples/go/agent-harnesses/ordersupport/slack_connector_tools.go
安装 @superdurable/connectors-sdk 以及 Connector 包,例如 @superdurable/connector-slack(安装命令,英文)。connectorTool 把 operation 变成 tool。
export async function openSlackConnectionFromProject(
environment: NodeJS.ProcessEnv = process.env,
): Promise<Connection | undefined> {
// ...
const project = await loadFromEnvironment(environment);
// ...
return newProjectConnection(project, slackConnectionName);
}
// ...
export function createSlackConnectorToolSources(slack: Connection | undefined): ToolSource[] {
if (slack === undefined) {
return [];
}
return [
new ConnectorToolSource([
connectorTool(slack.operations.postThreadReply(), slack.reference, {
manifest,
inputValidator: PostThreadReplyInputSchema,
// The manifest does not ask for approval; this agent asks before every post.
requiresApproval: true,
}),
]),
];
}
Worker 在启动时打开一次 connection,每个 Agent 都使用它:
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
// One Slack connection for the agent; without it the agent offers no Slack tool.
slackConnection, err := ordersupport.OpenSlackProjectConnection(ctx)
if err != nil {
return err
}
slackToolSources, err := ordersupport.NewSlackToolSources(slackConnection)
if err != nil {
return err
}
// One Slack connection for the agent examples; without it they offer no Slack tools.
const slack = await openSlackConnectionFromProject();
Agent 把这个 tool source 和它自己的 tool 一起传入:
- Claude Agent SDK
- Eino
- Google ADK
- LangGraph
- Mastra
- OpenAI Agents SDK
- Pi
- Pydantic AI
- Vercel AI SDK
- Dex Agent Framework
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
return createClaudeAgentSessionFlow(
{
// ...
toolSources: createSlackConnectorToolSources(slack),
},
claudeAgentSdkOrderSupportFlowType,
);
return dexeino.NewAgentSessionFlow(config, EinoOrderSupportFlowType,
dexeino.WithToolEffects(map[string]dexagents.ToolEffect{
"look_up_order": dexagents.ToolEffectRead,
// Not safe to repeat, so Dex asks for approval first and runs it at most once.
"cancel_order": dexagents.ToolEffectNonIdempotentWrite,
}),
dexeino.WithToolSources(toolSources...))
例子: examples/go/agent-harnesses/ordersupport/eino_order_support.go
return adk_agent_session_flow(
agent,
flow_type=GOOGLE_ADK_ORDER_SUPPORT_FLOW_TYPE,
tool_sources=build_slack_tool_sources(slack_connection),
# ...
)
例子: examples/python/agent-harnesses/agent_harness_examples/google_adk_order_support.py
return langchain_agent_session_flow(
build_order_support_agent,
flow_type=LANGCHAIN_ORDER_SUPPORT_FLOW_TYPE,
tool_sources=build_slack_tool_sources(slack_connection),
# ...
)
例子: examples/python/agent-harnesses/agent_harness_examples/langchain_order_support.py
return createMastraAgentSessionFlow(agent, mastraOrderSupportFlowType, {
// ...
toolSources: createSlackConnectorToolSources(slack),
});
例子: examples/typescript/src/products/agent-harnesses/mastra/mastra-order-support-flow.ts
return openai_agents_session_flow(
agent,
flow_type=OPENAI_AGENTS_ORDER_SUPPORT_FLOW_TYPE,
tool_sources=build_slack_tool_sources(slack_connection),
# ...
)
例子: examples/python/agent-harnesses/agent_harness_examples/openai_agents_order_support.py
return createOpenAIAgentsSessionFlow(agent, openAIAgentsOrderSupportFlowType, {
// ...
toolSources: createSlackConnectorToolSources(slack),
});
例子: examples/typescript/src/products/agent-harnesses/openai-agents/openai-agents-order-support-flow.ts
return createBuiltinAgentSessionFlow(
{
// ...
toolSources: createSlackConnectorToolSources(slack),
},
piOrderSupportFlowType,
);
例子: examples/typescript/src/products/agent-harnesses/pi/pi-order-support-flow.ts
return pydantic_ai_session_flow(
agent,
flow_type=PYDANTIC_AI_ORDER_SUPPORT_FLOW_TYPE,
tool_sources=build_slack_tool_sources(slack_connection),
# ...
)
例子: examples/python/agent-harnesses/agent_harness_examples/pydantic_ai_order_support.py
return createVercelAiAgentSessionFlow(
{
// ...
toolSources: createSlackConnectorToolSources(slack),
},
vercelAiOrderSupportFlowType,
);
例子: examples/typescript/src/products/agent-harnesses/vercel-ai/vercel-ai-order-support-flow.ts
Dex Agent Framework 示例安装的包与 提供 tool 相同,并有自己的一份 tool source 模块:
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/dex_examples/products/ai-agent/slack_connector_tools.py
export async function openSlackConnectionFromProject(
environment: NodeJS.ProcessEnv = process.env,
): Promise<Connection | undefined> {
// ...
const project = await loadFromEnvironment(environment);
// ...
return newProjectConnection(project, slackConnectionName);
}
// ...
export function createSlackConnectorToolSources(slack: Connection | undefined): ToolSource[] {
if (slack === undefined) {
return [];
}
return [
new ConnectorToolSource([
connectorTool(slack.operations.postThreadReply(), slack.reference, {
manifest,
inputValidator: PostThreadReplyInputSchema,
// The manifest does not ask for approval; this agent asks before every post.
requiresApproval: true,
}),
]),
];
}
Worker 在启动时打开一次 connection,每个 Agent 都使用它:
async def main() -> None:
load_dotenv(Path(__file__).resolve().parents[1] / ".env")
config = ExamplesConfig.from_env()
slack_setup = await open_slack_project_connection()
try:
app_state = ExampleApp(config, slack_setup.connection if slack_setup else None)
# ...
finally:
if slack_setup is not None:
await slack_setup.aclose()
// One Slack connection for the agent examples; without it they offer no Slack tools.
const slack = await openSlackConnectionFromProject();
Agent 把 Slack tool source 和 MCP tool source 放在一起:
mcp_tool_sources = (
[McpToolSource(mcp_servers, resource_and_prompt_tools_enabled=True)] if mcp_servers else []
)
definition = AgentDefinition(
# ...
tool_sources=[*mcp_tool_sources, *build_slack_tool_sources(slack_connection)],
# ...
)
例子: examples/python/dex_examples/products/ai-agent/ai_agent_session.py
// Each MCP tool's annotations pick its effect, and so whether it waits for approval.
toolSources: [
new McpToolSource(config.mcpServers, { resourceAndPromptToolsEnabled: true }),
...createSlackConnectorToolSources(slack),
],
例子: examples/typescript/src/products/ai-agent/ai-agent-flow.ts
试用 Slack tool
先设置 DEX_CONNECTOR_CONFIG_FILE 再启动示例;Worker 从哪里找到 support-slack,见 Connections(英文)。然后让 Agent 在某个 Slack thread 中回复,并给出 channel ID 和 thread timestamp:
Reply in Slack thread C0123456789 1710000000.000100: Order 1002 ships on Thursday.
这次发帖和 cancel_order 一样,会等待审批。
下一步
- Dex Agent Framework:不用其他 agent SDK 的 Agent。
- Connector tools reference(英文):package、tool 名称、结果大小、connection,以及各 agent SDK 怎样把调用交给它的 tool Step。
- Connector Triggers(英文):从 Connector 事件启动 Session 并给它发送消息。