CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com-modelcontextprotocol--go-sdk

Official Go SDK for the Model Context Protocol (MCP) enabling developers to build MCP clients and servers for AI-powered applications

Overview
Eval results
Files

MCP Go SDK

The Model Context Protocol (MCP) Go SDK is an official implementation that enables building MCP clients and servers in Go. It provides a complete, type-safe implementation of the MCP specification with support for tools, prompts, resources, sampling, and multiple transport mechanisms.

Package Information

  • Package Name: go-sdk
  • Package Type: go
  • Language: Go
  • Installation: go get github.com/modelcontextprotocol/go-sdk

Core Imports

import "github.com/modelcontextprotocol/go-sdk/mcp"

Additional packages for specialized functionality:

import "github.com/modelcontextprotocol/go-sdk/auth"      // OAuth authentication
import "github.com/modelcontextprotocol/go-sdk/jsonrpc"   // Custom transports
import "github.com/modelcontextprotocol/go-sdk/oauthex"   // OAuth extensions

Basic Usage

Simple Server

Create a server with a typed tool handler:

package main

import (
	"context"
	"log"
	"github.com/modelcontextprotocol/go-sdk/mcp"
)

type Input struct {
	Name string `json:"name" jsonschema:"the name of the person to greet"`
}

type Output struct {
	Greeting string `json:"greeting" jsonschema:"the greeting to tell to the user"`
}

func SayHi(ctx context.Context, req *mcp.CallToolRequest, input Input) (
	*mcp.CallToolResult,
	Output,
	error,
) {
	return nil, Output{Greeting: "Hi " + input.Name}, nil
}

func main() {
	// Create a server with a single tool
	server := mcp.NewServer(&mcp.Implementation{Name: "greeter", Version: "v1.0.0"}, nil)
	mcp.AddTool(server, &mcp.Tool{Name: "greet", Description: "say hi"}, SayHi)

	// Run the server over stdin/stdout
	if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
		log.Fatal(err)
	}
}

Simple Client

Connect to a server and call tools:

package main

import (
	"context"
	"log"
	"os/exec"
	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	ctx := context.Background()

	// Create a new client
	client := mcp.NewClient(&mcp.Implementation{Name: "mcp-client", Version: "v1.0.0"}, nil)

	// Connect to a server over stdin/stdout
	transport := &mcp.CommandTransport{Command: exec.Command("myserver")}
	session, err := client.Connect(ctx, transport, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	// Call a tool on the server
	params := &mcp.CallToolParams{
		Name:      "greet",
		Arguments: map[string]any{"name": "you"},
	}
	res, err := session.CallTool(ctx, params)
	if err != nil {
		log.Fatalf("CallTool failed: %v", err)
	}
	if res.IsError {
		log.Fatal("tool failed")
	}
	for _, c := range res.Content {
		log.Print(c.(*mcp.TextContent).Text)
	}
}

Architecture

The MCP Go SDK follows a layered architecture:

  • Client/Server: Top-level objects that manage MCP implementations
  • Session: Logical connections between client and server (ClientSession, ServerSession)
  • Transport: Pluggable communication layer (stdio, HTTP, SSE, in-memory)
  • Protocol: Type-safe request/response/notification types
  • Content: Polymorphic content types for messages and resources

Key Concepts

  • Implementation: Identifies name and version of client or server
  • Capabilities: Declared features that client/server support (negotiated during initialization)
  • Typed Handlers: Generic handlers with automatic schema inference and validation
  • Middleware: Composable request/response interceptors
  • Iterators: Go 1.23+ iterator support for paginated results

Capabilities

Server Operations

Create and manage MCP servers with tools, prompts, and resources.

func NewServer(impl *Implementation, options *ServerOptions) *Server

MCP Server

Client Operations

Connect to MCP servers and invoke their capabilities.

func NewClient(impl *Implementation, opts *ClientOptions) *Client

MCP Client

Transport Layer

Multiple transport implementations for different communication scenarios.

type Transport interface {
	Connect(ctx context.Context) (Connection, error)
}

Available transports:

  • StdioTransport: stdin/stdout communication
  • CommandTransport: Execute command and communicate over its stdio
  • IOTransport: Custom ReadCloser/WriteCloser
  • SSEClientTransport/SSEServerTransport: Server-Sent Events
  • StreamableHTTPHandler: HTTP with streaming support
  • InMemoryTransport: Testing and local communication
  • LoggingTransport: Debug wrapper

MCP Transports

Protocol Types

Request, response, and parameter types for all MCP operations.

type CallToolParams struct {
	Meta      `json:"_meta,omitempty"`
	Name      string `json:"name"`
	Arguments any    `json:"arguments,omitempty"`
}

type InitializeParams struct {
	Meta            `json:"_meta,omitempty"`
	Capabilities    *ClientCapabilities `json:"capabilities"`
	ClientInfo      *Implementation     `json:"clientInfo"`
	ProtocolVersion string              `json:"protocolVersion"`
}

MCP Protocol

Content Types

Polymorphic content system for text, images, audio, and resources.

type Content interface {
	MarshalJSON() ([]byte, error)
}

Implementations:

  • TextContent: Plain text content
  • ImageContent: Base64-encoded images
  • AudioContent: Base64-encoded audio
  • ResourceLink: Reference to a resource
  • EmbeddedResource: Embedded resource contents

MCP Content

Capability Negotiation

Client and server capability declarations and negotiation.

type ServerCapabilities struct {
	Completions  *CompletionCapabilities `json:"completions,omitempty"`
	Experimental map[string]any          `json:"experimental,omitempty"`
	Logging      *LoggingCapabilities    `json:"logging,omitempty"`
	Prompts      *PromptCapabilities     `json:"prompts,omitempty"`
	Resources    *ResourceCapabilities   `json:"resources,omitempty"`
	Tools        *ToolCapabilities       `json:"tools,omitempty"`
}

MCP Capabilities

Authentication

OAuth bearer token authentication for MCP servers.

func RequireBearerToken(verifier TokenVerifier, opts *RequireBearerTokenOptions) func(http.Handler) http.Handler

Authentication

JSON-RPC

Low-level JSON-RPC types for custom transport implementations.

func DecodeMessage(data []byte) (Message, error)
func EncodeMessage(msg Message) ([]byte, error)

JSON-RPC

OAuth Extensions

RFC implementations for OAuth metadata and dynamic client registration.

func GetProtectedResourceMetadata(ctx context.Context, resourceURL string, c *http.Client) (*ProtectedResourceMetadata, error)
func RegisterClient(ctx context.Context, registrationEndpoint string, clientMeta *ClientRegistrationMetadata, c *http.Client) (*ClientRegistrationResponse, error)

Note: OAuth features require mcp_go_client_oauth build tag.

OAuth Extensions

Protocol Version

The SDK implements MCP protocol version: 2025-06-18

Constants

const (
	LevelDebug     = slog.LevelDebug
	LevelInfo      = slog.LevelInfo
	LevelNotice    = (slog.LevelInfo + slog.LevelWarn) / 2
	LevelWarning   = slog.LevelWarn
	LevelError     = slog.LevelError
	LevelCritical  = slog.LevelError + 4
	LevelAlert     = slog.LevelError + 8
	LevelEmergency = slog.LevelError + 12
)

const DefaultPageSize = 1000

Errors

var ErrConnectionClosed = errors.New("connection closed")
var ErrEventsPurged = errors.New("data purged")

Types

Common Types

type Implementation struct {
	Name    string `json:"name"`
	Title   string `json:"title,omitempty"`
	Version string `json:"version"`
}

type Meta map[string]any

type Role string

type LoggingLevel string

Request and Result Interfaces

type Params interface {
	GetMeta() map[string]any
	SetMeta(map[string]any)
}

type RequestParams interface {
	Params
	GetProgressToken() any
	SetProgressToken(any)
}

type Result interface {
	GetMeta() map[string]any
	SetMeta(map[string]any)
}

type Request interface {
	GetSession() Session
	GetParams() Params
	GetExtra() *RequestExtra
}

type Session interface {
	ID() string
}

Request Extra Information

type RequestExtra struct {
	TokenInfo *auth.TokenInfo
	Header    http.Header
}

Install with Tessl CLI

npx tessl i tessl/golang-github-com-modelcontextprotocol--go-sdk
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/modelcontextprotocol/go-sdk@v1.1.0