mcp

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package mcp implements the Model Context Protocol (MCP) client. It supports connecting to MCP servers over two transports, listing tools and resources, and invoking tool calls:

  • stdio: JSON-RPC 2.0 framed as newline-delimited messages over a subprocess's stdin/stdout. Requests are serialized and each call reads its own response, honoring the per-call context via read deadlines.
  • sse (HTTP+SSE, MCP 2024-11-05): the client opens a long-lived text/event-stream GET to the server URL. The server's first event (event: endpoint) names the URL to POST JSON-RPC requests to; subsequent (event: message) events carry JSON-RPC responses and notifications. A background reader correlates responses to waiting callers by JSON-RPC id.

The high-level methods (ListTools, CallTool, ListResources, ReadResource) work identically over both transports.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterTools

func RegisterTools(ctx context.Context, client *Client, registry *tool.Registry) (int, error)

RegisterTools fetches tools from the MCP server and registers them in the given tool registry. Each MCP tool becomes a tool.Definition whose handler routes calls through the MCP client.

The per-tool permission comes from the server's ServerConfig.Permission when set (e.g. "allow" for a trusted read-only server), otherwise it falls back to PermRequireApproval since MCP tools are externally provided.

func ToolInfoToDefinitions

func ToolInfoToDefinitions(client *Client, tools []ToolInfo) []*tool.Definition

ToolInfoToDefinitions converts MCP ToolInfo items into tool.Definition items without registering them. Useful for inspection or custom registration.

func ToolInfoToJSON

func ToolInfoToJSON(tools []ToolInfo) ([]byte, error)

ToolInfoToJSON converts tool info into a JSON representation suitable for model tool definitions.

Types

type Client

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

Client communicates with an MCP server using JSON-RPC 2.0 over stdio.

Concurrency model:

  • mu serializes in-flight requests. It is held while writing a request and reading its response. The read honors the per-call context via a read deadline, so it never blocks indefinitely while holding mu.
  • Close does NOT acquire mu. It force-kills the subprocess and clears any read deadline, which unblocks any in-flight read so a hung server can be torn down even while a call is stuck. The closed flag is atomic so it can be observed without the lock.

The SSE transport adds an HTTP client, the POST endpoint advertised by the server, a background-reader cancel function, and a correlation map keyed by JSON-RPC id that routes streamed responses back to waiting callers. These fields are nil/zero for stdio clients.

func NewClient

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

NewClient creates a new MCP client for the given server configuration. For stdio transport, it launches the command as a subprocess on Connect. For SSE transport, it opens the HTTP event stream on Connect; cfg.URL is required and validated here rather than deferring the failure to call time.

func (*Client) CallTool

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

CallTool invokes a tool on the MCP server with the given arguments.

func (*Client) Close

func (c *Client) Close() error

Close shuts down the MCP server connection. It force-kills the subprocess and clears any read deadline so that an in-flight call blocked on a hung server is unblocked promptly. Close does not acquire the request mutex, so it can tear down a client even while a call is stuck in a read. Close is idempotent and safe to call multiple times.

func (*Client) Config added in v0.12.1

func (c *Client) Config() ServerConfig

Config returns the ServerConfig this client was constructed with, so callers can read connection metadata (Name, Transport, Permission, ...) without holding a separate reference to the config.

func (*Client) Connect

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

Connect establishes the transport and performs the initialize handshake. For stdio it starts the subprocess; for SSE it opens the event stream and waits for the endpoint event before handshaking.

func (*Client) Info

func (c *Client) Info() ServerInfo

Info returns the server information from the initialize handshake.

func (*Client) ListResources

func (c *Client) ListResources(ctx context.Context) ([]ResourceInfo, error)

ListResources fetches the available resources from the MCP server.

func (*Client) ListTools

func (c *Client) ListTools(ctx context.Context) ([]ToolInfo, error)

ListTools fetches the available tools from the MCP server.

func (*Client) ReadResource

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

ReadResource fetches the content of a resource by URI.

type ResourceContent

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

ResourceContent holds the content returned when reading a resource.

type ResourceInfo

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

ResourceInfo describes a resource provided by an MCP server.

type ServerConfig

type ServerConfig struct {
	Name      string    `json:"name" yaml:"name"`
	Transport Transport `json:"transport" yaml:"transport"`
	Command   string    `json:"command,omitempty" yaml:"command,omitempty"`
	Args      []string  `json:"args,omitempty" yaml:"args,omitempty"`
	URL       string    `json:"url,omitempty" yaml:"url,omitempty"`
	// Permission overrides the default per-tool permission applied when this
	// server's tools are registered. Empty keeps the safe default
	// ("require_approval"); "allow" auto-approves read-only trusted servers so
	// they don't block on stdin during non-interactive team runs.
	Permission string `json:"permission,omitempty" yaml:"permission,omitempty"`
}

ServerConfig holds the connection configuration for an MCP server.

type ServerInfo

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

ServerInfo holds the server's initialization response.

type ToolInfo

type ToolInfo struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	InputSchema map[string]any `json:"inputSchema,omitempty"`
}

ToolInfo describes a tool provided by an MCP server.

type Transport

type Transport string

Transport defines how the client communicates with an MCP server.

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

Jump to

Keyboard shortcuts

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