mcp

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package mcp provides a client for the Model Context Protocol.

Index

Constants

View Source
const (
	ErrCodeParse          = -32700
	ErrCodeInvalidRequest = -32600
	ErrCodeMethodNotFound = -32601
	ErrCodeInvalidParams  = -32602
	ErrCodeInternal       = -32603
)

Error codes

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

Protocol version

Variables

View Source
var DefaultRegistry = map[string]RegistryEntry{
	"filesystem": {
		Name:        "filesystem",
		Description: "File system access (read, write, search, list)",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-filesystem"},
	},
	"memory": {
		Name:        "memory",
		Description: "Persistent knowledge graph memory",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-memory"},
	},
	"github": {
		Name:        "github",
		Description: "GitHub API access (repos, issues, PRs, files)",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-github"},
		RequiredEnv: []string{"GITHUB_PERSONAL_ACCESS_TOKEN"},
	},
	"brave-search": {
		Name:        "brave-search",
		Description: "Web search via Brave Search API",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-brave-search"},
		RequiredEnv: []string{"BRAVE_API_KEY"},
	},
	"fetch": {
		Name:        "fetch",
		Description: "HTTP fetch for web content retrieval (native Go — no Node.js required)",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-fetch"},
		BuiltinGo:   true,
	},
	"postgres": {
		Name:        "postgres",
		Description: "PostgreSQL database access",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-postgres"},
		RequiredEnv: []string{"POSTGRES_CONNECTION_STRING"},
	},
	"sqlite": {
		Name:        "sqlite",
		Description: "SQLite database access",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-sqlite"},
	},
	"slack": {
		Name:        "slack",
		Description: "Slack workspace integration",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-slack"},
		RequiredEnv: []string{"SLACK_BOT_TOKEN"},
		OptionalEnv: []string{"SLACK_TEAM_ID"},
	},
	"puppeteer": {
		Name:        "puppeteer",
		Description: "Browser automation via Puppeteer",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-puppeteer"},
	},
	"sequential-thinking": {
		Name:        "sequential-thinking",
		Description: "Dynamic reasoning and thought revision",
		Command:     "npx",
		Args:        []string{"-y", "@modelcontextprotocol/server-sequential-thinking"},
	},
}

DefaultRegistry contains well-known MCP servers.

Functions

This section is empty.

Types

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

type Client

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

Client is an MCP client that can connect to MCP servers.

func NewClient

func NewClient(config ServerConfig) (*Client, error)

NewClient creates a new MCP client.

func (*Client) CallTool

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

CallTool executes a tool on the server.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection to the server.

func (*Client) Connect

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

Connect establishes a connection to the MCP server and performs the handshake.

func (*Client) Connected

func (c *Client) Connected() bool

Connected returns whether the client is connected.

func (*Client) DiscoverResources

func (c *Client) DiscoverResources(ctx context.Context) ([]MCPResource, error)

DiscoverResources retrieves the list of resources from the server.

func (*Client) DiscoverTools

func (c *Client) DiscoverTools(ctx context.Context) ([]MCPTool, error)

DiscoverTools retrieves the list of tools from the server.

func (*Client) Name

func (c *Client) Name() string

Name returns the server name.

func (*Client) ReadResource

func (c *Client) ReadResource(ctx context.Context, uri string) (string, error)

ReadResource reads a resource from the server.

func (*Client) ServerInfo

func (c *Client) ServerInfo() *ServerInfo

ServerInfo returns information about the connected server.

func (*Client) Tools

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

Tools returns the cached tools list.

type ClientCapabilities

type ClientCapabilities struct {
	Roots    *RootsCapability    `json:"roots,omitempty"`
	Sampling *SamplingCapability `json:"sampling,omitempty"`
}

ClientCapabilities describes what the client supports.

type ClientInfo

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

ClientInfo describes the client.

type ContentBlock

type ContentBlock struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
	Data     string `json:"data,omitempty"` // Base64 for binary
}

ContentBlock is a content block in a tool result.

type HTTPTransport

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

HTTPTransport implements Transport over HTTP with optional SSE.

func NewHTTPTransport

func NewHTTPTransport(config ServerConfig) *HTTPTransport

NewHTTPTransport creates a new HTTP transport.

func (*HTTPTransport) Close

func (t *HTTPTransport) Close() error

Close closes the HTTP transport.

func (*HTTPTransport) Connect

func (t *HTTPTransport) Connect(ctx context.Context) error

Connect establishes the HTTP connection.

func (*HTTPTransport) OnNotification

func (t *HTTPTransport) OnNotification(handler func(method string, params json.RawMessage))

OnNotification registers a handler for server notifications.

func (*HTTPTransport) Send

func (t *HTTPTransport) Send(ctx context.Context, method string, params any) (json.RawMessage, error)

Send sends a JSON-RPC request over HTTP.

type InitializeParams

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

InitializeParams are the 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 result of the initialize request.

type JSONRPCError

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

JSONRPCError is a JSON-RPC 2.0 error.

func (*JSONRPCError) Error

func (e *JSONRPCError) Error() string

type JSONRPCNotification

type JSONRPCNotification struct {
	JSONRPC string `json:"jsonrpc"`
	Method  string `json:"method"`
	Params  any    `json:"params,omitempty"`
}

JSONRPCNotification is a JSON-RPC 2.0 notification.

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string `json:"jsonrpc"`
	ID      int64  `json:"id"`
	Method  string `json:"method"`
	Params  any    `json:"params,omitempty"`
}

JSONRPCRequest is a JSON-RPC 2.0 request.

type JSONRPCResponse

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

JSONRPCResponse is a JSON-RPC 2.0 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 provided by an MCP server.

type MCPTool

type MCPTool struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	InputSchema map[string]any `json:"inputSchema"`
	ServerName  string         `json:"-"` // Set by client
}

MCPTool represents a tool provided by an MCP server.

type PromptsCapability

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

PromptsCapability indicates prompt support.

type RegistryEntry

type RegistryEntry struct {
	// Name is the short name used in DSL (e.g. "filesystem").
	Name string

	// Description briefly explains what the server provides.
	Description string

	// Command is the executable to run.
	Command string

	// Args are default command-line arguments.
	Args []string

	// RequiredEnv lists environment variables that must be set.
	RequiredEnv []string

	// OptionalEnv lists environment variables that are useful but not required.
	OptionalEnv []string

	// BuiltinGo indicates this server has a native Go implementation
	// that runs in-process without requiring Node.js or any external binary.
	BuiltinGo bool
}

RegistryEntry describes a well-known MCP server.

func Lookup

func Lookup(name string) (RegistryEntry, bool)

Lookup finds a registry entry by name.

func (RegistryEntry) ToServerConfig

func (e RegistryEntry) ToServerConfig(overrideEnv map[string]string) ServerConfig

ToServerConfig converts a registry entry to a ServerConfig, merging any overrides from the caller.

type ResourceContent

type ResourceContent struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"`
	Blob     string `json:"blob,omitempty"` // Base64
}

ResourceContent is the content of a resource.

type ResourceReadParams

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

ResourceReadParams are the parameters for resources/read.

type ResourceReadResult

type ResourceReadResult struct {
	Contents []ResourceContent `json:"contents"`
}

ResourceReadResult is the result of resources/read.

type ResourcesCapability

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

ResourcesCapability indicates resource support.

type ResourcesListResult

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

ResourcesListResult is the result of resources/list.

type RootsCapability

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

RootsCapability indicates root support.

type SamplingCapability

type SamplingCapability struct{}

SamplingCapability indicates sampling support.

type ServerConfig

type ServerConfig struct {
	// Name is a human-readable identifier for the server.
	Name string

	// Transport specifies the transport type.
	Transport TransportType

	// Command is the executable for stdio transport.
	Command string

	// Args are command-line arguments for stdio transport.
	Args []string

	// Env are environment variables for stdio transport.
	Env map[string]string

	// URL is the endpoint for HTTP/SSE transport.
	URL string

	// Headers are HTTP headers for HTTP/SSE transport.
	Headers map[string]string

	// Timeout for operations (default: 30s).
	Timeout time.Duration
}

ServerConfig configures an MCP server connection.

type ServerInfo

type ServerInfo struct {
	Name            string       `json:"name"`
	Version         string       `json:"version"`
	ProtocolVersion string       `json:"protocolVersion"`
	Capabilities    Capabilities `json:"capabilities"`
}

ServerInfo contains information about the connected MCP server.

type StdioTransport

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

StdioTransport implements Transport over subprocess stdin/stdout.

func NewStdioTransport

func NewStdioTransport(config ServerConfig) *StdioTransport

NewStdioTransport creates a new stdio transport.

func (*StdioTransport) Close

func (t *StdioTransport) Close() error

Close shuts down the transport.

func (*StdioTransport) Connect

func (t *StdioTransport) Connect(ctx context.Context) error

Connect starts the subprocess and establishes communication.

func (*StdioTransport) OnNotification

func (t *StdioTransport) OnNotification(handler func(method string, params json.RawMessage))

OnNotification registers a handler for server notifications.

func (*StdioTransport) Send

func (t *StdioTransport) Send(ctx context.Context, method string, params any) (json.RawMessage, error)

Send sends a JSON-RPC request and waits for the response.

type ToolCallParams

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

ToolCallParams are the parameters for tools/call.

type ToolCallResult

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

ToolCallResult is the result of tools/call.

type ToolsCapability

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

ToolsCapability indicates tool support.

type ToolsListResult

type ToolsListResult struct {
	Tools []MCPTool `json:"tools"`
}

ToolsListResult is the result of tools/list.

type Transport

type Transport interface {
	// Connect establishes the connection.
	Connect(ctx context.Context) error

	// Send sends a JSON-RPC request and returns the result.
	Send(ctx context.Context, method string, params any) (json.RawMessage, error)

	// Close closes the connection.
	Close() error

	// OnNotification registers a handler for server notifications.
	OnNotification(handler func(method string, params json.RawMessage))
}

Transport is the interface for MCP communication.

type TransportType

type TransportType string

TransportType identifies the transport mechanism.

const (
	// TransportStdio uses subprocess stdin/stdout.
	TransportStdio TransportType = "stdio"
	// TransportHTTP uses HTTP with SSE for notifications.
	TransportHTTP TransportType = "http"
	// TransportSSE uses Server-Sent Events.
	TransportSSE TransportType = "sse"
)

Jump to

Keyboard shortcuts

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