mcp

package
v0.1.0-alpha.3 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ParseError     = -32700
	InvalidRequest = -32600
	MethodNotFound = -32601
	InvalidParams  = -32602
	InternalError  = -32603
)

Standard JSON-RPC error codes

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 {
	// 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) CallTool

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

CallTool invokes a tool on the downstream agent.

func (*Client) Endpoint

func (c *Client) Endpoint() string

Endpoint returns the agent endpoint.

func (*Client) Initialize

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

Initialize performs the MCP initialize handshake.

func (*Client) IsInitialized

func (c *Client) IsInitialized() bool

IsInitialized returns whether the client has been initialized.

func (*Client) Name

func (c *Client) Name() string

Name returns the agent name.

func (*Client) Ping

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

Ping checks if the agent is reachable.

func (*Client) RefreshTools

func (c *Client) 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 (*Client) ServerInfo

func (c *Client) ServerInfo() ServerInfo

ServerInfo returns the server information.

func (*Client) SetToolWhitelist

func (c *Client) 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 (*Client) Tools

func (c *Client) Tools() []Tool

Tools returns the cached tools for this agent.

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 Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

Error represents a JSON-RPC 2.0 error.

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) 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) HandleInitialize

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

HandleInitialize handles the initialize request.

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) 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) 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) SetVersion

func (g *Gateway) SetVersion(version string)

SetVersion sets the gateway version string.

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 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 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)
	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)
	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
}

MCPServerStatus returns status information about registered MCP servers.

type ProcessClient

type ProcessClient struct {
	// 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) CallTool

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

CallTool invokes a tool on the agent.

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) Initialize

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

Initialize performs the MCP initialize handshake.

func (*ProcessClient) IsInitialized

func (c *ProcessClient) IsInitialized() bool

IsInitialized returns whether the client has been initialized.

func (*ProcessClient) Name

func (c *ProcessClient) Name() string

Name returns the agent name.

func (*ProcessClient) RefreshTools

func (c *ProcessClient) 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 (*ProcessClient) ServerInfo

func (c *ProcessClient) ServerInfo() ServerInfo

ServerInfo returns the server information.

func (*ProcessClient) SetToolWhitelist

func (c *ProcessClient) 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 (*ProcessClient) Tools

func (c *ProcessClient) Tools() []Tool

Tools returns the cached tools for this agent.

type PromptsCapability

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

PromptsCapability indicates prompts support.

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 Request

type Request struct {
	JSONRPC string           `json:"jsonrpc"`
	ID      *json.RawMessage `json:"id,omitempty"`
	Method  string           `json:"method"`
	Params  json.RawMessage  `json:"params,omitempty"`
}

Request represents a JSON-RPC 2.0 request.

type ResourcesCapability

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

ResourcesCapability indicates resources support.

type Response

type Response struct {
	JSONRPC string           `json:"jsonrpc"`
	ID      *json.RawMessage `json:"id,omitempty"`
	Result  json.RawMessage  `json:"result,omitempty"`
	Error   *Error           `json:"error,omitempty"`
}

Response represents a JSON-RPC 2.0 response.

func NewErrorResponse

func NewErrorResponse(id *json.RawMessage, code int, message string) Response

NewErrorResponse creates a JSON-RPC error response.

func NewSuccessResponse

func NewSuccessResponse(id *json.RawMessage, result any) Response

NewSuccessResponse creates a JSON-RPC success response.

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.

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
	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) Create

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

Create creates a new session.

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 {
	// 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) CallTool

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

CallTool invokes a tool on the agent.

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) Initialize

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

Initialize performs the MCP initialize handshake.

func (*StdioClient) IsInitialized

func (c *StdioClient) IsInitialized() bool

IsInitialized returns whether the client has been initialized.

func (*StdioClient) Name

func (c *StdioClient) Name() string

Name returns the agent name.

func (*StdioClient) RefreshTools

func (c *StdioClient) 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 (*StdioClient) ServerInfo

func (c *StdioClient) ServerInfo() ServerInfo

ServerInfo returns the server information.

func (*StdioClient) SetToolWhitelist

func (c *StdioClient) 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 (*StdioClient) Tools

func (c *StdioClient) Tools() []Tool

Tools returns the cached tools for this agent.

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 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