Documentation
¶
Overview ¶
Package mcp provides MCP (Model Context Protocol) integration for Genie using trpc-agent-go. It enables Genie to connect to MCP servers via multiple transports (stdio, HTTP, SSE) and manage tool discovery and execution.
The package leverages trpc-agent-go's out-of-the-box MCP tool integration (mcp.NewMCPToolSet) and provides a configuration-driven approach to managing MCP server connections.
Key Features ¶
- Multiple transport support: stdio, streamable_http, and sse
- Tool filtering with include/exclude patterns
- Session reconnection for automatic recovery
- Configurable retry behavior with exponential backoff
- Multiple concurrent MCP server connections
Basic Usage ¶
import (
"context"
"github.com/stackgenhq/genie/pkg/mcp"
"time"
)
// Create configuration
config := mcp.MCPConfig{
Servers: []mcp.MCPServerConfig{
{
Name: "terraform",
Transport: "streamable_http",
ServerURL: "http://localhost:3000/mcp",
Timeout: 10 * time.Second,
IncludeTools: []string{"search_modules", "get_module"},
},
},
}
// Initialize client
ctx := context.Background()
client, err := mcp.NewClient(ctx, config)
if err != nil {
// handle error
}
defer client.Close(ctx)
// Get available tools (cached for 30s, fresh connections on cache miss)
tools := client.GetTools(ctx)
Configuration Examples ¶
See README.md for comprehensive configuration examples including:
- Stdio transport configuration
- HTTP/SSE transport configuration
- Tool filtering
- Session reconnection
- Retry configuration
Integration with trpc-agent-go ¶
This package uses trpc-agent-go's mcp.NewMCPToolSet to create MCP tool sets. The tools returned by GetTools() implement the tool.Tool interface and can be used directly with trpc-agent-go agents.
For more details on trpc-agent-go MCP integration, see: https://github.com/trpc-group/trpc-agent-go/tree/main/tool/mcp
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client manages MCP server connections and provides access to MCP tools. It uses mark3labs/mcp-go for MCP protocol communication and wraps tools to be compatible with trpc-agent-go.
Tool metadata (names, descriptions, schemas) is fetched just-in-time via GetTools(ctx) and cached for a short TTL (defaultCacheTTL). Each tool's Call() method dials its own ephemeral MCP connection, so cache refreshes never close connections that are still in use by in-flight tool calls.
func NewClient ¶
NewClient creates a new MCP client from the provided configuration. It validates the configuration but does NOT connect to MCP servers at startup. Tool metadata is fetched just-in-time via GetTools(ctx).
Options (e.g. WithSecretProvider) can be used to enable secret lookup for MCP server env values containing "${VAR}".
func (*Client) Close ¶
Close clears the tool metadata cache. No live connections are held, so this is a lightweight operation. Safe to call multiple times.
func (*Client) GetPromptRepositories ¶
func (c *Client) GetPromptRepositories() []*PromptRepository
GetPromptRepositories returns a PromptRepository for each configured MCP server so the agent can discover and read MCP Prompts as Genie Skills.
func (*Client) GetTools ¶
GetTools returns all available tools from all configured MCP servers. Tool metadata (names, descriptions, schemas) is cached for cacheTTL (default 30s) to avoid reconnecting on every Registry lookup (GetTool, ToolNames, AllTools, etc.). Each returned tool dials its own ephemeral connection per Call(), so cache refreshes never interfere with in-flight tool calls.
func (*Client) RegisterDatasources ¶
func (c *Client) RegisterDatasources() []datasource.DataSource
RegisterDatasources registers a ConnectorFactory for each configured MCP server so that the datasource sync pipeline can enumerate and vectorize MCP resources.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption configures an MCP Client (e.g. WithSecretProvider).
func WithSecretProvider ¶
func WithSecretProvider(sp security.SecretProvider) ClientOption
WithSecretProvider sets the SecretProvider used to resolve env values that start with "${" when building the stdio subprocess environment. If not set, env values are used as-is (config load may have already expanded them).
type ClientTool ¶
type ClientTool struct {
// contains filtered or unexported fields
}
ClientTool wraps an MCP Tool definition to implement the trpc-agent-go tool.Tool interface. Each Call() dials a fresh ephemeral MCP connection via the dialer, executes the tool, and tears the connection down. This eliminates the race where a shared cached connection could be closed by a concurrent cache refresh while an in-flight tool call is still using it.
Tools are namespaced by server name to avoid collisions when multiple MCP servers expose tools with the same name (e.g. "search").
func NewClientTool ¶
func NewClientTool(caller MCPCaller, mcpTool mcp.Tool, serverName string) *ClientTool
NewClientTool creates a ClientTool that uses a static MCPCaller for every Call(). This constructor is kept for backward compatibility with code that already holds a live MCPCaller (e.g. tests using counterfeiter fakes).
func (*ClientTool) Call ¶
Call dials a fresh MCP connection, executes the tool, and closes the connection. Each invocation is fully independent — no shared state.
func (*ClientTool) Declaration ¶
func (t *ClientTool) Declaration() *tool.Declaration
Declaration returns the tool declaration.
func (*ClientTool) Description ¶
func (t *ClientTool) Description() string
Description returns the tool description.
func (*ClientTool) Name ¶
func (t *ClientTool) Name() string
Name returns the namespaced tool name (serverName_toolName).
type MCPCaller ¶ added in v0.1.6
type MCPCaller interface {
CallTool(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)
}
MCPCaller is the subset of the MCP client interface used by ClientTool. Extracting this allows unit testing Call() with counterfeiter fakes.
type MCPConfig ¶
type MCPConfig struct {
// Servers is a list of MCP server configurations
Servers []MCPServerConfig `json:"servers,omitempty" yaml:"servers,omitempty" toml:"servers,omitempty"`
}
MCPConfig represents the top-level MCP configuration for multiple server connections. This configuration enables Genie to connect to MCP servers via different transports (stdio, HTTP, SSE) and manage tool discovery and execution.
type MCPPromptCaller ¶
type MCPPromptCaller interface {
GetPrompt(ctx context.Context, req mcp.GetPromptRequest) (*mcp.GetPromptResult, error)
ListPrompts(ctx context.Context, req mcp.ListPromptsRequest) (*mcp.ListPromptsResult, error)
io.Closer
}
MCPPromptCaller is an interface for fetching prompts from an MCP server. Extracted to allow unit testing with counterfeiter fakes.
type MCPServerConfig ¶
type MCPServerConfig struct {
// Name is a unique identifier for this server configuration
Name string `json:"name,omitempty" yaml:"name,omitempty" toml:"name,omitempty"`
// Transport specifies the connection type: "stdio", "streamable_http", or "sse"
Transport string `json:"transport,omitempty" yaml:"transport,omitempty" toml:"transport,omitempty"`
// ServerURL is the HTTP/SSE server URL (required for streamable_http and sse transports)
ServerURL string `json:"server_url,omitempty" yaml:"server_url,omitempty" toml:"server_url,omitempty"`
// Command is the executable command (required for stdio transport)
Command string `json:"command,omitempty" yaml:"command,omitempty" toml:"command,omitempty"`
// Args are the command arguments (optional for stdio transport)
Args []string `json:"args,omitempty" yaml:"args,omitempty" toml:"args,omitempty"`
// Timeout is the connection timeout duration (default: 60s)
Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty" toml:"timeout,omitempty"`
// Headers are custom HTTP headers (optional for HTTP/SSE transports)
Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty" toml:"headers,omitempty"`
// Env is environment variables for the MCP subprocess (stdio transport only).
// Values support ${VAR} expansion from config. Use for tokens, e.g.
// GITHUB_PERSONAL_ACCESS_TOKEN = "${GH_TOKEN}" with GH_TOKEN=$(gh auth token).
Env map[string]string `json:"env,omitempty" yaml:"env,omitempty" toml:"env,omitempty"`
// IncludeTools is a list of tool names to include (allowlist)
// If specified, only these tools will be available
IncludeTools []string `json:"include_tools,omitempty" yaml:"include_tools,omitempty" toml:"include_tools,omitempty"`
// ExcludeTools is a list of tool names to exclude (blocklist)
// If specified, these tools will be filtered out
ExcludeTools []string `json:"exclude_tools,omitempty" yaml:"exclude_tools,omitempty" toml:"exclude_tools,omitempty"`
// SessionReconnect enables automatic session reconnection with max retry attempts
// Set to 0 to disable session reconnection
SessionReconnect int `json:"session_reconnect,omitempty" yaml:"session_reconnect,omitempty" toml:"session_reconnect,omitempty,omitzero"`
//Datasource Keyword Regex
DatasourceKeywordRegex []string `json:"datasource_keyword_regex,omitempty" yaml:"datasource_keyword_regex,omitempty" toml:"datasource_keyword_regex,omitempty"`
}
MCPServerConfig represents configuration for a single MCP server connection. It supports multiple transport types and provides fine-grained control over connection behavior, tool filtering, and error handling.
func (*MCPServerConfig) SetDefaults ¶
func (s *MCPServerConfig) SetDefaults()
SetDefaults sets default values for the MCP configuration. This ensures that optional fields have sensible defaults when not specified.
func (*MCPServerConfig) Validate ¶
func (s *MCPServerConfig) Validate() error
Validate validates a single MCP server configuration. It checks that required fields are present based on transport type and that values are within acceptable ranges.
type PromptRepository ¶
type PromptRepository struct {
// contains filtered or unexported fields
}
PromptRepository exposes MCP Prompts as Genie Skills. It implements the trpc.group/trpc-go/trpc-agent-go/skill.Repository interface. Each call to Summaries or Get creates an ephemeral MCP client connection to the configured server, fetches the data, and closes the connection.
func NewPromptRepository ¶
func NewPromptRepository(cfg MCPServerConfig, sp security.SecretProvider) *PromptRepository
NewPromptRepository creates a new PromptRepository for the given MCP server config. secretProvider is optional; when set it is used to resolve ${VAR} references in stdio env values and HTTP headers.
func (*PromptRepository) Get ¶
func (r *PromptRepository) Get(name string) (*skill.Skill, error)
Get connects to the MCP server, fetches a specific prompt by name, and maps it to a Skill.
func (*PromptRepository) Path ¶
func (r *PromptRepository) Path(name string) (string, error)
Path is not applicable to MCP Prompts as they are remote.
func (*PromptRepository) Summaries ¶
func (r *PromptRepository) Summaries() []skill.Summary
Summaries connects to the MCP server, lists all prompts, and returns them as skill.Summary entries. The skill name is prefixed with the server name to avoid namespace collisions.