or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

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

mcp-server.mddocs/

MCP Server

The server API enables building MCP servers that expose tools, prompts, and resources to clients. Servers handle initialization, capability negotiation, and request routing.

Server Creation

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

Creates a new MCP server instance.

Server Type

type Server struct {
	// Has unexported fields
}

Server Options

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
}

Fields:

  • Instructions: Instructions shown to client after initialization
  • Logger: Optional structured logger for server operations
  • InitializedHandler: Called when client sends initialized notification
  • PageSize: Items per page for list operations (default: DefaultPageSize)
  • RootsListChangedHandler: Called when client root list changes
  • ProgressNotificationHandler: Called on client progress notifications
  • CompletionHandler: Handler for argument completion requests
  • KeepAlive: Duration for connection keep-alive (0 to disable)
  • SubscribeHandler: Handler for resource subscription requests
  • UnsubscribeHandler: Handler for resource unsubscription requests
  • HasPrompts: Server declares prompt capability
  • HasResources: Server declares resource capability
  • HasTools: Server declares tool capability
  • GetSessionID: Custom session ID generator

Server Methods

Running the Server

func (s *Server) Run(ctx context.Context, t Transport) error

Runs the server over the given transport until the client disconnects or context is cancelled.

func (s *Server) Connect(ctx context.Context, t Transport, opts *ServerSessionOptions) (*ServerSession, error)

Connects to a client over the given transport, returning a session for sending requests.

Tool Management

func (s *Server) AddTool(t *Tool, h ToolHandler)

Adds or replaces a tool with a low-level handler.

func AddTool[In, Out any](s *Server, t *Tool, h ToolHandlerFor[In, Out])

Adds a tool with typed handler that automatically infers input/output schemas and handles validation.

func (s *Server) RemoveTools(names ...string)

Removes tools by name.

Prompt Management

func (s *Server) AddPrompt(p *Prompt, h PromptHandler)

Adds or replaces a prompt with its handler.

func (s *Server) RemovePrompts(names ...string)

Removes prompts by name.

Resource Management

func (s *Server) AddResource(r *Resource, h ResourceHandler)

Adds or replaces a resource with its handler.

func (s *Server) AddResourceTemplate(t *ResourceTemplate, h ResourceHandler)

Adds or replaces a resource template with its handler.

func (s *Server) RemoveResources(uris ...string)

Removes resources by URI.

func (s *Server) RemoveResourceTemplates(uriTemplates ...string)

Removes resource templates by URI template.

func (s *Server) ResourceUpdated(ctx context.Context, params *ResourceUpdatedNotificationParams) error

Sends a notification to all sessions that a resource has been updated.

Middleware

func (s *Server) AddReceivingMiddleware(middleware ...Middleware)

Adds middleware for processing incoming requests.

func (s *Server) AddSendingMiddleware(middleware ...Middleware)

Adds middleware for processing outgoing requests to clients.

Session Management

func (s *Server) Sessions() iter.Seq[*ServerSession]

Returns an iterator over all active server sessions.

Server Session

type ServerSession struct {
	// Has unexported fields
}

A logical connection from a single MCP client.

Server Session Options

type ServerSessionOptions struct {
	State *ServerSessionState
	// Has unexported fields
}

Server Session State

type ServerSessionState struct {
	InitializeParams  *InitializeParams  `json:"initializeParams"`
	InitializedParams *InitializedParams `json:"initializedParams"`
	LogLevel          LoggingLevel       `json:"logLevel"`
}

Represents the state of a server session.

Server Session Methods

func (s *ServerSession) ID() string

Returns the unique session identifier.

func (s *ServerSession) InitializeParams() *InitializeParams

Returns the initialization parameters from the client.

func (s *ServerSession) Close() error

Gracefully closes the connection to the client.

func (s *ServerSession) Wait() error

Waits for the client to close the connection.

Calling Client Features

func (s *ServerSession) CreateMessage(ctx context.Context, params *CreateMessageParams) (*CreateMessageResult, error)

Sends a sampling request to the client to generate a message using an LLM.

func (s *ServerSession) Elicit(ctx context.Context, params *ElicitParams) (*ElicitResult, error)

Sends an elicitation request to prompt user for structured input.

func (s *ServerSession) ListRoots(ctx context.Context, params *ListRootsParams) (*ListRootsResult, error)

Lists the client's root directories/files.

func (s *ServerSession) Log(ctx context.Context, params *LoggingMessageParams) error

Sends a log message to the client.

func (s *ServerSession) NotifyProgress(ctx context.Context, params *ProgressNotificationParams) error

Sends a progress notification to the client.

func (s *ServerSession) Ping(ctx context.Context, params *PingParams) error

Pings the client to check connectivity.

Handler Types

Tool Handlers

type ToolHandler func(context.Context, *CallToolRequest) (*CallToolResult, error)

Low-level handler for tools/call requests with raw JSON arguments.

type ToolHandlerFor[In, Out any] func(context.Context, *CallToolRequest, In) (*CallToolResult, Out, error)

Typed handler that automatically validates input against inferred schema and serializes output.

Prompt Handler

type PromptHandler func(context.Context, *GetPromptRequest) (*GetPromptResult, error)

Handler for prompts/get requests.

Resource Handler

type ResourceHandler func(context.Context, *ReadResourceRequest) (*ReadResourceResult, error)

Handler for resources/read requests.

Tool Types

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

Definition for a tool the client can call.

Fields:

  • Meta: Additional metadata
  • Annotations: Hints about tool behavior
  • Description: Human-readable description
  • InputSchema: JSON schema for input parameters
  • Name: Unique identifier
  • OutputSchema: Optional JSON schema for output
  • Title: Human-readable title
type ToolAnnotations struct {
	DestructiveHint *bool  `json:"destructiveHint,omitempty"`
	IdempotentHint  bool   `json:"idempotentHint,omitempty"`
	OpenWorldHint   *bool  `json:"openWorldHint,omitempty"`
	ReadOnlyHint    bool   `json:"readOnlyHint,omitempty"`
	Title           string `json:"title,omitempty"`
}

Additional properties describing a tool (all are hints).

Fields:

  • DestructiveHint: Whether tool makes destructive changes
  • IdempotentHint: Whether tool is idempotent
  • OpenWorldHint: Whether tool interacts with external systems
  • ReadOnlyHint: Whether tool only reads data
  • Title: Human-readable title

Prompt Types

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

A prompt or prompt template offered by the server.

Fields:

  • Meta: Additional metadata
  • Arguments: Arguments the prompt accepts
  • Description: Human-readable description
  • Name: Unique identifier
  • Title: Human-readable title
type PromptArgument struct {
	Name        string `json:"name"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

Describes an argument that a prompt accepts.

Resource Types

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

A resource that the server can read.

Fields:

  • Meta: Additional metadata
  • Annotations: Display and usage hints
  • Description: Human-readable description
  • MIMEType: Resource MIME type
  • Name: Human-readable name
  • Size: Resource size in bytes
  • Title: Human-readable title
  • URI: Unique resource identifier
type ResourceTemplate struct {
	Meta        `json:"_meta,omitempty"`
	Annotations *Annotations `json:"annotations,omitempty"`
	Description string       `json:"description,omitempty"`
	MIMEType    string       `json:"mimeType,omitempty"`
	Name        string       `json:"name"`
	Title       string       `json:"title,omitempty"`
	URITemplate string       `json:"uriTemplate"`
}

Template description for resources available on server.

Fields:

  • Meta: Additional metadata
  • Annotations: Display and usage hints
  • Description: Human-readable description
  • MIMEType: Resource MIME type
  • Name: Human-readable name
  • Title: Human-readable title
  • URITemplate: URI template (RFC 6570) for generating resource URIs
type ResourceContents struct {
	URI      string `json:"uri"`
	MIMEType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"`
	Blob     []byte `json:"blob,omitempty"`
	Meta     Meta   `json:"_meta,omitempty"`
}

Contents of a resource or sub-resource. Either Text or Blob should be set.

Methods:

func (r *ResourceContents) MarshalJSON() ([]byte, error)

Server Requests

These types represent requests received by the server from clients.

type ServerRequest[P Params] struct {
	Session *ServerSession
	Params  P
	Extra   *RequestExtra
}

Generic server request with session, parameters, and extra transport information.

Methods:

func (r *ServerRequest[P]) GetExtra() *RequestExtra
func (r *ServerRequest[P]) GetParams() Params
func (r *ServerRequest[P]) GetSession() Session

Specific Server Request Types

type InitializedRequest = ServerRequest[*InitializedParams]
type CallToolRequest = ServerRequest[*CallToolParamsRaw]
type GetPromptRequest = ServerRequest[*GetPromptParams]
type ListPromptsRequest = ServerRequest[*ListPromptsParams]
type ReadResourceRequest = ServerRequest[*ReadResourceParams]
type ListResourcesRequest = ServerRequest[*ListResourcesParams]
type ListResourceTemplatesRequest = ServerRequest[*ListResourceTemplatesParams]
type CompleteRequest = ServerRequest[*CompleteParams]
type SubscribeRequest = ServerRequest[*SubscribeParams]
type UnsubscribeRequest = ServerRequest[*UnsubscribeParams]
type RootsListChangedRequest = ServerRequest[*RootsListChangedParams]
type ProgressNotificationServerRequest = ServerRequest[*ProgressNotificationParams]

Middleware

type Middleware func(MethodHandler) MethodHandler

Function that wraps a MethodHandler to intercept and modify requests or responses.

Utility Functions

func ResourceNotFoundError(uri string) error

Returns an error indicating that a resource could not be found.

Example: Complete Server with All Features

package main

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

type CalculateInput struct {
	Operation string  `json:"operation" jsonschema:"add, subtract, multiply, or divide"`
	A         float64 `json:"a" jsonschema:"first operand"`
	B         float64 `json:"b" jsonschema:"second operand"`
}

type CalculateOutput struct {
	Result float64 `json:"result" jsonschema:"calculation result"`
}

func calculate(ctx context.Context, req *mcp.CallToolRequest, input CalculateInput) (
	*mcp.CallToolResult,
	CalculateOutput,
	error,
) {
	var result float64
	switch input.Operation {
	case "add":
		result = input.A + input.B
	case "subtract":
		result = input.A - input.B
	case "multiply":
		result = input.A * input.B
	case "divide":
		if input.B == 0 {
			return &mcp.CallToolResult{IsError: true}, CalculateOutput{}, nil
		}
		result = input.A / input.B
	default:
		return &mcp.CallToolResult{IsError: true}, CalculateOutput{}, nil
	}
	return nil, CalculateOutput{Result: result}, nil
}

func greetingPrompt(ctx context.Context, req *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
	name := req.Params.Arguments["name"]
	if name == "" {
		name = "friend"
	}
	return &mcp.GetPromptResult{
		Messages: []*mcp.PromptMessage{
			{
				Role: "user",
				Content: &mcp.TextContent{
					Text: "Hello, " + name + "! How can I help you today?",
				},
			},
		},
	}, nil
}

func readConfig(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
	return &mcp.ReadResourceResult{
		Contents: []*mcp.ResourceContents{
			{
				URI:      req.Params.URI,
				MIMEType: "application/json",
				Text:     `{"version": "1.0", "enabled": true}`,
			},
		},
	}, nil
}

func main() {
	server := mcp.NewServer(
		&mcp.Implementation{Name: "example-server", Version: "1.0.0"},
		&mcp.ServerOptions{
			Instructions: "A server with tools, prompts, and resources",
			HasTools:     true,
			HasPrompts:   true,
			HasResources: true,
		},
	)

	// Add tool
	mcp.AddTool(server, &mcp.Tool{
		Name:        "calculate",
		Description: "Perform basic arithmetic",
	}, calculate)

	// Add prompt
	server.AddPrompt(&mcp.Prompt{
		Name:        "greeting",
		Description: "Generate a personalized greeting",
		Arguments: []*mcp.PromptArgument{
			{Name: "name", Description: "Person to greet", Required: false},
		},
	}, greetingPrompt)

	// Add resource
	server.AddResource(&mcp.Resource{
		URI:      "config://app.json",
		Name:     "App Config",
		MIMEType: "application/json",
	}, readConfig)

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