Official Go software development kit (SDK) for the Model Context Protocol (MCP)
npx @tessl/cli install tessl/golang-github-com-modelcontextprotocol--go-sdk@1.1.0The MCP Go SDK provides a comprehensive implementation of the Model Context Protocol (MCP) for building AI-powered applications in Go. It enables developers to create MCP clients and servers with support for tools, prompts, resources, sampling, and various transport mechanisms.
go get github.com/modelcontextprotocol/go-sdkgithub.com/modelcontextprotocol/go-sdkimport (
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/modelcontextprotocol/go-sdk/auth"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
"github.com/modelcontextprotocol/go-sdk/oauthex"
)package main
import (
"context"
"log"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func main() {
// Create a server
server := mcp.NewServer(&mcp.Implementation{Name: "greeter"}, nil)
// Add a tool with typed arguments
type args struct {
Name string `json:"name" jsonschema:"the person to greet"`
}
mcp.AddTool(server, &mcp.Tool{
Name: "greet",
Description: "say hi",
}, func(ctx context.Context, req *mcp.CallToolRequest, args args) (*mcp.CallToolResult, any, error) {
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: "Hi " + args.Name},
},
}, nil, nil
})
// Run the server on stdio transport
if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
log.Printf("Server failed: %v", err)
}
}package main
import (
"context"
"log"
"os/exec"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func main() {
// Create a client
client := mcp.NewClient(&mcp.Implementation{
Name: "mcp-client",
Version: "v1.0.0",
}, nil)
// Connect to a server via command transport
transport := &mcp.CommandTransport{Command: exec.Command("myserver")}
session, err := client.Connect(context.Background(), transport, nil)
if err != nil {
log.Fatal(err)
}
defer session.Close()
// Call a tool
params := &mcp.CallToolParams{
Name: "greet",
Arguments: map[string]any{"name": "you"},
}
res, err := session.CallTool(context.Background(), params)
if err != nil {
log.Fatalf("CallTool failed: %v", err)
}
}The MCP Go SDK follows a session-based architecture:
Client Server
⇅ (jsonrpc2) ⇅
ClientSession ⇄ Client Transport ⇄ Server Transport ⇄ ServerSessionBoth Client and Server can handle many concurrent sessions. Each connection creates a new session for bi-directional communication.
Create and configure MCP clients with custom handlers for sampling, elicitation, and notifications.
func NewClient(impl *Implementation, opts *ClientOptions) *Clienttype Implementation struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Version string `json:"version"`
}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
}Create and configure MCP servers with tools, prompts, resources, and custom handlers.
func NewServer(impl *Implementation, options *ServerOptions) *Servertype ServerOptions struct {
Instructions string
Logger *slog.Logger
InitializedHandler func(context.Context, *InitializedRequest)
PageSize int
RootsListChangedHandler func(context.Context, *RootsListChangedRequest)
ProgressNotificationHandler func(context.Context, *ProgressNotificationServerRequest)
CompletionHandler func(context.Context, *CompleteRequest) (*CompleteResult, error)
KeepAlive time.Duration
SubscribeHandler func(context.Context, *SubscribeRequest) error
UnsubscribeHandler func(context.Context, *UnsubscribeRequest) error
HasPrompts bool
HasResources bool
HasTools bool
GetSessionID func() string
}Multiple transport options for client-server communication.
type Transport interface {
Connect(ctx context.Context) (Connection, error)
}Available transports:
Define and execute tools with automatic schema generation.
func AddTool[In, Out any](s *Server, t *Tool, h ToolHandlerFor[In, Out])type Tool struct {
Meta `json:"_meta,omitempty"`
Annotations *ToolAnnotations `json:"annotations,omitempty"`
Description string `json:"description,omitempty"`
InputSchema any `json:"inputSchema"`
Name string `json:"name"`
OutputSchema any `json:"outputSchema,omitempty"`
Title string `json:"title,omitempty"`
}type ToolHandlerFor[In, Out any] func(
_ context.Context,
request *CallToolRequest,
input In,
) (result *CallToolResult, output Out, _ error)Define prompt templates with typed arguments.
type Prompt struct {
Meta `json:"_meta,omitempty"`
Arguments []*PromptArgument `json:"arguments,omitempty"`
Description string `json:"description,omitempty"`
Name string `json:"name"`
Title string `json:"title,omitempty"`
}type PromptHandler func(context.Context, *GetPromptRequest) (*GetPromptResult, error)Expose resources for clients to read.
type Resource struct {
Meta `json:"_meta,omitempty"`
Annotations *Annotations `json:"annotations,omitempty"`
Description string `json:"description,omitempty"`
MIMEType string `json:"mimeType,omitempty"`
Name string `json:"name"`
Size int64 `json:"size,omitempty"`
Title string `json:"title,omitempty"`
URI string `json:"uri"`
}type ResourceHandler func(context.Context, *ReadResourceRequest) (*ReadResourceResult, error)Multiple content types for rich data exchange.
type Content interface {
MarshalJSON() ([]byte, error)
}type TextContent struct {
Text string
Meta Meta
Annotations *Annotations
}type ImageContent struct {
Meta Meta
Annotations *Annotations
Data []byte
MIMEType string
}type AudioContent struct {
Data []byte
MIMEType string
Meta Meta
Annotations *Annotations
}Low-level protocol types for requests and responses.
type CallToolParams struct {
Meta `json:"_meta,omitempty"`
Name string `json:"name"`
Arguments any `json:"arguments,omitempty"`
}type CallToolResult struct {
Meta `json:"_meta,omitempty"`
Content []Content `json:"content"`
StructuredContent any `json:"structuredContent,omitempty"`
IsError bool `json:"isError,omitempty"`
}OAuth 2.0 bearer token authentication for MCP servers.
func RequireBearerToken(
verifier TokenVerifier,
opts *RequireBearerTokenOptions,
) func(http.Handler) http.Handlertype TokenVerifier func(
ctx context.Context,
token string,
req *http.Request,
) (*TokenInfo, error)Low-level JSON-RPC message handling.
func EncodeMessage(msg Message) ([]byte, error)
func DecodeMessage(data []byte) (Message, error)
func MakeID(v any) (ID, error)OAuth 2.0 protected resource metadata (RFC 9728).
type ProtectedResourceMetadata struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers,omitempty"`
JWKSURI string `json:"jwks_uri,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
ResourceSigningAlgValuesSupported []string `json:"resource_signing_alg_values_supported,omitempty"`
ResourceName string `json:"resource_name,omitempty"`
ResourceDocumentation string `json:"resource_documentation,omitempty"`
ResourcePolicyURI string `json:"resource_policy_uri,omitempty"`
ResourceTOSURI string `json:"resource_tos_uri,omitempty"`
TLSClientCertificateBoundAccessTokens bool `json:"tls_client_certificate_bound_access_tokens,omitempty"`
AuthorizationDetailsTypesSupported []string `json:"authorization_details_types_supported,omitempty"`
DPOPSigningAlgValuesSupported []string `json:"dpop_signing_alg_values_supported,omitempty"`
DPOPBoundAccessTokensRequired bool `json:"dpop_bound_access_tokens_required,omitempty"`
}