api

package
v2.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: Apache-2.0 Imports: 59 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ContextPostKey    = "post"
	ContextChannelKey = "channel"
	ContextBotKey     = "bot"
)
View Source
const (
	TitleSummarizeUnreads = "Summarize Unreads"
	TitleSummarizeChannel = "Summarize Channel"
)
View Source
const (
	TitleThreadSummary     = "Thread Summary"
	TitleFindActionItems   = "Action Items"
	TitleFindOpenQuestions = "Open Questions"
)
View Source
const (
	// Config.
	AuditEventSaveConfig = "saveConfig"

	// Admin operations.
	AuditEventReindexPosts          = "reindexPosts"
	AuditEventCancelReindexJob      = "cancelReindexJob"
	AuditEventCatchUpReindex        = "catchUpReindex"
	AuditEventRebuildVectorIndex    = "rebuildVectorIndex"
	AuditEventClearMCPToolsCache    = "clearMCPToolsCache"
	AuditEventUpdateMCPPluginServer = "updateMCPPluginServer"

	// Agent CRUD.
	AuditEventCreateAgent       = "createAgent"
	AuditEventUpdateAgent       = "updateAgent"
	AuditEventDeleteAgent       = "deleteAgent"
	AuditEventUpdateAgentAvatar = "updateAgentAvatar"

	// Custom prompts.
	AuditEventCreateCustomPrompt = "createCustomPrompt"
	AuditEventUpdateCustomPrompt = "updateCustomPrompt"
	AuditEventDeleteCustomPrompt = "deleteCustomPrompt"

	// Channel configuration.
	AuditEventUpdateChannelAutoReply = "updateChannelAutoReply"

	// Credentials: third-party MCP OAuth grant/revocation and per-user tool
	// provider preferences.
	AuditEventMCPOAuthStart            = "mcpOAuthStart"
	AuditEventMCPOAuthCallback         = "mcpOAuthCallback"
	AuditEventMCPOAuthDisconnect       = "mcpOAuthDisconnect"
	AuditEventUpdateMCPUserPreferences = "updateMCPUserPreferences"

	// Inter-plugin MCP server registration (bridge routes).
	AuditEventRegisterMCPPluginServer   = "registerMCPPluginServer"
	AuditEventUnregisterMCPPluginServer = "unregisterMCPPluginServer"

	// In-channel tool approval: the human decision the server cannot see.
	AuditEventToolCallApproval   = "toolCallApproval"
	AuditEventToolResultApproval = "toolResultApproval"

	// MCP session grant: an external MCP client obtained a dedicated session
	// holding API access as the user. Not a gin route — emitted directly by
	// delegateToMCPHandler when a session is newly created, so it has no
	// registry entry below.
	AuditEventMCPSessionGrant = "mcpSessionGrant"
)

Audit event names for every state-changing operation in the plugin: 22 routed events plus the non-gin MCP session grant. All are declared here, including ones whose instrumentation lands in later changes, so call sites never use inline string literals; new state-changing routes add their names here rather than inline.

The server stamps the plugin ID into every record's parameters when it is logged, so the names stay unprefixed.

View Source
const AgentActiveCountHeader = "X-Agent-Active-Count"

AgentActiveCountHeader is returned on GET /agents for unlicensed servers so the webapp can gate creation against the server-wide count (not the access-filtered list).

View Source
const FreeTierAgentLimit = 1

FreeTierAgentLimit is the maximum number of self-service agents allowed when the server does not have a multi-LLM (E20+) license.

View Source
const MaxAgentRequestBodyBytes = 2 << 20 // 2 MiB

MaxAgentRequestBodyBytes caps agent create/update JSON bodies. It must comfortably exceed the worst-case encoded size of llm.MaxCustomInstructionsRunes plus the remaining payload.

View Source
const WebsocketEventBotsInvalidate = "bots_invalidate"

WebsocketEventBotsInvalidate is the event name for PublishWebSocketEvent (webapp: custom_mattermost-ai_<name>).

View Source
const WebsocketEventChannelAutoReplyUpdated = "channel_autoreply_updated"

WebsocketEventChannelAutoReplyUpdated is the event name for PublishWebSocketEvent (webapp: custom_mattermost-ai_<name>).

View Source
const WebsocketEventMCPConnectionUpdated = "mcp_connection_updated"

WebsocketEventMCPConnectionUpdated is the event name for user-scoped MCP OAuth connection updates (webapp: custom_mattermost-ai_<name>).

Variables

This section is empty.

Functions

This section is empty.

Types

type AIBotInfo

type AIBotInfo struct {
	ID                    string                 `json:"id"`
	DisplayName           string                 `json:"displayName"`
	Username              string                 `json:"username"`
	LastIconUpdate        int64                  `json:"lastIconUpdate"`
	DMChannelID           string                 `json:"dmChannelID"`
	ChannelAccessLevel    llm.ChannelAccessLevel `json:"channelAccessLevel"`
	ChannelIDs            []string               `json:"channelIDs"`
	UserAccessLevel       llm.UserAccessLevel    `json:"userAccessLevel"`
	UserIDs               []string               `json:"userIDs"`
	EnabledMCPTools       []llm.EnabledMCPTool   `json:"enabledMCPTools"`
	AutoEnableNewMCPTools bool                   `json:"autoEnableNewMCPTools"`
	// UseServiceAccountAuth is the effective mode, not the raw agent flag: it is
	// false when the server is not licensed for remote MCP.
	UseServiceAccountAuth bool `json:"useServiceAccountAuth"`
	IsDefault             bool `json:"isDefault,omitempty"`
}

type AIBotsResponse

type AIBotsResponse struct {
	Bots             []AIBotInfo `json:"bots"`
	SearchEnabled    bool        `json:"searchEnabled"`
	AllowUnsafeLinks bool        `json:"allowUnsafeLinks"`
}

type API

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

API represents the HTTP API functionality for the plugin

func New

func New(
	bots *bots.MMBots,
	conversationsService *conversations.Conversations,
	meetingsService *meetings.Service,
	indexerService *indexer.Indexer,
	searchService *search.Search,
	pluginAPI *pluginapi.Client,
	metricsService metrics.Metrics,
	llmContextBuilder *llmcontext.Builder,
	config Config,
	prompts *llm.Prompts,
	mmClient mmapi.Client,
	dbClient *mmapi.DBClient,
	licenseChecker *enterprise.LicenseChecker,
	streamingService streaming.Service,
	i18nBundle *i18n.Bundle,
	mcpClientManager MCPClientManager,
	mcpHandlers *mcpserver.PluginMCPHandlers,
	llmUpstreamHTTPClient *http.Client,
	configStore ConfigStore,
	agentStore AgentStore,
	configUpdater ConfigUpdater,
	clusterNotifier ClusterNotifier,
	clusterAgentNotifier ClusterAgentNotifier,
	mcpOAuthNotifier MCPOAuthClusterNotifier,
	streamStopNotifier StreamStopClusterNotifier,
	conversationStore ConversationStore,
	getSearchInitError func() string,
	customPromptsStore *customprompts.Store,
	autoReplyStore ChannelAutoReplyStore,
) *API

New creates a new API instance

func (*API) MattermostAuthorizationRequired

func (a *API) MattermostAuthorizationRequired(c *gin.Context)

func (*API) ServeHTTP

func (a *API) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request)

ServeHTTP handles HTTP requests to the plugin

func (*API) ServeMetrics

func (a *API) ServeMetrics(c *plugin.Context, w http.ResponseWriter, r *http.Request)

ServeMetrics serves the metrics endpoint

func (*API) SetConversationService

func (a *API) SetConversationService(svc *conversation.Service)

SetConversationService sets the conversation entity service for channel analysis.

func (*API) SetExternalRebuilderForTest

func (a *API) SetExternalRebuilderForTest(rb externalServerRebuilder)

SetExternalRebuilderForTest installs a test-only externalServerRebuilder.

type AgentStore

type AgentStore interface {
	CreateAgent(cfg *llm.BotConfig) error
	GetAgent(id string) (*llm.BotConfig, error)
	ListAgents() ([]*llm.BotConfig, error)
	ListAgentsByCreator(creatorID string) ([]*llm.BotConfig, error)
	CountActiveAgents() (int, error)
	UpdateAgent(cfg *llm.BotConfig) error
	DeleteAgent(id string) error
}

AgentStore provides CRUD access to user-created agents in the database.

type ChannelAutoReply added in v2.6.0

type ChannelAutoReply struct {
	BotID string `json:"bot_id"`
	Mode  string `json:"mode"`
}

ChannelAutoReply is the request and response payload for GET/PUT /channel/{channelid}/autoreply.

type ChannelAutoReplyStore added in v2.6.0

type ChannelAutoReplyStore interface {
	Get(channelID string) (*autoreply.Setting, error)
	Set(channelID, botID string, mode autoreply.Mode, updatedBy string) (*autoreply.Setting, error)
	Delete(channelID string) error
}

ChannelAutoReplyStore provides read/write access to per-channel auto-reply settings. Implemented by *autoreply.Service (Phase 1). Get reads the database so API reads are read-your-writes across cluster nodes; Set/Delete validate, persist, and handle cluster cache invalidation internally.

type ClearMCPToolsCacheResponse

type ClearMCPToolsCacheResponse struct {
	ClearedServers int    `json:"cleared_servers"`
	Message        string `json:"message"`
}

ClearMCPToolsCacheResponse represents the response for clearing the cache

type ClusterAgentNotifier

type ClusterAgentNotifier interface {
	PublishAgentUpdate() error
}

ClusterAgentNotifier broadcasts agent update events to other cluster nodes.

type ClusterNotifier

type ClusterNotifier interface {
	PublishConfigUpdate() error
}

ClusterNotifier broadcasts config update events to other cluster nodes.

type Config

type Config interface {
	GetDefaultBotName() string
	MCP() mcp.Config
	AllowUnsafeLinks() bool
	EmbeddingSearchConfig() embeddings.EmbeddingSearchConfig
	EnableChannelMentionToolCalling() bool
}

type ConfigStore

type ConfigStore interface {
	GetConfig() (*config.Config, error)
	SaveConfig(cfg config.Config) error
}

ConfigStore provides read/write access to the plugin configuration in the database.

type ConfigUpdater

type ConfigUpdater interface {
	Update(cfg *config.Config)
}

ConfigUpdater updates the in-memory plugin configuration.

type ConversationResponse

type ConversationResponse struct {
	ID         string         `json:"id"`
	UserID     string         `json:"user_id"`
	BotID      string         `json:"bot_id"`
	ChannelID  *string        `json:"channel_id"`
	RootPostID *string        `json:"root_post_id"`
	Title      string         `json:"title"`
	Operation  string         `json:"operation"`
	Turns      []TurnResponse `json:"turns"`
}

ConversationResponse is the JSON shape returned by GET /conversations/{id}.

type ConversationStore

type ConversationStore interface {
	GetConversation(id string) (*store.Conversation, error)
	GetTurnsForConversation(conversationID string) ([]store.Turn, error)
	GetTurnByPostID(postID string) (*store.Turn, error)
	UpdateTurnContent(id string, content json.RawMessage) error
	GetConversationSummariesForUser(userID string, limit, offset int) ([]store.ConversationSummary, error)
}

ConversationStore provides read/write access to conversation and turn data.

type CreateAgentRequest

type CreateAgentRequest struct {
	DisplayName             string               `json:"displayName" binding:"required"`
	Username                string               `json:"username" binding:"required"`
	ServiceID               string               `json:"serviceID" binding:"required"`
	CustomInstructions      string               `json:"customInstructions"`
	ChannelAccessLevel      int                  `json:"channelAccessLevel"`
	ChannelIDs              []string             `json:"channelIDs"`
	UserAccessLevel         int                  `json:"userAccessLevel"`
	UserIDs                 []string             `json:"userIDs"`
	TeamIDs                 []string             `json:"teamIDs"`
	AdminUserIDs            []string             `json:"adminUserIDs"`
	EnabledMCPTools         []llm.EnabledMCPTool `json:"enabledMCPTools"`
	AutoEnableNewMCPTools   bool                 `json:"autoEnableNewMCPTools"`
	MCPDynamicToolLoading   bool                 `json:"mcpDynamicToolLoading"`
	UseServiceAccountAuth   bool                 `json:"useServiceAccountAuth"`
	Model                   string               `json:"model"`
	EnableVision            bool                 `json:"enableVision"`
	DisableTools            bool                 `json:"disableTools"`
	EnabledNativeTools      []string             `json:"enabledNativeTools"`
	ReasoningEnabled        bool                 `json:"reasoningEnabled"`
	ReasoningEffort         string               `json:"reasoningEffort"`
	ThinkingBudget          int                  `json:"thinkingBudget"`
	StructuredOutputEnabled bool                 `json:"structuredOutputEnabled"`
	MaxToolTurns            int                  `json:"maxToolTurns"`
}

CreateAgentRequest is the JSON body for POST /agents. Field values are stored as given (no server-side fill-in). MCP tool access is controlled by two independent fields:

  • autoEnableNewMCPTools=true gives the agent every currently configured MCP tool and any added later.
  • Otherwise, the agent gets only the tools listed in enabledMCPTools (empty/missing = no MCP tools).

type FetchModelsForServiceRequest

type FetchModelsForServiceRequest struct {
	ServiceID string `json:"serviceID" binding:"required"`
}

FetchModelsForServiceRequest is the JSON body for POST /agents/models/fetch.

type FetchModelsRequest

type FetchModelsRequest struct {
	ServiceType string `json:"serviceType"`
	APIKey      string `json:"apiKey"`
	APIURL      string `json:"apiURL"`
	OrgID       string `json:"orgID"`

	// Region applies to providers that require it for model listing (Vertex AI).
	Region string `json:"region"`

	// Vertex AI credentials. VertexAuthCredentials may be empty to signal ADC.
	VertexProjectID       string `json:"vertexProjectID"`
	VertexProjectNumber   string `json:"vertexProjectNumber"`
	VertexAuthCredentials string `json:"vertexAuthCredentials"`
}

type MCPClientManager

type MCPClientManager interface {
	GetOAuthManager() *mcp.OAuthManager
	GetToolsCache() *mcp.ToolsCache
	GetHTTPClient() *http.Client
	ProcessOAuthCallback(ctx context.Context, loggedInUserID, state, code, iss string) (*mcp.OAuthSession, error)
	DisconnectUserOAuth(ctx context.Context, userID, serverName string) error
	MarkOAuthNeeded(userID, serverName, authURL string) error
	GetEmbeddedServer() mcp.EmbeddedMCPServer
	EnsureMCPSessionID(userID string) (sessionID string, created bool, err error)
	GetTools(ctx context.Context, req mcp.CatalogRequest) ([]llm.Tool, *mcp.Errors)
	RefreshToolsForUser(ctx context.Context, userID string) ([]llm.Tool, *mcp.Errors, error)
	GetConfig() mcp.Config

	RegisterPluginServer(cfg mcp.PluginServerConfig)
	UpdatePluginServer(cfg mcp.PluginServerConfig)
	UnregisterPluginServer(pluginID string)
	ListPluginServers() []mcp.PluginServerConfig
	GetPluginServer(pluginID string) (mcp.PluginServerConfig, bool)
	IsPluginRegistered(pluginID string) bool

	DiscoverPluginServerTools(ctx context.Context, userID string, cfg mcp.PluginServerConfig) ([]mcp.ToolInfo, error)
}

type MCPOAuthClusterNotifier

type MCPOAuthClusterNotifier interface {
	PublishMCPOAuthUpdate(userID string) error
}

MCPOAuthClusterNotifier broadcasts MCP OAuth updates to other cluster nodes.

type MCPServerInfo

type MCPServerInfo struct {
	Name       string        `json:"name"`
	URL        string        `json:"url"`
	Tools      []MCPToolInfo `json:"tools"`
	NeedsOAuth bool          `json:"needsOAuth"`
	OAuthURL   string        `json:"oauthURL,omitempty"` // URL to redirect for OAuth if needed
	Error      *string       `json:"error"`

	// ServerType is one of "embedded", "remote", or "plugin".
	ServerType string `json:"serverType"`
	Enabled    bool   `json:"enabled"`
	// ToolConfigs is populated for plugin rows only.
	ToolConfigs []mcp.ToolConfig `json:"toolConfigs,omitempty"`
}

MCPServerInfo represents a server and its tools for API response

type MCPToolInfo

type MCPToolInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	InputSchema any    `json:"inputSchema"`
}

MCPToolInfo represents a tool from an MCP server for API response

type MCPToolsResponse

type MCPToolsResponse struct {
	Servers []MCPServerInfo `json:"servers"`
}

MCPToolsResponse represents the response structure for MCP tools endpoint

type RawFileContentRequest

type RawFileContentRequest struct {
	FileID string `json:"file_id"`
	Offset int    `json:"offset,omitempty"`
	Limit  int    `json:"limit,omitempty"`
}

RawFileContentRequest is the request body for the raw file content endpoint.

type RawFileContentResponse

type RawFileContentResponse struct {
	Name       string `json:"name"`
	MimeType   string `json:"mime_type"`
	TotalRunes int    `json:"total_runes"`
	Offset     int    `json:"offset"`
	Returned   int    `json:"returned"`
	HasMore    bool   `json:"has_more"`
	HasText    bool   `json:"has_text"`
	Text       string `json:"text"`
}

RawFileContentResponse is the response body for the raw file content endpoint.

type RawSearchRequest

type RawSearchRequest struct {
	Query     string `json:"query"`
	TeamID    string `json:"team_id,omitempty"`
	ChannelID string `json:"channel_id,omitempty"`
	Limit     int    `json:"limit,omitempty"`
	Offset    int    `json:"offset,omitempty"`
}

RawSearchRequest represents the request body for the raw semantic search endpoint

type RawSearchResponse

type RawSearchResponse struct {
	Results []RawSearchResult `json:"results"`
}

RawSearchResponse represents the response body for the raw semantic search endpoint

type RawSearchResult

type RawSearchResult struct {
	PostID      string  `json:"post_id"`
	ChannelID   string  `json:"channel_id"`
	ChannelName string  `json:"channel_name"`
	UserID      string  `json:"user_id"`
	Username    string  `json:"username"`
	Content     string  `json:"content"`
	Score       float32 `json:"score"`
	CreateAt    int64   `json:"create_at"` // Post creation timestamp (Unix millis)
}

RawSearchResult represents a single raw semantic search result

type ReindexRequest

type ReindexRequest struct {
	ClearIndex *bool `json:"clearIndex"`
}

ReindexRequest represents the request body for reindexing

type RenderRequest

type RenderRequest struct {
	ChannelID   string `json:"channel_id"`
	BotUsername string `json:"bot_username"`
}

RenderRequest represents the request body for rendering a custom prompt template.

type SearchRequest

type SearchRequest struct {
	Query      string `json:"query"`
	TeamID     string `json:"teamId"`
	ChannelID  string `json:"channelId"`
	MaxResults int    `json:"maxResults"`
}

SearchRequest represents a search query request from the API

type ServiceInfo

type ServiceInfo struct {
	ID               string `json:"id"`
	Name             string `json:"name"`
	Type             string `json:"type"`
	DefaultModel     string `json:"defaultModel"`
	OutputTokenLimit int    `json:"outputTokenLimit"`
	UseResponsesAPI  bool   `json:"useResponsesAPI"`
}

ServiceInfo is a client-safe view of an AI service (no secrets).

type SetPinRequest

type SetPinRequest struct {
	PromptID string `json:"prompt_id"`
	Pinned   bool   `json:"pinned"`
}

SetPinRequest represents the request body for pinning/unpinning a prompt.

type StreamStopClusterNotifier

type StreamStopClusterNotifier interface {
	PublishStreamStop(postID string) error
}

StreamStopClusterNotifier broadcasts a stop-streaming request to peer nodes so HA deployments without sticky sessions can cancel an in-flight LLM stream no matter which node handles the /stop request.

type TurnResponse

type TurnResponse struct {
	ID        string          `json:"id"`
	PostID    *string         `json:"post_id"`
	Role      string          `json:"role"`
	Content   json.RawMessage `json:"content"`
	TokensIn  int64           `json:"tokens_in"`
	TokensOut int64           `json:"tokens_out"`
	Sequence  int             `json:"sequence"`
	// ApprovalState is set only on post-anchor assistant turns (those with
	// a non-nil PostID). One of "call" | "result" | "done". Computed by the
	// server so the webapp renders approval UI from a single source of truth.
	ApprovalState string `json:"approval_state,omitempty"`
}

TurnResponse is the JSON shape for a single turn within a conversation response.

type UpdateAgentRequest

type UpdateAgentRequest struct {
	DisplayName             string               `json:"displayName" binding:"required"`
	Username                string               `json:"username"`
	ServiceID               string               `json:"serviceID" binding:"required"`
	CustomInstructions      string               `json:"customInstructions"`
	ChannelAccessLevel      int                  `json:"channelAccessLevel"`
	ChannelIDs              []string             `json:"channelIDs"`
	UserAccessLevel         int                  `json:"userAccessLevel"`
	UserIDs                 []string             `json:"userIDs"`
	TeamIDs                 []string             `json:"teamIDs"`
	AdminUserIDs            []string             `json:"adminUserIDs"`
	EnabledMCPTools         []llm.EnabledMCPTool `json:"enabledMCPTools"`
	AutoEnableNewMCPTools   bool                 `json:"autoEnableNewMCPTools"`
	MCPDynamicToolLoading   bool                 `json:"mcpDynamicToolLoading"`
	UseServiceAccountAuth   bool                 `json:"useServiceAccountAuth"`
	Model                   string               `json:"model"`
	EnableVision            bool                 `json:"enableVision"`
	DisableTools            bool                 `json:"disableTools"`
	EnabledNativeTools      []string             `json:"enabledNativeTools"`
	ReasoningEnabled        bool                 `json:"reasoningEnabled"`
	ReasoningEffort         string               `json:"reasoningEffort"`
	ThinkingBudget          int                  `json:"thinkingBudget"`
	StructuredOutputEnabled bool                 `json:"structuredOutputEnabled"`
	MaxToolTurns            int                  `json:"maxToolTurns"`
	// contains filtered or unexported fields
}

UpdateAgentRequest is the JSON body for PUT /agents/:agentid (full document replace, same shape as create). Username cannot change after create (enforced in the handler).

func (*UpdateAgentRequest) UnmarshalJSON

func (r *UpdateAgentRequest) UnmarshalJSON(data []byte) error

type UpdatePluginServerRequest

type UpdatePluginServerRequest struct {
	Enabled     *bool             `json:"enabled,omitempty"`
	ToolConfigs *[]mcp.ToolConfig `json:"tool_configs,omitempty"`
}

UpdatePluginServerRequest is the body shape for PUT /admin/mcp/plugin-servers/:pluginID. Pointer fields use partial-update semantics: nil means unchanged.

type UserMCPServerInfo

type UserMCPServerInfo struct {
	Name                     string            `json:"name"`
	ServerOrigin             string            `json:"serverOrigin"`
	Kind                     string            `json:"kind"`
	Authenticated            bool              `json:"authenticated"`
	NeedsOAuth               bool              `json:"needsOAuth"`
	AuthEmail                string            `json:"authEmail,omitempty"`
	AuthURL                  string            `json:"authURL,omitempty"`
	ServiceAccountConfigured bool              `json:"serviceAccountConfigured"`
	Tools                    []UserMCPToolInfo `json:"tools"`
}

UserMCPServerInfo describes a single MCP server and its visible tools.

type UserMCPToolInfo

type UserMCPToolInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Enabled     bool   `json:"enabled"`
	Policy      string `json:"policy"`
}

UserMCPToolInfo describes a single tool within a server response.

type UserMCPToolsResponse

type UserMCPToolsResponse struct {
	Servers []UserMCPServerInfo `json:"servers"`
}

UserMCPToolsResponse is the top-level response for GET /mcp/tools.

Jump to

Keyboard shortcuts

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