sdk

package
v0.31.4 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2025 License: MIT Imports: 9 Imported by: 4

README

MCPHost SDK

The MCPHost SDK allows you to use MCPHost programmatically from Go applications without spawning OS processes.

Installation

go get github.com/mark3labs/mcphost

Basic Usage

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/mark3labs/mcphost/sdk"
)

func main() {
    ctx := context.Background()
    
    // Create MCPHost instance with default configuration
    host, err := sdk.New(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer host.Close()
    
    // Send a prompt
    response, err := host.Prompt(ctx, "What is 2+2?")
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println(response)
}

Configuration

The SDK behaves identically to the CLI:

  • Loads configuration from ~/.mcphost.yml by default
  • Creates default configuration if none exists
  • Respects all environment variables (MCPHOST_*)
  • Uses the same defaults as the CLI
Options

You can override specific settings:

host, err := sdk.New(ctx, &sdk.Options{
    Model:        "ollama:llama3",           // Override model
    SystemPrompt: "You are a helpful bot",   // Override system prompt
    ConfigFile:   "/path/to/config.yml",     // Use specific config file
    MaxSteps:     10,                        // Override max steps
    Streaming:    true,                      // Enable streaming
    Quiet:        true,                      // Suppress debug output
})

Advanced Usage

With Tool Callbacks

Monitor tool execution in real-time:

response, err := host.PromptWithCallbacks(
    ctx,
    "List files in the current directory",
    func(name, args string) {
        fmt.Printf("Calling tool: %s\n", name)
    },
    func(name, args, result string, isError bool) {
        if isError {
            fmt.Printf("Tool %s failed: %s\n", name, result)
        } else {
            fmt.Printf("Tool %s succeeded\n", name)
        }
    },
    func(chunk string) {
        fmt.Print(chunk) // Stream output
    },
)
Session Management

Maintain conversation context:

// First message
host.Prompt(ctx, "My name is Alice")

// Second message (remembers context)
response, _ := host.Prompt(ctx, "What's my name?")
// Response: "Your name is Alice"

// Save session
host.SaveSession("./session.json")

// Load session later
host.LoadSession("./session.json")

// Clear session
host.ClearSession()

API Reference

Types
  • MCPHost - Main SDK type
  • Options - Configuration options
  • Message - Conversation message
  • ToolCall - Tool invocation details
Methods
  • New(ctx, opts) - Create new MCPHost instance
  • Prompt(ctx, message) - Send message and get response
  • PromptWithCallbacks(ctx, message, ...) - Send message with progress callbacks
  • LoadSession(path) - Load session from file
  • SaveSession(path) - Save session to file
  • ClearSession() - Clear conversation history
  • GetSessionManager() - Get session manager for advanced usage
  • GetModelString() - Get current model string
  • Close() - Clean up resources

Environment Variables

All CLI environment variables work with the SDK:

  • MCPHOST_MODEL - Override model
  • ANTHROPIC_API_KEY - Anthropic API key
  • OPENAI_API_KEY - OpenAI API key
  • GEMINI_API_KEY - Google API key
  • etc.

License

Same as MCPHost CLI

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertToSchemaMessage

func ConvertToSchemaMessage(msg *Message) *schema.Message

ConvertToSchemaMessage converts an SDK message to the underlying schema message format used by the agent for LLM interactions.

Types

type MCPHost

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

MCPHost provides programmatic access to mcphost functionality, allowing integration of MCP tools and LLM interactions into Go applications. It manages agents, sessions, and model configurations.

func New

func New(ctx context.Context, opts *Options) (*MCPHost, error)

New creates an MCPHost instance using the same initialization as the CLI. It loads configuration, initializes MCP servers, creates the LLM model, and sets up the agent for interaction. Returns an error if initialization fails.

func (*MCPHost) ClearSession

func (m *MCPHost) ClearSession()

ClearSession clears the current session history, starting a new conversation with an empty message history.

func (*MCPHost) Close

func (m *MCPHost) Close() error

Close cleans up resources including MCP server connections and model resources. Should be called when the MCPHost instance is no longer needed. Returns an error if cleanup fails.

func (*MCPHost) GetModelString

func (m *MCPHost) GetModelString() string

GetModelString returns the current model string identifier (e.g., "anthropic:claude-3-sonnet" or "openai:gpt-4") being used by the agent.

func (*MCPHost) GetSessionManager

func (m *MCPHost) GetSessionManager() *session.Manager

GetSessionManager returns the current session manager for direct access to conversation history and session manipulation.

func (*MCPHost) LoadSession

func (m *MCPHost) LoadSession(path string) error

LoadSession loads a previously saved session from a file, restoring the conversation history. Returns an error if the file cannot be loaded or parsed.

func (*MCPHost) Prompt

func (m *MCPHost) Prompt(ctx context.Context, message string) (string, error)

Prompt sends a message to the agent and returns the response. The agent may use tools as needed to generate the response. The conversation history is automatically maintained in the session. Returns an error if generation fails.

func (*MCPHost) PromptWithCallbacks

func (m *MCPHost) PromptWithCallbacks(
	ctx context.Context,
	message string,
	onToolCall func(name, args string),
	onToolResult func(name, args, result string, isError bool),
	onStreaming func(chunk string),
) (string, error)

PromptWithCallbacks sends a message with callbacks for monitoring tool execution and streaming responses. The callbacks allow real-time observation of tool calls, results, and response generation. Returns the final response or an error.

func (*MCPHost) SaveSession

func (m *MCPHost) SaveSession(path string) error

SaveSession saves the current session to a file for later restoration. Returns an error if the session cannot be written to the specified path.

type Message

type Message = session.Message

Message is an alias for session.Message providing SDK users with access to message structures for conversation history and tool interactions.

func ConvertFromSchemaMessage

func ConvertFromSchemaMessage(msg *schema.Message) Message

ConvertFromSchemaMessage converts a schema message from the agent to an SDK message format for use in the SDK API.

type Options

type Options struct {
	Model        string // Override model (e.g., "anthropic:claude-3-sonnet")
	SystemPrompt string // Override system prompt
	ConfigFile   string // Override config file path
	MaxSteps     int    // Override max steps (0 = use default)
	Streaming    bool   // Enable streaming (default from config)
	Quiet        bool   // Suppress debug output
}

Options configures MCPHost creation with optional overrides for model, prompts, configuration, and behavior settings. All fields are optional and will use CLI defaults if not specified.

type ToolCall

type ToolCall = session.ToolCall

ToolCall is an alias for session.ToolCall representing a tool invocation with its name, arguments, and result within a conversation.

Directories

Path Synopsis
examples
basic command
scripting command

Jump to

Keyboard shortcuts

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