<span id="连接消息通道"></span>

# Connect Messaging Channels

Check the channel ingress capabilities advertised by your deployment, create a managed Slack Socket Mode connection for an agent, and verify connection state and live message delivery.

(sdk-ai-studio-agent-ingress-flow)=
<span id="任务流程"></span>

## Task flow

```text
List advertised channel ingress capabilities
                     │
                     ▼
Create a Slack managed_stream connection
                     │
                     ▼
Check observed_state until connected
                     │
                     ▼
Send a Slack test message and verify the reply
```

(sdk-ai-studio-agent-ingress-prepare)=
<span id="准备"></span>

## Prerequisites

1. Complete the endpoint, personal access token, and workspace setup in [Use the SDK](../../../quickstart/ai-studio/sdk.md).
2. Obtain the target agent ID (`AGENT_ID`) and source workspace ID (`AGENT_WORKSPACE_ID`) via [Discover and Select Agents](发现与选择智能体.md#sdk-ai-studio-agents-s1), and choose an execution model (`AGENT_MODEL`) via [Inspect Model Backends and Endpoints](../资源中心/管理模型后端.md).
3. Follow [Configure Slack](../../../../guides/ai-studio/agents/manage-agents/im-connection/slack.md) to prepare your Slack app credentials and export **App ID** (`SLACK_APP_ID`), **App-Level Token** (`SLACK_APP_TOKEN`), and **Bot Token** (`SLACK_BOT_TOKEN`) in protected environment variables.

(sdk-ai-studio-agent-ingress-create)=
<span id="检查能力并创建托管连接"></span>

## Check capabilities and create a managed connection

Call `list_ingress_capabilities` (`ListIngressCapabilities` in Go) to verify that Slack `managed_stream` ingress is enabled on the deployment, then call `create_ingress_connection` (`CreateIngressConnection` in Go) to bind the agent and Slack credentials.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
import os

import moi_product_sdk as sdk

client = sdk.new_with_personal_access_token(
    os.environ["PRODUCT_API_BASE_URL"],
    os.environ["PRODUCT_API_KEY"],
)
service = client.agents(os.environ["WORKSPACE_ID"])

capabilities = service.list_ingress_capabilities()
if not any(
    item.provider == "slack"
    and item.channel_type == "slack_app"
    and "managed_stream" in item.receive_modes
    for item in capabilities.items
):
    raise SystemExit("Slack managed streams are not advertised on this deployment")

connection = service.create_ingress_connection(
    sdk.IngressConnectionCreateRequest(
        target=sdk.AgentTargetRef(
            kind="agent",
            workspace_id=os.environ["AGENT_WORKSPACE_ID"],
            id=os.environ["AGENT_ID"],
        ),
        provider="slack",
        channel_type="slack_app",
        receive_mode="managed_stream",
        agent_model=os.environ["AGENT_MODEL"],
        managed_stream=sdk.IngressManagedStreamConfig(
            app_id=os.environ["SLACK_APP_ID"],
            app_token=os.environ["SLACK_APP_TOKEN"],
            bot_token=os.environ["SLACK_BOT_TOKEN"],
        ),
    )
)
print("Connection:", connection.id, "Versions:", connection.association_version, connection.config_version)
print("State:", connection.desired_state, connection.observed_state, connection.last_error_code)
```

::::

::::{tab-item} Go
:sync: go

```go
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)

func main() {
	ctx := context.Background()
	client, err := sdk.NewWithPersonalAccessToken(
		os.Getenv("PRODUCT_API_BASE_URL"),
		os.Getenv("PRODUCT_API_KEY"),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	service := client.Agents(os.Getenv("WORKSPACE_ID"))
	capabilities, err := service.ListIngressCapabilities(ctx)
	if err != nil {
		log.Fatal(err)
	}
	supported := false
	for _, item := range capabilities.GetItems() {
		if item.GetProvider() == "slack" && item.GetChannelType() == "slack_app" {
			for _, mode := range item.GetReceiveModes() {
				if mode == "managed_stream" {
					supported = true
				}
			}
		}
	}
	if !supported {
		fmt.Println("Slack managed streams are not advertised on this deployment")
		return
	}

	connection, err := service.CreateIngressConnection(ctx, sdk.IngressConnectionCreateRequest{
		Target: &sdk.AgentTargetRef{
			Kind:        "agent",
			WorkspaceId: os.Getenv("AGENT_WORKSPACE_ID"),
			Id:          os.Getenv("AGENT_ID"),
		},
		Provider:    "slack",
		ChannelType: "slack_app",
		ReceiveMode: "managed_stream",
		AgentModel:  os.Getenv("AGENT_MODEL"),
		ManagedStream: &sdk.IngressManagedStreamConfig{
			AppID:    os.Getenv("SLACK_APP_ID"),
			AppToken: os.Getenv("SLACK_APP_TOKEN"),
			BotToken: os.Getenv("SLACK_BOT_TOKEN"),
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connection:", connection.GetId(), "Versions:", connection.GetAssociationVersion(), connection.GetConfigVersion())
	fmt.Println("State:", connection.GetDesiredState(), connection.GetObservedState(), connection.GetLastErrorCode())
}
```

::::

:::::

Record the returned connection `id`, `association_version`, and `config_version` for optimistic concurrency control when updating or disabling the connection later.

(sdk-ai-studio-agent-ingress-verify)=
<span id="确认连接状态与消息收发"></span>

## Verify connection state and message delivery

For Slack `managed_stream` connections, the platform receiver establishes the outbound Socket Mode stream automatically. Continue from the previous step by calling `get_ingress_connection` (`GetIngressConnection` in Go) to inspect `observed_state` and `last_error_code`:

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
current = service.get_ingress_connection(connection.id)
print(current.desired_state, current.observed_state, current.last_error_code)
if current.observed_state in ("auth_failed", "config_invalid"):
    raise RuntimeError("Correct the Slack credentials or connection configuration")
if current.observed_state != "connected":
    print("Receiver is still connecting; check observed_state again before testing delivery")
```

::::

::::{tab-item} Go
:sync: go

```go
current, err := service.GetIngressConnection(ctx, connection.GetId())
if err != nil {
	log.Fatal(err)
}
fmt.Println(current.GetDesiredState(), current.GetObservedState(), current.GetLastErrorCode())
if current.GetObservedState() == "auth_failed" || current.GetObservedState() == "config_invalid" {
	log.Fatal("correct the Slack credentials or connection configuration")
}
if current.GetObservedState() != "connected" {
	fmt.Println("Receiver is still connecting; check observed_state again before testing delivery")
}
```

::::

:::::

(sdk-ai-studio-agent-ingress-limit)=
<span id="限制和注意事项"></span>

## Limitations and notes

- An `observed_state` of `starting` or `reconnecting` indicates that the receiver is still establishing or restoring the stream. Once `observed_state` reaches `connected`, send a test message to the app in Slack and verify the agent's conversation records and reply.
- Updating connection settings or target bindings requires passing the latest `association_version` and `config_version`; on a version conflict, read back the latest connection object before retrying.

(sdk-ai-studio-agent-ingress-next)=
<span id="下一步"></span>

## Next steps

- [Test Channel Configurations](测试通道配置.md)
- [Read Agent Conversations](管理会话和消息.md#sdk-ai-studio-sessions-s1)
