<span id="连接插件账号"></span>

# Connect Plugin Accounts

Create an account connection for a plugin that requires external authentication, initiate browser OAuth or device-code authorization, and poll until authorization succeeds.

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

## Task flow

```text
Inspect plugin release requirements and OAuth profile
                        │
                        ▼
Create plugin connection and start OAuth flow
                        │
                        ▼
Complete login and consent in the browser
                        │
                        ▼
Poll and verify connection authorization status
```

(sdk-ai-studio-plugin-account-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. Query the target plugin release via `service.list_plugin_releases(sdk.with_query_param("namespace", "system"))` and `service.get_plugin_release(release_id, sdk.with_query_param("namespace", "system"))` (`ListPluginReleases` and `GetPluginRelease` in Go), and record the release namespace (`RELEASE_NAMESPACE`), release ID (`RELEASE_ID`), connection requirement (`CONNECTION_REQUIREMENT`), and `oauth` profile identifier (`CONNECTION_PROFILE`).
3. Prepare an account on the target external service to complete sign-in and authorization in your browser.

(sdk-ai-studio-plugin-account-connect)=
<span id="创建连接并发起授权"></span>

## Create a connection and start OAuth

If a reusable plugin connection already exists in the workspace, list and reuse it directly. The example below calls `create_plugin_connection` (`CreatePluginConnection` in Go) to create a new connection, then calls `begin_plugin_oauth` (`BeginPluginOAuth` in Go) to obtain the authorization URL and attempt metadata.

:::::{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"])

connection = service.create_plugin_connection(
    sdk.PluginCreateConnectionRequest(
        release_namespace=os.environ["RELEASE_NAMESPACE"],
        release_id=os.environ["RELEASE_ID"],
        requirement=os.environ["CONNECTION_REQUIREMENT"],
        profile=os.environ["CONNECTION_PROFILE"],
        name="My plugin account",
    )
)
action = service.begin_plugin_oauth(connection.id, connection.version)
print("Connection:", connection.id, "Version:", connection.version)
print("Grant:", action.grant)
print("Open in browser:", action.authorization_url)
print("User code:", action.user_code)
print("Attempt:", action.attempt_id, "Poll after:", action.poll_after)
```

::::

::::{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"))
	connection, err := service.CreatePluginConnection(ctx, &sdk.PluginCreateConnectionRequest{
		ReleaseNamespace: os.Getenv("RELEASE_NAMESPACE"),
		ReleaseId:        os.Getenv("RELEASE_ID"),
		Requirement:      os.Getenv("CONNECTION_REQUIREMENT"),
		Profile:          os.Getenv("CONNECTION_PROFILE"),
		Name:             "My plugin account",
	})
	if err != nil {
		log.Fatal(err)
	}
	action, err := service.BeginPluginOAuth(ctx, connection.GetId(), int(connection.GetVersion()))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connection:", connection.GetId(), "Version:", connection.GetVersion())
	fmt.Println("Grant:", action.GetGrant())
	fmt.Println("Open in browser:", action.GetAuthorizationUrl())
	fmt.Println("User code:", action.GetUserCode())
	fmt.Println("Attempt:", action.GetAttemptId(), "Poll after:", action.GetPollAfter())
}
```

::::

:::::

Save the returned connection `id`, `version`, `grant`, and any non-empty `attempt_id`:

- When `grant` is `browser_handoff`, open `authorization_url` to complete the flow in the product browser page (`attempt_id` is empty).
- When `attempt_id` is non-empty, open `authorization_url` to authorize the external account (entering `user_code` as well for device-code grants) and use `attempt_id` to poll authorization progress.

(sdk-ai-studio-plugin-account-status)=
<span id="查询并推进授权结果"></span>

## Check and poll authorization status

After completing authorization in the browser, continue with `connection` and `action` from the previous step to inspect the connection's authorization status. While `status` is `pending` and an `attempt_id` is present, call `poll_plugin_oauth` (`PollPluginOAuth` in Go) at the returned `poll_after` interval within a bounded timeout.

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

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

```python
status = service.get_plugin_authorization(connection.id)
print("Status:", status.status)
if status.connection_version != connection.version:
    raise RuntimeError("Connection version changed; review latest state before continuing")

if status.status == "pending":
    attempt_id = action.attempt_id or status.attempt_id
    if attempt_id:
        progress = service.poll_plugin_oauth(
            connection.id,
            attempt_id,
            connection.version,
        )
        print(progress.status, progress.reason, progress.poll_after)
        status = service.get_plugin_authorization(connection.id)
        print("Authorization:", status.status)
    elif action.grant == "browser_handoff":
        print("Continue authorization in the product browser page")
    else:
        raise RuntimeError("Saved attempt ID is required before polling")
```

::::

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

```go
status, err := service.GetPluginAuthorization(ctx, connection.GetId())
if err != nil {
	log.Fatal(err)
}
fmt.Println("Status:", status.GetStatus())
if status.GetConnectionVersion() != connection.GetVersion() {
	log.Fatal("connection version changed; review latest state before continuing")
}

if status.GetStatus() == "pending" {
	attemptID := action.GetAttemptId()
	if attemptID == "" {
		attemptID = status.GetAttemptId()
	}
	if attemptID != "" {
		progress, err := service.PollPluginOAuth(ctx, connection.GetId(), attemptID, int(connection.GetVersion()))
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(progress.GetStatus(), progress.GetReason(), progress.GetPollAfter())
		status, err = service.GetPluginAuthorization(ctx, connection.GetId())
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("Authorization:", status.GetStatus())
	} else if action.GetGrant() == "browser_handoff" {
		fmt.Println("Continue authorization in the product browser page")
	} else {
		log.Fatal("saved attempt ID is required before polling")
	}
}
```

::::

:::::

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

## Limitations and notes

- `get_plugin_authorization` does not always populate `attempt_id`; persist `attempt_id` from `begin_plugin_oauth` so interrupted processes can resume polling cleanly.
- If `connection_version` changes while authorization is pending, inspect the latest connection configuration before continuing with the matching version number.
- Once authorized, associate the connection with the plugin installation and read back to verify. To disconnect an authorized plugin account later, call `service.disconnect_plugin_connection(connection_id, expected_generation)` (`service.DisconnectPluginConnection(ctx, connectionID, expectedGeneration)` in Go).

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

## Next steps

- [Inspect and Import Skill Packages](检查与导入技能包.md)
- [Invoke Agents and Track Tasks](调用智能体并跟踪任务.md#sdk-ai-studio-agent-task-send)
