Skip to content

Commit 63704f5

Browse files
committed
godoc
1 parent d3281a2 commit 63704f5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+1769
-459
lines changed

cmd/auth.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ import (
1010
"github.com/spf13/cobra"
1111
)
1212

13+
// authCmd represents the auth command for managing AI provider authentication.
14+
// This command provides subcommands for login, logout, and status checking
15+
// of authentication credentials for various AI providers, with OAuth support
16+
// for providers like Anthropic.
1317
var authCmd = &cobra.Command{
1418
Use: "auth",
1519
Short: "Manage authentication credentials for AI providers",
@@ -27,6 +31,9 @@ Examples:
2731
mcphost auth status`,
2832
}
2933

34+
// authLoginCmd represents the login subcommand for authenticating with AI providers.
35+
// It handles OAuth flow for supported providers, opening a browser for authentication
36+
// and securely storing the resulting credentials for future use.
3037
var authLoginCmd = &cobra.Command{
3138
Use: "login [provider]",
3239
Short: "Authenticate with an AI provider using OAuth",
@@ -45,6 +52,9 @@ Example:
4552
RunE: runAuthLogin,
4653
}
4754

55+
// authLogoutCmd represents the logout subcommand for removing stored authentication credentials.
56+
// This command removes stored API keys or OAuth tokens for specified providers,
57+
// requiring the user to authenticate again or use environment variables.
4858
var authLogoutCmd = &cobra.Command{
4959
Use: "logout [provider]",
5060
Short: "Remove stored authentication credentials for a provider",
@@ -62,6 +72,9 @@ Example:
6272
RunE: runAuthLogout,
6373
}
6474

75+
// authStatusCmd represents the status subcommand for checking authentication status.
76+
// It displays which providers have stored credentials, their types (OAuth vs API key),
77+
// creation dates, and expiration status without revealing the actual credentials.
6578
var authStatusCmd = &cobra.Command{
6679
Use: "status",
6780
Short: "Show authentication status for all providers",

cmd/hooks.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,18 @@ import (
1010
"gopkg.in/yaml.v3"
1111
)
1212

13+
// hooksCmd represents the hooks command for managing MCPHost hook configurations.
14+
// Hooks allow users to execute custom scripts or commands at various points
15+
// during MCPHost execution, such as before/after tool use or when prompts are submitted.
1316
var hooksCmd = &cobra.Command{
1417
Use: "hooks",
1518
Short: "Manage MCPHost hooks",
1619
Long: "Commands for managing and testing MCPHost hooks configuration",
1720
}
1821

22+
// hooksListCmd represents the list subcommand for displaying all configured hooks.
23+
// It shows a formatted table of hook events, matchers, commands, and timeouts
24+
// to help users understand their current hook configuration.
1925
var hooksListCmd = &cobra.Command{
2026
Use: "list",
2127
Short: "List all configured hooks",
@@ -45,6 +51,9 @@ var hooksListCmd = &cobra.Command{
4551
},
4652
}
4753

54+
// hooksValidateCmd represents the validate subcommand for checking hook configuration validity.
55+
// It loads and validates the hooks configuration file, ensuring proper syntax,
56+
// valid event types, and correct matcher patterns before use.
4857
var hooksValidateCmd = &cobra.Command{
4958
Use: "validate",
5059
Short: "Validate hooks configuration",
@@ -64,6 +73,9 @@ var hooksValidateCmd = &cobra.Command{
6473
},
6574
}
6675

76+
// hooksInitCmd represents the init subcommand for generating an example hooks configuration.
77+
// It creates a .mcphost/hooks.yml file with sample hook configurations demonstrating
78+
// various hook events and common use cases like logging commands and tool usage.
6779
var hooksInitCmd = &cobra.Command{
6880
Use: "init",
6981
Short: "Generate example hooks configuration",

cmd/root.go

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,10 @@ func (a *agentUIAdapter) GetLoadedServerNames() []string {
8484
return a.agent.GetLoadedServerNames()
8585
}
8686

87+
// rootCmd represents the base command when called without any subcommands.
88+
// This is the main entry point for the MCPHost CLI application, providing
89+
// an interface to interact with various AI models through a unified interface
90+
// with support for MCP servers and tool integration.
8791
var rootCmd = &cobra.Command{
8892
Use: "mcphost",
8993
Short: "Chat with AI models through a unified interface",
@@ -120,12 +124,21 @@ Examples:
120124
},
121125
}
122126

123-
// GetRootCommand returns the root command with the version set
127+
// GetRootCommand returns the root command with the version set.
128+
// This function is the main entry point for the MCPHost CLI and should be
129+
// called from main.go with the appropriate version string.
124130
func GetRootCommand(v string) *cobra.Command {
125131
rootCmd.Version = v
126132
return rootCmd
127133
}
128134

135+
// InitConfig initializes the configuration for MCPHost by loading config files,
136+
// environment variables, and hooks configuration. It follows this priority order:
137+
// 1. Command-line specified config file (--config flag)
138+
// 2. Current directory config file (.mcphost or .mcp)
139+
// 3. Home directory config file (~/.mcphost or ~/.mcp)
140+
// 4. Environment variables (MCPHOST_* prefix)
141+
// This function is automatically called by cobra before command execution.
129142
func InitConfig() {
130143
if configFile != "" {
131144
// Use config file from the flag
@@ -202,7 +215,12 @@ func InitConfig() {
202215

203216
}
204217

205-
// LoadConfigWithEnvSubstitution loads a config file with environment variable substitution
218+
// LoadConfigWithEnvSubstitution loads a config file with environment variable substitution.
219+
// It reads the config file, replaces any ${ENV_VAR} patterns with their corresponding
220+
// environment variable values, and then parses the resulting configuration using viper.
221+
// The function automatically detects JSON or YAML format based on file extension.
222+
// Returns an error if the file cannot be read, environment variable substitution fails,
223+
// or the configuration cannot be parsed.
206224
func LoadConfigWithEnvSubstitution(configPath string) error {
207225
// Read raw config file content
208226
rawContent, err := os.ReadFile(configPath)
@@ -728,7 +746,9 @@ func runNormalMode(ctx context.Context) error {
728746
return runInteractiveMode(ctx, mcpAgent, cli, serverNames, toolNames, modelName, messages, sessionManager, hookExecutor)
729747
}
730748

731-
// AgenticLoopConfig configures the behavior of the unified agentic loop
749+
// AgenticLoopConfig configures the behavior of the unified agentic loop.
750+
// This struct controls how the main interaction loop operates, whether in
751+
// interactive or non-interactive mode, and manages various UI and session options.
732752
type AgenticLoopConfig struct {
733753
// Mode configuration
734754
IsInteractive bool // true for interactive mode, false for non-interactive

cmd/script.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ import (
2121
"github.com/spf13/viper"
2222
)
2323

24+
// scriptCmd represents the script command for executing MCPHost script files.
25+
// Script files can contain YAML frontmatter configuration followed by a prompt,
26+
// allowing for reproducible AI interactions with custom configurations and
27+
// variable substitution support.
2428
var scriptCmd = &cobra.Command{
2529
Use: "script <script-file>",
2630
Short: "Execute a script file with YAML frontmatter configuration",
@@ -413,11 +417,13 @@ func parseScriptContent(content string, variables map[string]string) (*config.Co
413417
return &scriptConfig, nil
414418
}
415419

416-
// Variable represents a script variable with optional default value
420+
// Variable represents a script variable with optional default value.
421+
// Variables can be declared in scripts using ${variable} syntax for required variables
422+
// or ${variable:-default} syntax for variables with default values.
417423
type Variable struct {
418-
Name string
419-
DefaultValue string
420-
HasDefault bool
424+
Name string // The name of the variable as it appears in the script
425+
DefaultValue string // The default value if specified using ${variable:-default} syntax
426+
HasDefault bool // Whether this variable has a default value
421427
}
422428

423429
// findVariables extracts all unique variable names from ${variable} patterns in content

internal/agent/agent.go

Lines changed: 50 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,35 +16,49 @@ import (
1616
"time"
1717
)
1818

19-
// AgentConfig is the config for agent.
19+
// AgentConfig holds configuration options for creating a new Agent.
20+
// It includes model configuration, MCP settings, and various behavioral options.
2021
type AgentConfig struct {
21-
ModelConfig *models.ProviderConfig
22-
MCPConfig *config.Config
23-
SystemPrompt string
24-
MaxSteps int
22+
// ModelConfig specifies the LLM provider and model to use
23+
ModelConfig *models.ProviderConfig
24+
// MCPConfig contains MCP server configurations
25+
MCPConfig *config.Config
26+
// SystemPrompt is the initial system message for the agent
27+
SystemPrompt string
28+
// MaxSteps limits the number of tool calls (0 for unlimited)
29+
MaxSteps int
30+
// StreamingEnabled controls whether responses are streamed
2531
StreamingEnabled bool
26-
DebugLogger tools.DebugLogger // Optional debug logger
32+
// DebugLogger is an optional logger for debugging MCP communications
33+
DebugLogger tools.DebugLogger // Optional debug logger
2734
}
2835

29-
// ToolCallHandler is a function type for handling tool calls as they happen
36+
// ToolCallHandler is a function type for handling tool calls as they happen.
37+
// It receives the tool name and its arguments when a tool is about to be invoked.
3038
type ToolCallHandler func(toolName, toolArgs string)
3139

32-
// ToolExecutionHandler is a function type for handling tool execution start/end
40+
// ToolExecutionHandler is a function type for handling tool execution start/end events.
41+
// The isStarting parameter indicates whether the tool is starting (true) or finished (false).
3342
type ToolExecutionHandler func(toolName string, isStarting bool)
3443

35-
// ToolResultHandler is a function type for handling tool results
44+
// ToolResultHandler is a function type for handling tool results.
45+
// It receives the tool name, arguments, result, and whether the result is an error.
3646
type ToolResultHandler func(toolName, toolArgs, result string, isError bool)
3747

38-
// ResponseHandler is a function type for handling LLM responses
48+
// ResponseHandler is a function type for handling LLM responses.
49+
// It receives the complete response content from the model.
3950
type ResponseHandler func(content string)
4051

41-
// StreamingResponseHandler is a function type for handling streaming LLM responses
52+
// StreamingResponseHandler is a function type for handling streaming LLM responses.
53+
// It receives content chunks as they are streamed from the model.
4254
type StreamingResponseHandler func(content string)
4355

44-
// ToolCallContentHandler is a function type for handling content that accompanies tool calls
56+
// ToolCallContentHandler is a function type for handling content that accompanies tool calls.
57+
// It receives any text content that the model generates alongside tool calls.
4558
type ToolCallContentHandler func(content string)
4659

47-
// Agent is the agent with real-time tool call display.
60+
// Agent represents an AI agent with MCP tool integration and real-time tool call display.
61+
// It manages the interaction between an LLM and various tools through the MCP protocol.
4862
type Agent struct {
4963
toolManager *tools.MCPToolManager
5064
model model.ToolCallingChatModel
@@ -55,7 +69,10 @@ type Agent struct {
5569
streamingEnabled bool // Whether streaming is enabled
5670
}
5771

58-
// NewAgent creates an agent with MCP tool integration and real-time tool call display
72+
// NewAgent creates a new Agent with MCP tool integration and streaming support.
73+
// It initializes the LLM provider, loads MCP tools, and configures the agent
74+
// based on the provided configuration. Returns an error if provider creation
75+
// or tool loading fails.
5976
func NewAgent(ctx context.Context, config *AgentConfig) (*Agent, error) {
6077
// Create the LLM provider
6178
providerResult, err := models.CreateProvider(ctx, config.ModelConfig)
@@ -98,20 +115,27 @@ func NewAgent(ctx context.Context, config *AgentConfig) (*Agent, error) {
98115
}, nil
99116
}
100117

101-
// GenerateWithLoopResult contains the result and conversation history
118+
// GenerateWithLoopResult contains the result and conversation history from an agent interaction.
119+
// It includes both the final response and the complete message history with tool interactions.
102120
type GenerateWithLoopResult struct {
103-
FinalResponse *schema.Message
121+
// FinalResponse is the last message generated by the model
122+
FinalResponse *schema.Message
123+
// ConversationMessages contains all messages in the conversation including tool calls and results
104124
ConversationMessages []*schema.Message // All messages in the conversation (including tool calls and results)
105125
}
106126

107-
// GenerateWithLoop processes messages with a custom loop that displays tool calls in real-time
127+
// GenerateWithLoop processes messages with a custom loop that displays tool calls in real-time.
128+
// It handles the conversation flow, executing tools as needed and invoking callbacks for various events.
129+
// This method does not support streaming responses; use GenerateWithLoopAndStreaming for streaming support.
108130
func (a *Agent) GenerateWithLoop(ctx context.Context, messages []*schema.Message,
109131
onToolCall ToolCallHandler, onToolExecution ToolExecutionHandler, onToolResult ToolResultHandler, onResponse ResponseHandler, onToolCallContent ToolCallContentHandler) (*GenerateWithLoopResult, error) {
110132

111133
return a.GenerateWithLoopAndStreaming(ctx, messages, onToolCall, onToolExecution, onToolResult, onResponse, onToolCallContent, nil)
112134
}
113135

114-
// GenerateWithLoopAndStreaming processes messages with a custom loop that displays tool calls in real-time and supports streaming callbacks
136+
// GenerateWithLoopAndStreaming processes messages with a custom loop that displays tool calls in real-time and supports streaming callbacks.
137+
// It handles the conversation flow, executing tools as needed and invoking callbacks for various events including streaming chunks.
138+
// The onStreamingResponse callback is invoked for each content chunk during streaming if streaming is enabled.
115139
func (a *Agent) GenerateWithLoopAndStreaming(ctx context.Context, messages []*schema.Message,
116140
onToolCall ToolCallHandler, onToolExecution ToolExecutionHandler, onToolResult ToolResultHandler, onResponse ResponseHandler, onToolCallContent ToolCallContentHandler, onStreamingResponse StreamingResponseHandler) (*GenerateWithLoopResult, error) {
117141

@@ -256,17 +280,20 @@ func (a *Agent) GenerateWithLoopAndStreaming(ctx context.Context, messages []*sc
256280
}, nil
257281
}
258282

259-
// GetTools returns the list of available tools
283+
// GetTools returns the list of available tools loaded in the agent.
284+
// These tools are available for the model to use during interactions.
260285
func (a *Agent) GetTools() []tool.BaseTool {
261286
return a.toolManager.GetTools()
262287
}
263288

264-
// GetLoadingMessage returns the loading message from provider creation (e.g., GPU fallback info)
289+
// GetLoadingMessage returns the loading message from provider creation.
290+
// This may contain information about GPU fallback or other provider-specific initialization details.
265291
func (a *Agent) GetLoadingMessage() string {
266292
return a.loadingMessage
267293
}
268294

269-
// GetLoadedServerNames returns the names of successfully loaded MCP servers
295+
// GetLoadedServerNames returns the names of successfully loaded MCP servers.
296+
// This includes both builtin servers and external MCP server configurations.
270297
func (a *Agent) GetLoadedServerNames() []string {
271298
return a.toolManager.GetLoadedServerNames()
272299
}
@@ -486,7 +513,8 @@ func (a *Agent) listenForESC(stopChan chan bool, readyChan chan bool) bool {
486513
}
487514
}
488515

489-
// Close closes the agent and cleans up resources
516+
// Close closes the agent and cleans up resources.
517+
// It ensures all MCP connections are properly closed and resources are released.
490518
func (a *Agent) Close() error {
491519
return a.toolManager.Close()
492520
}

internal/agent/factory.go

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,36 @@ import (
1010
"github.com/mark3labs/mcphost/internal/tools"
1111
)
1212

13-
// SpinnerFunc is a function type for showing spinners during agent creation
13+
// SpinnerFunc is a function type for showing spinners during agent creation.
14+
// It executes the provided function while displaying a spinner with the given message.
1415
type SpinnerFunc func(message string, fn func() error) error
1516

16-
// AgentCreationOptions contains options for creating an agent
17+
// AgentCreationOptions contains options for creating an agent.
18+
// It extends AgentConfig with UI-related options for showing progress during creation.
1719
type AgentCreationOptions struct {
18-
ModelConfig *models.ProviderConfig
19-
MCPConfig *config.Config
20-
SystemPrompt string
21-
MaxSteps int
20+
// ModelConfig specifies the LLM provider and model to use
21+
ModelConfig *models.ProviderConfig
22+
// MCPConfig contains MCP server configurations
23+
MCPConfig *config.Config
24+
// SystemPrompt is the initial system message for the agent
25+
SystemPrompt string
26+
// MaxSteps limits the number of tool calls (0 for unlimited)
27+
MaxSteps int
28+
// StreamingEnabled controls whether responses are streamed
2229
StreamingEnabled bool
23-
ShowSpinner bool // For Ollama models
24-
Quiet bool // Skip spinner if quiet
25-
SpinnerFunc SpinnerFunc // Function to show spinner (provided by caller)
26-
DebugLogger tools.DebugLogger // Optional debug logger
30+
// ShowSpinner indicates whether to show a spinner for Ollama models during loading
31+
ShowSpinner bool // For Ollama models
32+
// Quiet suppresses the spinner even if ShowSpinner is true
33+
Quiet bool // Skip spinner if quiet
34+
// SpinnerFunc is the function to show spinner, provided by the caller
35+
SpinnerFunc SpinnerFunc // Function to show spinner (provided by caller)
36+
// DebugLogger is an optional logger for debugging MCP communications
37+
DebugLogger tools.DebugLogger // Optional debug logger
2738
}
2839

29-
// CreateAgent creates an agent with optional spinner for Ollama models
40+
// CreateAgent creates an agent with optional spinner for Ollama models.
41+
// It shows a loading spinner for Ollama models if ShowSpinner is true and not in quiet mode.
42+
// Returns the created agent or an error if creation fails.
3043
func CreateAgent(ctx context.Context, opts *AgentCreationOptions) (*Agent, error) {
3144
agentConfig := &AgentConfig{
3245
ModelConfig: opts.ModelConfig,
@@ -57,7 +70,9 @@ func CreateAgent(ctx context.Context, opts *AgentCreationOptions) (*Agent, error
5770
return agent, nil
5871
}
5972

60-
// ParseModelName extracts provider and model name from model string
73+
// ParseModelName extracts provider and model name from a model string.
74+
// Model strings are formatted as "provider:model" (e.g., "anthropic:claude-3-5-sonnet-20241022").
75+
// If the string doesn't contain a colon, returns "unknown" for both provider and model.
6176
func ParseModelName(modelString string) (provider, model string) {
6277
parts := strings.SplitN(modelString, ":", 2)
6378
if len(parts) == 2 {

internal/agent/streaming.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ import (
88
"github.com/cloudwego/eino/schema"
99
)
1010

11-
// StreamWithCallback streams content with real-time callbacks and returns complete response
11+
// StreamWithCallback streams content with real-time callbacks and returns the complete response.
12+
// It accumulates content and tool calls from the stream, invoking the callback for each content chunk.
1213
// IMPORTANT: Tool calls are only processed after EOF is reached to ensure we have the complete
1314
// and final tool call information. This prevents premature tool execution on partial data.
1415
// Handles different provider streaming patterns:

0 commit comments

Comments
 (0)