The server API enables building MCP servers that expose tools, prompts, and resources to clients. Servers handle initialization, capability negotiation, and request routing.
func NewServer(impl *Implementation, options *ServerOptions) *ServerCreates a new MCP server instance.
type Server struct {
// Has unexported fields
}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 initializationLogger: Optional structured logger for server operationsInitializedHandler: Called when client sends initialized notificationPageSize: Items per page for list operations (default: DefaultPageSize)RootsListChangedHandler: Called when client root list changesProgressNotificationHandler: Called on client progress notificationsCompletionHandler: Handler for argument completion requestsKeepAlive: Duration for connection keep-alive (0 to disable)SubscribeHandler: Handler for resource subscription requestsUnsubscribeHandler: Handler for resource unsubscription requestsHasPrompts: Server declares prompt capabilityHasResources: Server declares resource capabilityHasTools: Server declares tool capabilityGetSessionID: Custom session ID generatorfunc (s *Server) Run(ctx context.Context, t Transport) errorRuns 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.
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.
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.
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) errorSends a notification to all sessions that a resource has been updated.
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.
func (s *Server) Sessions() iter.Seq[*ServerSession]Returns an iterator over all active server sessions.
type ServerSession struct {
// Has unexported fields
}A logical connection from a single MCP client.
type ServerSessionOptions struct {
State *ServerSessionState
// Has unexported fields
}type ServerSessionState struct {
InitializeParams *InitializeParams `json:"initializeParams"`
InitializedParams *InitializedParams `json:"initializedParams"`
LogLevel LoggingLevel `json:"logLevel"`
}Represents the state of a server session.
func (s *ServerSession) ID() stringReturns the unique session identifier.
func (s *ServerSession) InitializeParams() *InitializeParamsReturns the initialization parameters from the client.
func (s *ServerSession) Close() errorGracefully closes the connection to the client.
func (s *ServerSession) Wait() errorWaits for the client to close the connection.
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) errorSends a log message to the client.
func (s *ServerSession) NotifyProgress(ctx context.Context, params *ProgressNotificationParams) errorSends a progress notification to the client.
func (s *ServerSession) Ping(ctx context.Context, params *PingParams) errorPings the client to check connectivity.
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.
type PromptHandler func(context.Context, *GetPromptRequest) (*GetPromptResult, error)Handler for prompts/get requests.
type ResourceHandler func(context.Context, *ReadResourceRequest) (*ReadResourceResult, error)Handler for resources/read requests.
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 metadataAnnotations: Hints about tool behaviorDescription: Human-readable descriptionInputSchema: JSON schema for input parametersName: Unique identifierOutputSchema: Optional JSON schema for outputTitle: Human-readable titletype 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 changesIdempotentHint: Whether tool is idempotentOpenWorldHint: Whether tool interacts with external systemsReadOnlyHint: Whether tool only reads dataTitle: Human-readable titletype 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 metadataArguments: Arguments the prompt acceptsDescription: Human-readable descriptionName: Unique identifierTitle: Human-readable titletype 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.
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 metadataAnnotations: Display and usage hintsDescription: Human-readable descriptionMIMEType: Resource MIME typeName: Human-readable nameSize: Resource size in bytesTitle: Human-readable titleURI: Unique resource identifiertype 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 metadataAnnotations: Display and usage hintsDescription: Human-readable descriptionMIMEType: Resource MIME typeName: Human-readable nameTitle: Human-readable titleURITemplate: URI template (RFC 6570) for generating resource URIstype 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)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() Sessiontype 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]type Middleware func(MethodHandler) MethodHandlerFunction that wraps a MethodHandler to intercept and modify requests or responses.
func ResourceNotFoundError(uri string) errorReturns an error indicating that a resource could not be found.
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)
}
}