mcp

package
v1.21.21 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBuilderNoRoot = builderError("Builder.Build() requires a rootCmd; pass it to NewMcpServer or use Command() to defer initialisation")

ErrBuilderNoRoot is returned by Build() when the Builder was created without a root cobra.Command.

Functions

func BuildDiscoverToolsText

func BuildDiscoverToolsText(tools map[string]*ToolDefinition) api.Text

BuildDiscoverToolsText returns a colorized, structured catalogue of the registered MCP tools as an api.Text. Caller picks the rendering format (ANSI for terminals, Markdown for AI clients, plain for text/no-color).

func GetConfigPath

func GetConfigPath() string

GetConfigPath returns the default config file path for the legacy shared "clicky" namespace. New callers should use GetConfigPathFor with the host application's name so multiple clicky-based MCP servers don't stomp on each other's config files.

func GetConfigPathFor

func GetConfigPathFor(appName string) string

GetConfigPathFor returns the default config file path for the given application name. A clicky-based MCP server should pass its CLI name (e.g. "gavel") so each app gets its own ~/.config/<app>/mcp-config.json.

func GetPromptsPath

func GetPromptsPath() string

GetPromptsPath returns the default prompts file path for the legacy shared "clicky" namespace. New callers should use GetPromptsPathFor with the host application's name.

func GetPromptsPathFor

func GetPromptsPathFor(appName string) string

GetPromptsPathFor returns the default prompts file path for the given application name (e.g. "gavel" -> ~/.config/gavel/mcp-prompts.json).

func NewCommand

func NewCommand() *cobra.Command

NewCommand creates the MCP command group that can be added to any cobra CLI

func NewCommandWithConfig

func NewCommandWithConfig(config *Config) *cobra.Command

NewCommandWithConfig creates the MCP command group with custom configuration

func RenderDiscoverToolsString

func RenderDiscoverToolsString(tools map[string]*ToolDefinition, opts *formatters.FormatOptions) string

RenderDiscoverToolsString renders the catalogue as a plain string in the requested format. format is one of "markdown", "pretty"/"ansi", "plain"/"text". Empty defaults to Markdown.

func SaveConfig

func SaveConfig(config *Config, configPath string) error

SaveConfig saves configuration to file

Types

type Builder

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

Builder is a fluent helper for assembling an MCP server configuration. All state is held on an underlying *Config; methods append to slices or overwrite scalar fields, then return the receiver for chaining.

Example:

mcp.NewMcpServer(rootCmd).
    WithExclude("mcp", "ui serve").
    IgnoreParams("*", "--addr", "--ui").
    WithFormat(formatters.FormatOptions{Markdown: true, NoColor: true}).
    Command()

func NewMcpServer

func NewMcpServer(rootCmd ...*cobra.Command) *Builder

NewMcpServer creates a Builder seeded with DefaultConfig(). Pass the host CLI's root cobra.Command if you want Build() to return a fully-initialised *MCPServer; otherwise Command() can be used to wire the `mcp` cobra subtree onto your CLI without immediate server start.

func (*Builder) AutoExpose

func (b *Builder) AutoExpose() *Builder

AutoExpose flips ToolsConfig.AutoExpose to true so every cobra command (subject to Exclude rules) is registered as an MCP tool.

func (*Builder) Build

func (b *Builder) Build() (*MCPServer, error)

Build constructs and initialises an *MCPServer using the configured values. Requires a rootCmd to have been supplied to NewMcpServer.

func (*Builder) Command

func (b *Builder) Command() *cobra.Command

Command returns the `mcp` cobra command group wired with the configured initial config. Add it to your CLI's root command tree.

func (*Builder) Config

func (b *Builder) Config() *Config

Config returns the underlying *Config. Mutations on the returned pointer are visible to subsequent Build/Command calls.

func (*Builder) IgnoreParams

func (b *Builder) IgnoreParams(toolGlob string, params ...string) *Builder

IgnoreParams strips the named parameters from MCP-facing tool schemas. toolGlob uses path.Match syntax: "*" matches every tool, "ai *" matches subcommands of ai, and a bare name matches one tool exactly. Param names may include the leading "--" or omit it.

MCP-only — OpenAPI schemas generated from the same cobra tree are untouched.

func (*Builder) WithConfig

func (b *Builder) WithConfig(cfg *Config) *Builder

WithConfig replaces the underlying Config. Useful when callers want to start from a loaded JSON config and chain further overrides.

func (*Builder) WithExclude

func (b *Builder) WithExclude(patterns ...string) *Builder

WithExclude appends regex patterns to ToolsConfig.Exclude. Patterns match against the cobra command path ("ui serve", "ai cache"), as applied by shouldExposeCommand.

func (*Builder) WithFormat

func (b *Builder) WithFormat(opts formatters.FormatOptions) *Builder

WithFormat sets the format/color overrides applied to every tool execution by injecting matching --format and --no-color flag values before the underlying cobra command runs. Tools without those flags are left untouched.

func (*Builder) WithInclude

func (b *Builder) WithInclude(patterns ...string) *Builder

WithInclude appends regex patterns to ToolsConfig.Include. Has no effect when AutoExpose is true.

type CommandOptions

type CommandOptions struct {
	ConfigPath    string
	Transport     string
	Address       string
	Port          int
	AutoExpose    bool
	InitialConfig *Config
}

CommandOptions holds options for MCP command creation

type Config

type Config struct {
	// Server settings
	Name        string `json:"name"`
	Description string `json:"description"`
	Version     string `json:"version"`

	// Transport configuration
	Transport TransportConfig `json:"transport"`

	// Security settings
	Security SecurityConfig `json:"security"`

	// Tool exposure settings
	Tools ToolsConfig `json:"tools"`
}

Config holds MCP server configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a secure default configuration

func LoadConfig

func LoadConfig(configPath string) (*Config, error)

LoadConfig loads configuration from file, creating default if not found

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

ContentBlock represents a content block in MCP

type GetPromptResponse

type GetPromptResponse struct {
	Description string           `json:"description"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
	Messages    []PromptMessage  `json:"messages"`
}

GetPromptResponse represents the MCP prompts/get response

type IgnoredParamRule

type IgnoredParamRule struct {
	ToolGlob string   `json:"tool_glob"`
	Params   []string `json:"params"`
}

IgnoredParamRule describes a per-tool parameter exclusion. ToolGlob uses path.Match syntax, so "*" matches everything, "ai *" matches all subcommands of "ai", and an exact name like "status" matches only itself.

type JSONRPCError

type JSONRPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

JSONRPCError represents an MCP JSON-RPC error

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id,omitempty"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params,omitempty"`
}

JSONRPCRequest represents an MCP JSON-RPC request

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string        `json:"jsonrpc"`
	ID      interface{}   `json:"id,omitempty"`
	Result  interface{}   `json:"result,omitempty"`
	Error   *JSONRPCError `json:"error,omitempty"`
}

JSONRPCResponse represents an MCP JSON-RPC response

type ListPromptsResponse

type ListPromptsResponse struct {
	Prompts []Prompt `json:"prompts"`
}

ListPromptsResponse represents the MCP prompts/list response

type ListToolsResponse

type ListToolsResponse struct {
	Tools []ToolDefinition `json:"tools"`
}

ListToolsResponse represents the MCP tools/list response

type MCPServer

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

MCPServer implements the MCP protocol server using TaskManager for execution

func NewMCPServer

func NewMCPServer(config *Config, rootCmd *cobra.Command) *MCPServer

NewMCPServer creates a new MCP server

func (*MCPServer) Initialize

func (s *MCPServer) Initialize() error

Initialize registers all commands with the tool registry

func (*MCPServer) Start

func (s *MCPServer) Start(ctx context.Context) error

Start starts the MCP server using the configured transport

type Prompt

type Prompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
	Template    string           `json:"template"`
	Tags        []string         `json:"tags,omitempty"`
	Examples    []string         `json:"examples,omitempty"`
}

Prompt represents an MCP prompt that can be provided to AI assistants

func (*Prompt) ToMCPResponse

func (p *Prompt) ToMCPResponse(args map[string]string) *GetPromptResponse

ToMCPResponse converts a prompt to MCP response format

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Required    bool   `json:"required"`
	Default     string `json:"default,omitempty"`
}

PromptArgument represents an argument for a prompt

type PromptMessage

type PromptMessage struct {
	Role    string      `json:"role"`
	Content interface{} `json:"content"`
}

PromptMessage represents a message in a prompt

type PromptRegistry

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

PromptRegistry manages available prompts

func NewPromptRegistry

func NewPromptRegistry(config *Config) *PromptRegistry

NewPromptRegistry creates a new prompt registry

func (*PromptRegistry) Get

func (r *PromptRegistry) Get(name string) (*Prompt, bool)

Get retrieves a prompt by name

func (*PromptRegistry) List

func (r *PromptRegistry) List() []*Prompt

List returns all available prompts

func (*PromptRegistry) ListByTag

func (r *PromptRegistry) ListByTag(tag string) []*Prompt

ListByTag returns prompts with a specific tag

func (*PromptRegistry) LoadDefaults

func (r *PromptRegistry) LoadDefaults()

LoadDefaults loads default prompts for common CLI operations

func (*PromptRegistry) LoadFromFile

func (r *PromptRegistry) LoadFromFile(path string) error

LoadFromFile loads prompts from a JSON file

func (*PromptRegistry) Register

func (r *PromptRegistry) Register(prompt *Prompt)

Register adds a prompt to the registry

func (*PromptRegistry) SaveToFile

func (r *PromptRegistry) SaveToFile(path string) error

SaveToFile saves prompts to a JSON file

type PromptsGetParams

type PromptsGetParams struct {
	Name      string            `json:"name"`
	Arguments map[string]string `json:"arguments,omitempty"`
}

PromptsGetParams represents the parameters for a prompts/get request

type Property

type Property struct {
	Type        string      `json:"type"`
	Description string      `json:"description"`
	Enum        []string    `json:"enum,omitempty"`
	Default     interface{} `json:"default,omitempty"`
}

Property represents a JSON schema property

type Schema

type Schema struct {
	Type       string              `json:"type"`
	Properties map[string]Property `json:"properties"`
	Required   []string            `json:"required"`
}

Schema represents a JSON schema for tool input/output

type SecurityConfig

type SecurityConfig struct {
	// Require user confirmation for tool invocations
	RequireConfirmation bool `json:"require_confirmation"`

	// Allowed commands (if empty, all commands are allowed)
	AllowedCommands []string `json:"allowed_commands"`

	// Blocked commands
	BlockedCommands []string `json:"blocked_commands"`

	// Enable audit logging
	AuditLog bool `json:"audit_log"`

	// Maximum execution time for tools
	TimeoutSeconds int `json:"timeout_seconds"`
}

SecurityConfig defines security and permission settings

type ToolCallParams

type ToolCallParams struct {
	Name      string                 `json:"name"`
	Arguments map[string]interface{} `json:"arguments"`
}

ToolCallParams represents the parameters for a tools/call request

type ToolCallResult

type ToolCallResult struct {
	Content []ContentBlock `json:"content"`
	IsError bool           `json:"isError,omitempty"`
}

ToolCallResult represents the result of a tool call

type ToolDefinition

type ToolDefinition struct {
	Name         string         `json:"name"`
	Title        string         `json:"title"`
	Description  string         `json:"description"`
	InputSchema  Schema         `json:"inputSchema"`
	OutputSchema *Schema        `json:"outputSchema,omitempty"`
	Command      *cobra.Command `json:"-"` // Internal reference
}

ToolDefinition represents an MCP tool definition

func NewMcpTool

func NewMcpTool(rpcOp *rpc.RPCOperation) *ToolDefinition

NewMcpTool creates an MCP ToolDefinition from a generic RPC operation

type ToolRegistry

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

ToolRegistry manages the mapping between cobra commands and MCP tools

func NewToolRegistry

func NewToolRegistry(config *Config) *ToolRegistry

NewToolRegistry creates a new tool registry

func (*ToolRegistry) GetTool

func (r *ToolRegistry) GetTool(name string) (*ToolDefinition, bool)

GetTool returns a specific tool by name

func (*ToolRegistry) GetTools

func (r *ToolRegistry) GetTools() map[string]*ToolDefinition

GetTools returns all registered tools

func (*ToolRegistry) NewMcpToolWithConfig

func (r *ToolRegistry) NewMcpToolWithConfig(rpcOp *rpc.RPCOperation) *ToolDefinition

NewMcpToolWithConfig creates an MCP ToolDefinition from a generic RPC operation with config overrides

func (*ToolRegistry) RegisterCommand

func (r *ToolRegistry) RegisterCommand(cmd *cobra.Command) error

RegisterCommand registers a cobra command as an MCP tool

func (*ToolRegistry) RegisterCommandTree

func (r *ToolRegistry) RegisterCommandTree(cmd *cobra.Command) error

RegisterCommandTree recursively registers a command and its subcommands

func (*ToolRegistry) ToListResponse

func (r *ToolRegistry) ToListResponse() *ListToolsResponse

ToListResponse converts the registry to an MCP tools/list response

type ToolsConfig

type ToolsConfig struct {
	// Auto-expose all commands
	AutoExpose bool `json:"auto_expose"`

	// Include pattern for command names
	Include []string `json:"include"`

	// Exclude pattern for command names
	Exclude []string `json:"exclude"`

	// Override descriptions for specific commands
	Descriptions map[string]string `json:"descriptions,omitempty"`

	// IgnoredParams strips parameters (flags or positional names) from
	// the MCP-facing tool schema. Each rule applies to tools whose name
	// matches ToolGlob (path.Match semantics; "*" matches all). Names
	// in Params may include the "--" prefix or omit it.
	// MCP-only — does not affect OpenAPI generation.
	IgnoredParams []IgnoredParamRule `json:"ignored_params,omitempty"`

	// Format overrides the format/color settings of every tool execution
	// by setting the corresponding cobra flags on the command before it
	// runs. Useful for forcing Markdown without ANSI for AI clients.
	Format *formatters.FormatOptions `json:"format,omitempty"`
}

ToolsConfig defines which cobra commands to expose as MCP tools

type TransportConfig

type TransportConfig struct {
	Type    string `json:"type"`    // "stdio" or "http"
	Address string `json:"address"` // For HTTP transport
	Port    int    `json:"port"`    // For HTTP transport
}

TransportConfig defines how the MCP server communicates

Jump to

Keyboard shortcuts

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