or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

auth.mdindex.mdjsonrpc.mdmcp-client.mdmcp-protocol.mdmcp-server.mdmcp-transports.mdmcp-types.mdoauthex.md
tile.json

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

Official Go software development kit (SDK) for the Model Context Protocol (MCP)

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

To install, run

npx @tessl/cli install tessl/golang-github-com-modelcontextprotocol--go-sdk@1.1.0

index.mddocs/

MCP Go SDK

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

Package Information

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

Core Imports

import (
    "github.com/modelcontextprotocol/go-sdk/mcp"
    "github.com/modelcontextprotocol/go-sdk/auth"
    "github.com/modelcontextprotocol/go-sdk/jsonrpc"
    "github.com/modelcontextprotocol/go-sdk/oauthex"
)

Basic Usage

Creating an MCP Server

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)
    }
}

Creating an MCP Client

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)
    }
}

Architecture

The MCP Go SDK follows a session-based architecture:

  • Client: An MCP client that can connect to multiple servers
  • Server: An MCP server that can handle multiple client connections
  • ClientSession: A logical connection from client to server
  • ServerSession: A logical connection from server to client
  • Transport: Communication mechanism (stdio, command, HTTP, SSE, in-memory)
  • Connection: Low-level JSON-RPC connection interface
Client                                                   Server
 ⇅                          (jsonrpc2)                     ⇅
ClientSession ⇄ Client Transport ⇄ Server Transport ⇄ ServerSession

Both Client and Server can handle many concurrent sessions. Each connection creates a new session for bi-directional communication.

Capabilities

Client Construction and Configuration

Create and configure MCP clients with custom handlers for sampling, elicitation, and notifications.

func NewClient(impl *Implementation, opts *ClientOptions) *Client
type 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
}

MCP Client

Server Construction and Configuration

Create and configure MCP servers with tools, prompts, resources, and custom handlers.

func NewServer(impl *Implementation, options *ServerOptions) *Server
type 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
}

MCP Server

Transport Mechanisms

Multiple transport options for client-server communication.

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

Available transports:

  • StdioTransport: Communicate over stdin/stdout
  • CommandTransport: Run and communicate with a subprocess
  • IOTransport: Communicate over custom readers/writers
  • InMemoryTransport: In-memory connections for testing
  • SSEClientTransport: Client-side Server-Sent Events
  • SSEHandler: Server-side Server-Sent Events
  • StreamableClientTransport: Client-side streamable HTTP
  • StreamableHTTPHandler: Server-side streamable HTTP

MCP Transports

Tools

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)

MCP Types

Prompts

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)

MCP Types

Resources

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)

MCP Types

Content Types

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
}

MCP Types

Protocol Types

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"`
}

MCP Protocol

Authentication

OAuth 2.0 bearer token authentication for MCP servers.

func RequireBearerToken(
    verifier TokenVerifier,
    opts *RequireBearerTokenOptions,
) func(http.Handler) http.Handler
type TokenVerifier func(
    ctx context.Context,
    token string,
    req *http.Request,
) (*TokenInfo, error)

Authentication

JSON-RPC Utilities

Low-level JSON-RPC message handling.

func EncodeMessage(msg Message) ([]byte, error)
func DecodeMessage(data []byte) (Message, error)
func MakeID(v any) (ID, error)

JSON-RPC

OAuth Extensions

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"`
}

OAuth Extensions