mcp

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 22 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/tagus/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/tagus/agent-sdk-go/pkg/agent"
    "github.com/tagus/agent-sdk-go/pkg/interfaces"
    "github.com/tagus/agent-sdk-go/pkg/llm/openai"
    "github.com/tagus/agent-sdk-go/pkg/mcp"
    "github.com/tagus/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

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

func CreateFileInfoSchema() map[string]interface{}

CreateFileInfoSchema creates a schema for file information

func CreateWeatherSchema

func CreateWeatherSchema() map[string]interface{}

CreateWeatherSchema creates a schema for weather data

func ExtractCodeFromResponse

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

func FormatConversationHistory(messages []interfaces.MCPMessage) string

FormatConversationHistory formats a conversation for display

func FormatUserFriendlyError

func FormatUserFriendlyError(err error) string

FormatUserFriendlyError creates a user-friendly error message

func GetOrCreateServerFromCache

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

GetOrCreateServerFromCache provides public access to the global server cache

func GetPresetInfo

func GetPresetInfo(name string) (string, error)

GetPresetInfo returns information about a preset

func GetPromptParameterInfo

func GetPromptParameterInfo(prompt interfaces.MCPPrompt) string

GetPromptParameterInfo returns human-readable information about prompt parameters

func GetResourceExtension

func GetResourceExtension(resource interfaces.MCPResource) string

GetResourceExtension extracts file extension from resource URI

func GetServerMetadataFromCache

func GetServerMetadataFromCache(config LazyMCPServerConfig) *interfaces.MCPServerInfo

GetServerMetadataFromCache gets server metadata from the global cache

func IsBinaryResource

func IsBinaryResource(resource interfaces.MCPResource) bool

IsBinaryResource checks if a resource contains binary content

func IsTextResource

func IsTextResource(resource interfaces.MCPResource) bool

IsTextResource checks if a resource contains text content

func ListPresets

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

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

NewHTTPServerWithRetry creates a new HTTP MCPServer with retry logic

func NewLazyMCPTool

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

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

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

NewStdioServerWithRetry creates a new MCPServer with retry logic

func RetryWithExponentialBackoff

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

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

SuggestPromptVariables suggests default values for prompt variables

Types

type Builder

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

Builder provides a fluent interface for creating MCP server configurations

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new MCP configuration builder

func (*Builder) AddHTTPServer

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

AddHTTPServer adds an HTTP-based MCP server

func (*Builder) AddHTTPServerWithAuth

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

AddHTTPServerWithAuth adds an HTTP-based MCP server with authentication

func (*Builder) AddPreset

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

AddPreset adds a predefined MCP server configuration

func (*Builder) AddServer

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

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

AddStdioServer adds a stdio-based MCP server

func (*Builder) Build

Build creates the MCP servers and returns them

func (*Builder) BuildLazy

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

BuildLazy returns only lazy configurations without initializing any servers

func (*Builder) WithHealthCheck

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

WithHealthCheck enables or disables health checking

func (*Builder) WithLogger

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

WithLogger sets a custom logger

func (*Builder) WithRetry

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

WithRetry configures retry options

func (*Builder) WithTimeout

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

WithTimeout sets the connection timeout

type ConfigOption

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

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
	ApiKey       string
	ProtocolType ServerProtocolType
	Logger       logging.Logger

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

HTTPServerConfig holds configuration for an HTTP MCP server

type InstallationInfo

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

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

LazyMCPServerCache manages shared MCP server instances

type LazyMCPServerConfig

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
	HttpTransportMode string // "sse" or "streamable"
}

LazyMCPServerConfig holds configuration for creating an MCP server on demand

func GetPreset

func GetPreset(name string) (LazyMCPServerConfig, error)

GetPreset returns a preset configuration by name

type LazyMCPTool

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

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

func (*LazyMCPTool) Description

func (t *LazyMCPTool) Description() string

Description returns a description of what the tool does

func (*LazyMCPTool) DisplayName

func (t *LazyMCPTool) DisplayName() string

DisplayName implements interfaces.ToolWithDisplayName.DisplayName

func (*LazyMCPTool) Execute

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

Execute executes the tool with the given arguments

func (*LazyMCPTool) Internal

func (t *LazyMCPTool) Internal() bool

Internal implements interfaces.InternalTool.Internal

func (*LazyMCPTool) Name

func (t *LazyMCPTool) Name() string

Name returns the name of the tool

func (*LazyMCPTool) Parameters

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

Parameters returns the parameters that the tool accepts

func (*LazyMCPTool) Run

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

Run executes the tool with the given input

type MCPError

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

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

ClassifyError attempts to classify an error based on its message

func NewConfigurationError

func NewConfigurationError(operation string, cause error) *MCPError

NewConfigurationError creates a configuration error

func NewConnectionError

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

NewConnectionError creates a connection-related error

func NewMCPError

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

NewMCPError creates a new MCP error

func NewServerError

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

NewServerError creates a server-related error

func NewTimeoutError

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

NewTimeoutError creates a timeout error

func NewToolError

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

NewToolError creates a tool-related error

func (*MCPError) Error

func (e *MCPError) Error() string

Error implements the error interface

func (*MCPError) IsRetryable

func (e *MCPError) IsRetryable() bool

IsRetryable returns whether this error might succeed on retry

func (*MCPError) Unwrap

func (e *MCPError) Unwrap() error

Unwrap returns the underlying error

func (*MCPError) WithMetadata

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

WithMetadata adds metadata to the error (thread-safe)

type MCPErrorType

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

CreateMessage requests the client to generate a completion using its LLM

func (*MCPServerImpl) GetCapabilities

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

GetCapabilities returns the server capabilities discovered during initialization

func (*MCPServerImpl) GetPrompt

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

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

GetResource retrieves a specific resource by URI

func (*MCPServerImpl) GetServerInfo

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

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

ListPrompts lists the prompts available on the MCP server

func (*MCPServerImpl) ListResources

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

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

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

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

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

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

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

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

PromptCategory represents a category of prompts

type PromptManager

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

PromptManager provides high-level operations for MCP prompts

func NewPromptManager

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

NewPromptManager creates a new prompt manager

func (*PromptManager) BuildVariablesFromTemplate

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

BuildVariablesFromTemplate builds variables from a Go template string

func (*PromptManager) ExecutePromptTemplate

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

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

FindPrompts searches for prompts by name pattern across all servers

func (*PromptManager) GetPrompt

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

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

GetPromptsByCategory returns prompts filtered by category (from metadata)

func (*PromptManager) ListAllPrompts

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

ListAllPrompts lists prompts from all MCP servers

func (*PromptManager) ValidatePromptVariables

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

ValidatePromptVariables checks if all required variables are provided

type PromptMatch

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

PromptMatch represents a prompt found on a specific server

type PromptResult

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

PromptResult represents a prompt result with its source

type RegistryAuthor

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

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

RegistryClient handles interaction with MCP Registry for server discovery

func NewRegistryClient

func NewRegistryClient(baseURL string) *RegistryClient

NewRegistryClient creates a new MCP Registry client

func (*RegistryClient) GetServer

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

GetServer retrieves a specific server by ID

func (*RegistryClient) GetServersByCategory

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

GetServersByCategory retrieves servers in a specific category

func (*RegistryClient) GetServersByTags

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

GetServersByTags retrieves servers with specific tags

func (*RegistryClient) GetVerifiedServers

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

GetVerifiedServers retrieves only verified servers

func (*RegistryClient) ListServers

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

ListServers retrieves all available servers from the registry

func (*RegistryClient) SearchServers

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

SearchServers searches for servers matching criteria

type RegistryManager

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

RegistryManager integrates registry discovery with MCP server creation

func NewRegistryManager

func NewRegistryManager(registryURL string) *RegistryManager

NewRegistryManager creates a new registry manager

func (*RegistryManager) BuildServerFromRegistry

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

BuildServerFromRegistry creates an MCP server from a registry entry

func (*RegistryManager) DiscoverAndInstallServer

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

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

DiscoverCodeServers finds servers that can work with code

func (*RegistryManager) DiscoverDatabaseServers

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

DiscoverDatabaseServers finds servers that can work with databases

func (*RegistryManager) DiscoverFileSystemServers

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

DiscoverFileSystemServers finds servers that can work with files

func (*RegistryManager) DiscoverServersByCapability

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

DiscoverServersByCapability finds servers that provide specific capabilities

func (*RegistryManager) DiscoverWebServers

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

DiscoverWebServers finds servers that can work with web APIs

func (*RegistryManager) GetPopularServers

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

GetPopularServers retrieves the most popular/downloaded servers

type RegistryPrompt

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

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

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

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

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

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

ResourceManager provides high-level operations for MCP resources

func NewResourceManager

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

NewResourceManager creates a new resource manager

func (*ResourceManager) FindResources

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

FindResources searches for resources by pattern across all servers

func (*ResourceManager) GetResourceContent

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

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

GetResourcesByType returns resources filtered by MIME type

func (*ResourceManager) ListAllResources

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

ListAllResources lists resources from all MCP servers

func (*ResourceManager) WatchResources

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

WatchResources watches multiple resources for changes

type ResourceMatch

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

ResourceMatch represents a resource found on a specific server

type ResourceUpdate

type ResourceUpdate struct {
	Server string
	Update interfaces.MCPResourceUpdate
}

ResourceUpdate represents an update from any server

type RetryConfig

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

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig returns a sensible default retry configuration

type RetryOptions

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

RetryOptions configures retry behavior for MCP connections

type RetryableServer

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

RetryableServer wraps an MCP server with retry logic

func (*RetryableServer) CallTool

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

CallTool calls a tool with retry logic

func (*RetryableServer) Close

func (r *RetryableServer) Close() error

Close closes the connection (no retry needed)

func (*RetryableServer) CreateMessage

CreateMessage creates a message with retry logic

func (*RetryableServer) GetCapabilities

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

GetCapabilities returns server capabilities

func (*RetryableServer) GetPrompt

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

GetResource gets a resource with retry logic

func (*RetryableServer) GetServerInfo

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

GetServerInfo returns server metadata

func (*RetryableServer) Initialize

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

Initialize initializes the connection with retry logic

func (*RetryableServer) ListPrompts

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

ListPrompts lists prompts with retry logic

func (*RetryableServer) ListResources

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

ListResources lists resources with retry logic

func (*RetryableServer) ListTools

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

ListTools lists tools with retry logic

func (*RetryableServer) WatchResource

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

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

SamplingManager provides high-level operations for MCP sampling

func NewSamplingManager

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

NewSamplingManager creates a new sampling manager

func (*SamplingManager) CreateCodeGeneration

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

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

CreateConversation creates a multi-turn conversation

func (*SamplingManager) CreateImageAnalysisMessage

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

CreateMessage creates a message using the first available server

func (*SamplingManager) CreateSummary

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

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

type SamplingOption func(*interfaces.MCPSamplingRequest)

SamplingOption is a function that modifies a sampling request

func WithIncludeContext

func WithIncludeContext(context string) SamplingOption

WithIncludeContext sets context inclusion preference

func WithMaxTokens

func WithMaxTokens(maxTokens int) SamplingOption

WithMaxTokens sets the maximum number of tokens

func WithModelHint

func WithModelHint(modelName string) SamplingOption

WithModelHint suggests a specific model

func WithModelPreferences

func WithModelPreferences(cost, speed, intelligence float64) SamplingOption

WithModelPreferences sets custom model preferences

func WithStopSequences

func WithStopSequences(sequences ...string) SamplingOption

WithStopSequences sets stop sequences for generation

func WithSystemPrompt

func WithSystemPrompt(prompt string) SamplingOption

WithSystemPrompt sets the system prompt

func WithTemperature

func WithTemperature(temperature float64) SamplingOption

WithTemperature sets the sampling temperature

type SchemaBuilder

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

SchemaBuilder helps create JSON schemas for tool outputs

func NewSchemaBuilder

func NewSchemaBuilder() *SchemaBuilder

NewSchemaBuilder creates a new schema builder

func (*SchemaBuilder) Array

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

Array creates an array schema

func (*SchemaBuilder) Boolean

func (sb *SchemaBuilder) Boolean() *SchemaBuilder

Boolean creates a boolean schema

func (*SchemaBuilder) Build

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

Build returns the completed schema

func (*SchemaBuilder) Description

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

Description adds a description to the schema

func (*SchemaBuilder) Number

func (sb *SchemaBuilder) Number() *SchemaBuilder

Number creates a number schema

func (*SchemaBuilder) Object

func (sb *SchemaBuilder) Object() *SchemaBuilder

Object creates an object schema

func (*SchemaBuilder) Property

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

Property adds a property to an object schema

func (*SchemaBuilder) Required

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

Required sets required fields for an object schema

func (*SchemaBuilder) String

func (sb *SchemaBuilder) String() *SchemaBuilder

String creates a string schema

type SchemaValidator

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

SchemaValidator handles validation of tool outputs against their schemas

func NewSchemaValidator

func NewSchemaValidator() *SchemaValidator

NewSchemaValidator creates a new schema validator

func (*SchemaValidator) ValidateToolResponse

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

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

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

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

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

ToolManager provides enhanced tool operations with schema support

func NewToolManager

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

NewToolManager creates a new tool manager with schema validation

func (*ToolManager) CallToolWithValidation

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

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

GetToolsByCategory returns tools filtered by category or functionality

func (*ToolManager) GetToolsWithOutputSchema

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

GetToolsWithOutputSchema returns only tools that have output schemas defined

func (*ToolManager) ListAllTools

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

ListAllTools lists tools from all servers with their output schemas

type ToolMatch

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