mcp

package
v0.2.21 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2025 License: MIT Imports: 24 Imported by: 0

README

MCP Integration for Agent SDK Go

This package provides integration with the Model Context Protocol (MCP) for the Agent SDK Go. It allows agents to connect to MCP servers and use their tools.

Overview

The MCP integration allows agents to:

  1. Connect to MCP servers using different transports (stdio, HTTP)
  2. List and use tools provided by MCP servers
  3. Convert MCP tools to agent tools

Usage

Creating an MCP Server Connection
import (
    "context"
    "github.com/Ingenimax/agent-sdk-go/pkg/mcp"
)

// Create an HTTP-based MCP server client
httpServer, err := mcp.NewHTTPServer(context.Background(), mcp.HTTPServerConfig{
    BaseURL: "http://localhost:8083/mcp",
})
if err != nil {
    log.Printf("Failed to initialize HTTP MCP server: %v", err)
}

// Create a stdio-based MCP server
stdioServer, err := mcp.NewStdioServer(context.Background(), mcp.StdioServerConfig{
    Command: "go",
    Args:    []string{"run", "./server-stdio/main.go"},
})
if err != nil {
    log.Printf("Failed to initialize STDIO MCP server: %v", err)
}
Creating an Agent with MCP Servers
import (
    "github.com/Ingenimax/agent-sdk-go/pkg/agent"
    "github.com/Ingenimax/agent-sdk-go/pkg/interfaces"
    "github.com/Ingenimax/agent-sdk-go/pkg/llm/openai"
    "github.com/Ingenimax/agent-sdk-go/pkg/mcp"
    "github.com/Ingenimax/agent-sdk-go/pkg/memory"
)

// Create MCP servers
var mcpServers []interfaces.MCPServer
mcpServers = append(mcpServers, httpServer)
mcpServers = append(mcpServers, stdioServer)

// Create an LLM (e.g., OpenAI)
llm := openai.NewClient(apiKey, openai.WithModel("gpt-4o-mini"))

// Create the agent with MCP server support
myAgent, err := agent.NewAgent(
    agent.WithLLM(llm),
    agent.WithMCPServers(mcpServers),
    agent.WithMemory(memory.NewConversationBuffer()),
    agent.WithSystemPrompt("You are an AI assistant that can use tools from MCP servers."),
)
Listing MCP Tools
// List tools from an MCP server
tools, err := mcpServer.ListTools(context.Background())
if err != nil {
    log.Printf("Failed to list tools: %v", err)
    return
}

for _, tool := range tools {
    fmt.Printf("Tool: %s - %s\n", tool.Name, tool.Description)
}

Transports

The MCP integration supports different transports for connecting to MCP servers:

  • stdio: For local MCP servers that communicate over standard input/output
  • HTTP: For remote MCP servers that communicate over HTTP

Implementation Details

The MCP integration is built on top of the mcp-go library, which provides a Go implementation of the Model Context Protocol.

The integration consists of:

  1. MCPServer: An interface for interacting with MCP servers
  2. MCPTool: A struct that implements the interfaces.Tool interface for MCP tools
  3. Agent integration: The agent can use MCP tools alongside its regular tools

Example

See the MCP examples for complete examples of using the MCP integration:

  • client: A client that connects to both HTTP and stdio MCP servers and uses their tools
  • server-http: An example HTTP MCP server implementation with tools for time and drink recommendations
  • server-stdio: An example stdio MCP server implementation with a food recommendation tool

To run the examples:

  1. Start the HTTP server: go run cmd/examples/mcp/server-http/main.go
  2. Run the client, which will also start the stdio server: go run cmd/examples/mcp/client/main.go

Documentation

Index

Constants

View Source
const DefaultRegistryURL = "https://registry.modelcontextprotocol.io"

DefaultRegistryURL is the official MCP Registry URL

View Source
const TraceParentAttribute = "traceparent"

Variables

This section is empty.

Functions

func ConvertMCPTools

func ConvertMCPTools(server interfaces.MCPServer, mcpTools []map[string]interface{}) ([]interfaces.Tool, error)

ConvertMCPTools converts a list of MCP tools to agent SDK tools

func CreateFileInfoSchema added in v0.1.14

func CreateFileInfoSchema() map[string]interface{}

CreateFileInfoSchema creates a schema for file information

func CreateWeatherSchema added in v0.1.14

func CreateWeatherSchema() map[string]interface{}

CreateWeatherSchema creates a schema for weather data

func ExtractCodeFromResponse added in v0.1.14

func ExtractCodeFromResponse(response *interfaces.MCPSamplingResponse) string

ExtractCodeFromResponse extracts code from a sampling response

func FetchMCPToolsFromServer

func FetchMCPToolsFromServer(ctx context.Context, url string) ([]map[string]interface{}, error)

FetchMCPToolsFromServer fetches the list of tools from an MCP server

func FormatConversationHistory added in v0.1.14

func FormatConversationHistory(messages []interfaces.MCPMessage) string

FormatConversationHistory formats a conversation for display

func FormatUserFriendlyError added in v0.1.14

func FormatUserFriendlyError(err error) string

FormatUserFriendlyError creates a user-friendly error message

func GetOrCreateServerFromCache added in v0.1.14

func GetOrCreateServerFromCache(ctx context.Context, config LazyMCPServerConfig) (interfaces.MCPServer, error)

GetOrCreateServerFromCache provides public access to the global server cache

func GetPresetInfo added in v0.1.14

func GetPresetInfo(name string) (string, error)

GetPresetInfo returns information about a preset

func GetPromptParameterInfo added in v0.1.14

func GetPromptParameterInfo(prompt interfaces.MCPPrompt) string

GetPromptParameterInfo returns human-readable information about prompt parameters

func GetResourceExtension added in v0.1.14

func GetResourceExtension(resource interfaces.MCPResource) string

GetResourceExtension extracts file extension from resource URI

func GetServerMetadataFromCache added in v0.1.14

func GetServerMetadataFromCache(config LazyMCPServerConfig) *interfaces.MCPServerInfo

GetServerMetadataFromCache gets server metadata from the global cache

func IsBinaryResource added in v0.1.14

func IsBinaryResource(resource interfaces.MCPResource) bool

IsBinaryResource checks if a resource contains binary content

func IsTextResource added in v0.1.14

func IsTextResource(resource interfaces.MCPResource) bool

IsTextResource checks if a resource contains text content

func ListPresets added in v0.1.14

func ListPresets() []string

ListPresets returns a list of available preset names

func NewHTTPServer

func NewHTTPServer(ctx context.Context, config HTTPServerConfig) (interfaces.MCPServer, error)

NewHTTPServer creates a new MCPServer that communicates over HTTP using the official SDK

func NewHTTPServerWithRetry added in v0.1.14

func NewHTTPServerWithRetry(ctx context.Context, config HTTPServerConfig, retryConfig *RetryConfig) (interfaces.MCPServer, error)

NewHTTPServerWithRetry creates a new HTTP MCPServer with retry logic

func NewLazyMCPTool added in v0.0.42

func NewLazyMCPTool(name, description string, schema interface{}, config LazyMCPServerConfig) interfaces.Tool

NewLazyMCPTool creates a new lazy MCP tool

func NewMCPServer

func NewMCPServer(ctx context.Context, transport mcp.Transport) (interfaces.MCPServer, error)

NewMCPServer creates a new MCPServer with the given transport using the official SDK

func NewMCPTool

func NewMCPTool(name, description string, schema interface{}, server interfaces.MCPServer) interfaces.Tool

NewMCPTool creates a new MCPTool

func NewRetryableServer added in v0.1.14

func NewRetryableServer(server interfaces.MCPServer, config *RetryConfig) interfaces.MCPServer

NewRetryableServer creates a new MCP server wrapper with retry capabilities

func NewStdioServer

func NewStdioServer(ctx context.Context, config StdioServerConfig) (interfaces.MCPServer, error)

NewStdioServer creates a new MCPServer that communicates over stdio using the official SDK

func NewStdioServerWithRetry added in v0.1.14

func NewStdioServerWithRetry(ctx context.Context, config StdioServerConfig, retryConfig *RetryConfig) (interfaces.MCPServer, error)

NewStdioServerWithRetry creates a new MCPServer with retry logic

func RetryWithExponentialBackoff added in v0.1.14

func RetryWithExponentialBackoff(
	ctx context.Context,
	operation func() error,
	config *RetryConfig,
) error

RetryWithExponentialBackoff is a utility function for retrying any operation

func RunStdioToolCommand

func RunStdioToolCommand(cmd *exec.Cmd, payload []byte) ([]byte, error)

RunStdioToolCommand executes a command for an MCP stdio server

func SuggestPromptVariables added in v0.1.14

func SuggestPromptVariables(prompt interfaces.MCPPrompt, context map[string]interface{}) map[string]interface{}

SuggestPromptVariables suggests default values for prompt variables

Types

type Builder added in v0.1.14

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

Builder provides a fluent interface for creating MCP server configurations

func NewBuilder added in v0.1.14

func NewBuilder() *Builder

NewBuilder creates a new MCP configuration builder

func (*Builder) AddHTTPServer added in v0.1.14

func (b *Builder) AddHTTPServer(name, baseURL string) *Builder

AddHTTPServer adds an HTTP-based MCP server

func (*Builder) AddHTTPServerWithAuth added in v0.1.14

func (b *Builder) AddHTTPServerWithAuth(name, baseURL, token string) *Builder

AddHTTPServerWithAuth adds an HTTP-based MCP server with authentication

func (*Builder) AddPreset added in v0.1.14

func (b *Builder) AddPreset(presetName string) *Builder

AddPreset adds a predefined MCP server configuration

func (*Builder) AddServer added in v0.1.14

func (b *Builder) AddServer(urlStr string) *Builder

AddServer adds an MCP server from a URL string Supports formats: - stdio://command/path/to/executable - http://localhost:8080/mcp - https://api.example.com/mcp?token=xxx - mcp://preset-name (for presets)

func (*Builder) AddStdioServer added in v0.1.14

func (b *Builder) AddStdioServer(name, command string, args ...string) *Builder

AddStdioServer adds a stdio-based MCP server

func (*Builder) Build added in v0.1.14

Build creates the MCP servers and returns them

func (*Builder) BuildLazy added in v0.1.14

func (b *Builder) BuildLazy() ([]LazyMCPServerConfig, error)

BuildLazy returns only lazy configurations without initializing any servers

func (*Builder) WithHealthCheck added in v0.1.14

func (b *Builder) WithHealthCheck(enabled bool) *Builder

WithHealthCheck enables or disables health checking

func (*Builder) WithLogger added in v0.1.14

func (b *Builder) WithLogger(logger logging.Logger) *Builder

WithLogger sets a custom logger

func (*Builder) WithRetry added in v0.1.14

func (b *Builder) WithRetry(maxAttempts int, initialDelay time.Duration) *Builder

WithRetry configures retry options

func (*Builder) WithTimeout added in v0.1.14

func (b *Builder) WithTimeout(timeout time.Duration) *Builder

WithTimeout sets the connection timeout

type ConfigOption added in v0.1.14

type ConfigOption struct {
	Name        string      `json:"name"`
	Description string      `json:"description"`
	Type        string      `json:"type"` // "string", "number", "boolean", "array"
	Default     interface{} `json:"default,omitempty"`
	Enum        []string    `json:"enum,omitempty"`
	Required    bool        `json:"required"`
	Sensitive   bool        `json:"sensitive"` // For API keys, passwords, etc.
}

ConfigOption represents a configuration option

type ConfigurationInfo added in v0.1.14

type ConfigurationInfo struct {
	Required []ConfigOption `json:"required,omitempty"`
	Optional []ConfigOption `json:"optional,omitempty"`
}

ConfigurationInfo describes server configuration options

type HTTPServerConfig

type HTTPServerConfig struct {
	BaseURL      string
	Path         string
	Token        string
	ProtocolType ServerProtocolType
	Logger       logging.Logger

	ResourceIndicator string `json:"resource_indicator,omitempty"`
}

HTTPServerConfig holds configuration for an HTTP MCP server

type InstallationInfo added in v0.1.14

type InstallationInfo struct {
	Type    string                 `json:"type"`    // "npm", "pip", "docker", "binary", "stdio"
	Command string                 `json:"command"` // Command to run the server
	Args    []string               `json:"args,omitempty"`
	Env     map[string]string      `json:"env,omitempty"`
	Config  map[string]interface{} `json:"config,omitempty"`
}

InstallationInfo describes how to install and run the server

type LazyMCPServerCache added in v0.0.42

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

LazyMCPServerCache manages shared MCP server instances

type LazyMCPServerConfig added in v0.0.42

type LazyMCPServerConfig struct {
	Name    string
	Type    string // "stdio" or "http"
	Command string
	Args    []string
	Env     []string
	URL     string
	Token   string // Bearer token for HTTP authentication
}

LazyMCPServerConfig holds configuration for creating an MCP server on demand

func GetPreset added in v0.1.14

func GetPreset(name string) (LazyMCPServerConfig, error)

GetPreset returns a preset configuration by name

type LazyMCPTool added in v0.0.42

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

LazyMCPTool is a tool that initializes its MCP server on first use

func (*LazyMCPTool) Description added in v0.0.42

func (t *LazyMCPTool) Description() string

Description returns a description of what the tool does

func (*LazyMCPTool) DisplayName added in v0.0.53

func (t *LazyMCPTool) DisplayName() string

DisplayName implements interfaces.ToolWithDisplayName.DisplayName

func (*LazyMCPTool) Execute added in v0.0.42

func (t *LazyMCPTool) Execute(ctx context.Context, args string) (string, error)

Execute executes the tool with the given arguments

func (*LazyMCPTool) Internal added in v0.0.53

func (t *LazyMCPTool) Internal() bool

Internal implements interfaces.InternalTool.Internal

func (*LazyMCPTool) Name added in v0.0.42

func (t *LazyMCPTool) Name() string

Name returns the name of the tool

func (*LazyMCPTool) Parameters added in v0.0.42

func (t *LazyMCPTool) Parameters() map[string]interfaces.ParameterSpec

Parameters returns the parameters that the tool accepts

func (*LazyMCPTool) Run added in v0.0.42

func (t *LazyMCPTool) Run(ctx context.Context, input string) (string, error)

Run executes the tool with the given input

type MCPError added in v0.1.14

type MCPError struct {
	Operation  string            // The operation that failed (e.g., "ListTools", "CallTool")
	ServerName string            // Name of the MCP server
	ServerType string            // Type of server (stdio, http, etc.)
	ErrorType  MCPErrorType      // Category of error
	Cause      error             // The underlying error
	Retryable  bool              // Whether the error might succeed on retry
	Metadata   map[string]string // Additional context
	// contains filtered or unexported fields
}

MCPError represents a structured error from MCP operations

func ClassifyError added in v0.1.14

func ClassifyError(err error, operation, serverName, serverType string) *MCPError

ClassifyError attempts to classify an error based on its message

func NewConfigurationError added in v0.1.14

func NewConfigurationError(operation string, cause error) *MCPError

NewConfigurationError creates a configuration error

func NewConnectionError added in v0.1.14

func NewConnectionError(serverName, serverType string, cause error) *MCPError

NewConnectionError creates a connection-related error

func NewMCPError added in v0.1.14

func NewMCPError(operation, serverName, serverType string, errorType MCPErrorType, cause error) *MCPError

NewMCPError creates a new MCP error

func NewServerError added in v0.1.14

func NewServerError(serverName, serverType string, errorType MCPErrorType, cause error) *MCPError

NewServerError creates a server-related error

func NewTimeoutError added in v0.1.14

func NewTimeoutError(operation, serverName, serverType string, cause error) *MCPError

NewTimeoutError creates a timeout error

func NewToolError added in v0.1.14

func NewToolError(toolName, serverName, serverType string, errorType MCPErrorType, cause error) *MCPError

NewToolError creates a tool-related error

func (*MCPError) Error added in v0.1.14

func (e *MCPError) Error() string

Error implements the error interface

func (*MCPError) IsRetryable added in v0.1.14

func (e *MCPError) IsRetryable() bool

IsRetryable returns whether this error might succeed on retry

func (*MCPError) Unwrap added in v0.1.14

func (e *MCPError) Unwrap() error

Unwrap returns the underlying error

func (*MCPError) WithMetadata added in v0.1.14

func (e *MCPError) WithMetadata(key, value string) *MCPError

WithMetadata adds metadata to the error (thread-safe)

type MCPErrorType added in v0.1.14

type MCPErrorType string

MCPErrorType categorizes different types of MCP errors

const (
	// Connection errors
	MCPErrorTypeConnection     MCPErrorType = "CONNECTION_ERROR"
	MCPErrorTypeTimeout        MCPErrorType = "TIMEOUT_ERROR"
	MCPErrorTypeAuthentication MCPErrorType = "AUTHENTICATION_ERROR"

	// Server errors
	MCPErrorTypeServerNotFound MCPErrorType = "SERVER_NOT_FOUND"
	MCPErrorTypeServerStartup  MCPErrorType = "SERVER_STARTUP_ERROR"
	MCPErrorTypeServerCrash    MCPErrorType = "SERVER_CRASH"

	// Tool errors
	MCPErrorTypeToolNotFound    MCPErrorType = "TOOL_NOT_FOUND"
	MCPErrorTypeToolInvalidArgs MCPErrorType = "TOOL_INVALID_ARGS"
	MCPErrorTypeToolExecution   MCPErrorType = "TOOL_EXECUTION_ERROR"

	// Protocol errors
	MCPErrorTypeProtocol      MCPErrorType = "PROTOCOL_ERROR"
	MCPErrorTypeSerialization MCPErrorType = "SERIALIZATION_ERROR"

	// Configuration errors
	MCPErrorTypeConfiguration MCPErrorType = "CONFIGURATION_ERROR"
	MCPErrorTypeValidation    MCPErrorType = "VALIDATION_ERROR"

	// Unknown errors
	MCPErrorTypeUnknown MCPErrorType = "UNKNOWN_ERROR"
)

type MCPServerImpl

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

MCPServerImpl is the implementation of interfaces.MCPServer using the official SDK

func (*MCPServerImpl) CallTool

func (s *MCPServerImpl) CallTool(ctx context.Context, name string, args interface{}) (*interfaces.MCPToolResponse, error)

CallTool calls a tool on the MCP server

func (*MCPServerImpl) Close

func (s *MCPServerImpl) Close() error

Close closes the connection to the MCP server

func (*MCPServerImpl) CreateMessage added in v0.1.14

CreateMessage requests the client to generate a completion using its LLM

func (*MCPServerImpl) GetCapabilities added in v0.1.14

func (s *MCPServerImpl) GetCapabilities() (*interfaces.MCPServerCapabilities, error)

GetCapabilities returns the server capabilities discovered during initialization

func (*MCPServerImpl) GetPrompt added in v0.1.14

func (s *MCPServerImpl) GetPrompt(ctx context.Context, name string, variables map[string]interface{}) (*interfaces.MCPPromptResult, error)

GetPrompt retrieves a specific prompt with variables

func (*MCPServerImpl) GetResource added in v0.1.14

func (s *MCPServerImpl) GetResource(ctx context.Context, uri string) (*interfaces.MCPResourceContent, error)

GetResource retrieves a specific resource by URI

func (*MCPServerImpl) GetServerInfo added in v0.1.14

func (s *MCPServerImpl) GetServerInfo() (*interfaces.MCPServerInfo, error)

GetServerInfo returns the server metadata discovered during initialization

func (*MCPServerImpl) Initialize

func (s *MCPServerImpl) Initialize(ctx context.Context) error

Initialize initializes the connection to the MCP server

func (*MCPServerImpl) ListPrompts added in v0.1.14

func (s *MCPServerImpl) ListPrompts(ctx context.Context) ([]interfaces.MCPPrompt, error)

ListPrompts lists the prompts available on the MCP server

func (*MCPServerImpl) ListResources added in v0.1.14

func (s *MCPServerImpl) ListResources(ctx context.Context) ([]interfaces.MCPResource, error)

ListResources lists the resources available on the MCP server

func (*MCPServerImpl) ListTools

func (s *MCPServerImpl) ListTools(ctx context.Context) ([]interfaces.MCPTool, error)

ListTools lists the tools available on the MCP server

func (*MCPServerImpl) WatchResource added in v0.1.14

func (s *MCPServerImpl) WatchResource(ctx context.Context, uri string) (<-chan interfaces.MCPResourceUpdate, error)

WatchResource watches for changes to a resource (if supported)

type MCPTool

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

MCPTool implements interfaces.Tool for MCP tools

func (*MCPTool) Description

func (t *MCPTool) Description() string

Description returns a description of what the tool does

func (*MCPTool) DisplayName added in v0.0.53

func (t *MCPTool) DisplayName() string

DisplayName implements interfaces.ToolWithDisplayName.DisplayName

func (*MCPTool) Execute

func (t *MCPTool) Execute(ctx context.Context, args string) (string, error)

Execute executes the tool with the given arguments

func (*MCPTool) Internal added in v0.0.53

func (t *MCPTool) Internal() bool

Internal implements interfaces.InternalTool.Internal

func (*MCPTool) Name

func (t *MCPTool) Name() string

Name returns the name of the tool

func (*MCPTool) Parameters

func (t *MCPTool) Parameters() map[string]interfaces.ParameterSpec

Parameters returns the parameters that the tool accepts

func (*MCPTool) Run

func (t *MCPTool) Run(ctx context.Context, input string) (string, error)

Run executes the tool with the given input

type MCPToolAdapter

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

MCPToolAdapter converts MCP tools to the agent SDK tool interface

func NewMCPToolAdapter

func NewMCPToolAdapter(server interfaces.MCPServer, name, description string, params map[string]ParameterSpec) *MCPToolAdapter

NewMCPToolAdapter creates a new adapter for an MCP tool

func (*MCPToolAdapter) Description

func (a *MCPToolAdapter) Description() string

Description returns the description of the tool

func (*MCPToolAdapter) DisplayName added in v0.0.53

func (a *MCPToolAdapter) DisplayName() string

DisplayName implements interfaces.ToolWithDisplayName.DisplayName

func (*MCPToolAdapter) Execute

func (a *MCPToolAdapter) Execute(ctx context.Context, args string) (string, error)

Execute executes the tool with the given arguments string

func (*MCPToolAdapter) InputSchema

func (a *MCPToolAdapter) InputSchema() map[string]interfaces.ParameterSpec

InputSchema returns the schema for the tool's input

func (*MCPToolAdapter) Internal added in v0.0.53

func (a *MCPToolAdapter) Internal() bool

Internal implements interfaces.InternalTool.Internal

func (*MCPToolAdapter) Name

func (a *MCPToolAdapter) Name() string

Name returns the name of the tool

func (*MCPToolAdapter) Parameters

func (a *MCPToolAdapter) Parameters() map[string]interfaces.ParameterSpec

Parameters returns the parameters that the tool accepts

func (*MCPToolAdapter) Run

func (a *MCPToolAdapter) Run(ctx context.Context, input string) (string, error)

Run executes the tool with the given input

type MCPToolResponse

type MCPToolResponse struct {
	Content interface{} `json:"content"`
	Error   string      `json:"error,omitempty"`
	Text    string      `json:"text,omitempty"`
}

MCPToolResponse represents the response from an MCP tool call

type ParameterSpec

type ParameterSpec struct {
	Type        string `json:"type"`
	Description string `json:"description"`
	Required    bool   `json:"required"`
}

ParameterSpec represents a parameter specification for an MCP tool

type PresetServer added in v0.1.14

type PresetServer struct {
	Name        string
	Description string
	Type        string // "stdio" or "http"
	Command     string
	Args        []string
	Env         []string
	URL         string
	RequiredEnv []string // Environment variables that must be set
}

PresetServer represents a predefined MCP server configuration

type PromptCategory added in v0.1.14

type PromptCategory struct {
	Name        string
	Description string
	Prompts     []PromptMatch
}

PromptCategory represents a category of prompts

type PromptManager added in v0.1.14

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

PromptManager provides high-level operations for MCP prompts

func NewPromptManager added in v0.1.14

func NewPromptManager(servers []interfaces.MCPServer) *PromptManager

NewPromptManager creates a new prompt manager

func (*PromptManager) BuildVariablesFromTemplate added in v0.1.14

func (pm *PromptManager) BuildVariablesFromTemplate(templateStr string, data interface{}) (map[string]interface{}, error)

BuildVariablesFromTemplate builds variables from a Go template string

func (*PromptManager) ExecutePromptTemplate added in v0.1.14

func (pm *PromptManager) ExecutePromptTemplate(ctx context.Context, promptName string, variables map[string]interface{}) (string, error)

ExecutePromptTemplate executes a prompt template with variables and returns rendered content

func (*PromptManager) FindPrompts added in v0.1.14

func (pm *PromptManager) FindPrompts(ctx context.Context, pattern string) ([]PromptMatch, error)

FindPrompts searches for prompts by name pattern across all servers

func (*PromptManager) GetPrompt added in v0.1.14

func (pm *PromptManager) GetPrompt(ctx context.Context, name string, variables map[string]interface{}) (*PromptResult, error)

GetPrompt retrieves a prompt by name from any server that has it

func (*PromptManager) GetPromptsByCategory added in v0.1.14

func (pm *PromptManager) GetPromptsByCategory(ctx context.Context, category string) ([]PromptMatch, error)

GetPromptsByCategory returns prompts filtered by category (from metadata)

func (*PromptManager) ListAllPrompts added in v0.1.14

func (pm *PromptManager) ListAllPrompts(ctx context.Context) (map[string][]interfaces.MCPPrompt, error)

ListAllPrompts lists prompts from all MCP servers

func (*PromptManager) ValidatePromptVariables added in v0.1.14

func (pm *PromptManager) ValidatePromptVariables(prompt interfaces.MCPPrompt, variables map[string]interface{}) error

ValidatePromptVariables checks if all required variables are provided

type PromptMatch added in v0.1.14

type PromptMatch struct {
	Server interfaces.MCPServer
	Prompt interfaces.MCPPrompt
}

PromptMatch represents a prompt found on a specific server

type PromptResult added in v0.1.14

type PromptResult struct {
	Server interfaces.MCPServer
	Prompt interfaces.MCPPrompt
	Result interfaces.MCPPromptResult
}

PromptResult represents a prompt result with its source

type RegistryAuthor added in v0.1.14

type RegistryAuthor struct {
	Name   string `json:"name"`
	Email  string `json:"email,omitempty"`
	URL    string `json:"url,omitempty"`
	GitHub string `json:"github,omitempty"`
}

RegistryAuthor represents the author of a registry server

type RegistryClient added in v0.1.14

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

RegistryClient handles interaction with MCP Registry for server discovery

func NewRegistryClient added in v0.1.14

func NewRegistryClient(baseURL string) *RegistryClient

NewRegistryClient creates a new MCP Registry client

func (*RegistryClient) GetServer added in v0.1.14

func (rc *RegistryClient) GetServer(ctx context.Context, serverID string) (*RegistryServer, error)

GetServer retrieves a specific server by ID

func (*RegistryClient) GetServersByCategory added in v0.1.14

func (rc *RegistryClient) GetServersByCategory(ctx context.Context, category string) (*SearchResponse, error)

GetServersByCategory retrieves servers in a specific category

func (*RegistryClient) GetServersByTags added in v0.1.14

func (rc *RegistryClient) GetServersByTags(ctx context.Context, tags []string) (*SearchResponse, error)

GetServersByTags retrieves servers with specific tags

func (*RegistryClient) GetVerifiedServers added in v0.1.14

func (rc *RegistryClient) GetVerifiedServers(ctx context.Context) (*SearchResponse, error)

GetVerifiedServers retrieves only verified servers

func (*RegistryClient) ListServers added in v0.1.14

func (rc *RegistryClient) ListServers(ctx context.Context, opts *SearchOptions) (*SearchResponse, error)

ListServers retrieves all available servers from the registry

func (*RegistryClient) SearchServers added in v0.1.14

func (rc *RegistryClient) SearchServers(ctx context.Context, query string) (*SearchResponse, error)

SearchServers searches for servers matching criteria

type RegistryManager added in v0.1.14

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

RegistryManager integrates registry discovery with MCP server creation

func NewRegistryManager added in v0.1.14

func NewRegistryManager(registryURL string) *RegistryManager

NewRegistryManager creates a new registry manager

func (*RegistryManager) BuildServerFromRegistry added in v0.1.14

func (rm *RegistryManager) BuildServerFromRegistry(ctx context.Context, serverID string) (interfaces.MCPServer, error)

BuildServerFromRegistry creates an MCP server from a registry entry

func (*RegistryManager) DiscoverAndInstallServer added in v0.1.14

func (rm *RegistryManager) DiscoverAndInstallServer(ctx context.Context, serverID string) (*LazyMCPServerConfig, error)

DiscoverAndInstallServer discovers a server from registry and creates MCP server config

func (*RegistryManager) DiscoverCodeServers added in v0.1.14

func (rm *RegistryManager) DiscoverCodeServers(ctx context.Context) ([]*RegistryServer, error)

DiscoverCodeServers finds servers that can work with code

func (*RegistryManager) DiscoverDatabaseServers added in v0.1.14

func (rm *RegistryManager) DiscoverDatabaseServers(ctx context.Context) ([]*RegistryServer, error)

DiscoverDatabaseServers finds servers that can work with databases

func (*RegistryManager) DiscoverFileSystemServers added in v0.1.14

func (rm *RegistryManager) DiscoverFileSystemServers(ctx context.Context) ([]*RegistryServer, error)

DiscoverFileSystemServers finds servers that can work with files

func (*RegistryManager) DiscoverServersByCapability added in v0.1.14

func (rm *RegistryManager) DiscoverServersByCapability(ctx context.Context, capability string) ([]*RegistryServer, error)

DiscoverServersByCapability finds servers that provide specific capabilities

func (*RegistryManager) DiscoverWebServers added in v0.1.14

func (rm *RegistryManager) DiscoverWebServers(ctx context.Context) ([]*RegistryServer, error)

DiscoverWebServers finds servers that can work with web APIs

func (*RegistryManager) GetPopularServers added in v0.1.14

func (rm *RegistryManager) GetPopularServers(ctx context.Context) (*SearchResponse, error)

GetPopularServers retrieves the most popular/downloaded servers

type RegistryPrompt added in v0.1.14

type RegistryPrompt struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Variables   []string `json:"variables,omitempty"`
	Category    string   `json:"category,omitempty"`
}

RegistryPrompt represents a prompt advertised by the server

type RegistryResource added in v0.1.14

type RegistryResource struct {
	Type        string   `json:"type"` // "file", "database", "api", etc.
	Description string   `json:"description"`
	Pattern     string   `json:"pattern,omitempty"` // URI pattern
	MimeTypes   []string `json:"mime_types,omitempty"`
}

RegistryResource represents a resource advertised by the server

type RegistryServer added in v0.1.14

type RegistryServer struct {
	ID          string         `json:"id"`
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Namespace   string         `json:"namespace"`
	Version     string         `json:"version"`
	Tags        []string       `json:"tags,omitempty"`
	Category    string         `json:"category,omitempty"`
	Author      RegistryAuthor `json:"author"`
	Repository  RepositoryInfo `json:"repository,omitempty"`
	License     string         `json:"license,omitempty"`
	Homepage    string         `json:"homepage,omitempty"`

	// Installation and configuration
	Installation  InstallationInfo  `json:"installation"`
	Configuration ConfigurationInfo `json:"configuration,omitempty"`

	// Capabilities
	Tools     []RegistryTool     `json:"tools,omitempty"`
	Resources []RegistryResource `json:"resources,omitempty"`
	Prompts   []RegistryPrompt   `json:"prompts,omitempty"`

	// Registry metadata
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	Downloads int       `json:"downloads,omitempty"`
	Rating    float64   `json:"rating,omitempty"`
	Verified  bool      `json:"verified"`
}

RegistryServer represents a server entry in the MCP Registry

type RegistryTool added in v0.1.14

type RegistryTool struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Parameters  map[string]interface{} `json:"parameters,omitempty"`
	Category    string                 `json:"category,omitempty"`
}

RegistryTool represents a tool advertised by the server

type RepositoryInfo added in v0.1.14

type RepositoryInfo struct {
	Type string `json:"type"` // "git", "github", etc.
	URL  string `json:"url"`
	Ref  string `json:"ref,omitempty"` // branch, tag, or commit
}

RepositoryInfo represents repository information

type ResourceManager added in v0.1.14

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

ResourceManager provides high-level operations for MCP resources

func NewResourceManager added in v0.1.14

func NewResourceManager(servers []interfaces.MCPServer) *ResourceManager

NewResourceManager creates a new resource manager

func (*ResourceManager) FindResources added in v0.1.14

func (rm *ResourceManager) FindResources(ctx context.Context, pattern string) ([]ResourceMatch, error)

FindResources searches for resources by pattern across all servers

func (*ResourceManager) GetResourceContent added in v0.1.14

func (rm *ResourceManager) GetResourceContent(ctx context.Context, uri string) (*interfaces.MCPResourceContent, error)

GetResourceContent retrieves content for a resource, trying all servers if URI is ambiguous

func (*ResourceManager) GetResourcesByType added in v0.1.14

func (rm *ResourceManager) GetResourcesByType(ctx context.Context, mimeType string) ([]ResourceMatch, error)

GetResourcesByType returns resources filtered by MIME type

func (*ResourceManager) ListAllResources added in v0.1.14

func (rm *ResourceManager) ListAllResources(ctx context.Context) (map[string][]interfaces.MCPResource, error)

ListAllResources lists resources from all MCP servers

func (*ResourceManager) WatchResources added in v0.1.14

func (rm *ResourceManager) WatchResources(ctx context.Context, uris []string) (<-chan ResourceUpdate, error)

WatchResources watches multiple resources for changes

type ResourceMatch added in v0.1.14

type ResourceMatch struct {
	Server   interfaces.MCPServer
	Resource interfaces.MCPResource
}

ResourceMatch represents a resource found on a specific server

type ResourceUpdate added in v0.1.14

type ResourceUpdate struct {
	Server string
	Update interfaces.MCPResourceUpdate
}

ResourceUpdate represents an update from any server

type RetryConfig added in v0.1.14

type RetryConfig struct {
	MaxAttempts       int
	InitialDelay      time.Duration
	MaxDelay          time.Duration
	BackoffMultiplier float64
	RetryableErrors   []string // Error message substrings that should trigger retry
}

RetryConfig configures retry behavior for MCP operations

func DefaultRetryConfig added in v0.1.14

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig returns a sensible default retry configuration

type RetryOptions added in v0.1.14

type RetryOptions struct {
	MaxAttempts       int
	InitialDelay      time.Duration
	MaxDelay          time.Duration
	BackoffMultiplier float64
}

RetryOptions configures retry behavior for MCP connections

type RetryableServer added in v0.1.14

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

RetryableServer wraps an MCP server with retry logic

func (*RetryableServer) CallTool added in v0.1.14

func (r *RetryableServer) CallTool(ctx context.Context, name string, args interface{}) (*interfaces.MCPToolResponse, error)

CallTool calls a tool with retry logic

func (*RetryableServer) Close added in v0.1.14

func (r *RetryableServer) Close() error

Close closes the connection (no retry needed)

func (*RetryableServer) CreateMessage added in v0.1.14

CreateMessage creates a message with retry logic

func (*RetryableServer) GetCapabilities added in v0.1.14

func (r *RetryableServer) GetCapabilities() (*interfaces.MCPServerCapabilities, error)

GetCapabilities returns server capabilities

func (*RetryableServer) GetPrompt added in v0.1.14

func (r *RetryableServer) GetPrompt(ctx context.Context, name string, variables map[string]interface{}) (*interfaces.MCPPromptResult, error)

GetPrompt gets a prompt with retry logic

func (*RetryableServer) GetResource added in v0.1.14

GetResource gets a resource with retry logic

func (*RetryableServer) GetServerInfo added in v0.1.14

func (r *RetryableServer) GetServerInfo() (*interfaces.MCPServerInfo, error)

GetServerInfo returns server metadata

func (*RetryableServer) Initialize added in v0.1.14

func (r *RetryableServer) Initialize(ctx context.Context) error

Initialize initializes the connection with retry logic

func (*RetryableServer) ListPrompts added in v0.1.14

func (r *RetryableServer) ListPrompts(ctx context.Context) ([]interfaces.MCPPrompt, error)

ListPrompts lists prompts with retry logic

func (*RetryableServer) ListResources added in v0.1.14

func (r *RetryableServer) ListResources(ctx context.Context) ([]interfaces.MCPResource, error)

ListResources lists resources with retry logic

func (*RetryableServer) ListTools added in v0.1.14

func (r *RetryableServer) ListTools(ctx context.Context) ([]interfaces.MCPTool, error)

ListTools lists tools with retry logic

func (*RetryableServer) WatchResource added in v0.1.14

func (r *RetryableServer) WatchResource(ctx context.Context, uri string) (<-chan interfaces.MCPResourceUpdate, error)

WatchResource watches a resource (no retry needed as it's a continuous operation)

type SamplingManager added in v0.1.14

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

SamplingManager provides high-level operations for MCP sampling

func NewSamplingManager added in v0.1.14

func NewSamplingManager(servers []interfaces.MCPServer) *SamplingManager

NewSamplingManager creates a new sampling manager

func (*SamplingManager) CreateCodeGeneration added in v0.1.14

func (sm *SamplingManager) CreateCodeGeneration(ctx context.Context, prompt string, language string, opts ...SamplingOption) (*interfaces.MCPSamplingResponse, error)

CreateCodeGeneration creates a message optimized for code generation

func (*SamplingManager) CreateConversation added in v0.1.14

func (sm *SamplingManager) CreateConversation(ctx context.Context, messages []interfaces.MCPMessage, opts ...SamplingOption) (*interfaces.MCPSamplingResponse, error)

CreateConversation creates a multi-turn conversation

func (*SamplingManager) CreateImageAnalysisMessage added in v0.1.14

func (sm *SamplingManager) CreateImageAnalysisMessage(ctx context.Context, imageData, mimeType, prompt string, opts ...SamplingOption) (*interfaces.MCPSamplingResponse, error)

CreateImageAnalysisMessage creates a message for image analysis

func (*SamplingManager) CreateMessage added in v0.1.14

CreateMessage creates a message using the first available server

func (*SamplingManager) CreateSummary added in v0.1.14

func (sm *SamplingManager) CreateSummary(ctx context.Context, content string, maxLength int, opts ...SamplingOption) (*interfaces.MCPSamplingResponse, error)

CreateSummary creates a message optimized for summarization tasks

func (*SamplingManager) CreateTextMessage added in v0.1.14

func (sm *SamplingManager) CreateTextMessage(ctx context.Context, prompt string, opts ...SamplingOption) (*interfaces.MCPSamplingResponse, error)

CreateTextMessage creates a simple text message using the first available server

type SamplingOption added in v0.1.14

type SamplingOption func(*interfaces.MCPSamplingRequest)

SamplingOption is a function that modifies a sampling request

func WithIncludeContext added in v0.1.14

func WithIncludeContext(context string) SamplingOption

WithIncludeContext sets context inclusion preference

func WithMaxTokens added in v0.1.14

func WithMaxTokens(maxTokens int) SamplingOption

WithMaxTokens sets the maximum number of tokens

func WithModelHint added in v0.1.14

func WithModelHint(modelName string) SamplingOption

WithModelHint suggests a specific model

func WithModelPreferences added in v0.1.14

func WithModelPreferences(cost, speed, intelligence float64) SamplingOption

WithModelPreferences sets custom model preferences

func WithStopSequences added in v0.1.14

func WithStopSequences(sequences ...string) SamplingOption

WithStopSequences sets stop sequences for generation

func WithSystemPrompt added in v0.1.14

func WithSystemPrompt(prompt string) SamplingOption

WithSystemPrompt sets the system prompt

func WithTemperature added in v0.1.14

func WithTemperature(temperature float64) SamplingOption

WithTemperature sets the sampling temperature

type SchemaBuilder added in v0.1.14

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

SchemaBuilder helps create JSON schemas for tool outputs

func NewSchemaBuilder added in v0.1.14

func NewSchemaBuilder() *SchemaBuilder

NewSchemaBuilder creates a new schema builder

func (*SchemaBuilder) Array added in v0.1.14

func (sb *SchemaBuilder) Array(itemSchema map[string]interface{}) *SchemaBuilder

Array creates an array schema

func (*SchemaBuilder) Boolean added in v0.1.14

func (sb *SchemaBuilder) Boolean() *SchemaBuilder

Boolean creates a boolean schema

func (*SchemaBuilder) Build added in v0.1.14

func (sb *SchemaBuilder) Build() map[string]interface{}

Build returns the completed schema

func (*SchemaBuilder) Description added in v0.1.14

func (sb *SchemaBuilder) Description(desc string) *SchemaBuilder

Description adds a description to the schema

func (*SchemaBuilder) Number added in v0.1.14

func (sb *SchemaBuilder) Number() *SchemaBuilder

Number creates a number schema

func (*SchemaBuilder) Object added in v0.1.14

func (sb *SchemaBuilder) Object() *SchemaBuilder

Object creates an object schema

func (*SchemaBuilder) Property added in v0.1.14

func (sb *SchemaBuilder) Property(name string, propertySchema map[string]interface{}) *SchemaBuilder

Property adds a property to an object schema

func (*SchemaBuilder) Required added in v0.1.14

func (sb *SchemaBuilder) Required(fields ...string) *SchemaBuilder

Required sets required fields for an object schema

func (*SchemaBuilder) String added in v0.1.14

func (sb *SchemaBuilder) String() *SchemaBuilder

String creates a string schema

type SchemaValidator added in v0.1.14

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

SchemaValidator handles validation of tool outputs against their schemas

func NewSchemaValidator added in v0.1.14

func NewSchemaValidator() *SchemaValidator

NewSchemaValidator creates a new schema validator

func (*SchemaValidator) ValidateToolResponse added in v0.1.14

func (sv *SchemaValidator) ValidateToolResponse(ctx context.Context, tool interfaces.MCPTool, response *interfaces.MCPToolResponse) error

ValidateToolResponse validates a tool response against its expected schema

type SearchOptions added in v0.1.14

type SearchOptions struct {
	Query    string   `json:"query,omitempty"`
	Tags     []string `json:"tags,omitempty"`
	Category string   `json:"category,omitempty"`
	Author   string   `json:"author,omitempty"`
	Verified bool     `json:"verified,omitempty"`
	Limit    int      `json:"limit,omitempty"`
	Offset   int      `json:"offset,omitempty"`
}

SearchOptions configures server search parameters

type SearchResponse added in v0.1.14

type SearchResponse struct {
	Servers []RegistryServer `json:"servers"`
	Total   int              `json:"total"`
	Limit   int              `json:"limit"`
	Offset  int              `json:"offset"`
}

SearchResponse represents the response from server search

type ServerProtocolType added in v0.0.46

type ServerProtocolType string

ServerProtocolType defines the protocol type for the MCP server communication Supported types are "streamable" and "sse"

const (
	StreamableHTTP ServerProtocolType = "streamable"
	SSE            ServerProtocolType = "sse"
)

type StdioServerConfig

type StdioServerConfig struct {
	Command string
	Args    []string
	Env     []string
	Logger  logging.Logger
}

StdioServerConfig holds configuration for a stdio MCP server

type ToolManager added in v0.1.14

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

ToolManager provides enhanced tool operations with schema support

func NewToolManager added in v0.1.14

func NewToolManager(servers []interfaces.MCPServer) *ToolManager

NewToolManager creates a new tool manager with schema validation

func (*ToolManager) CallToolWithValidation added in v0.1.14

func (tm *ToolManager) CallToolWithValidation(ctx context.Context, toolName string, args interface{}) (*interfaces.MCPToolResponse, error)

CallToolWithValidation calls a tool and validates the response against its schema

func (*ToolManager) GetToolsByCategory added in v0.1.14

func (tm *ToolManager) GetToolsByCategory(ctx context.Context, category string) ([]ToolMatch, error)

GetToolsByCategory returns tools filtered by category or functionality

func (*ToolManager) GetToolsWithOutputSchema added in v0.1.14

func (tm *ToolManager) GetToolsWithOutputSchema(ctx context.Context) ([]ToolMatch, error)

GetToolsWithOutputSchema returns only tools that have output schemas defined

func (*ToolManager) ListAllTools added in v0.1.14

func (tm *ToolManager) ListAllTools(ctx context.Context) (map[string][]interfaces.MCPTool, error)

ListAllTools lists tools from all servers with their output schemas

type ToolMatch added in v0.1.14

type ToolMatch struct {
	Server interfaces.MCPServer
	Tool   interfaces.MCPTool
}

ToolMatch represents a tool found on a specific server

Jump to

Keyboard shortcuts

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