mcp

package
v1.114.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrServerNotConfigured  = errors.New("MCP server is not configured")
	ErrServerAlreadyRunning = errors.New("MCP server is already running")
)

Sentinel errors returned by StartOne / StopOne. The manager keeps the messages in English (Go convention for library errors) but the CLI handler wraps them with errors.Is and translates via i18n before printing — that keeps user-facing text out of this layer while still letting external callers detect "unknown server" / "already running" cases programmatically.

Functions

func DefaultConfigPath

func DefaultConfigPath() string

DefaultConfigPath returns the default MCP config file path.

Types

type ChannelHandler added in v1.97.0

type ChannelHandler func(msg ChannelMessage)

ChannelHandler is called when a channel message is received.

type ChannelManager added in v1.97.0

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

ChannelManager manages MCP channel subscriptions and message delivery.

func NewChannelManager added in v1.97.0

func NewChannelManager(logger *zap.Logger) *ChannelManager

NewChannelManager creates a new channel manager.

func (*ChannelManager) Count added in v1.97.0

func (cm *ChannelManager) Count() int

Count returns the total number of stored messages.

func (*ChannelManager) FormatForPrompt added in v1.97.0

func (cm *ChannelManager) FormatForPrompt(maxMessages int) string

FormatForPrompt returns recent channel messages formatted for system prompt injection.

func (*ChannelManager) GetByChannel added in v1.97.0

func (cm *ChannelManager) GetByChannel(channel string, n int) []ChannelMessage

GetByChannel returns recent messages filtered by channel name.

func (*ChannelManager) GetRecent added in v1.97.0

func (cm *ChannelManager) GetRecent(n int) []ChannelMessage

GetRecent returns the N most recent channel messages.

func (*ChannelManager) OnMessage added in v1.97.0

func (cm *ChannelManager) OnMessage(handler ChannelHandler)

OnMessage registers a handler that will be called for each incoming channel message.

func (*ChannelManager) ProcessSSENotification added in v1.97.0

func (cm *ChannelManager) ProcessSSENotification(serverName string, data []byte)

ProcessSSENotification handles a notification pushed via SSE from an MCP server. This is called when the SSE stream receives a message that's not a response to a request.

func (*ChannelManager) Push added in v1.97.0

func (cm *ChannelManager) Push(msg ChannelMessage)

Push processes an incoming channel message from an MCP server.

type ChannelMessage added in v1.97.0

type ChannelMessage struct {
	ServerName string            `json:"serverName"`
	Channel    string            `json:"channel"` // e.g., "ci", "alerts", "chat"
	Content    string            `json:"content"`
	Metadata   map[string]string `json:"metadata,omitempty"`
	Timestamp  time.Time         `json:"timestamp"`
}

ChannelMessage represents a push message from an MCP server.

type MCPTool

type MCPTool struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Parameters  map[string]interface{} `json:"inputSchema"`
	ServerName  string                 `json:"-"`
}

MCPTool represents a tool discovered from an MCP server.

type MCPToolResult

type MCPToolResult struct {
	Content  string `json:"content"`
	IsError  bool   `json:"isError,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
}

MCPToolResult is the result of executing an MCP tool.

type Manager

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

Manager manages MCP server connections and tool routing.

func NewManager

func NewManager(logger *zap.Logger) *Manager

NewManager creates a new MCP manager.

func (*Manager) Channels added in v1.97.0

func (m *Manager) Channels() *ChannelManager

Channels returns the channel manager for push message handling.

func (*Manager) ExecuteTool

func (m *Manager) ExecuteTool(ctx context.Context, toolName string, args map[string]interface{}) (*MCPToolResult, error)

ExecuteTool executes an MCP tool by name.

func (*Manager) GetServerStatus

func (m *Manager) GetServerStatus() []ServerStatus

GetServerStatus returns status for all servers.

func (*Manager) GetShadowedBuiltins added in v1.97.0

func (m *Manager) GetShadowedBuiltins() []string

GetShadowedBuiltins returns the list of built-in plugin names that should be hidden because a connected MCP server declares them in its "overrides" field. Only overrides from currently connected servers are returned — if a server disconnects, its overrides are automatically released and the built-ins become visible to the LLM again.

func (*Manager) GetToolSchema added in v1.97.0

func (m *Manager) GetToolSchema(toolName string) map[string]interface{}

GetToolSchema returns the full JSON schema for a specific MCP tool. Used when the model attempts to invoke a tool and needs parameter details.

func (*Manager) GetTools

func (m *Manager) GetTools() []models.ToolDefinition

GetTools returns all discovered MCP tools as ToolDefinitions.

func (*Manager) GetToolsSummary added in v1.97.0

func (m *Manager) GetToolsSummary() []models.ToolDefinition

GetToolsSummary returns lightweight tool descriptions (name + description only). This saves tokens in the system prompt by deferring full schemas until invocation.

func (*Manager) IsMCPTool

func (m *Manager) IsMCPTool(name string) bool

IsMCPTool checks if a tool name is an MCP tool.

func (*Manager) LoadConfig

func (m *Manager) LoadConfig(configPath string) error

LoadConfig loads MCP server configurations from a JSON file.

func (*Manager) RecentLogs added in v1.113.0

func (m *Manager) RecentLogs(name string) []string

RecentLogs returns up to mcpLogRingCapacity recent log lines for the named server, oldest first. Returns nil if the server is not configured. The slice is a copy and safe to mutate.

func (*Manager) Reload added in v1.112.2

func (m *Manager) Reload(ctx context.Context, configPath string) (ReloadDiff, error)

func (*Manager) ServerNames added in v1.113.0

func (m *Manager) ServerNames() []string

ServerNames returns the names of all configured servers in alphabetical order. Used by the /mcp completer to suggest valid targets and by callers that need to iterate the configured set without holding any internal locks.

func (*Manager) StartAll

func (m *Manager) StartAll(ctx context.Context) error

StartAll starts all configured MCP servers.

Failures of individual servers are logged and recorded on ServerStatus.LastError, but they never abort the loop — the manager always returns nil so a single broken server does not poison the rest of the session. Inspect /mcp status (or GetServerStatus) to see which servers came up and which did not.

The connection map is snapshotted under m.mu and iterated unlocked so startServer (and the discoverTools call inside it, which takes m.mu.Lock) can run without deadlocking against this loop and so that /mcp status — which also takes m.mu — stays responsive while servers are coming up in the background.

func (*Manager) StartOne added in v1.113.0

func (m *Manager) StartOne(ctx context.Context, name string) error

StartOne starts a single configured server by name. The server must already be in m.servers (loaded by LoadConfig/Reload or left behind by a previous StopOne) — StartOne does not invent a config from thin air. Returns ErrServerNotConfigured / ErrServerAlreadyRunning (wrapped with the server name) so callers can branch on the cause via errors.Is and translate user-facing messages.

func (*Manager) StopAll

func (m *Manager) StopAll()

StopAll stops all running MCP servers.

func (*Manager) StopOne added in v1.113.0

func (m *Manager) StopOne(name string) error

StopOne stops a single running server but keeps its entry in the configured set so /mcp start <name> can revive it later. This is the public counterpart to the internal stopOne (which Reload uses to drop servers that vanished from the config file). Returns an error if the server name isn't known.

func (*Manager) ToolCount added in v1.97.0

func (m *Manager) ToolCount() int

ToolCount returns the number of discovered MCP tools.

type ReloadDiff added in v1.112.2

type ReloadDiff struct {
	Started []string
	Stopped []string
	Updated []string
}

Reload reconciles the live server set with the on-disk config so edits to mcp_servers.json take effect without restarting chatcli.

Diff semantics:

  • Server present in file but not running → start it.
  • Server running but no longer in file → stop and forget.
  • Server in both, config bytes equal → leave alone.
  • Server in both, config bytes differ → stop, replace, start.

`enabled: false` is treated as "not in file" — disabling a server in the JSON stops it on the next reload.

Returns the set of changes applied, empty when nothing changed.

type ServerConfig

type ServerConfig struct {
	Name      string            `json:"name"`
	Command   string            `json:"command"`
	Args      []string          `json:"args,omitempty"`
	Env       map[string]string `json:"env,omitempty"`
	Transport TransportType     `json:"transport"`
	URL       string            `json:"url,omitempty"` // For SSE transport
	Enabled   bool              `json:"enabled"`
	// Overrides lists built-in plugin names that this MCP server replaces.
	// When the server is connected, these built-ins are shadowed (hidden from the LLM).
	// If the server disconnects, the built-ins are automatically restored.
	// Example: ["@webfetch", "@websearch"]
	Overrides []string `json:"overrides,omitempty"`
}

ServerConfig represents a configured MCP server.

type ServerConnection

type ServerConnection struct {
	Config  ServerConfig
	Status  ServerStatus
	Process *os.Process
	// contains filtered or unexported fields
}

ServerConnection represents an active MCP server.

type ServerStatus

type ServerStatus struct {
	Name      string
	Connected bool
	Starting  bool // true while the server is being launched in background
	ToolCount int
	LastPing  time.Time
	LastError error
	StartedAt time.Time
}

ServerStatus tracks the health of an MCP server connection.

type TransportType

type TransportType string

TransportType defines MCP transport mechanism.

const (
	TransportStdio TransportType = "stdio"
	TransportSSE   TransportType = "sse"
)

Jump to

Keyboard shortcuts

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