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.

Task flow

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

Prerequisites

  1. Complete the endpoint, personal access token, and workspace setup in Use the SDK.

  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.

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.

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)
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.

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.

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")
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")
	}
}

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).

Next steps

Last updated on