barndoor

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 24 Imported by: 0

README

Barndoor Go SDK

A lightweight, framework-agnostic Go client for the Barndoor Platform REST APIs and Model Context Protocol (MCP) servers.

The SDK removes boiler-plate around:

  • Secure, offline-friendly authentication to Barndoor (interactive PKCE flow + token caching).
  • Server registry – list, inspect and connect third-party providers (Salesforce, Notion, Slack …).
  • Managed Connector Proxy – build ready-to-use connection parameters for any LLM/agent framework without importing Barndoor-specific adapters.

How it works

The SDK orchestrates a multi-step flow to connect your code to third-party services:

You → Barndoor Auth (get JWT) → Registry API (with JWT) → MCP Proxy (with JWT) → Third-party service
  1. Authentication: You log in via Barndoor to get a JWT token
  2. Registry API: Using the JWT, query available MCP servers and manage OAuth connections
  3. MCP Proxy: Stream requests through Barndoor's proxy with the JWT for authorization
  4. Third-party service: The proxy forwards your requests to Salesforce, Notion, etc.

This architecture provides secure, managed access to external services without handling OAuth flows or storing third-party credentials in your code.


Installation

go get github.com/barndoor-ai/barndoor-go-sdk

Go 1.22+ is required.


Quick start

package main

import (
	"context"
	"fmt"
	"log"

	barndoor "github.com/barndoor-ai/barndoor-go-sdk"
)

func main() {
	ctx := context.Background()

	// 1. Login (handles OAuth PKCE flow + token caching)
	sdk, err := barndoor.LoginInteractive(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer sdk.Close()

	// 2. Ensure server is connected (launches OAuth if needed)
	err = barndoor.EnsureServerConnectedQuickstart(ctx, sdk, "salesforce", 0)
	if err != nil {
		log.Fatal(err)
	}

	// 3. Get connection parameters for your MCP client
	params, mcpURL, err := barndoor.MakeMCPConnectionParams(ctx, sdk, "salesforce")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("MCP URL:", mcpURL)
	fmt.Println("Transport:", params.Transport)
	fmt.Println("Headers:", params.Headers)
}

Manual setup

For programmatic use (e.g., in agents), create an SDK directly with a known JWT:

sdk, err := barndoor.NewBarndoorSDK("https://myorg.platform.barndoor.ai", &barndoor.SDKOptions{
    Token: myJWT,
})
if err != nil {
    log.Fatal(err)
}
defer sdk.Close()

Or authenticate later:

sdk, err := barndoor.NewBarndoorSDK("https://myorg.platform.barndoor.ai", nil)
if err != nil {
    log.Fatal(err)
}
defer sdk.Close()

err = sdk.Authenticate(ctx, myJWT)

Environment configuration

The SDK automatically configures endpoints based on BARNDOOR_ENV. Just set your credentials:

export AGENT_CLIENT_ID=your_client_id
export AGENT_CLIENT_SECRET=your_client_secret

See env.example for the full list of options.

Variable Description Default
BARNDOOR_ENV Environment name (production, uat, dev, enterprise-production, etc.) production
AGENT_CLIENT_ID OAuth client ID —
AGENT_CLIENT_SECRET OAuth client secret —
BARNDOOR_URL / BARNDOOR_API API base URL override per-environment default
AUTH_URL Auth issuer override per-environment default
BARNDOOR_REDIRECT_HOST OAuth callback host 127.0.0.1

Authentication workflow

Barndoor APIs expect a user JWT issued by your Barndoor tenant. The SDK offers two ways to obtain and store a token:

Option Function When to use
Interactive login barndoor.LoginInteractive(ctx, nil) Development, CLI tools, scripts
Direct token barndoor.NewBarndoorSDK(url, &SDKOptions{Token: jwt}) Agents, services with pre-obtained tokens

The interactive flow:

  1. Spins up a tiny localhost callback server (default port 52765).
  2. Opens the system browser to Barndoor.
  3. Exchanges the returned authorization code for a JWT via PKCE.
  4. Persists the token to ~/.barndoor/token.json (0600 permissions).

The cached token is checked on every run; if it is expired or revoked, a new browser flow is launched.

Note: The OAuth default callback uses port 52765. Make sure to register this callback in your Barndoor Agent configuration. As some machines resolve localhost to 127.0.0.1, we recommend having two callback entries:

http://localhost:52765/cb
http://127.0.0.1:52765/cb
Using a custom OAuth callback port

If port 52765 is blocked (or you prefer another), register the new callback URL and pass the port in options:

sdk, err := barndoor.LoginInteractive(ctx, &barndoor.LoginInteractiveOptions{
    Port: 60000,
})

Using the Registry API

// List all MCP servers available to the current user
servers, err := sdk.ListServers(ctx)
for _, s := range servers {
    fmt.Printf("%s (%s)\n", s.Slug, s.ConnectionStatus)
}

// Get detailed metadata
server, err := sdk.GetServer(ctx, "notion")

// Initiate an OAuth connection (returns auth URL for browser)
authURL, err := sdk.InitiateConnection(ctx, "notion", "")

// Check connection status
status, err := sdk.GetConnectionStatus(ctx, "notion")

// Disconnect from a server
err = sdk.DisconnectServer(ctx, "notion")

MCP connection

Once a server is connected, build connection parameters for any MCP client:

params, mcpURL, err := barndoor.MakeMCPConnectionParams(ctx, sdk, "notion")

fmt.Println(params.URL)       // https://myorg.mcp.barndoor.ai/mcp/notion
fmt.Println(params.Transport) // streamable-http
fmt.Println(params.Headers)   // Authorization, x-barndoor-session-id

The returned MCPConnectionParams struct contains URL, Transport, and Headers — ready to plug into any HTTP/SSE/WebSocket MCP client.


Error handling

The SDK provides a typed error hierarchy. Use type assertions to handle specific cases:

servers, err := sdk.ListServers(ctx)
if err != nil {
    switch e := err.(type) {
    case *barndoor.HTTPError:
        fmt.Printf("HTTP %d: %s\n", e.StatusCode, e.Message)
    case *barndoor.TokenError:
        fmt.Println("Token error — re-authenticate")
    case *barndoor.ConnectionError:
        fmt.Printf("Connection failed to %s: %s\n", e.URL, e.Message)
    case *barndoor.ConfigurationError:
        fmt.Println("Config error:", e.Message)
    case *barndoor.ServerNotFoundError:
        fmt.Println("Server not found:", e.ServerIdentifier)
    default:
        fmt.Println(err)
    }
}

API reference

Full godoc documentation is available via:

go doc github.com/barndoor-ai/barndoor-go-sdk
Key types
Type Description
BarndoorSDK Main client — holds token, HTTP client, base URL
SDKOptions Constructor options (token, timeout, retries)
ServerSummary Server list entry (ID, name, slug, connection status)
ServerDetail Extended server info (embeds ServerSummary + URL)
MCPConnectionParams MCP connection config (URL, transport, headers)
LoginInteractiveOptions Options for the interactive PKCE login flow
Key functions
Function Description
NewBarndoorSDK(url, opts) Create an SDK instance
LoginInteractive(ctx, opts) Interactive OAuth PKCE login
MakeMCPConnectionParams(ctx, sdk, slug) Build MCP connection params
EnsureServerConnectedQuickstart(ctx, sdk, slug, timeout) Connect + poll with logging
GetStaticConfig() Read environment config
SDK methods
Method Description
Authenticate(ctx, token) Set/validate a JWT
ListServers(ctx) List all available MCP servers
GetServer(ctx, id) Get server details (by UUID or slug)
InitiateConnection(ctx, id, returnURL) Start OAuth connection flow
GetConnectionStatus(ctx, id) Check connection status
DisconnectServer(ctx, id) Disconnect from a server
EnsureServerConnected(ctx, id, pollSeconds) Connect + poll until ready
Close() Release resources

Contributing

See CONTRIBUTING.md for development setup instructions.

Documentation

Overview

Package barndoor provides a Go SDK for the Barndoor Platform API.

The SDK provides methods for:

  • User authentication via OAuth/PKCE flows
  • MCP server discovery and management
  • OAuth connection handling for third-party providers
  • Agent credential exchange
  • Token lifecycle management (storage, validation, refresh)

Quick Start

The simplest way to get started is with LoginInteractive, which handles the full OAuth login flow:

sdk, err := barndoor.LoginInteractive(ctx, nil)
if err != nil {
    log.Fatal(err)
}
defer sdk.Close()

servers, err := sdk.ListServers(ctx)

Manual Setup

For programmatic use (e.g., in agents), create an SDK directly:

sdk, err := barndoor.NewBarndoorSDK("https://myorg.platform.barndoor.ai", &barndoor.SDKOptions{
    Token: myJWT,
})
if err != nil {
    log.Fatal(err)
}
defer sdk.Close()

Configuration

The SDK reads configuration from environment variables:

  • BARNDOOR_ENV: environment name (production, uat, dev, enterprise-production, etc.)
  • AGENT_CLIENT_ID: OAuth client ID
  • AGENT_CLIENT_SECRET: OAuth client secret
  • BARNDOOR_API or BARNDOOR_URL: API base URL override

Auth configuration (issuer, audience, base URL) is baked in per environment. See AuthConfig for the full list.

Index

Examples

Constants

View Source
const Version = "1.3.0"

Version is the semantic version of the barndoor-go-sdk.

Variables

View Source
var AuthConfig = map[string]AuthEnvironmentConfig{

	"production": {
		Issuer:   "https://auth.trial.barndoor.ai/realms/barndoor",
		Audience: "https://barndoor.ai/",
		BaseURL:  "https://{org_slug}.platform.barndoor.ai",
	},
	"uat": {
		Issuer:   "https://auth.barndooruat.com/realms/barndoor",
		Audience: "https://barndoor.ai/",
		BaseURL:  "https://{org_slug}.trial.barndooruat.com",
	},
	"dev": {
		Issuer:   "https://auth.barndoordev.com/realms/barndoor",
		Audience: "https://barndoor.ai/",
		BaseURL:  "https://{org_slug}.platform.barndoordev.com",
	},

	"enterprise-production": {
		Issuer:   "https://auth.barndoor.ai",
		Audience: "https://barndoor.ai/",
		BaseURL:  "https://{org_slug}.mcp.barndoor.ai",
	},
	"enterprise-uat": {
		Issuer:   "https://auth.barndooruat.com",
		Audience: "https://barndoor.ai/",
		BaseURL:  "https://{org_slug}.mcp.barndooruat.com",
	},
	"enterprise-dev": {
		Issuer:   "https://auth.barndoordev.com",
		Audience: "https://barndoor.ai/",
		BaseURL:  "https://{org_slug}.mcp.barndoordev.com",
	},

	"localdev": {
		Issuer:   "http://localhost:8080/realms/barndoor",
		Audience: "https://barndoor.ai/",
		BaseURL:  "http://localhost:8000",
	},
}

AuthConfig holds all pre-configured environment settings.

Functions

func ClearCachedToken

func ClearCachedToken() error

ClearCachedToken clears the cached token.

func ClearOidcConfigCache

func ClearOidcConfigCache()

ClearOidcConfigCache clears the OIDC config cache.

func EnsureServerConnectedQuickstart

func EnsureServerConnectedQuickstart(ctx context.Context, sdk *BarndoorSDK, serverIdentifier string, timeout int) error

EnsureServerConnectedQuickstart is a convenience wrapper around EnsureServerConnected that adds helpful logging for interactive use.

func HasOrganizationInfo

func HasOrganizationInfo(jwtToken string) bool

HasOrganizationInfo checks if a JWT token has organization information.

func IsTokenActive

func IsTokenActive(ctx context.Context) bool

IsTokenActive checks if the cached token is active without attempting refresh.

func IsTokenActiveWithRefresh

func IsTokenActiveWithRefresh(ctx context.Context) bool

IsTokenActiveWithRefresh checks if the cached token is active, attempting refresh if needed.

func LoadUserToken

func LoadUserToken() (string, error)

LoadUserToken loads a user token from storage.

func SaveUserToken

func SaveUserToken(token string) error

SaveUserToken saves a user token to storage.

func SaveUserTokenData

func SaveUserTokenData(tokenData *TokenData) error

SaveUserTokenData saves full token data to storage.

func SetLogger

func SetLogger(logger Logger)

SetLogger sets a custom logger for the entire SDK.

func StartLocalCallbackServer

func StartLocalCallbackServer(port int) (string, <-chan callbackResult, error)

StartLocalCallbackServer starts a local HTTP server for OAuth callback. It returns the redirect URI and a channel that receives (code, state) on callback.

func ValidateToken

func ValidateToken(ctx context.Context, token string) bool

ValidateToken validates a token using local verification with remote fallback.

Types

type AgentToken

type AgentToken struct {
	// AgentToken is the agent access token.
	AgentToken string `json:"agent_token"`
	// ExpiresIn is the token lifetime in seconds.
	ExpiresIn int `json:"expires_in"`
}

AgentToken represents a response from the agent token exchange endpoint.

func (*AgentToken) Validate

func (t *AgentToken) Validate() error

Validate checks that required fields are present.

type AlertTypeOption added in v1.3.0

type AlertTypeOption struct {
	// Value is what to send as a subscription's AlertType.
	Value string `json:"value"`
	// Label is a human-readable label for display.
	Label string `json:"label"`
	// Category is the type's category. Intrinsic to the type, not configurable.
	Category string `json:"category"`
	// Severity is the type's severity ("info", "warning", "critical"). Also intrinsic.
	Severity string `json:"severity"`
}

AlertTypeOption is one subscribable alert type, with its intrinsic category and severity. Both are properties of the alert type itself, not per-channel settings.

type AuthEnvironmentConfig

type AuthEnvironmentConfig struct {
	Issuer   string
	Audience string
	BaseURL  string
}

AuthEnvironmentConfig holds baked-in auth configuration for an environment.

type AuthenticationError

type AuthenticationError struct {
	BarndoorError
	ErrorCode string
}

AuthenticationError is returned when authentication fails.

type AuthorizationURLParams

type AuthorizationURLParams struct {
	Domain      string // deprecated: use Issuer
	ClientID    string
	RedirectURI string
	Audience    string
	Scope       string
	Issuer      string
}

AuthorizationURLParams holds parameters for building an authorization URL.

type BarndoorConfig

type BarndoorConfig struct {
	AuthIssuer     string
	ClientID       string
	ClientSecret   string // #nosec G117 -- OAuth client secret config field
	APIAudience    string
	BaseURL        string
	Environment    string
	PromptForLogin bool
	SkipLoginLocal bool
}

BarndoorConfig holds unified configuration for the SDK.

func GetDynamicConfig

func GetDynamicConfig(jwtToken string, requireOrganization bool, fallbackOrgID string) (*BarndoorConfig, error)

GetDynamicConfig returns a configuration with org slug substituted from JWT claims.

func GetStaticConfig

func GetStaticConfig() *BarndoorConfig

GetStaticConfig returns a static configuration without organization substitution.

Example
package main

import (
	"fmt"

	barndoor "github.com/barndoor-ai/barndoor-go-sdk"
)

func main() {
	cfg := barndoor.GetStaticConfig()
	fmt.Println("Environment:", cfg.Environment)
	fmt.Println("Auth Issuer:", cfg.AuthIssuer)
}

func NewBarndoorConfig

func NewBarndoorConfig(opts *BarndoorConfigOptions) *BarndoorConfig

NewBarndoorConfig creates a new configuration from options.

func (*BarndoorConfig) Validate

func (c *BarndoorConfig) Validate() error

Validate checks the configuration for required fields.

type BarndoorConfigOptions

type BarndoorConfigOptions struct {
	AuthIssuer     string
	AuthDomain     string // deprecated: use AuthIssuer
	ClientID       string
	ClientSecret   string // #nosec G117 -- OAuth client secret config field
	APIAudience    string
	BaseURL        string
	Environment    string
	PromptForLogin bool
	SkipLoginLocal bool
}

BarndoorConfigOptions are options for creating a BarndoorConfig.

type BarndoorError

type BarndoorError struct {
	Message string
}

BarndoorError is the base error type for all Barndoor SDK errors.

func (*BarndoorError) Error

func (e *BarndoorError) Error() string

type BarndoorSDK

type BarndoorSDK struct {
	// Base is the base URL of the Barndoor API.
	Base string
	// contains filtered or unexported fields
}

BarndoorSDK is the main client for interacting with the Barndoor Platform API.

func LoginInteractive

func LoginInteractive(ctx context.Context, opts *LoginInteractiveOptions) (*BarndoorSDK, error)

LoginInteractive performs an interactive OAuth login and returns an initialized SDK.

It opens the system browser for OAuth authentication, waits for the user to complete login, exchanges the authorization code for a JWT, and returns a configured BarndoorSDK instance.

Auth configuration is baked in per environment (set via BARNDOOR_ENV). You typically only need to set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.

Example
package main

import (
	"context"
	"fmt"
	"log"

	barndoor "github.com/barndoor-ai/barndoor-go-sdk"
)

func main() {
	ctx := context.Background()

	// LoginInteractive handles the full OAuth PKCE flow:
	// 1. Checks for a cached token
	// 2. Opens browser for auth if needed
	// 3. Exchanges code for JWT
	// 4. Returns a ready-to-use SDK
	sdk, err := barndoor.LoginInteractive(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer sdk.Close()

	servers, err := sdk.ListServers(ctx)
	if err != nil {
		log.Fatal(err)
	}

	for _, s := range servers {
		fmt.Printf("%s (%s)\n", s.Name, s.ConnectionStatus)
	}
}

func NewBarndoorSDK

func NewBarndoorSDK(apiBaseURL string, opts *SDKOptions) (*BarndoorSDK, error)

NewBarndoorSDK creates a new SDK instance.

Example
package main

import (
	"fmt"
	"log"

	barndoor "github.com/barndoor-ai/barndoor-go-sdk"
)

func main() {
	sdk, err := barndoor.NewBarndoorSDK("https://myorg.platform.barndoor.ai", &barndoor.SDKOptions{
		Token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.signature",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer sdk.Close()

	fmt.Println("SDK initialized for", sdk.Base)
}

func (*BarndoorSDK) Authenticate

func (s *BarndoorSDK) Authenticate(ctx context.Context, token string) error

Authenticate sets the authentication token for the SDK.

func (*BarndoorSDK) Close

func (s *BarndoorSDK) Close()

Close closes the SDK and releases resources.

func (*BarndoorSDK) DeleteChannel added in v1.3.0

func (s *BarndoorSDK) DeleteChannel(ctx context.Context, channelID string) error

DeleteChannel deletes a notification channel.

Its subscriptions cascade and any stored secret is removed. Irreversible — to stop delivery reversibly, call UpsertChannel with Enabled set to false.

Returns an *HTTPError with status 404 when no such channel exists in the caller's organization.

func (*BarndoorSDK) DisconnectServer

func (s *BarndoorSDK) DisconnectServer(ctx context.Context, serverID string) error

DisconnectServer disconnects from a specific MCP server.

func (*BarndoorSDK) EnsureServerConnected

func (s *BarndoorSDK) EnsureServerConnected(ctx context.Context, serverIdentifier string, pollSeconds int) error

EnsureServerConnected ensures a server is connected, initiating OAuth if needed.

func (*BarndoorSDK) EnsureValidToken

func (s *BarndoorSDK) EnsureValidToken(ctx context.Context) error

EnsureValidToken ensures the token is valid, validating if necessary.

func (*BarndoorSDK) GetChannelOptions added in v1.3.0

func (s *BarndoorSDK) GetChannelOptions(ctx context.Context) (*ChannelOptions, error)

GetChannelOptions lists the alert types this organization may subscribe a channel to.

Read this before building a subscription set: the alert-type vocabulary grows over time and is gated per organization, so this endpoint — not a hardcoded list — is the authoritative answer to what Subscriptions accepts. Subscribing to a type absent here is accepted but never delivers.

func (*BarndoorSDK) GetConnectionStatus

func (s *BarndoorSDK) GetConnectionStatus(ctx context.Context, serverID string) (string, error)

GetConnectionStatus gets the user's connection status for a specific server.

func (*BarndoorSDK) GetServer

func (s *BarndoorSDK) GetServer(ctx context.Context, serverID string) (*ServerDetail, error)

GetServer gets detailed information about a specific server.

func (*BarndoorSDK) InitiateConnection

func (s *BarndoorSDK) InitiateConnection(ctx context.Context, serverID string, returnURL string) (string, error)

InitiateConnection initiates an OAuth connection flow for a server. It returns the auth URL to open in a browser, or an empty string if none was provided.

func (*BarndoorSDK) ListChannels added in v1.3.0

func (s *BarndoorSDK) ListChannels(ctx context.Context) ([]Channel, error)

ListChannels lists the organization's shared notification channels.

Returns the organization-wide channels — email, webhook, slack, teams — with their current subscription sets. Personal channels are not included; use ListUserChannels for those. Secrets are never returned.

func (*BarndoorSDK) ListServers

func (s *BarndoorSDK) ListServers(ctx context.Context) ([]ServerSummary, error)

ListServers lists all MCP servers available to the caller's organization. It automatically fetches all pages if results are paginated.

func (*BarndoorSDK) ListUserChannels added in v1.3.0

func (s *BarndoorSDK) ListUserChannels(ctx context.Context) ([]Channel, error)

ListUserChannels lists the caller's own personal notification channels.

Returns the authenticated caller's in_app and user_email channels. Always self-scoped — there is no way to read another user's personal channels, and no user parameter to pass.

func (*BarndoorSDK) RegenerateChannelSecret added in v1.3.0

func (s *BarndoorSDK) RegenerateChannelSecret(ctx context.Context, channelID string) (*WebhookSecret, error)

RegenerateChannelSecret rotates a webhook channel's signing secret.

The new secret is returned once. The previous secret stops verifying immediately, so deploy the new one to your receiver before the next alert fires. There is no endpoint that reads the current secret, so this is also the recovery path when the secret from channel creation was lost.

func (*BarndoorSDK) TestChannel added in v1.3.0

func (s *BarndoorSDK) TestChannel(ctx context.Context, channelID string) (*ChannelTestResult, error)

TestChannel sends a stock connectivity-test message through a channel's real transport, so you can verify a webhook receiver, email address, Slack channel, or Teams workflow actually works.

It is not an alert: nothing is persisted, no other channel is notified, and it does not depend on the channel's subscriptions.

A transport failure comes back as a result with OK=false and an Error string, not as a non-nil error — the request succeeded, the delivery did not.

func (*BarndoorSDK) Token

func (s *BarndoorSDK) Token() (string, error)

Token returns the current token, or an error if none is set.

func (*BarndoorSDK) UpsertChannel added in v1.3.0

func (s *BarndoorSDK) UpsertChannel(ctx context.Context, input UpsertChannelInput) (*Channel, error)

UpsertChannel creates or updates a notification channel and replaces its subscriptions.

This is a full upsert, not a patch: Subscriptions REPLACES the channel's existing set, so leaving it nil removes every subscription the channel had. Send the complete desired set on every call — which is what makes the endpoint safe to drive from a declarative tool.

Without ChannelID the channel is keyed on its type's natural identity, so repeating an identical call is idempotent rather than creating duplicates: email by address, webhook by URL, slack by channel id, and the personal types by (organization, type, caller). With ChannelID it is an authoritative edit of that row — the only way to update a teams channel, whose natural identity is a secret URL.

When this call creates a webhook channel, the returned Channel's SigningSecret carries the one-time reveal — store it. A retried create that lands after the first attempt already succeeded returns a nil SigningSecret rather than a second secret; use RegenerateChannelSecret if you need one.

func (*BarndoorSDK) ValidateCachedToken

func (s *BarndoorSDK) ValidateCachedToken(ctx context.Context) (bool, error)

ValidateCachedToken validates the cached token by making a test API call.

type Channel added in v1.3.0

type Channel struct {
	// ID is the server-assigned channel id.
	ID string `json:"id"`
	// Type is the kind of destination.
	Type ChannelType `json:"type"`
	// Enabled reports whether the channel currently delivers.
	Enabled bool `json:"enabled"`
	// UserID is the owning user for a personal channel; nil for organization-wide types.
	UserID *string `json:"user_id,omitempty"`
	// EmailAddress is the destination for ChannelTypeEmail.
	EmailAddress *string `json:"email_address,omitempty"`
	// URL is the destination for ChannelTypeWebhook.
	URL *string `json:"url,omitempty"`
	// Label is a human-readable name, set for slack and teams channels.
	Label *string `json:"label,omitempty"`
	// SlackChannelID is the Slack channel id for ChannelTypeSlack.
	SlackChannelID *string `json:"slack_channel_id,omitempty"`
	// Subscriptions are the alert types this channel delivers. Empty means it
	// delivers nothing.
	Subscriptions []ChannelSubscription `json:"subscriptions"`
	CreatedAt     string                `json:"created_at,omitempty"`
	UpdatedAt     string                `json:"updated_at,omitempty"`
	// HasSigningSecret reports whether a webhook channel has a stored signing secret.
	// The secret itself is never readable back.
	HasSigningSecret bool `json:"has_signing_secret"`
	// HasWorkflowURL reports whether a teams channel has a stored Workflows URL
	// (itself a secret, never returned).
	HasWorkflowURL bool `json:"has_workflow_url"`
	// SigningSecret is the one-time reveal of a newly generated webhook signing
	// secret. Populated ONLY on the response that created it, and nil on every later
	// read — store it when you receive it, or rotate with RegenerateChannelSecret.
	SigningSecret *string `json:"signing_secret,omitempty"`
}

Channel is a notification delivery destination.

Only the destination field belonging to Type is populated; the rest are nil. Secrets are never returned — a webhook's signing secret and a Teams workflow URL surface only as the HasSigningSecret / HasWorkflowURL flags.

func (*Channel) Validate added in v1.3.0

func (c *Channel) Validate() error

Validate checks that required fields are present.

type ChannelOptions added in v1.3.0

type ChannelOptions struct {
	// AlertTypes is every alert type this organization may subscribe a channel to.
	AlertTypes []AlertTypeOption `json:"alert_types"`
	// Categories is the full category vocabulary, unfiltered.
	Categories []LabeledOption `json:"categories"`
	// Severities is the full severity vocabulary, unfiltered.
	Severities []LabeledOption `json:"severities"`
}

ChannelOptions is the subscription vocabulary a channel's subscriptions may draw from.

AlertTypes is filtered to what the caller's organization is admitted to — subscribing to a type absent here is accepted but never delivers.

type ChannelSubscription added in v1.3.0

type ChannelSubscription struct {
	// AlertType is the alert type delivered to the channel (e.g. "break_glass_used").
	// Read the live vocabulary from GetChannelOptions rather than hardcoding it — the
	// set grows over time and is gated per organization.
	AlertType string `json:"alert_type"`
}

ChannelSubscription is one alert type a channel is subscribed to.

type ChannelTestResult added in v1.3.0

type ChannelTestResult struct {
	// OK reports whether the test message reached the destination transport.
	OK bool `json:"ok"`
	// Error is why delivery failed, when OK is false.
	Error *string `json:"error,omitempty"`
}

ChannelTestResult is the result of sending a connectivity-test message through a channel's real transport.

A transport failure is reported here as OK=false with a reason, not as an error return: the request to test succeeded, the delivery is what failed.

type ChannelType added in v1.3.0

type ChannelType string

ChannelType is the kind of destination a notification channel delivers to.

The type discriminates the whole model: it decides which destination field is required, whether the channel is personal (owned by one user) or organization-wide, and which natural-identity key an upsert without an ID dedupes on.

const (
	// ChannelTypeInApp delivers to the owner's notification inbox in the platform UI.
	// Personal: the owner is always the authenticated caller.
	ChannelTypeInApp ChannelType = "in_app"
	// ChannelTypeUserEmail delivers to the owner's own account email. Personal.
	ChannelTypeUserEmail ChannelType = "user_email"
	// ChannelTypeEmail delivers to an arbitrary address (a team alias, a ticketing
	// inbox). Organization-wide; requires EmailAddress.
	ChannelTypeEmail ChannelType = "email"
	// ChannelTypeWebhook delivers to an HTTPS endpoint you own, signed with a
	// Standard Webhooks secret. Organization-wide; requires URL.
	ChannelTypeWebhook ChannelType = "webhook"
	// ChannelTypeSlack delivers to a channel in the organization's connected Slack
	// workspace. Requires SlackChannelID and Label, and the Slack app must already be
	// installed (an interactive flow that is not part of this API).
	ChannelTypeSlack ChannelType = "slack"
	// ChannelTypeTeams delivers to a Microsoft Teams channel behind a Workflows
	// incoming-webhook URL. Requires Label, plus TeamsWorkflowURL on create.
	ChannelTypeTeams ChannelType = "teams"
)

type ConfigurationError

type ConfigurationError struct {
	BarndoorError
}

ConfigurationError is returned when there's an issue with SDK configuration.

func NewConfigurationError

func NewConfigurationError(message string) *ConfigurationError

type ConnectionError

type ConnectionError struct {
	BarndoorError
	URL           string
	OriginalError error
}

ConnectionError is returned when unable to connect to the Barndoor API.

func NewConnectionError

func NewConnectionError(url string, originalError error) *ConnectionError

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

type ConnectionStatus

type ConnectionStatus string

ConnectionStatus represents the connection status of an MCP server.

const (
	ConnectionStatusAvailable ConnectionStatus = "available"
	ConnectionStatusPending   ConnectionStatus = "pending"
	ConnectionStatusConnected ConnectionStatus = "connected"
)

type FileTokenStorage

type FileTokenStorage struct {
	// contains filtered or unexported fields
}

FileTokenStorage stores tokens in the filesystem.

func NewFileTokenStorage

func NewFileTokenStorage() *FileTokenStorage

NewFileTokenStorage creates a new file-based token storage using the default path (~/.barndoor/token.json).

func NewFileTokenStorageWithPath

func NewFileTokenStorageWithPath(path string) *FileTokenStorage

NewFileTokenStorageWithPath creates a new file-based token storage at the specified path.

func (*FileTokenStorage) ClearToken

func (s *FileTokenStorage) ClearToken() error

ClearToken removes the token file.

func (*FileTokenStorage) LoadToken

func (s *FileTokenStorage) LoadToken() (*TokenData, error)

LoadToken loads token data from the file.

func (*FileTokenStorage) SaveToken

func (s *FileTokenStorage) SaveToken(tokenData *TokenData) error

SaveToken saves token data to the file.

type HTTPError

type HTTPError struct {
	BarndoorError
	StatusCode   int
	ResponseBody string
}

HTTPError is returned for HTTP error responses.

func NewHTTPError

func NewHTTPError(statusCode int, message string, responseBody string) *HTTPError

type JWTVerificationResult

type JWTVerificationResult int

JWTVerificationResult represents the result of JWT verification.

const (
	JWTValid JWTVerificationResult = iota
	JWTExpired
	JWTInvalid
)

func VerifyJWTLocal

func VerifyJWTLocal(ctx context.Context, tokenString, issuer, audience string) JWTVerificationResult

VerifyJWTLocal verifies a JWT token locally using JWKS. It returns the verification result.

type LabeledOption added in v1.3.0

type LabeledOption struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

LabeledOption is an enum value paired with its display label.

type Logger

type Logger interface {
	Debug(message string, args ...any)
	Info(message string, args ...any)
	Warn(message string, args ...any)
	Error(message string, args ...any)
}

Logger defines the interface for SDK logging.

func GetLogger

func GetLogger() Logger

GetLogger returns the current logger instance.

type LoginInteractiveOptions

type LoginInteractiveOptions struct {
	// AuthIssuer is the OIDC issuer URL.
	AuthIssuer string
	// AuthDomain is deprecated; use AuthIssuer.
	AuthDomain string
	// ClientID is the OAuth client ID.
	ClientID string
	// ClientSecret is the OAuth client secret.
	ClientSecret string // #nosec G117 -- OAuth client secret config field
	// Audience is the API audience identifier.
	Audience string
	// BaseURL is the base URL of the Barndoor API.
	BaseURL string
	// Port is the local port for OAuth callback (default: 52765).
	Port int
	// TokenPath is an optional file path for storing the auth token.
	// Useful when authenticating multiple agents concurrently.
	// If empty, defaults to ~/.barndoor/token.json.
	TokenPath string
}

LoginInteractiveOptions configures the interactive login flow.

type MCPConnectionParams

type MCPConnectionParams struct {
	URL       string            `json:"url"`
	Transport string            `json:"transport"`
	Headers   map[string]string `json:"headers"`
}

MCPConnectionParams holds parameters for connecting to an MCP server.

func MakeMCPConnectionParams

func MakeMCPConnectionParams(ctx context.Context, sdk *BarndoorSDK, serverSlugOrID string) (*MCPConnectionParams, string, error)

MakeMCPConnectionParams creates MCP connection parameters for a server.

Returns connection parameters that can be used with any MCP client framework.

Example
package main

import (
	"context"
	"fmt"
	"log"

	barndoor "github.com/barndoor-ai/barndoor-go-sdk"
)

func main() {
	ctx := context.Background()

	sdk, err := barndoor.NewBarndoorSDK("https://myorg.platform.barndoor.ai", &barndoor.SDKOptions{
		Token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.signature",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer sdk.Close()

	params, mcpURL, err := barndoor.MakeMCPConnectionParams(ctx, sdk, "github")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("MCP URL:", mcpURL)
	fmt.Println("Transport:", params.Transport)
}

type OAuthError

type OAuthError struct {
	AuthenticationError
}

OAuthError is returned when OAuth authentication fails.

func NewOAuthError

func NewOAuthError(message string) *OAuthError

type OidcConfig

type OidcConfig struct {
	Issuer                string `json:"issuer"`
	TokenEndpoint         string `json:"token_endpoint"`
	AuthorizationEndpoint string `json:"authorization_endpoint"`
	UserinfoEndpoint      string `json:"userinfo_endpoint"`
	JWKSURI               string `json:"jwks_uri"`
}

OidcConfig holds the OIDC discovery configuration.

func GetOidcConfig

func GetOidcConfig(ctx context.Context, issuer string) (*OidcConfig, error)

GetOidcConfig fetches and caches OIDC configuration from the issuer's discovery endpoint.

type OrganizationExtractionResult

type OrganizationExtractionResult struct {
	OrganizationID  string
	HasOrganization bool
	Error           string
}

OrganizationExtractionResult holds the result of extracting org info from JWT.

func CheckTokenOrganization

func CheckTokenOrganization(jwtToken string) OrganizationExtractionResult

CheckTokenOrganization checks if a JWT token contains organization information.

type PKCEManager

type PKCEManager struct {
	// contains filtered or unexported fields
}

PKCEManager handles PKCE OAuth flow state.

func NewPKCEManager

func NewPKCEManager() *PKCEManager

NewPKCEManager creates a new PKCE manager.

func (*PKCEManager) BuildAuthorizationURL

func (p *PKCEManager) BuildAuthorizationURL(ctx context.Context, params AuthorizationURLParams) (string, error)

BuildAuthorizationURL generates PKCE parameters and builds an authorization URL.

func (*PKCEManager) ClearState

func (p *PKCEManager) ClearState()

ClearState clears the PKCE state.

func (*PKCEManager) ExchangeCodeForToken

func (p *PKCEManager) ExchangeCodeForToken(ctx context.Context, params TokenExchangeParams) (map[string]any, error)

ExchangeCodeForToken exchanges an authorization code for tokens.

func (*PKCEManager) GetState

func (p *PKCEManager) GetState() (codeVerifier, state string)

GetState returns the current PKCE state (for debugging/testing).

func (*PKCEManager) ValidateState

func (p *PKCEManager) ValidateState(receivedState string) bool

ValidateState validates the state parameter to prevent CSRF attacks.

type SDKOptions

type SDKOptions struct {
	// Token is the user JWT token (optional - can be set later via Authenticate).
	Token string
	// ValidateTokenOnInit controls whether the token is validated on initialization.
	ValidateTokenOnInit bool
	// Timeout is the request timeout in seconds (default: 30).
	Timeout float64
	// MaxRetries is the maximum number of retries (default: 3).
	MaxRetries int
}

SDKOptions configures the BarndoorSDK.

type ServerDetail

type ServerDetail struct {
	ServerSummary
	// URL is the MCP base URL from the server directory.
	URL *string `json:"url,omitempty"`
}

ServerDetail contains detailed information about an MCP server.

type ServerNotFoundError

type ServerNotFoundError struct {
	BarndoorError
	ServerIdentifier string
	AvailableServers []string
}

ServerNotFoundError is returned when a requested server is not found.

func NewServerNotFoundError

func NewServerNotFoundError(serverIdentifier string, availableServers []string) *ServerNotFoundError

type ServerSummary

type ServerSummary struct {
	// ID is the unique identifier (UUID) for the server.
	ID string `json:"id"`
	// Name is the human-readable name of the server.
	Name string `json:"name"`
	// Slug is the URL-friendly identifier used in API paths.
	Slug string `json:"slug"`
	// Provider is the third-party provider name (e.g., "github", "slack").
	Provider *string `json:"provider,omitempty"`
	// ConnectionStatus is the current connection status.
	ConnectionStatus ConnectionStatus `json:"connection_status"`
}

ServerSummary represents summary information about an MCP server.

func (*ServerSummary) Validate

func (s *ServerSummary) Validate() error

Validate checks that required fields are present.

type TimeoutError

type TimeoutError struct {
	BarndoorError
}

TimeoutError is returned when an operation times out.

func NewTimeoutError

func NewTimeoutError(message string) *TimeoutError

type TokenData

type TokenData struct {
	AccessToken  string `json:"access_token"`            // #nosec G117 -- OAuth token field
	RefreshToken string `json:"refresh_token,omitempty"` // #nosec G117 -- OAuth token field
	TokenType    string `json:"token_type,omitempty"`
	ExpiresIn    int    `json:"expires_in,omitempty"`
	Scope        string `json:"scope,omitempty"`
}

TokenData represents token data for storage.

type TokenError

type TokenError struct {
	AuthenticationError
	HelpText string
}

TokenError is returned when token operations fail.

func NewTokenError

func NewTokenError(message string, helpText string) *TokenError

type TokenExchangeParams

type TokenExchangeParams struct {
	Domain       string // deprecated: use Issuer
	ClientID     string
	Code         string
	RedirectURI  string
	ClientSecret string // #nosec G117 -- OAuth client secret param
	Issuer       string
}

TokenExchangeParams holds parameters for exchanging a code for tokens.

type TokenExpiredError

type TokenExpiredError struct {
	TokenError
}

TokenExpiredError is returned when a token has expired.

func NewTokenExpiredError

func NewTokenExpiredError(message string) *TokenExpiredError

type TokenManager

type TokenManager struct {
	// contains filtered or unexported fields
}

TokenManager handles token validation, refresh, and storage.

func NewTokenManager

func NewTokenManager() *TokenManager

NewTokenManager creates a new token manager.

func (*TokenManager) GetValidToken

func (m *TokenManager) GetValidToken(ctx context.Context) (string, error)

GetValidToken returns a valid access token, refreshing if necessary.

type TokenStorage

type TokenStorage interface {
	LoadToken() (*TokenData, error)
	SaveToken(tokenData *TokenData) error
	ClearToken() error
}

TokenStorage provides an interface for persisting token data.

func GetTokenStorage

func GetTokenStorage() TokenStorage

GetTokenStorage returns the default token storage.

type TokenValidationError

type TokenValidationError struct {
	TokenError
}

TokenValidationError is returned when token validation fails.

type UpsertChannelInput added in v1.3.0

type UpsertChannelInput struct {
	// Type is the kind of destination. Required.
	Type ChannelType
	// ChannelID is an existing channel to edit authoritatively. Empty means
	// create-or-dedup on the type's natural identity. When set and unknown — or owned
	// by another organization — the call returns an *HTTPError with status 404.
	ChannelID string
	// Enabled controls whether the channel delivers. Nil defaults to true. Setting it
	// to false suspends delivery while keeping the channel and its subscriptions —
	// the reversible alternative to deleting it.
	Enabled *bool
	// EmailAddress is the destination for ChannelTypeEmail.
	EmailAddress string
	// URL is the destination for ChannelTypeWebhook. Must be https and resolve to a
	// public address.
	URL string
	// Label is a human-readable name. Required for slack and teams.
	Label string
	// SlackChannelID is the Slack channel id (not its name) for ChannelTypeSlack.
	SlackChannelID string
	// TeamsWorkflowURL is the Teams Workflows URL for ChannelTypeTeams. Write-only:
	// never returned by any endpoint. Required on create, optional when editing by ID
	// (omit to keep the stored URL).
	TeamsWorkflowURL string
	// Subscriptions is the complete set of alert types to deliver. It REPLACES the
	// channel's existing set — a nil or empty slice unsubscribes it from everything.
	// At most one entry per alert type.
	Subscriptions []string
}

UpsertChannelInput describes a channel to create or update.

Which destination fields are permitted depends on Type; sending one that does not belong is a 422 from the server rather than a silently ignored field:

in_app / user_email  no destination fields
email                EmailAddress
webhook              URL
slack                SlackChannelID + Label
teams                Label (+ TeamsWorkflowURL on create)

type WebhookSecret added in v1.3.0

type WebhookSecret struct {
	// SigningSecret is a Standard Webhooks secret ("whsec_" + base64), shown exactly
	// once. Rotating invalidates the previous secret immediately, so deploy this value
	// before the next alert fires.
	SigningSecret string `json:"signing_secret"`
}

WebhookSecret is the one-time reveal of a webhook channel's signing secret.

Directories

Path Synopsis
examples
connect command
Command connect demonstrates using the Barndoor Go SDK to authenticate, list available MCP servers, and build connection parameters for one.
Command connect demonstrates using the Barndoor Go SDK to authenticate, list available MCP servers, and build connection parameters for one.
proto

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址