mcpserver

package
v0.6.5 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2026 License: BSD-3-Clause Imports: 38 Imported by: 0

Documentation

Overview

Package mcpserver provides the MCP server framework for X509 certificate chain resolution. It implements the Model Context Protocol (MCP) server with tools for certificate operations, including chain resolution, validation, expiry checking, and AI-powered analysis. The package uses a builder pattern for server construction and supports bidirectional AI communication.

Index

Constants

View Source
const (
	// MaxTemplateSize defines the maximum allowed size for template files (1MB)
	MaxTemplateSize = 1024 * 1024
	// MaxMessageContentSize defines the maximum allowed size for individual message content (64KB)
	MaxMessageContentSize = 64 * 1024
	// MaxMessagesPerTemplate defines the maximum number of messages allowed per template
	MaxMessagesPerTemplate = 50
)
View Source
const (
	// ToolResolveCertChain resolves a single X509 certificate chain from file or base64 data.
	// Used for building complete certificate chains from leaf certificates.
	ToolResolveCertChain = "resolve_cert_chain"

	// ToolValidateCertChain validates a certificate chain for correctness and trust.
	// Performs comprehensive chain validation including signature verification and trust path validation.
	ToolValidateCertChain = "validate_cert_chain"

	// ToolBatchResolveCertChain processes multiple certificate chains in a single operation.
	// Optimizes performance for bulk certificate processing scenarios.
	ToolBatchResolveCertChain = "batch_resolve_cert_chain"

	// ToolCheckCertExpiry monitors certificate expiration dates with configurable warning thresholds.
	// Essential for certificate lifecycle management and renewal planning.
	ToolCheckCertExpiry = "check_cert_expiry"

	// ToolFetchRemoteCert retrieves certificate chains from remote TLS endpoints.
	// Enables analysis of server certificates without local file access.
	ToolFetchRemoteCert = "fetch_remote_cert"

	// ToolAnalyzeCertificateWithAI performs advanced certificate analysis using AI collaboration.
	// Provides security assessments, compliance checks, and actionable recommendations.
	ToolAnalyzeCertificateWithAI = "analyze_certificate_with_ai"

	// ToolGetResourceUsage provides server resource usage statistics and CRL cache metrics.
	// Includes memory usage, GC statistics, and performance monitoring data.
	ToolGetResourceUsage = "get_resource_usage"

	// ToolVisualizeCertChain provides certificate chain visualization in multiple formats.
	// Supports ASCII tree, markdown table, and JSON output for better certificate chain analysis.
	ToolVisualizeCertChain = "visualize_cert_chain"
)

Tool names as constants for consistency and type safety.

View Source
const (
	// RoleChainResolver handles single certificate chain resolution operations.
	// Responsible for building complete certificate chains from leaf certificates.
	RoleChainResolver = "chainResolver"

	// RoleChainValidator performs certificate chain validation and trust verification.
	// Ensures certificate chains meet security and correctness requirements.
	RoleChainValidator = "chainValidator"

	// RoleBatchResolver manages bulk certificate chain processing operations.
	// Optimizes performance for high-volume certificate processing scenarios.
	RoleBatchResolver = "batchResolver"

	// RoleExpiryChecker monitors certificate expiration dates and renewal requirements.
	// Critical for certificate lifecycle management and preventing outages.
	RoleExpiryChecker = "expiryChecker"

	// RoleRemoteFetcher retrieves certificate chains from remote TLS endpoints.
	// Enables analysis of server certificates without requiring local file access.
	RoleRemoteFetcher = "remoteFetcher"

	// RoleAIAnalyzer performs advanced certificate analysis using AI collaboration.
	// Provides intelligent security assessments and actionable recommendations.
	RoleAIAnalyzer = "aiAnalyzer"

	// RoleResourceMonitor tracks server resource usage and performance metrics.
	// Provides insights into memory usage, GC statistics, and CRL cache efficiency.
	RoleResourceMonitor = "resourceMonitor"

	// RoleChainVisualizer provides certificate chain visualization capabilities.
	// Supports multiple output formats for enhanced certificate analysis and debugging.
	RoleChainVisualizer = "chainVisualizer"
)

Tool roles as constants for consistency and type safety.

Variables

This section is empty.

Functions

func FormatResourceUsageAsJSON added in v0.4.3

func FormatResourceUsageAsJSON(data *ResourceUsageData) (string, error)

FormatResourceUsageAsJSON formats resource usage data as JSON.

FormatResourceUsageAsJSON converts ResourceUsageData into a formatted JSON string with proper indentation. It includes all available data fields based on what was collected.

Parameters:

  • data: The resource usage data to format

Returns:

  • string: JSON-formatted resource usage data
  • error: Formatting error if marshaling fails

The output includes:

  • timestamp: RFC3339 timestamp
  • memory_usage: Basic memory statistics
  • gc_stats: Garbage collection information
  • system_info: Go runtime and system details
  • detailed_memory: Optional detailed memory stats
  • crl_cache: Optional CRL cache metrics

JSON is formatted with 2-space indentation for readability.

func FormatResourceUsageAsMarkdown added in v0.4.3

func FormatResourceUsageAsMarkdown(data *ResourceUsageData) string

FormatResourceUsageAsMarkdown formats resource usage data as a readable markdown table.

FormatResourceUsageAsMarkdown creates a comprehensive markdown report with sections for system information, memory usage, garbage collection stats, and optionally detailed memory and CRL cache metrics.

Parameters:

  • data: The resource usage data to format

Returns:

  • string: Markdown-formatted resource usage report

The report includes:

  • Header with timestamp and version information
  • System Information table (Go version, OS, CPU, goroutines)
  • Memory Usage table (heap, stack statistics in MB)
  • Garbage Collection table (cycles, CPU fraction, etc.)
  • Optional Detailed Memory Statistics
  • Optional CRL Cache Metrics with hit rate

Tables use emoji headers (📊 METRIC, 📈 VALUE) and are formatted using the tablewriter library with markdown renderer.

func GetVersion added in v0.3.4

func GetVersion() string

GetVersion returns the current version of the MCP server.

GetVersion provides access to the server's version string, which is set during server initialization via the Run function. This allows other components to access the version information for logging, user-agent strings, or API responses.

Returns:

  • string: The current server version (e.g., "0.4.9")

The version is initially set to the default from the version package, but can be overridden when calling Run() with a specific version string.

func Run

func Run(version string, configFile string) error

Run starts the MCP server with X509 certificate chain resolution tools.

Run initializes and starts the MCP server with all certificate chain resolution capabilities, including AI-powered analysis, remote certificate fetching, batch processing, and resource monitoring. The server supports graceful shutdown and integrates with the CRL cache cleanup system.

Parameters:

  • version: Version string to set for the server (e.g., "0.4.9")
  • configFile: Path to the configuration file (overrides environment variable)

Returns:

  • error: Server startup or runtime error, or graceful shutdown signal

Configuration:

  • Loads config from configFile parameter if provided, otherwise from MCP_X509_CONFIG_FILE environment variable
  • Falls back to default config if no configuration file is specified

Features:

  • Certificate chain resolution and validation
  • Expiry checking with configurable warning thresholds
  • Batch processing for multiple certificates
  • Remote certificate fetching from hostnames
  • AI-powered security analysis with revocation checking
  • Resource usage monitoring and reporting
  • Static resources (config template, version, formats, status)
  • Guided prompts for certificate workflows

Server Lifecycle:

  1. Load configuration from file or defaults
  2. Initialize CRL cache cleanup with context
  3. Set up signal handling for graceful shutdown
  4. Build MCP server using ServerBuilder pattern
  5. Start stdio server with context cancellation support
  6. Wait for either server error or shutdown signal

Graceful Shutdown:

  • Responds to SIGINT (Ctrl+C) and SIGTERM signals
  • Cancels context to stop CRL cache cleanup
  • Waits for server to stop cleanly
  • Returns context.Canceled error on signal-based shutdown

Error Handling:

  • Configuration errors: Wrapped with "config error" prefix
  • Server build errors: Wrapped with "failed to build server" prefix
  • Shutdown errors: Wrapped with "server shutdown" prefix

Types

type ADKTransportBuilder added in v0.4.8

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

ADKTransportBuilder helps construct MCP transports for ADK integration. This builder provides a fluent API for configuring and creating MCP transports that work with Google ADK's mcptoolset. It handles configuration loading, validation, and transport creation with proper error handling.

func NewADKTransportBuilder added in v0.4.8

func NewADKTransportBuilder() *ADKTransportBuilder

NewADKTransportBuilder creates a new ADK transport builder with default configuration. Initializes the builder with sensible defaults:

  • MCPConfigFile from MCP_X509_CONFIG_FILE environment variable
  • Version from version.Version
  • TransportType set to "inmemory"

Returns a builder ready for fluent configuration.

func (*ADKTransportBuilder) BuildTransport added in v0.4.8

func (b *ADKTransportBuilder) BuildTransport(ctx context.Context) (mcptransport.Transport, error)

BuildTransport creates an MCP server for ADK integration. This returns an mcp.Transport interface that can be used directly with ADK's [mcptoolset]. The implementation bridges between mark3labs/mcp-go server and Official MCP SDK transport expectations.

The method validates configuration, loads MCP settings, builds the server with certificate tools, and creates the transport with sampling support.

Example usage:

transport, err := NewADKTransportBuilder().WithInMemoryTransport().BuildTransport(ctx)
if err != nil {
	log.Fatal(err)
}
// Use transport with ADK mcptoolset
mcpToolSet, err := mcptoolset.New(mcptoolset.Config{Transport: transport})

func (*ADKTransportBuilder) ValidateConfig added in v0.4.8

func (b *ADKTransportBuilder) ValidateConfig() error

ValidateConfig validates the transport builder configuration. Checks that all required settings are present and supported. Currently only validates transport type - returns error for unsupported types.

func (*ADKTransportBuilder) WithInMemoryTransport added in v0.4.8

func (b *ADKTransportBuilder) WithInMemoryTransport() *ADKTransportBuilder

WithInMemoryTransport configures in-memory transport (connects directly to handlers). Sets the transport type to "inmemory" for direct handler communication. This is the default and currently the only supported transport type.

func (*ADKTransportBuilder) WithMCPConfig added in v0.4.8

func (b *ADKTransportBuilder) WithMCPConfig(configFile string) *ADKTransportBuilder

WithMCPConfig sets the MCP server configuration file path. Specifies the path to the JSON configuration file containing MCP server settings. If not set, uses the MCP_X509_CONFIG_FILE environment variable.

func (*ADKTransportBuilder) WithVersion added in v0.4.8

func (b *ADKTransportBuilder) WithVersion(version string) *ADKTransportBuilder

WithVersion sets the MCP server version. Overrides the default version string that will be reported by the MCP server.

type ADKTransportConfig added in v0.4.8

type ADKTransportConfig struct {
	// MCP server configuration
	MCPConfigFile string
	Version       string

	// Transport type: "inmemory"
	TransportType string
}

ADKTransportConfig holds configuration for creating MCP transports for ADK integration. This struct contains all necessary settings to build MCP transports that are compatible with Google ADK's mcptoolset.

Fields:

  • MCPConfigFile: Path to the MCP server configuration file (defaults to MCP_X509_CONFIG_FILE env var)
  • Version: Server version string (defaults to version.Version)
  • TransportType: Type of transport to create ("inmemory" supported)

Example usage with ADK:

transport, err := NewADKTransportBuilder().WithInMemoryTransport().BuildTransport(ctx)
if err != nil {
	log.Fatal(err)
}
mcpToolSet, err := mcptoolset.New(mcptoolset.Config{Transport: transport})

type ADKTransportConnection added in v0.4.8

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

ADKTransportConnection wraps InMemoryTransport for ADK SDK compatibility.

This struct implements the official MCP SDK's Connection interface, providing JSON-RPC message encoding/decoding and session management for seamless ADK integration.

Fields:

  • transport: The underlying InMemoryTransport instance

func (*ADKTransportConnection) Close added in v0.4.8

func (c *ADKTransportConnection) Close() error

Close implements mcptransport.Connection.Close. Delegates to the underlying transport's Close method for cleanup.

func (*ADKTransportConnection) Read added in v0.4.8

Read implements mcptransport.Connection.Read. Reads and decodes a JSON-RPC message from the underlying transport. Uses the official MCP SDK's DecodeMessage for proper message parsing.

func (*ADKTransportConnection) SessionID added in v0.4.8

func (c *ADKTransportConnection) SessionID() string

SessionID implements mcptransport.Connection.SessionID. Returns a static session identifier for this in-memory transport.

TODO: Do we need a unique session ID that uses a cryptographic mechanism?

func (*ADKTransportConnection) Write added in v0.4.8

Write implements mcptransport.Connection.Write. Encodes and sends a JSON-RPC message through the underlying transport. Uses the official MCP SDK's EncodeMessage for proper message serialization.

type CLIFramework added in v0.5.5

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

CLIFramework integrates Cobra CLI with MCP server capabilities. It provides a unified interface for both CLI operations and MCP server functionality.

The CLIFramework serves as a bridge between command-line interface patterns and MCP server operations, enabling users to interact with certificate tools through both traditional CLI commands and MCP protocol communication.

Key features:

  • Dynamic executable naming based on actual binary path (not hardcoded)
  • Gopls-style --instructions flag for displaying certificate operation workflows
  • Configuration file support via --config flag or MCP_X509_CONFIG_FILE environment variable
  • Default MCP server startup when no arguments are provided
  • Graceful shutdown handling with signal interception

Fields:

  • configFile: Path to the MCP server configuration file. Can be set via --config flag or defaults to empty string for environment variable fallback.
  • config: Server configuration containing AI settings, timeouts, and other options. Loaded from configFile or defaults when not specified.
  • embed: Embedded filesystem interface for static resources and templates. Used for accessing embedded documentation, prompts, and resource files.
  • version: Server version string for identification and User-Agent headers. Displayed in CLI --version flag and used in HTTP requests.
  • certManager: Certificate encoding/decoding operations interface. Handles PEM/DER format conversions and multiple certificate parsing.
  • chainResolver: Certificate chain creation and management interface. Provides methods for building certificate chains from leaf certificates.
  • tools: List of tool definitions without configuration requirements. These tools operate independently without needing server config access.
  • toolsWithConfig: List of tool definitions that require configuration access. These tools receive the server Config parameter for AI API keys or timeouts.
  • resources: List of static and dynamic resources provided by the server. Resources like documentation or status information accessible via MCP protocol.
  • resourcesWithEmbed: List of resources that require embedded filesystem access. Resources that need to load templates or documentation from embedded files.
  • prompts: List of predefined prompts for guided workflows. Prompts for certificate analysis, expiry monitoring, security audits, etc.
  • promptsWithEmbed: List of prompts that require embedded filesystem access. Prompts that load dynamic content from embedded templates.
  • samplingHandler: Handler for bidirectional AI communication and streaming responses. Enables real-time AI analysis of certificates with streaming token callbacks.
  • instructions: Server instructions for MCP clients describing capabilities and behavior. Instructions sent during MCP initialization handshake.
  • populateCache: Whether to populate metadata cache for resource handlers. When enabled, resource handlers can access cached tool/prompt/resource metadata.

This struct enables seamless integration between CLI and MCP server operations, providing both traditional command-line usage and modern MCP protocol support.

func NewCLIFramework added in v0.5.5

func NewCLIFramework(configFile string, deps ServerDependencies) *CLIFramework

NewCLIFramework creates a new CLI framework instance with MCP server integration. It initializes the framework with all necessary dependencies for both CLI and MCP operations.

The constructor performs dependency injection by accepting a configFile path and ServerDependencies struct containing all required components. This approach enables loose coupling and testability while ensuring all framework components are properly initialized with their dependencies.

Configuration loading is deferred until runtime (in BuildRootCommand or startMCPServer) to allow CLI flag overrides and environment variable fallbacks.

Parameters:

  • configFile: Path to the MCP server configuration file. Can be overridden via --config flag or MCP_X509_CONFIG_FILE environment variable. Pass empty string to use environment variable or default configuration.
  • deps: Server dependencies containing all required components for MCP server operation. Includes certificate managers, chain resolvers, tools, resources, prompts, and handlers.

Returns:

  • *CLIFramework: Initialized CLI framework ready for building commands.

The returned framework can be used to build Cobra commands and start MCP servers, providing unified access to certificate operations through both CLI and MCP protocols.

Example usage:

deps := ServerDependencies{
    Version: "1.0.0",
    Config: &Config{...},
    CertManager: &DefaultCertManager{},
    // ... other dependencies
}
framework := NewCLIFramework("config.json", deps)
cmd := framework.BuildRootCommand()

This constructor enables clean separation between configuration and initialization, allowing the framework to be configured at startup time rather than compile time.

func (*CLIFramework) BuildRootCommand added in v0.5.5

func (cf *CLIFramework) BuildRootCommand() *cobra.Command

BuildRootCommand creates the root Cobra command with integrated MCP server capabilities. It sets up the CLI structure and provides access to MCP server functionality through subcommands.

The command is designed to be flexible and user-friendly:

  • Uses dynamic executable naming based on os.Args[0] to match the actual binary name
  • Provides gopls-style --instructions flag for displaying certificate operation workflows
  • Includes --config flag for specifying MCP server configuration file
  • Defaults to starting MCP server when no arguments are provided (no server subcommand needed)
  • Supports --help and --version flags automatically via Cobra

Command behavior:

  • With --instructions: Displays formatted workflows and exits
  • With arguments: Executes the specified subcommand (if any)
  • Without arguments: Starts MCP server directly (default behavior)

The root command serves as the main entry point for both CLI operations and MCP server startup, providing a unified interface that adapts to different usage patterns.

Returns:

  • *cobra.Command: Root command with MCP server integration.

The returned command can be executed directly or used as a parent for subcommands. When executed, it handles the --instructions flag, loads configuration, and starts the MCP server with proper signal handling and graceful shutdown.

Example usage:

framework := NewCLIFramework("config.json", deps)
rootCmd := framework.BuildRootCommand()
if err := rootCmd.Execute(); err != nil {
    log.Fatal(err)
}

This method encapsulates the CLI-MCP integration logic, making it easy to create professional command-line applications that also serve as MCP servers.

type CertificateManager

type CertificateManager interface {
	Decode(data []byte) (*x509.Certificate, error)
	DecodeMultiple(data []byte) ([]*x509.Certificate, error)
	EncodePEM(cert *x509.Certificate) []byte
	EncodeMultiplePEM(certs []*x509.Certificate) []byte
	EncodeDER(cert *x509.Certificate) []byte
	EncodeMultipleDER(certs []*x509.Certificate) []byte
}

CertificateManager defines the interface for certificate operations. It provides methods for encoding and decoding certificates in various formats.

Methods:

  • Decode: Parses a single certificate from PEM or DER data
  • DecodeMultiple: Parses multiple certificates from concatenated PEM data
  • EncodePEM: Encodes a certificate to PEM format
  • EncodeMultiplePEM: Encodes multiple certificates to concatenated PEM format
  • EncodeDER: Encodes a certificate to DER format
  • EncodeMultipleDER: Encodes multiple certificates to concatenated DER format

Example usage:

cert, err := manager.Decode(pemData)
if err != nil {
    return err
}
pemBytes := manager.EncodePEM(cert)

type ChainResolver

type ChainResolver interface {
	New(cert *x509.Certificate, version string) *x509chain.Chain
}

ChainResolver defines the interface for certificate chain operations. It provides methods to create and manage certificate chains for validation.

Methods:

  • New: Creates a new certificate chain from a leaf certificate and version string

Example usage:

resolver := &DefaultChainResolver{}
chain := resolver.New(leafCert, "1.0.0")

type Config

type Config struct {
	// Defaults: Default settings for certificate chain operations
	Defaults struct {
		// WarnDays: Number of days before expiry to show warnings
		WarnDays int `json:"warnDays" yaml:"warnDays"`
		// Timeout: Default timeout in seconds for operations
		Timeout int `json:"timeoutSeconds" yaml:"timeoutSeconds"`
		// BatchConcurrency: Maximum concurrent goroutines for batch processing
		BatchConcurrency int `json:"batchConcurrency" yaml:"batchConcurrency"`
	} `json:"defaults" yaml:"defaults"`

	// AI: Configuration for sampling/LLM integration
	AI struct {
		// APIKey: API key for AI service authentication (can also be set via X509_AI_APIKEY env var)
		APIKey string `json:"apiKey,omitempty" yaml:"apiKey,omitempty"`
		// Endpoint: API endpoint URL for AI service (defaults to xAI)
		Endpoint string `json:"endpoint,omitempty" yaml:"endpoint,omitempty"`
		// Model: Default AI model to use for certificate analysis
		Model string `json:"model,omitempty" yaml:"model,omitempty"`
		// Timeout: API timeout in seconds for AI requests
		Timeout int `json:"timeout,omitempty" yaml:"timeout,omitempty"`
		// MaxTokens: Maximum tokens for AI analysis responses
		MaxTokens int `json:"maxTokens,omitempty" yaml:"maxTokens,omitempty"`
		// Temperature: Sampling temperature for AI responses (0.0 to 1.0)
		Temperature float64 `json:"temperature,omitempty" yaml:"temperature,omitempty"`
	} `json:"ai" yaml:"ai"`
}

Config represents the MCP server configuration structure. It contains default settings for certificate operations and AI integration parameters.

The configuration can be loaded from a JSON or YAML file specified by the MCP_X509_CONFIG_FILE environment variable, with defaults applied for any missing values. Supported file extensions: .json, .yaml, .yml

type DefaultChainResolver

type DefaultChainResolver struct{}

DefaultChainResolver implements ChainResolver using the x509chain.New function. It provides a default implementation that creates certificate chains using the internal chain package.

This implementation is used when no custom chain resolver is provided to the server builder.

func (DefaultChainResolver) New

func (d DefaultChainResolver) New(cert *x509.Certificate, version string) *x509chain.Chain

New creates a new certificate chain using the x509chain.New function. It takes a leaf certificate and version string to initialize the chain.

Parameters:

  • cert: The leaf certificate to start the chain from
  • version: Version string for the chain (used for User-Agent headers)

Returns:

  • A pointer to the newly created certificate chain

The returned chain can be used for fetching additional certificates, validating the chain, and checking revocation status.

type DefaultSamplingHandler

type DefaultSamplingHandler struct {

	// TokenCallback: Optional callback function called for each streaming token (enables real-time updates)
	TokenCallback func(string) // Callback for streaming tokens
	// contains filtered or unexported fields
}

DefaultSamplingHandler provides configurable AI API integration for bidirectional communication

func NewDefaultSamplingHandler

func NewDefaultSamplingHandler(config *Config, version string) *DefaultSamplingHandler

NewDefaultSamplingHandler creates a new sampling handler with configurable AI settings.

It initializes a DefaultSamplingHandler with AI API configuration, including API key, endpoint, model, and timeout settings from the provided config. The handler is used for bidirectional AI communication in MCP sampling.

Parameters:

  • config: Server configuration containing AI API settings
  • version: Application version string for user-agent headers

Returns:

  • *DefaultSamplingHandler: New initialized sampling handler

func (*DefaultSamplingHandler) CreateMessage

CreateMessage handles sampling requests by calling the configured AI API.

It processes an MCP CreateMessageRequest, converts messages to OpenAI format, sends them to the configured AI API, and streams the response back. Handles both successful streaming responses and error cases.

Parameters:

  • ctx: Context for cancellation and timeout handling
  • request: MCP create message request with messages, parameters, and preferences

Returns:

  • *mcp.CreateMessageResult: Response containing generated message and metadata
  • error: API call errors, parsing errors, or configuration issues

The method uses buffer pooling for efficient memory usage and supports real-time token streaming via the TokenCallback if configured.

type InMemoryTransport added in v0.4.8

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

InMemoryTransport implements the ADK SDK mcp.Transport interface. It bridges between Official MCP SDK transport expectations and mark3labs/mcp-go server. This transport enables in-memory communication between MCP clients and servers, supporting JSON-RPC message passing, sampling requests, and graceful shutdown.

Key features:

  • Channel-based message passing for thread-safe communication
  • Sampling handler support for AI model interactions
  • Context-aware cancellation and graceful shutdown

func NewInMemoryTransport added in v0.4.8

func NewInMemoryTransport(ctx context.Context) *InMemoryTransport

NewInMemoryTransport creates a new in-memory transport for MCP communication.

This constructor creates an InMemoryTransport that implements the official MCP SDK's Transport interface. It's designed for seamless integration with ADK's mcptoolset.New expectations and provides channel-based message passing with full context cancellation support for graceful shutdown.

The transport uses buffered channels to prevent blocking and supports:

  • Thread-safe message passing between client and server
  • Context-aware cancellation for clean shutdown
  • Sampling handler integration for AI-powered features

Parameters:

  • ctx: Parent context for lifecycle management and cancellation

Returns:

  • *InMemoryTransport: Initialized transport ready for server connection

Example usage:

transport := NewInMemoryTransport(ctx)
defer transport.Close()

// Connect server
err := transport.ConnectServer(ctx, server)

// Use with ADK
mcpToolSet, err := mcptoolset.New(mcptoolset.Config{Transport: transport})

func (*InMemoryTransport) Close added in v0.4.8

func (t *InMemoryTransport) Close() error

Close implements graceful shutdown of the in-memory transport.

It performs a coordinated shutdown by:

  1. Canceling the transport context to signal all operations to stop
  2. Waiting for the message processing loop to terminate (processWg)
  3. Waiting for all active goroutines to complete (shutdownWg)

Channels are intentionally not closed to prevent panics in concurrent operations. It ensures all goroutines exit cleanly without race conditions.

Returns:

  • error: Always nil (shutdown is synchronous)

Thread Safety: Safe to call concurrently, but typically called once during shutdown.

func (*InMemoryTransport) Connect added in v0.4.8

Connect implements ADK SDK mcp.Transport interface. Returns a connection wrapper that adapts this transport for ADK usage. The connection handles JSON-RPC message encoding/decoding automatically.

func (*InMemoryTransport) ConnectServer added in v0.4.8

func (t *InMemoryTransport) ConnectServer(ctx context.Context, srv *server.MCPServer, opts ...server.StdioOption) error

ConnectServer connects a mark3labs MCP server to this transport using StdioServer. This method enables direct in-memory communication by piping the ADK transport channels directly to the StdioServer's input/output streams. This avoids manual JSON-RPC bridging and leverages the server's native handling.

The server runs in a separate goroutine and can be cancelled via context. Options can be passed to configure the StdioServer behavior.

func (*InMemoryTransport) ReadMessage added in v0.4.8

func (t *InMemoryTransport) ReadMessage() ([]byte, error)

ReadMessage implements mcp.Transport.ReadMessage. For ADK compatibility, this should return JSON-RPC messages. Uses channel-based message passing for in-memory communication. This method blocks until a message is available or the context is cancelled. Returns io.EOF when the context is cancelled.

func (*InMemoryTransport) SendJSONRPCNotification added in v0.4.8

func (t *InMemoryTransport) SendJSONRPCNotification(method string, params any)

SendJSONRPCNotification sends a JSON-RPC notification asynchronously.

This method sends server-initiated notifications such as streaming progress updates, sampling tokens, or other events that don't require a response. The notification is sent asynchronously and will not block if the receive channel is full (the notification will be dropped in that case).

Common use cases:

  • Streaming AI token responses during certificate analysis
  • Progress updates for long-running certificate operations
  • Status notifications for certificate validation results

Parameters:

  • method: The JSON-RPC method name for the notification
  • params: The notification parameters (can be any serializable type)

func (*InMemoryTransport) SetSamplingHandler added in v0.4.8

func (t *InMemoryTransport) SetSamplingHandler(handler client.SamplingHandler)

SetSamplingHandler sets the sampling handler for AI model interactions.

The sampling handler is responsible for processing AI model requests (such as CreateMessage calls) that originate from the MCP server. This enables bidirectional communication for certificate analysis and other AI-powered features.

This method is thread-safe and can be called concurrently with other transport operations without requiring explicit synchronization.

Parameters:

  • handler: The sampling handler implementation for AI requests

func (*InMemoryTransport) WriteMessage added in v0.4.8

func (t *InMemoryTransport) WriteMessage(data []byte) error

WriteMessage implements mcp.Transport.WriteMessage. For ADK compatibility, this should accept JSON-RPC messages. Uses channel-based message passing for in-memory communication. Returns an error if the context is cancelled or the channel is full.

type PromptHandler

type PromptHandler = func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error)

PromptHandler defines the signature for prompt handlers that provide predefined prompts. It processes prompt requests and returns prompt content with optional arguments.

Parameters:

  • ctx: Context for cancellation and timeout handling
  • request: The MCP prompt request containing the prompt name and arguments

Returns:

  • The prompt result containing messages and description, or an error if the prompt is not found

Prompt handlers are used for guided workflows like certificate analysis or security audits.

type PromptHandlerWithEmbed added in v0.5.3

type PromptHandlerWithEmbed = func(ctx context.Context, request mcp.GetPromptRequest, embed templates.EmbedFS) (*mcp.GetPromptResult, error)

PromptHandlerWithEmbed defines prompt handlers that require access to the embedded filesystem. It extends PromptHandler to include an EmbedFS parameter for accessing embedded templates.

Parameters:

  • ctx: Context for cancellation and timeout handling
  • request: The MCP prompt request containing the prompt name and arguments
  • embed: The embedded filesystem interface for accessing templates and documentation

Returns:

  • The prompt result containing messages and description, or an error if the prompt is not found

This type is used for prompts that need to access embedded templates for dynamic content generation.

type ResourceHandler

type ResourceHandler = func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)

ResourceHandler defines the signature for resource handlers that provide static or dynamic resources. It processes resource read requests and returns the resource contents.

Parameters:

  • ctx: Context for cancellation and timeout handling
  • request: The MCP resource read request containing the resource URI

Returns:

  • A slice of resource contents or an error if the resource cannot be read

Resource handlers can return multiple content items for complex resources.

type ResourceHandlerWithEmbed added in v0.5.3

type ResourceHandlerWithEmbed = func(ctx context.Context, request mcp.ReadResourceRequest, embed templates.EmbedFS) ([]mcp.ResourceContents, error)

ResourceHandlerWithEmbed defines resource handlers that require access to the embedded filesystem. It extends ResourceHandler to include an EmbedFS parameter for accessing embedded templates.

Parameters:

  • ctx: Context for cancellation and timeout handling
  • request: The MCP resource read request containing the resource URI
  • embed: The embedded filesystem interface for accessing templates and documentation

Returns:

  • A slice of resource contents or an error if the resource cannot be read

This type is used for resources that need to access embedded templates like documentation.

type ResourceUsageData added in v0.4.3

type ResourceUsageData struct {
	Timestamp      string         `json:"timestamp"`
	MemoryUsage    map[string]any `json:"memory_usage"`
	GCStats        map[string]any `json:"gc_stats"`
	SystemInfo     map[string]any `json:"system_info"`
	DetailedMemory map[string]any `json:"detailed_memory,omitempty"`
	CRLCache       map[string]any `json:"crl_cache,omitempty"`
}

ResourceUsageData represents the complete resource usage information.

ResourceUsageData contains comprehensive statistics about the MCP server's current resource utilization, including memory usage, garbage collection metrics, system information, and optionally detailed memory statistics and CRL cache metrics.

Fields:

  • Timestamp: RFC3339-formatted timestamp when data was collected
  • MemoryUsage: Basic memory statistics in MB (heap, stack, etc.)
  • GCStats: Garbage collection cycle counts and CPU usage
  • SystemInfo: Go runtime and system information
  • DetailedMemory: Optional detailed memory statistics (allocations, pauses, etc.)
  • CRLCache: Optional CRL cache metrics (hits, misses, evictions, etc.)

This struct is used by the get_resource_usage MCP tool to provide comprehensive monitoring data for performance analysis and debugging.

func CollectResourceUsage added in v0.4.3

func CollectResourceUsage(detailed bool) *ResourceUsageData

CollectResourceUsage gathers current resource usage statistics.

CollectResourceUsage collects comprehensive resource usage data from the Go runtime and CRL cache. It provides both basic and detailed statistics depending on the detailed parameter.

Parameters:

  • detailed: If true, includes detailed memory stats and CRL cache metrics

Returns:

  • *ResourceUsageData: Complete resource usage information

The function collects:

  • Memory statistics from runtime.ReadMemStats()
  • System information from runtime package
  • GC statistics and CPU usage
  • CRL cache metrics when detailed=true (hits, misses, evictions, etc.)

Memory values are converted to MB for readability, and timestamps are formatted as RFC3339. CRL cache hit rate is calculated as a percentage.

type SamplingRequest

type SamplingRequest struct {
	Messages     []mcp.SamplingMessage
	SystemPrompt string
	MaxTokens    int
	Temperature  float64
}

SamplingRequest represents a request for AI sampling from a handler.

It contains all the parameters needed to make an AI API call, including messages, system prompt, and generation parameters.

Fields:

  • Messages: Array of MCP sampling messages for the conversation
  • SystemPrompt: Optional system prompt to set context
  • MaxTokens: Maximum number of tokens to generate
  • Temperature: Sampling temperature (0.0 to 2.0, higher = more random)

type SamplingRequestMarker

type SamplingRequestMarker struct {
	// Request: The sampling request containing messages and parameters
	Request SamplingRequest
}

SamplingRequestMarker is a special result that indicates a sampling request should be made.

It wraps a SamplingRequest to distinguish it from regular message results in the AI processing pipeline.

type ServerBuilder

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

ServerBuilder helps construct the MCP server with proper dependencies using a fluent interface. It implements the builder pattern to configure and create MCP servers with all required components.

The builder allows chaining configuration methods and provides default implementations for common dependencies. Use NewServerBuilder() to create an instance, chain configuration methods, and call Build() to create the server.

Example:

builder := NewServerBuilder().
    WithConfig(config).
    WithVersion("1.0.0").
    WithDefaultTools().
    WithSampling(samplingHandler)
server, err := builder.Build()

func NewServerBuilder

func NewServerBuilder() *ServerBuilder

NewServerBuilder creates a new server builder with default empty dependencies. It initializes a ServerBuilder instance that can be configured using the fluent interface methods.

Returns:

  • A pointer to a new ServerBuilder instance ready for configuration

The returned builder has no dependencies configured and should be chained with configuration methods before calling Build().

func (*ServerBuilder) Build

func (b *ServerBuilder) Build() (*server.MCPServer, error)

Build creates the MCP server with all configured dependencies. It validates the configuration and constructs a fully configured MCP server instance.

Returns:

  • A pointer to the configured MCPServer instance
  • An error if the configuration is invalid or server creation fails

The method enables sampling if a sampling handler was provided, registers all tools, resources, and prompts, and returns a ready-to-use server. The server will handle MCP protocol communication and route requests to the appropriate handlers.

func (*ServerBuilder) BuildCLI added in v0.5.5

func (b *ServerBuilder) BuildCLI() (*CLIFramework, error)

BuildCLI creates a CLI framework with integrated MCP server capabilities. It constructs a CLIFramework instance that provides both command-line interface and MCP server functionality, allowing unified access to certificate operations.

Returns:

  • *CLIFramework: CLI framework with MCP server integration
  • error: Configuration or initialization errors

The CLI framework enables running certificate operations through both CLI commands and MCP server protocols, with the --instructions flag providing usage workflows similar to gopls.

TODO: Extend BuildCLI() with comprehensive integration capabilities beyond dual CLI+MCP architecture. This would enable advanced features and integrations for enhanced certificate management.

func (*ServerBuilder) WithCertManager

func (b *ServerBuilder) WithCertManager(cm CertificateManager) *ServerBuilder

WithCertManager sets the certificate manager for encoding and decoding operations. It configures the server with a CertificateManager implementation for PEM/DER operations.

Parameters:

  • cm: The certificate manager implementation (must implement CertificateManager interface)

Returns:

  • The ServerBuilder instance for method chaining

If not set, certificate encoding/decoding operations may not be available. The default implementation uses the internal certs package.

func (*ServerBuilder) WithChainResolver

func (b *ServerBuilder) WithChainResolver(cr ChainResolver) *ServerBuilder

WithChainResolver sets the chain resolver for creating certificate chains. It configures the server with a ChainResolver implementation for chain operations.

Parameters:

  • cr: The chain resolver implementation (must implement ChainResolver interface)

Returns:

  • The ServerBuilder instance for method chaining

If not set, certificate chain resolution operations may not be available. The default implementation uses the internal chain package.

func (*ServerBuilder) WithConfig

func (b *ServerBuilder) WithConfig(config *Config) *ServerBuilder

WithConfig sets the server configuration containing AI settings and other options. It configures the server with the provided Config struct.

Parameters:

  • config: Pointer to the server configuration (can be nil for basic functionality)

Returns:

  • The ServerBuilder instance for method chaining

The configuration includes AI API settings, timeouts, and other server options. If config is nil, some features like AI analysis may not be available.

func (*ServerBuilder) WithDefaultTools

func (b *ServerBuilder) WithDefaultTools() *ServerBuilder

WithDefaultTools adds the default X509 certificate tools to the server. It automatically registers all standard certificate-related tools using createTools.

Returns:

  • The ServerBuilder instance for method chaining

This includes tools for certificate chain resolution, validation, expiry checking, remote certificate fetching, and AI-powered analysis. The tools are added to both the regular tools list and tools-with-config list as appropriate.

func (*ServerBuilder) WithEmbed

func (b *ServerBuilder) WithEmbed(embed templates.EmbedFS) *ServerBuilder

WithEmbed sets the embedded filesystem for static resources and templates. It configures the server with an embedded filesystem containing templates and documentation.

Parameters:

Returns:

  • The ServerBuilder instance for method chaining

The embedded filesystem is used to serve static resources like certificate format documentation and analysis templates. If not set, some resources may not be available.

func (*ServerBuilder) WithEmbeddedPrompts added in v0.5.3

func (b *ServerBuilder) WithEmbeddedPrompts(prompts ...ServerPromptWithEmbed) *ServerBuilder

WithEmbeddedPrompts adds prompts that require embedded filesystem access to the MCP server. It registers prompts that need access to embedded templates for dynamic content generation.

Parameters:

  • prompts: Variable number of ServerPromptWithEmbed structs containing prompt specs and handlers

Returns:

  • The ServerBuilder instance for method chaining

Prompts added with this method receive access to the embedded filesystem for loading templates and generating dynamic content.

func (*ServerBuilder) WithEmbeddedResources added in v0.5.3

func (b *ServerBuilder) WithEmbeddedResources(resources ...ServerResourceWithEmbed) *ServerBuilder

WithEmbeddedResources adds resources that require embedded filesystem access to the MCP server. It registers resources that need access to embedded templates or files.

Parameters:

  • resources: Variable number of ServerResourceWithEmbed structs containing resource specs and handlers

Returns:

  • The ServerBuilder instance for method chaining

Resources added with this method receive access to the embedded filesystem for accessing templates, documentation, or other embedded content.

func (*ServerBuilder) WithInstructions added in v0.5.1

func (b *ServerBuilder) WithInstructions(instructions string) *ServerBuilder

WithInstructions sets the server instructions for MCP clients. It configures the server with instructions that describe its capabilities and behavior.

Parameters:

  • instructions: The instruction text that will be provided to MCP clients

Returns:

  • The ServerBuilder instance for method chaining

Instructions help MCP clients understand how to interact with the server and what capabilities are available. They are sent during the MCP initialization handshake.

func (*ServerBuilder) WithPopulate added in v0.5.2

func (b *ServerBuilder) WithPopulate() *ServerBuilder

WithPopulate enables metadata cache population for resource handlers. It configures the server to populate the metadata cache with tool, prompt, and resource information that resource handlers can access dynamically.

Returns:

  • The ServerBuilder instance for method chaining

This should be called when using resource handlers that need access to server capabilities metadata. The cache is populated during the Build() method after all components are registered.

func (*ServerBuilder) WithPrompts

func (b *ServerBuilder) WithPrompts(prompts ...ServerPrompt) *ServerBuilder

WithPrompts adds predefined prompts to the MCP server for guided workflows. It registers prompts that provide structured interactions for common tasks.

Parameters:

  • prompts: Variable number of ServerPrompt structs containing prompt specs and handlers

Returns:

  • The ServerBuilder instance for method chaining

Prompts are used for workflows like certificate analysis or security audits, providing clients with predefined conversation starters and argument schemas.

func (*ServerBuilder) WithResources

func (b *ServerBuilder) WithResources(resources ...ServerResource) *ServerBuilder

WithResources adds static and dynamic resources to the MCP server. It registers resources that can be read by MCP clients using resource URIs.

Parameters:

  • resources: Variable number of ServerResource structs containing resource specs and handlers

Returns:

  • The ServerBuilder instance for method chaining

Resources can provide static content (like documentation) or dynamic content (like server status). Clients access resources using URIs like "info://version".

func (*ServerBuilder) WithSampling

func (b *ServerBuilder) WithSampling(handler client.SamplingHandler) *ServerBuilder

WithSampling adds a sampling handler for bidirectional AI communication. It configures the server to support AI-powered features like certificate analysis.

Parameters:

  • handler: The sampling handler implementation for AI API integration

Returns:

  • The ServerBuilder instance for method chaining

The sampling handler enables real-time AI analysis of certificates with streaming responses. If not set, AI-powered features will return static guidance messages.

func (*ServerBuilder) WithTools

func (b *ServerBuilder) WithTools(tools ...ToolDefinition) *ServerBuilder

WithTools adds tool definitions to the server that don't require configuration access. It registers multiple tools that can be called by MCP clients.

Parameters:

  • tools: Variable number of ToolDefinition structs containing tool specs and handlers

Returns:

  • The ServerBuilder instance for method chaining

Tools added with this method do not receive the server Config parameter. Use WithToolsWithConfig for tools that need configuration access.

func (*ServerBuilder) WithToolsWithConfig

func (b *ServerBuilder) WithToolsWithConfig(tools ...ToolDefinitionWithConfig) *ServerBuilder

WithToolsWithConfig adds tool definitions that require configuration access to the server. It registers multiple tools that receive the server Config parameter in their handlers.

Parameters:

  • tools: Variable number of ToolDefinitionWithConfig structs containing tool specs and handlers

Returns:

  • The ServerBuilder instance for method chaining

Tools added with this method receive access to server configuration like AI API keys. Use WithTools for tools that don't need configuration access.

func (*ServerBuilder) WithVersion

func (b *ServerBuilder) WithVersion(version string) *ServerBuilder

WithVersion sets the server version string used for identification and User-Agent headers. It configures the server with a version string that appears in logs and HTTP requests.

Parameters:

  • version: The server version string (e.g., "1.0.0" or "v1.2.3")

Returns:

  • The ServerBuilder instance for method chaining

The version is used in User-Agent headers for HTTP requests and server identification.

type ServerConfig

type ServerConfig struct {
	// Version: The server version string (e.g., "1.0.0")
	Version string
	// Config: Pointer to the server configuration containing AI and other settings
	Config *Config
	// Embed: Embedded filesystem for static resources like templates and documentation
	Embed templates.EmbedFS
}

ServerConfig holds configuration for the MCP server, including version, config, and embedded filesystem. It is used to initialize the server with necessary dependencies and settings.

Fields:

  • Version: The server version string (e.g., "1.0.0")
  • Config: Pointer to the server configuration containing AI and other settings
  • Embed: Embedded filesystem for static resources like templates and documentation

type ServerDependencies

type ServerDependencies struct {
	// Config: Server configuration containing AI settings and other options
	Config *Config
	// Embed: Embedded filesystem for static resources like templates and documentation
	Embed templates.EmbedFS
	// Version: Server version string for User-Agent headers and identification
	Version string
	// CertManager: Interface for certificate encoding/decoding operations
	CertManager CertificateManager
	// ChainResolver: Interface for creating certificate chains
	ChainResolver ChainResolver
	// Tools: List of tool definitions without configuration requirements
	Tools []ToolDefinition
	// ToolsWithConfig: List of tool definitions that need configuration access
	ToolsWithConfig []ToolDefinitionWithConfig
	// Resources: List of static and dynamic resources provided by the server
	Resources []ServerResource
	// ResourcesWithEmbed: List of resources that require embedded filesystem access
	ResourcesWithEmbed []ServerResourceWithEmbed
	// Prompts: List of predefined prompts for guided workflows
	Prompts []ServerPrompt
	// PromptsWithEmbed: List of prompts that require embedded filesystem access
	PromptsWithEmbed []ServerPromptWithEmbed
	// SamplingHandler: Handler for bidirectional AI communication and streaming responses
	SamplingHandler client.SamplingHandler // Added for bidirectional AI communication
	// Instructions: Server instructions for MCP clients describing capabilities and behavior
	Instructions string
	// PopulateCache: Whether to populate metadata cache for resource handlers
	PopulateCache bool
}

ServerDependencies holds all dependencies needed to create the MCP server. It consolidates all required components for server initialization using the builder pattern.

Fields:

  • Config: Server configuration containing AI settings and other options
  • Embed: Embedded filesystem for static resources like templates and documentation
  • Version: Server version string for User-Agent headers and identification
  • CertManager: Interface for certificate encoding/decoding operations
  • ChainResolver: Interface for creating certificate chains
  • Tools: List of tool definitions without configuration requirements
  • ToolsWithConfig: List of tool definitions that need configuration access
  • Resources: List of static and dynamic resources provided by the server
  • ResourcesWithEmbed: List of resources that require embedded filesystem access
  • Prompts: List of predefined prompts for guided workflows
  • PromptsWithEmbed: List of prompts that require embedded filesystem access
  • SamplingHandler: Handler for bidirectional AI communication and streaming responses
  • Instructions: Server instructions for MCP clients describing capabilities and behavior
  • PopulateCache: Whether to populate metadata cache for resource handlers

This struct is used internally by ServerBuilder and should not be instantiated directly.

type ServerPrompt added in v0.5.3

type ServerPrompt struct {
	// Prompt: The MCP prompt definition containing name, description, and arguments
	Prompt mcp.Prompt
	// Handler: The function that implements the prompt's logic
	Handler PromptHandler
}

ServerPrompt holds a prompt definition that doesn't require embedded filesystem access. It pairs an MCP prompt specification with its implementation function.

Fields:

  • Prompt: The MCP prompt definition containing name, description, and arguments
  • Handler: The function that implements the prompt's logic

This struct is used when registering prompts that don't need access to embedded templates.

type ServerPromptWithEmbed added in v0.5.3

type ServerPromptWithEmbed struct {
	// Prompt: The MCP prompt definition containing name, description, and arguments
	Prompt mcp.Prompt
	// Handler: The function that implements the prompt's logic with embed access
	Handler PromptHandlerWithEmbed
}

ServerPromptWithEmbed holds a prompt definition that requires embedded filesystem access. It pairs an MCP prompt specification with a handler that receives the embedded filesystem.

Fields:

  • Prompt: The MCP prompt definition containing name, description, and arguments
  • Handler: The function that implements the prompt's logic with embed access

This struct is used for prompts that need to access embedded templates for dynamic content generation.

type ServerResource added in v0.5.3

type ServerResource struct {
	// Resource: The MCP resource definition containing URI, name, description, and MIME type
	Resource mcp.Resource
	// Handler: The function that implements the resource's logic
	Handler ResourceHandler
}

ServerResource holds a resource definition that doesn't require embedded filesystem access. It pairs an MCP resource specification with its implementation function.

Fields:

  • Resource: The MCP resource definition containing URI, name, description, and MIME type
  • Handler: The function that implements the resource's logic

This struct is used when registering resources that don't need access to embedded templates.

type ServerResourceWithEmbed added in v0.5.3

type ServerResourceWithEmbed struct {
	// Resource: The MCP resource definition containing URI, name, description, and MIME type
	Resource mcp.Resource
	// Handler: The function that implements the resource's logic with embed access
	Handler ResourceHandlerWithEmbed
}

ServerResourceWithEmbed holds a resource definition that requires embedded filesystem access. It pairs an MCP resource specification with a handler that receives the embedded filesystem.

Fields:

  • Resource: The MCP resource definition containing URI, name, description, and MIME type
  • Handler: The function that implements the resource's logic with embed access

This struct is used for resources that need to access embedded templates like documentation.

type ToolDefinition

type ToolDefinition struct {
	// Tool: The MCP tool definition containing name, description, and input schema
	Tool mcp.Tool
	// Handler: The function that implements the tool's logic
	Handler ToolHandler
	// Role: Semantic role identifier for template generation (e.g., "chainResolver")
	Role string
}

ToolDefinition holds a tool definition that doesn't require configuration access. It pairs an MCP tool specification with its implementation function.

Fields:

  • Tool: The MCP tool definition containing name, description, and input schema
  • Handler: The function that implements the tool's logic
  • Role: Semantic role identifier for template generation (e.g., "chainResolver")

This struct is used when registering tools that don't require configuration access.

type ToolDefinitionWithConfig

type ToolDefinitionWithConfig struct {
	// Tool: The MCP tool definition containing name, description, and input schema
	Tool mcp.Tool
	// Handler: The function that implements the tool's logic with config access
	Handler ToolHandlerWithConfig
	// Role: Semantic role identifier for template generation (e.g., "expiryChecker")
	Role string
}

ToolDefinitionWithConfig holds a tool definition that requires configuration access. It pairs an MCP tool specification with a handler that receives server configuration.

Fields:

  • Tool: The MCP tool definition containing name, description, and input schema
  • Handler: The function that implements the tool's logic with config access
  • Role: Semantic role identifier for template generation (e.g., "expiryChecker")

This struct is used for tools that need configuration like AI API keys or timeouts. The handler receives a Config parameter in addition to the standard context and request.

type ToolHandler

type ToolHandler = func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

ToolHandler defines the signature for tool handlers that matches MCP server expectations. It processes tool calls and returns results.

Parameters:

  • ctx: Context for cancellation and timeout handling
  • request: The MCP tool call request containing arguments and metadata

Returns:

  • The tool execution result or an error if the tool failed

type ToolHandlerWithConfig

type ToolHandlerWithConfig = func(ctx context.Context, request mcp.CallToolRequest, config *Config) (*mcp.CallToolResult, error)

ToolHandlerWithConfig defines tool handlers that require access to server configuration. It extends ToolHandler to include a Config parameter for tools that need configuration data.

Parameters:

  • ctx: Context for cancellation and timeout handling
  • request: The MCP tool call request containing arguments and metadata
  • config: Pointer to the server configuration containing AI settings and other options

Returns:

  • The tool execution result or an error if the tool failed

This type is used for tools that need access to configuration like AI API keys or timeouts.

type TransportBuilder added in v0.4.8

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

TransportBuilder helps construct MCP transports for different integration scenarios.

This builder pattern implementation provides transport creation utilities for various integration layers (ADK, CLI, etc.). It wraps a ServerBuilder to create appropriate transport mechanisms for different use cases.

For in-memory scenarios, it builds the complete MCP server and returns a transport that can communicate with it directly.

Fields:

  • serverBuilder: The underlying ServerBuilder for MCP server construction

Example usage:

builder := NewTransportBuilder().
	WithConfig(config).
	WithVersion("1.0.0").
	WithDefaultTools()
transport, err := builder.BuildInMemoryTransport(ctx)

func NewTransportBuilder added in v0.4.8

func NewTransportBuilder() *TransportBuilder

NewTransportBuilder creates a new transport builder for MCP server construction.

It initializes a TransportBuilder with a new ServerBuilder instance, providing a fluent interface for configuring and building MCP transports. The builder pattern allows for flexible configuration of server settings, tools, and transport options before creating the final transport.

The builder supports fluent configuration methods like WithConfig(), WithVersion(), WithDefaultTools(), and finally BuildInMemoryTransport() to create an in-memory transport for ADK integration.

Returns:

  • *TransportBuilder: New builder instance ready for configuration

Example usage:

builder := NewTransportBuilder().
	WithConfig(config).
	WithVersion("1.0.0").
	WithDefaultTools()
transport, err := builder.BuildInMemoryTransport(ctx)

func (*TransportBuilder) BuildInMemoryTransport added in v0.4.8

func (tb *TransportBuilder) BuildInMemoryTransport(ctx context.Context) (mcptransport.Transport, error)

BuildInMemoryTransport creates an in-memory MCP transport for ADK integration. This follows the ADK pattern where mcp.NewInMemoryTransports creates paired client and server transports, server connects to server transport, and client transport is returned for use with [mcptoolset.New].

For our implementation using mark3labs/mcp-go, we create the server using ServerBuilder, then return a transport that can communicate with it.

Returns an error if server building or transport connection fails.

func (*TransportBuilder) WithConfig added in v0.4.8

func (tb *TransportBuilder) WithConfig(config *Config) *TransportBuilder

WithConfig sets the server configuration. Applies the provided configuration to the underlying server builder.

func (*TransportBuilder) WithDefaultTools added in v0.4.8

func (tb *TransportBuilder) WithDefaultTools() *TransportBuilder

WithDefaultTools adds the default X509 certificate tools. Registers all standard certificate chain resolution, validation, and analysis tools.

func (*TransportBuilder) WithVersion added in v0.4.8

func (tb *TransportBuilder) WithVersion(version string) *TransportBuilder

WithVersion sets the server version. Sets the version string that will be reported by the MCP server.

Directories

Path Synopsis
Package templates provides embedded filesystem access for MCP server template files.
Package templates provides embedded filesystem access for MCP server template files.

Jump to

Keyboard shortcuts

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