The MCP client implementation enables connecting to MCP servers, calling tools, accessing prompts and resources, and handling server notifications.
Creates a new MCP client.
import "github.com/modelcontextprotocol/go-sdk/mcp"
func NewClient(impl *Implementation, opts *ClientOptions) *ClientParameters:
impl: Implementation information (must not be nil)opts: Optional client configurationExample:
client := mcp.NewClient(&mcp.Implementation{
Name: "my-client",
Version: "1.0.0",
}, nil)Describes the name and version of an MCP implementation.
type Implementation struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Version string `json:"version"`
}Fields:
Name: Programmatic identifier for the implementationTitle: Human-readable title for UI contextsVersion: Version stringConfigures client behavior and capabilities.
type ClientOptions struct {
CreateMessageHandler func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error)
ElicitationHandler func(context.Context, *ElicitRequest) (*ElicitResult, error)
ToolListChangedHandler func(context.Context, *ToolListChangedRequest)
PromptListChangedHandler func(context.Context, *PromptListChangedRequest)
ResourceListChangedHandler func(context.Context, *ResourceListChangedRequest)
ResourceUpdatedHandler func(context.Context, *ResourceUpdatedNotificationRequest)
LoggingMessageHandler func(context.Context, *LoggingMessageRequest)
ProgressNotificationHandler func(context.Context, *ProgressNotificationClientRequest)
KeepAlive time.Duration
}Fields:
CreateMessageHandler: Handles sampling/createMessage requests (advertises sampling capability when set)ElicitationHandler: Handles elicitation/create requests (advertises elicitation capability when set)ToolListChangedHandler: Called when server tool list changesPromptListChangedHandler: Called when server prompt list changesResourceListChangedHandler: Called when server resource list changesResourceUpdatedHandler: Called when a subscribed resource is updatedLoggingMessageHandler: Called when server sends log messagesProgressNotificationHandler: Called for progress notificationsKeepAlive: Interval for automatic ping requests (0 disables)Connects the client to a server using a transport.
func (c *Client) Connect(
ctx context.Context,
t Transport,
_ *ClientSessionOptions,
) (cs *ClientSession, err error)Parameters:
ctx: Context for the connection operationt: Transport to use for communication_: Reserved for future options (pass nil)Returns: A new ClientSession for interacting with the server
Example:
transport := &mcp.CommandTransport{Command: exec.Command("myserver")}
session, err := client.Connect(ctx, transport, nil)
if err != nil {
log.Fatal(err)
}
defer session.Close()Adds roots to the client and notifies connected servers.
func (c *Client) AddRoots(roots ...*Root)Parameters:
roots: One or more Root objects to addExample:
client.AddRoots(&mcp.Root{
URI: "file:///home/user/project",
Name: "My Project",
})Removes roots by URI and notifies connected servers.
func (c *Client) RemoveRoots(uris ...string)Parameters:
uris: URIs of roots to removeWraps the sending method handler with middleware.
func (c *Client) AddSendingMiddleware(middleware ...Middleware)Wraps the receiving method handler with middleware.
func (c *Client) AddReceivingMiddleware(middleware ...Middleware)A ClientSession represents a logical connection with an MCP server. It provides methods to send requests and notifications to the server.
Calls a tool on the server.
func (cs *ClientSession) CallTool(
ctx context.Context,
params *CallToolParams,
) (*CallToolResult, error)Parameters:
ctx: Context for the operationparams: Tool call parametersExample:
result, err := session.CallTool(ctx, &mcp.CallToolParams{
Name: "greet",
Arguments: map[string]any{"name": "Alice"},
})Lists all available tools on the server.
func (cs *ClientSession) ListTools(
ctx context.Context,
params *ListToolsParams,
) (*ListToolsResult, error)Returns an iterator over all tools (handles pagination automatically).
func (cs *ClientSession) Tools(
ctx context.Context,
params *ListToolsParams,
) iter.Seq2[*Tool, error]Example:
for tool, err := range session.Tools(ctx, &mcp.ListToolsParams{}) {
if err != nil {
log.Fatal(err)
}
fmt.Printf("Tool: %s - %s\n", tool.Name, tool.Description)
}Gets a specific prompt from the server.
func (cs *ClientSession) GetPrompt(
ctx context.Context,
params *GetPromptParams,
) (*GetPromptResult, error)Example:
result, err := session.GetPrompt(ctx, &mcp.GetPromptParams{
Name: "greeting",
Arguments: map[string]string{"language": "spanish"},
})Lists all available prompts on the server.
func (cs *ClientSession) ListPrompts(
ctx context.Context,
params *ListPromptsParams,
) (*ListPromptsResult, error)Returns an iterator over all prompts (handles pagination automatically).
func (cs *ClientSession) Prompts(
ctx context.Context,
params *ListPromptsParams,
) iter.Seq2[*Prompt, error]Reads a resource from the server.
func (cs *ClientSession) ReadResource(
ctx context.Context,
params *ReadResourceParams,
) (*ReadResourceResult, error)Example:
result, err := session.ReadResource(ctx, &mcp.ReadResourceParams{
URI: "file:///path/to/file.txt",
})Lists all available resources on the server.
func (cs *ClientSession) ListResources(
ctx context.Context,
params *ListResourcesParams,
) (*ListResourcesResult, error)Returns an iterator over all resources (handles pagination automatically).
func (cs *ClientSession) Resources(
ctx context.Context,
params *ListResourcesParams,
) iter.Seq2[*Resource, error]Lists resource templates available on the server.
func (cs *ClientSession) ListResourceTemplates(
ctx context.Context,
params *ListResourceTemplatesParams,
) (*ListResourceTemplatesResult, error)Returns an iterator over all resource templates (handles pagination automatically).
func (cs *ClientSession) ResourceTemplates(
ctx context.Context,
params *ListResourceTemplatesParams,
) iter.Seq2[*ResourceTemplate, error]Subscribes to updates for a specific resource.
func (cs *ClientSession) Subscribe(
ctx context.Context,
params *SubscribeParams,
) errorUnsubscribes from updates for a specific resource.
func (cs *ClientSession) Unsubscribe(
ctx context.Context,
params *UnsubscribeParams,
) errorRequests completion suggestions from the server.
func (cs *ClientSession) Complete(
ctx context.Context,
params *CompleteParams,
) (*CompleteResult, error)Sets the logging level for server messages.
func (cs *ClientSession) SetLoggingLevel(
ctx context.Context,
params *SetLoggingLevelParams,
) errorSends a progress notification from the client to the server.
func (cs *ClientSession) NotifyProgress(
ctx context.Context,
params *ProgressNotificationParams,
) errorPerforms a graceful close of the connection.
func (cs *ClientSession) Close() errorWaits for the connection to be closed by the server.
func (cs *ClientSession) Wait() errorMakes an MCP "ping" request to the server.
func (cs *ClientSession) Ping(ctx context.Context, params *PingParams) errorReturns the session ID.
func (cs *ClientSession) ID() stringReturns the initialize result from the server.
func (cs *ClientSession) InitializeResult() *InitializeResultDescribes capabilities that a client may support.
type ClientCapabilities struct {
Experimental map[string]any `json:"experimental,omitempty"`
Roots struct { ListChanged bool } `json:"roots,omitempty"`
Sampling *SamplingCapabilities `json:"sampling,omitempty"`
Elicitation *ElicitationCapabilities `json:"elicitation,omitempty"`
}Fields:
Experimental: Non-standard capabilitiesRoots: Present if client supports listing rootsSampling: Present if client supports LLM samplingElicitation: Present if client supports elicitationIndicates the client supports sampling from an LLM.
type SamplingCapabilities struct{}Indicates the client supports elicitation from the server.
type ElicitationCapabilities struct{}Represents a root directory or file that the server can operate on.
type Root struct {
Meta `json:"_meta,omitempty"`
Name string `json:"name,omitempty"`
URI string `json:"uri"`
}Fields:
Meta: Reserved metadata fieldName: Optional name for the rootURI: URI identifying the root (must start with file://)A function type for wrapping method handlers.
type Middleware func(MethodHandler) MethodHandlerA function that handles MCP messages.
type MethodHandler func(
ctx context.Context,
method string,
req Request,
) (result Result, err error)Reserved for future use when connecting.
type ClientSessionOptions struct{}