mcp

package
v0.1.0-alpha.9 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultRequestTimeout is the timeout for individual MCP JSON-RPC requests.
	DefaultRequestTimeout = 30 * time.Second

	// DefaultReadyPollInterval is the interval between readiness checks.
	DefaultReadyPollInterval = 500 * time.Millisecond

	// DefaultReadyTimeout is the overall timeout for server readiness.
	DefaultReadyTimeout = 30 * time.Second
)

Default timeouts for MCP transport clients.

View Source
const DefaultHealthCheckInterval = 30 * time.Second

DefaultHealthCheckInterval is the default interval between health checks.

View Source
const DefaultPingTimeout = 5 * time.Second

DefaultPingTimeout is the timeout for health check pings.

View Source
const MCPProtocolVersion = "2024-11-05"

MCPProtocolVersion is the MCP protocol version supported by this implementation.

View Source
const MaxRequestBodySize = 1 * 1024 * 1024

MaxRequestBodySize is the maximum allowed size for incoming JSON-RPC request bodies (1MB).

View Source
const ToolNameDelimiter = "__"

ToolNameDelimiter is the separator between agent name and tool name in prefixed tool names. Format: "agentname__toolname" Uses double underscore to be compatible with Claude Desktop's tool name validation: ^[a-zA-Z0-9_-]{1,64}$

Variables

This section is empty.

Functions

func ParsePrefixedTool

func ParsePrefixedTool(prefixed string) (agentName, toolName string, err error)

ParsePrefixedTool parses a prefixed tool name into agent and tool names.

func PrefixTool

func PrefixTool(agentName, toolName string) string

PrefixTool creates a prefixed tool name: "agent__tool"

Types

type AgentClient

type AgentClient interface {
	Name() string
	Initialize(ctx context.Context) error
	RefreshTools(ctx context.Context) error
	Tools() []Tool
	CallTool(ctx context.Context, name string, arguments map[string]any) (*ToolCallResult, error)
	IsInitialized() bool
	ServerInfo() ServerInfo
}

AgentClient is the interface for communicating with MCP agents.

type Capabilities

type Capabilities struct {
	Tools     *ToolsCapability     `json:"tools,omitempty"`
	Resources *ResourcesCapability `json:"resources,omitempty"`
	Prompts   *PromptsCapability   `json:"prompts,omitempty"`
}

Capabilities describes what the server/client can do.

type Client

type Client struct {
	RPCClient
	// contains filtered or unexported fields
}

Client communicates with a downstream MCP server.

func NewClient

func NewClient(name, endpoint string) *Client

NewClient creates a new MCP client for a downstream agent.

func (*Client) Endpoint

func (c *Client) Endpoint() string

Endpoint returns the agent endpoint.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping checks if the agent is reachable.

type ClientBase

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

ClientBase provides shared state and accessor methods for all AgentClient implementations. Embed this struct to get Tools(), IsInitialized(), ServerInfo(), and SetToolWhitelist().

func (*ClientBase) IsInitialized

func (b *ClientBase) IsInitialized() bool

IsInitialized returns whether the client has been initialized.

func (*ClientBase) ServerInfo

func (b *ClientBase) ServerInfo() ServerInfo

ServerInfo returns the server information.

func (*ClientBase) SetInitialized

func (b *ClientBase) SetInitialized(info ServerInfo)

SetInitialized marks the client as initialized with the given server info.

func (*ClientBase) SetToolWhitelist

func (b *ClientBase) SetToolWhitelist(tools []string)

SetToolWhitelist sets the list of allowed tool names. Only tools in this list will be returned by Tools() and RefreshTools(). An empty or nil list means all tools are allowed.

func (*ClientBase) SetTools

func (b *ClientBase) SetTools(tools []Tool)

SetTools updates the cached tools, applying the whitelist filter.

func (*ClientBase) Tools

func (b *ClientBase) Tools() []Tool

Tools returns the cached tool list.

type ClientInfo

type ClientInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ClientInfo contains information about the MCP client.

type Content

type Content struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

Content represents content in a tool response.

func NewTextContent

func NewTextContent(text string) Content

NewTextContent creates a text content item.

type Gateway

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

Gateway aggregates multiple MCP servers into a single endpoint.

func NewGateway

func NewGateway() *Gateway

NewGateway creates a new MCP gateway.

func (*Gateway) CallTool

func (g *Gateway) CallTool(ctx context.Context, name string, arguments map[string]any) (*ToolCallResult, error)

CallTool implements the ToolCaller interface, allowing components to call tools through the gateway without a direct reference to the router.

func (*Gateway) Close

func (g *Gateway) Close()

Close stops the cleanup goroutine and closes all agent client connections.

func (*Gateway) GetAgentAllowedServers

func (g *Gateway) GetAgentAllowedServers(agentName string) []config.ToolSelector

GetAgentAllowedServers returns the MCP servers an agent can access. Returns nil if the agent is not registered (allows all for backward compatibility).

func (*Gateway) GetHealthStatus

func (g *Gateway) GetHealthStatus(name string) *HealthStatus

GetHealthStatus returns the health status for a named MCP server. Returns nil if no health data is available.

func (*Gateway) HandleInitialize

func (g *Gateway) HandleInitialize(params InitializeParams) (*InitializeResult, error)

HandleInitialize handles the initialize request.

func (*Gateway) HandlePromptsGet

func (g *Gateway) HandlePromptsGet(params PromptsGetParams) (*PromptsGetResult, error)

HandlePromptsGet returns a specific prompt with argument substitution.

func (*Gateway) HandlePromptsList

func (g *Gateway) HandlePromptsList() (*PromptsListResult, error)

HandlePromptsList returns all active prompts as MCP Prompts.

func (*Gateway) HandleResourcesList

func (g *Gateway) HandleResourcesList() (*ResourcesListResult, error)

HandleResourcesList returns prompts as MCP Resources.

func (*Gateway) HandleResourcesRead

func (g *Gateway) HandleResourcesRead(params ResourcesReadParams) (*ResourcesReadResult, error)

HandleResourcesRead returns the content of a prompt resource.

func (*Gateway) HandleToolsCall

func (g *Gateway) HandleToolsCall(ctx context.Context, params ToolCallParams) (*ToolCallResult, error)

HandleToolsCall routes a tool call to the appropriate MCP server.

func (*Gateway) HandleToolsCallForAgent

func (g *Gateway) HandleToolsCallForAgent(ctx context.Context, agentName string, params ToolCallParams) (*ToolCallResult, error)

HandleToolsCallForAgent routes a tool call with agent access validation. This validates both server-level and tool-level access.

func (*Gateway) HandleToolsList

func (g *Gateway) HandleToolsList() (*ToolsListResult, error)

HandleToolsList returns all aggregated tools.

func (*Gateway) HandleToolsListForAgent

func (g *Gateway) HandleToolsListForAgent(agentName string) (*ToolsListResult, error)

HandleToolsListForAgent returns tools filtered by agent access permissions. This applies both server-level and tool-level filtering.

func (*Gateway) HasAgent

func (g *Gateway) HasAgent(name string) bool

HasAgent returns true if the named agent is registered with the gateway.

func (*Gateway) RefreshAllTools

func (g *Gateway) RefreshAllTools(ctx context.Context) error

RefreshAllTools refreshes tools from all registered MCP servers.

func (*Gateway) RegisterAgent

func (g *Gateway) RegisterAgent(name string, uses []config.ToolSelector)

RegisterAgent registers an agent and its allowed MCP servers with optional tool filtering.

func (*Gateway) RegisterMCPServer

func (g *Gateway) RegisterMCPServer(ctx context.Context, cfg MCPServerConfig) error

RegisterMCPServer registers and initializes an MCP server.

func (*Gateway) Router

func (g *Gateway) Router() *Router

Router returns the tool router.

func (*Gateway) ServerInfo

func (g *Gateway) ServerInfo() ServerInfo

ServerInfo returns the gateway server info.

func (*Gateway) SessionCount

func (g *Gateway) SessionCount() int

SessionCount returns the number of active sessions.

func (*Gateway) Sessions

func (g *Gateway) Sessions() *SessionManager

Sessions returns the session manager.

func (*Gateway) SetDockerClient

func (g *Gateway) SetDockerClient(cli dockerclient.DockerClient)

SetDockerClient sets the Docker client for stdio transport.

func (*Gateway) SetLogger

func (g *Gateway) SetLogger(logger *slog.Logger)

SetLogger sets the logger for gateway operations. If nil is passed, logging is disabled (default).

func (*Gateway) SetServerMeta

func (g *Gateway) SetServerMeta(cfg MCPServerConfig)

SetServerMeta stores metadata for an MCP server without connecting to it. This is used by tests and by internal registration paths that manage their own client connections.

func (*Gateway) SetVersion

func (g *Gateway) SetVersion(version string)

SetVersion sets the gateway version string.

func (*Gateway) StartCleanup

func (g *Gateway) StartCleanup(ctx context.Context)

StartCleanup starts periodic session cleanup. Call Close() to stop.

func (*Gateway) StartHealthMonitor

func (g *Gateway) StartHealthMonitor(ctx context.Context, interval time.Duration)

StartHealthMonitor starts periodic health checking for all registered MCP servers. It runs alongside StartCleanup and stops when the gateway context is cancelled.

func (*Gateway) Status

func (g *Gateway) Status() []MCPServerStatus

Status returns status of all registered MCP servers. Note: This only returns actual MCP servers, not A2A adapters or other clients added directly to the router.

func (*Gateway) UnregisterAgent

func (g *Gateway) UnregisterAgent(name string)

UnregisterAgent removes an agent's access configuration.

func (*Gateway) UnregisterMCPServer

func (g *Gateway) UnregisterMCPServer(name string)

UnregisterMCPServer removes an MCP server from the gateway.

type Handler

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

Handler provides HTTP handlers for the MCP gateway.

func NewHandler

func NewHandler(gateway *Gateway) *Handler

NewHandler creates a new MCP HTTP handler.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles MCP requests at /mcp.

type HealthStatus

type HealthStatus struct {
	Healthy     bool      // Whether the server is responding to pings
	LastCheck   time.Time // When the last health check ran
	LastHealthy time.Time // When the server was last seen healthy
	Error       string    // Error message if unhealthy (empty when healthy)
}

HealthStatus tracks the health state of a downstream MCP server.

type InitializeParams

type InitializeParams struct {
	ProtocolVersion string       `json:"protocolVersion"`
	ClientInfo      ClientInfo   `json:"clientInfo"`
	Capabilities    Capabilities `json:"capabilities"`
}

InitializeParams contains parameters for the initialize request.

type InitializeResult

type InitializeResult struct {
	ProtocolVersion string       `json:"protocolVersion"`
	ServerInfo      ServerInfo   `json:"serverInfo"`
	Capabilities    Capabilities `json:"capabilities"`
}

InitializeResult is the response to initialize.

type InputSchemaObject

type InputSchemaObject struct {
	Type       string              `json:"type"`
	Properties map[string]Property `json:"properties,omitempty"`
	Required   []string            `json:"required,omitempty"`
}

InputSchemaObject is a helper for building simple input schemas. Use this when creating tools programmatically (e.g., A2A skill adapters). For MCP tools received from servers, use json.RawMessage directly to preserve the full JSON Schema without loss.

type MCPPrompt

type MCPPrompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description,omitempty"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

MCPPrompt represents a prompt in the MCP prompts/list response.

type MCPResource

type MCPResource struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	MimeType    string `json:"mimeType,omitempty"`
}

MCPResource represents a resource in the resources/list response.

type MCPServerConfig

type MCPServerConfig struct {
	Name            string
	Transport       Transport
	Endpoint        string               // For HTTP/SSE transport
	ContainerID     string               // For Docker Stdio transport
	External        bool                 // True for external URL servers (no container)
	LocalProcess    bool                 // True for local process servers (no container)
	SSH             bool                 // True for SSH servers (remote process over SSH)
	OpenAPI         bool                 // True for OpenAPI-based servers
	Command         []string             // For local process or SSH transport
	WorkDir         string               // For local process transport
	Env             map[string]string    // For local process or SSH transport
	SSHHost         string               // SSH hostname (for SSH servers)
	SSHUser         string               // SSH username (for SSH servers)
	SSHPort         int                  // SSH port (for SSH servers, 0 = default 22)
	SSHIdentityFile string               // SSH identity file path (for SSH servers)
	OpenAPIConfig   *OpenAPIClientConfig // OpenAPI configuration (for OpenAPI servers)
	Tools           []string             // Tool whitelist (empty = all tools)
}

MCPServerConfig contains configuration for connecting to an MCP server.

type MCPServerStatus

type MCPServerStatus struct {
	Name         string     `json:"name"`
	Transport    Transport  `json:"transport"`
	Endpoint     string     `json:"endpoint,omitempty"`
	ContainerID  string     `json:"containerId,omitempty"`
	Initialized  bool       `json:"initialized"`
	ToolCount    int        `json:"toolCount"`
	Tools        []string   `json:"tools"`
	External     bool       `json:"external"`              // True for external URL servers
	LocalProcess bool       `json:"localProcess"`          // True for local process servers
	SSH          bool       `json:"ssh"`                   // True for SSH servers
	SSHHost      string     `json:"sshHost,omitempty"`     // SSH hostname
	OpenAPI      bool       `json:"openapi"`               // True for OpenAPI servers
	OpenAPISpec  string     `json:"openapiSpec,omitempty"` // OpenAPI spec location
	Healthy      *bool      `json:"healthy,omitempty"`     // Health check result (nil if not yet checked)
	LastCheck    *time.Time `json:"lastCheck,omitempty"`   // When last health check ran
	HealthError  string     `json:"healthError,omitempty"` // Error message if unhealthy
}

MCPServerStatus returns status information about registered MCP servers.

type OpenAPIClient

type OpenAPIClient struct {
	ClientBase
	// contains filtered or unexported fields
}

OpenAPIClient implements AgentClient by transforming OpenAPI operations to MCP tools. It parses an OpenAPI specification and converts each operation into an MCP tool, proxying tool calls to HTTP requests against the target API.

func NewOpenAPIClient

func NewOpenAPIClient(name string, cfg *OpenAPIClientConfig) (*OpenAPIClient, error)

NewOpenAPIClient creates an OpenAPI-based MCP client.

func (*OpenAPIClient) CallTool

func (c *OpenAPIClient) CallTool(ctx context.Context, name string, args map[string]any) (*ToolCallResult, error)

CallTool executes an OpenAPI operation.

func (*OpenAPIClient) Initialize

func (c *OpenAPIClient) Initialize(ctx context.Context) error

Initialize loads and parses the OpenAPI spec.

func (*OpenAPIClient) Name

func (c *OpenAPIClient) Name() string

Name returns the client name.

func (*OpenAPIClient) Ping

func (c *OpenAPIClient) Ping(ctx context.Context) error

Ping checks if the OpenAPI backend is reachable by making a HEAD request to the base URL.

func (*OpenAPIClient) RefreshTools

func (c *OpenAPIClient) RefreshTools(ctx context.Context) error

RefreshTools builds MCP tools from OpenAPI operations. OpenAPIClient has custom include/exclude filtering in addition to the whitelist, so it manages tool storage directly rather than using ClientBase.SetTools().

func (*OpenAPIClient) SetLogger

func (c *OpenAPIClient) SetLogger(logger *slog.Logger)

SetLogger sets the logger for this client.

type OpenAPIClientConfig

type OpenAPIClientConfig struct {
	Spec       string   // URL or local file path to OpenAPI spec
	BaseURL    string   // Override server URL from spec
	AuthType   string   // "bearer" or "header"
	AuthToken  string   // Resolved bearer token (from env)
	AuthHeader string   // Header name for header-based auth
	AuthValue  string   // Resolved header value (from env)
	Include    []string // Operation IDs to include
	Exclude    []string // Operation IDs to exclude
	NoExpand   bool     // If true, skip environment variable expansion in spec file
}

OpenAPIClientConfig contains configuration for an OpenAPI-backed MCP client.

type OpenAPIOperation

type OpenAPIOperation struct {
	Method       string
	Path         string
	PathParams   []string // Parameter names in path order (always required)
	QueryParams  map[string]*openapi3.Parameter
	HeaderParams map[string]*openapi3.Parameter
	RequestBody  *openapi3.RequestBodyRef
}

OpenAPIOperation holds parsed OpenAPI operation details for execution.

type Pingable

type Pingable interface {
	Ping(ctx context.Context) error
}

Pingable is an optional interface for AgentClients that support health checks. The health monitor uses type assertion to check if a client implements this.

type ProcessClient

type ProcessClient struct {
	RPCClient
	// contains filtered or unexported fields
}

ProcessClient communicates with an MCP server via a local process stdin/stdout.

func NewProcessClient

func NewProcessClient(name string, command []string, workDir string, env map[string]string) *ProcessClient

NewProcessClient creates a new process-based MCP client. The command is executed with the given working directory and environment. Environment variables are merged with the current process environment.

func (*ProcessClient) Close

func (c *ProcessClient) Close() error

Close terminates the process gracefully. Sends SIGTERM, waits up to 5 seconds, then sends SIGKILL if still running.

func (*ProcessClient) Connect

func (c *ProcessClient) Connect(ctx context.Context) error

Connect starts the process and attaches to its stdin/stdout.

func (*ProcessClient) Ping

func (c *ProcessClient) Ping(ctx context.Context) error

Ping checks if the process is alive by verifying it's still running and sending a JSON-RPC ping.

func (*ProcessClient) Reconnect

func (c *ProcessClient) Reconnect(ctx context.Context) error

Reconnect terminates the existing process and starts a new one, including the MCP handshake and tool refresh. Thread-safe: concurrent callers will block until reconnection completes.

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

PromptArgument describes a prompt parameter.

type PromptArgumentData

type PromptArgumentData struct {
	Name        string
	Description string
	Required    bool
	Default     string
}

PromptArgumentData describes a prompt argument with default value support.

type PromptData

type PromptData struct {
	Name        string
	Description string
	Content     string
	Arguments   []PromptArgumentData
}

PromptData contains prompt information used by the MCP protocol layer.

type PromptMessage

type PromptMessage struct {
	Role    string  `json:"role"` // "user" or "assistant"
	Content Content `json:"content"`
}

PromptMessage represents a message in a prompts/get response.

type PromptProvider

type PromptProvider interface {
	ListPromptData() []PromptData
	GetPromptData(name string) (*PromptData, error)
}

PromptProvider is an optional interface for AgentClients that manage prompts. The gateway uses type assertion to detect prompt-capable clients and serve the MCP prompts/* and resources/* protocol methods.

type PromptsCapability

type PromptsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

PromptsCapability indicates prompts support.

type PromptsGetParams

type PromptsGetParams struct {
	Name      string            `json:"name"`
	Arguments map[string]string `json:"arguments,omitempty"`
}

PromptsGetParams contains parameters for prompts/get.

type PromptsGetResult

type PromptsGetResult struct {
	Description string          `json:"description,omitempty"`
	Messages    []PromptMessage `json:"messages"`
}

PromptsGetResult is the response to prompts/get.

type PromptsListResult

type PromptsListResult struct {
	Prompts []MCPPrompt `json:"prompts"`
}

PromptsListResult is the response to prompts/list.

type Property

type Property struct {
	Type        string   `json:"type"`
	Description string   `json:"description,omitempty"`
	Enum        []string `json:"enum,omitempty"`
	Default     any      `json:"default,omitempty"`
}

Property describes a single property in an input schema.

type RPCClient

type RPCClient struct {
	ClientBase
	// contains filtered or unexported fields
}

RPCClient provides shared JSON-RPC protocol methods for MCP transport clients. It embeds ClientBase for state management and delegates I/O to a transporter.

Embedding hierarchy: ConcreteClient -> RPCClient -> ClientBase

Each concrete client (Client, StdioClient, ProcessClient) embeds RPCClient and implements transporter, passing itself to initRPCClient. This allows the shared protocol methods to dispatch to transport-specific I/O.

OpenAPIClient is separate — it embeds ClientBase directly since it does not use JSON-RPC at all.

func (*RPCClient) CallTool

func (r *RPCClient) CallTool(ctx context.Context, name string, arguments map[string]any) (*ToolCallResult, error)

CallTool invokes a tool on the downstream agent.

func (*RPCClient) Initialize

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

Initialize performs the MCP initialize handshake. If the transport implements connector, Connect() is called first.

func (*RPCClient) Name

func (r *RPCClient) Name() string

Name returns the agent name.

func (*RPCClient) RefreshTools

func (r *RPCClient) RefreshTools(ctx context.Context) error

RefreshTools fetches the current tool list from the agent. If a tool whitelist has been set, only tools matching the whitelist are stored.

func (*RPCClient) SetLogger

func (r *RPCClient) SetLogger(logger *slog.Logger)

SetLogger sets the logger for this client.

type Reconnectable

type Reconnectable interface {
	Reconnect(ctx context.Context) error
}

Reconnectable is an optional interface for AgentClients that support reconnection after connection failures (e.g., container restart, process crash). The health monitor uses type assertion to trigger reconnection on unhealthy clients.

type ResourceContents

type ResourceContents struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"`
}

ResourceContents represents the content of a resource.

type ResourcesCapability

type ResourcesCapability struct {
	Subscribe   bool `json:"subscribe,omitempty"`
	ListChanged bool `json:"listChanged,omitempty"`
}

ResourcesCapability indicates resources support.

type ResourcesListResult

type ResourcesListResult struct {
	Resources []MCPResource `json:"resources"`
}

ResourcesListResult is the response to resources/list.

type ResourcesReadParams

type ResourcesReadParams struct {
	URI string `json:"uri"`
}

ResourcesReadParams contains parameters for resources/read.

type ResourcesReadResult

type ResourcesReadResult struct {
	Contents []ResourceContents `json:"contents"`
}

ResourcesReadResult is the response to resources/read.

type Router

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

Router routes tool calls to the appropriate agent.

func NewRouter

func NewRouter() *Router

NewRouter creates a new tool router.

func (*Router) AddClient

func (r *Router) AddClient(client AgentClient)

AddClient adds an agent client to the router.

func (*Router) AggregatedTools

func (r *Router) AggregatedTools() []Tool

AggregatedTools returns all tools from all agents with prefixed names.

func (*Router) Clients

func (r *Router) Clients() []AgentClient

Clients returns all registered clients.

func (*Router) GetClient

func (r *Router) GetClient(name string) AgentClient

GetClient returns a client by agent name.

func (*Router) RefreshTools

func (r *Router) RefreshTools()

RefreshTools updates the tool registry from all agents.

func (*Router) RemoveClient

func (r *Router) RemoveClient(name string)

RemoveClient removes an agent client from the router.

func (*Router) RouteToolCall

func (r *Router) RouteToolCall(prefixedName string) (AgentClient, string, error)

RouteToolCall routes a tool call to the appropriate agent.

type SSEServer

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

SSEServer handles Server-Sent Events connections for MCP.

func NewSSEServer

func NewSSEServer(gateway *Gateway) *SSEServer

NewSSEServer creates a new SSE server.

func (*SSEServer) Broadcast

func (s *SSEServer) Broadcast(event string, data any)

Broadcast sends an event to all connected sessions. Write errors are silently ignored so disconnected clients don't block delivery.

func (*SSEServer) Close

func (s *SSEServer) Close()

Close broadcasts a close event to all connected sessions, then clears the session map. The broadcast is best-effort: write errors to disconnected clients are silently ignored. After Close returns, active SSE handlers will exit when http.Server.Shutdown() cancels their request contexts.

func (*SSEServer) HandleMessage

func (s *SSEServer) HandleMessage(w http.ResponseWriter, r *http.Request)

HandleMessage handles POST requests to /message for a specific session.

func (*SSEServer) ServeHTTP

func (s *SSEServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles SSE connections at /sse.

func (*SSEServer) SessionCount

func (s *SSEServer) SessionCount() int

SessionCount returns the number of active sessions.

type SSESession

type SSESession struct {
	ID        string
	AgentName string // Agent identity for tool access control
	Writer    http.ResponseWriter
	Flusher   http.Flusher
	Done      chan struct{}
	MessageID atomic.Int64
}

SSESession represents a connected SSE client.

type ServerInfo

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ServerInfo contains information about the MCP server.

type Session

type Session struct {
	ID          string
	ClientInfo  ClientInfo
	Initialized bool
	CreatedAt   time.Time
	LastSeen    time.Time
}

Session represents an MCP client session.

type SessionManager

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

SessionManager manages client sessions.

func NewSessionManager

func NewSessionManager() *SessionManager

NewSessionManager creates a new session manager.

func (*SessionManager) Cleanup

func (m *SessionManager) Cleanup(maxAge time.Duration) int

Cleanup removes stale sessions older than the given duration.

func (*SessionManager) Count

func (m *SessionManager) Count() int

Count returns the number of active sessions.

func (*SessionManager) Create

func (m *SessionManager) Create(clientInfo ClientInfo) *Session

Create creates a new session. If the session count exceeds maxSessions, the oldest session (by LastSeen) is evicted.

func (*SessionManager) Delete

func (m *SessionManager) Delete(id string)

Delete removes a session.

func (*SessionManager) Get

func (m *SessionManager) Get(id string) *Session

Get retrieves a session by ID.

func (*SessionManager) List

func (m *SessionManager) List() []*Session

List returns all sessions.

func (*SessionManager) Touch

func (m *SessionManager) Touch(id string)

Touch updates the last seen time for a session.

type StdioClient

type StdioClient struct {
	RPCClient
	// contains filtered or unexported fields
}

StdioClient communicates with an MCP server via container stdin/stdout.

func NewStdioClient

func NewStdioClient(name, containerID string, cli dockerclient.DockerClient) *StdioClient

NewStdioClient creates a new stdio-based MCP client.

func (*StdioClient) Close

func (c *StdioClient) Close() error

Close closes the connection.

func (*StdioClient) Connect

func (c *StdioClient) Connect(ctx context.Context) error

Connect attaches to the container's stdin/stdout.

func (*StdioClient) Ping

func (c *StdioClient) Ping(ctx context.Context) error

Ping checks if the container stdio connection is alive by sending a JSON-RPC ping.

func (*StdioClient) Reconnect

func (c *StdioClient) Reconnect(ctx context.Context) error

Reconnect closes the existing connection and re-establishes it, including the MCP handshake and tool refresh. Thread-safe: concurrent callers will block until reconnection completes.

type Tool

type Tool struct {
	Name        string          `json:"name"`
	Title       string          `json:"title,omitempty"`
	Description string          `json:"description,omitempty"`
	InputSchema json.RawMessage `json:"inputSchema"`
}

Tool represents an MCP tool definition.

type ToolCallParams

type ToolCallParams struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
}

ToolCallParams contains parameters for tools/call.

type ToolCallResult

type ToolCallResult struct {
	Content []Content `json:"content"`
	IsError bool      `json:"isError,omitempty"`
}

ToolCallResult is the response to tools/call.

type ToolCaller

type ToolCaller interface {
	CallTool(ctx context.Context, name string, arguments map[string]any) (*ToolCallResult, error)
}

ToolCaller allows calling tools across the gateway's aggregated servers. This interface decouples the registry from the gateway to avoid circular dependencies. The gateway implements this interface and passes it to components that need to call tools without holding a direct reference to the gateway or router.

type ToolsCapability

type ToolsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

ToolsCapability indicates tools support.

type ToolsListResult

type ToolsListResult struct {
	Tools      []Tool  `json:"tools"`
	NextCursor *string `json:"nextCursor,omitempty"`
}

ToolsListResult is the response to tools/list.

type Transport

type Transport string

Transport represents the type of transport for an MCP connection.

const (
	TransportHTTP  Transport = "http"
	TransportStdio Transport = "stdio"
	TransportSSE   Transport = "sse"
)

Jump to

Keyboard shortcuts

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