mcp

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2025 License: MIT Imports: 38 Imported by: 148

Documentation

Overview

The mcp package provides an SDK for writing model context protocol clients and servers.

To get started, create either a Client or Server, add features to it using `AddXXX` functions, and connect it to a peer using a Transport.

For example, to run a simple server on the StdioTransport:

server := mcp.NewServer(&mcp.Implementation{Name: "greeter"}, nil)

// Using the generic AddTool automatically populates the the input and output
// schema of the tool.
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 the stdio transport.
if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
	log.Printf("Server failed: %v", err)
}

To connect to this server, use the CommandTransport:

client := mcp.NewClient(&mcp.Implementation{Name: "mcp-client", Version: "v1.0.0"}, nil)
transport := &mcp.CommandTransport{Command: exec.Command("myserver")}
session, err := client.Connect(ctx, transport, nil)
if err != nil {
	log.Fatal(err)
}
defer session.Close()

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

Clients, servers, and sessions

In this SDK, both a Client and Server may handle many concurrent connections. Each time a client or server is connected to a peer using a Transport, it creates a new session (either a ClientSession or ServerSession):

Client                                                   Server
 ⇅                          (jsonrpc2)                     ⇅
ClientSession ⇄ Client Transport ⇄ Server Transport ⇄ ServerSession

The session types expose an API to interact with its peer. For example, ClientSession.CallTool or ServerSession.ListRoots.

Adding features

Add MCP servers to your Client or Server using AddXXX methods (for example [Client.AddRoot] or Server.AddPrompt). If any peers are connected when AddXXX is called, they will receive a corresponding change notification (for example notifications/roots/list_changed).

Adding tools is special: tools may be bound to ordinary Go functions by using the top-level generic AddTool function, which allows specifying an input and output type. When AddTool is used, the tool's input schema and output schema are automatically populated, and inputs are automatically validated. As a special case, if the output type is 'any', no output schema is generated.

func double(_ context.Context, _ *mcp.CallToolRequest, in In) (*mcp.CallToolResponse, Out, error) {
	return nil, Out{Answer: 2*in.Number}, nil
}
...
mcp.AddTool(&mcp.Tool{Name: "double", Description: "double a number"}, double)

Index

Examples

Constants

View Source
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
)

Logging levels.

View Source
const (
	CodeResourceNotFound = -32002
	// The error code if the method exists and was called properly, but the peer does not support it.
	CodeUnsupportedMethod = -31001
	// The error code for invalid parameters
	CodeInvalidParams = -32602
)

Error codes

View Source
const DefaultPageSize = 1000

Variables

View Source
var ErrConnectionClosed = errors.New("connection closed")

ErrConnectionClosed is returned when sending a message to a connection that is closed or in the process of closing.

View Source
var ErrEventsPurged = errors.New("data purged")

ErrEventsPurged is the error that [EventStore.After] should return if the event just after the index is no longer available.

Functions

func AddTool added in v0.2.0

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

AddTool adds a tool and typed tool handler to the server.

If the tool's input schema is nil, it is set to the schema inferred from the In type parameter, using jsonschema.For. The In type argument must be a map or a struct, so that its inferred JSON Schema has type "object".

If the tool's output schema is nil, and the Out type is not 'any', the output schema is set to the schema inferred from the Out type argument, which also must be a map or struct.

Unlike Server.AddTool, AddTool does a lot automatically, and forces tools to conform to the MCP spec. See ToolHandlerFor for a detailed description of this automatic behavior.

func NewInMemoryTransports

func NewInMemoryTransports() (*InMemoryTransport, *InMemoryTransport)

NewInMemoryTransports returns two [InMemoryTransports] that connect to each other.

func ResourceNotFoundError

func ResourceNotFoundError(uri string) error

ResourceNotFoundError returns an error indicating that a resource being read could not be found.

Types

type Annotations

type Annotations struct {
	// Describes who the intended customer of this object or data is.
	//
	// It can include multiple entries to indicate content useful for multiple
	// audiences (e.g., []Role{"user", "assistant"}).
	Audience []Role `json:"audience,omitempty"`
	// The moment the resource was last modified, as an ISO 8601 formatted string.
	//
	// Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z").
	//
	// Examples: last activity timestamp in an open file, timestamp when the
	// resource was attached, etc.
	LastModified string `json:"lastModified,omitempty"`
	// Describes how important this data is for operating the server.
	//
	// A value of 1 means "most important," and indicates that the data is
	// effectively required, while 0 means "least important," and indicates that the
	// data is entirely optional.
	Priority float64 `json:"priority,omitempty"`
}

Optional annotations for the client. The client can use annotations to inform how objects are used or displayed

type AudioContent

type AudioContent struct {
	Data        []byte
	MIMEType    string
	Meta        Meta
	Annotations *Annotations
}

AudioContent contains base64-encoded audio data.

func (AudioContent) MarshalJSON

func (c AudioContent) MarshalJSON() ([]byte, error)

type CallToolParams

type CallToolParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta      `json:"_meta,omitempty"`
	Name      string `json:"name"`
	Arguments any    `json:"arguments,omitempty"`
}

CallToolParams is used by clients to call a tool.

func (*CallToolParams) GetProgressToken added in v0.3.0

func (x *CallToolParams) GetProgressToken() any

func (*CallToolParams) SetProgressToken added in v0.3.0

func (x *CallToolParams) SetProgressToken(t any)

type CallToolParamsRaw added in v0.4.0

type CallToolParamsRaw struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta      `json:"_meta,omitempty"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments,omitempty"`
}

CallToolParamsRaw is passed to tool handlers on the server. Its arguments are not yet unmarshaled (hence "raw"), so that the handlers can perform unmarshaling themselves.

func (*CallToolParamsRaw) GetProgressToken added in v0.4.0

func (x *CallToolParamsRaw) GetProgressToken() any

func (*CallToolParamsRaw) SetProgressToken added in v0.4.0

func (x *CallToolParamsRaw) SetProgressToken(t any)

type CallToolRequest added in v0.3.0

type CallToolRequest = ServerRequest[*CallToolParamsRaw]

type CallToolResult

type CallToolResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`

	// A list of content objects that represent the unstructured result of the tool
	// call.
	//
	// When using a [ToolHandlerFor] with structured output, if Content is unset
	// it will be populated with JSON text content corresponding to the
	// structured output value.
	Content []Content `json:"content"`

	// StructuredContent is an optional value that represents the structured
	// result of the tool call. It must marshal to a JSON object.
	//
	// When using a [ToolHandlerFor] with structured output, you should not
	// populate this field. It will be automatically populated with the typed Out
	// value.
	StructuredContent any `json:"structuredContent,omitempty"`

	// IsError reports whether the tool call ended in an error.
	//
	// If not set, this is assumed to be false (the call was successful).
	//
	// Any errors that originate from the tool should be reported inside the
	// Content field, with IsError set to true, not as an MCP protocol-level
	// error response. Otherwise, the LLM would not be able to see that an error
	// occurred and self-correct.
	//
	// However, any errors in finding the tool, an error indicating that the
	// server does not support tool calls, or any other exceptional conditions,
	// should be reported as an MCP error response.
	//
	// When using a [ToolHandlerFor], this field is automatically set when the
	// tool handler returns an error, and the error string is included as text in
	// the Content field.
	IsError bool `json:"isError,omitempty"`
}

A CallToolResult is the server's response to a tool call.

The ToolHandler and ToolHandlerFor handler functions return this result, though ToolHandlerFor populates much of it automatically as documented at each field.

func (*CallToolResult) UnmarshalJSON added in v0.3.0

func (x *CallToolResult) UnmarshalJSON(data []byte) error

UnmarshalJSON handles the unmarshalling of content into the Content interface.

type CancelledParams

type CancelledParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An optional string describing the reason for the cancellation. This may be
	// logged or presented to the user.
	Reason string `json:"reason,omitempty"`
	// The ID of the request to cancel.
	//
	// This must correspond to the ID of a request previously issued in the same
	// direction.
	RequestID any `json:"requestId"`
}

func (*CancelledParams) GetProgressToken

func (x *CancelledParams) GetProgressToken() any

func (*CancelledParams) SetProgressToken

func (x *CancelledParams) SetProgressToken(t any)

type Client

type Client struct {
	// contains filtered or unexported fields
}

A Client is an MCP client, which may be connected to an MCP server using the Client.Connect method.

func NewClient

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

NewClient creates a new Client.

Use Client.Connect to connect it to an MCP server.

The first argument must not be nil.

If non-nil, the provided options configure the Client.

func (*Client) AddReceivingMiddleware

func (c *Client) AddReceivingMiddleware(middleware ...Middleware)

AddReceivingMiddleware wraps the current receiving method handler using the provided middleware. Middleware is applied from right to left, so that the first one is executed first.

For example, AddReceivingMiddleware(m1, m2, m3) augments the method handler as m1(m2(m3(handler))).

Receiving middleware is called when a request is received. It is useful for tasks such as authentication, request logging and metrics.

func (*Client) AddRoots

func (c *Client) AddRoots(roots ...*Root)

AddRoots adds the given roots to the client, replacing any with the same URIs, and notifies any connected servers.

func (*Client) AddSendingMiddleware

func (c *Client) AddSendingMiddleware(middleware ...Middleware)

AddSendingMiddleware wraps the current sending method handler using the provided middleware. Middleware is applied from right to left, so that the first one is executed first.

For example, AddSendingMiddleware(m1, m2, m3) augments the method handler as m1(m2(m3(handler))).

Sending middleware is called when a request is sent. It is useful for tasks such as tracing, metrics, and adding progress tokens.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, t Transport, _ *ClientSessionOptions) (cs *ClientSession, err error)

Connect begins an MCP session by connecting to a server over the given transport, and initializing the session.

Typically, it is the responsibility of the client to close the connection when it is no longer needed. However, if the connection is closed by the server, calls or notifications will return an error wrapping ErrConnectionClosed.

func (*Client) RemoveRoots

func (c *Client) RemoveRoots(uris ...string)

RemoveRoots removes the roots with the given URIs, and notifies any connected servers if the list has changed. It is not an error to remove a nonexistent root.

type ClientCapabilities

type ClientCapabilities struct {
	// Experimental, non-standard capabilities that the client supports.
	Experimental map[string]any `json:"experimental,omitempty"`
	// Present if the client supports listing roots.
	Roots struct {
		// Whether the client supports notifications for changes to the roots list.
		ListChanged bool `json:"listChanged,omitempty"`
	} `json:"roots,omitempty"`
	// Present if the client supports sampling from an LLM.
	Sampling *SamplingCapabilities `json:"sampling,omitempty"`
	// Present if the client supports elicitation from the server.
	Elicitation *ElicitationCapabilities `json:"elicitation,omitempty"`
}

Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.

type ClientOptions

type ClientOptions struct {
	// Handler for sampling.
	// Called when a server calls CreateMessage.
	CreateMessageHandler func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error)
	// Handler for elicitation.
	// Called when a server requests user input via Elicit.
	ElicitationHandler func(context.Context, *ElicitRequest) (*ElicitResult, error)
	// Handlers for notifications from the server.
	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)
	// If non-zero, defines an interval for regular "ping" requests.
	// If the peer fails to respond to pings originating from the keepalive check,
	// the session is automatically closed.
	KeepAlive time.Duration
}

ClientOptions configures the behavior of the client.

type ClientRequest added in v0.3.0

type ClientRequest[P Params] struct {
	Session *ClientSession
	Params  P
}

A ClientRequest is a request to a client.

func (*ClientRequest[P]) GetExtra added in v0.3.0

func (r *ClientRequest[P]) GetExtra() *RequestExtra

func (*ClientRequest[P]) GetParams added in v0.3.0

func (r *ClientRequest[P]) GetParams() Params

func (*ClientRequest[P]) GetSession added in v0.3.0

func (r *ClientRequest[P]) GetSession() Session

type ClientSession

type ClientSession struct {
	// contains filtered or unexported fields
}

A ClientSession is a logical connection with an MCP server. Its methods can be used to send requests or notifications to the server. Create a session by calling Client.Connect.

Call ClientSession.Close to close the connection, or await server termination with ClientSession.Wait.

func (*ClientSession) CallTool

func (cs *ClientSession) CallTool(ctx context.Context, params *CallToolParams) (*CallToolResult, error)

CallTool calls the tool with the given name and arguments. The arguments can be any value that marshals into a JSON object.

func (*ClientSession) Close

func (cs *ClientSession) Close() error

Close performs a graceful close of the connection, preventing new requests from being handled, and waiting for ongoing requests to return. Close then terminates the connection.

func (*ClientSession) Complete

func (cs *ClientSession) Complete(ctx context.Context, params *CompleteParams) (*CompleteResult, error)

func (*ClientSession) GetPrompt

func (cs *ClientSession) GetPrompt(ctx context.Context, params *GetPromptParams) (*GetPromptResult, error)

GetPrompt gets a prompt from the server.

func (*ClientSession) ID

func (cs *ClientSession) ID() string

func (*ClientSession) InitializeResult added in v0.3.0

func (cs *ClientSession) InitializeResult() *InitializeResult

func (*ClientSession) ListPrompts

func (cs *ClientSession) ListPrompts(ctx context.Context, params *ListPromptsParams) (*ListPromptsResult, error)

ListPrompts lists prompts that are currently available on the server.

func (*ClientSession) ListResourceTemplates

func (cs *ClientSession) ListResourceTemplates(ctx context.Context, params *ListResourceTemplatesParams) (*ListResourceTemplatesResult, error)

ListResourceTemplates lists the resource templates that are currently available on the server.

func (*ClientSession) ListResources

func (cs *ClientSession) ListResources(ctx context.Context, params *ListResourcesParams) (*ListResourcesResult, error)

ListResources lists the resources that are currently available on the server.

func (*ClientSession) ListTools

func (cs *ClientSession) ListTools(ctx context.Context, params *ListToolsParams) (*ListToolsResult, error)

ListTools lists tools that are currently available on the server.

func (*ClientSession) NotifyProgress

func (cs *ClientSession) NotifyProgress(ctx context.Context, params *ProgressNotificationParams) error

NotifyProgress sends a progress notification from the client to the server associated with this session. This can be used if the client is performing a long-running task that was initiated by the server

func (*ClientSession) Ping

func (cs *ClientSession) Ping(ctx context.Context, params *PingParams) error

Ping makes an MCP "ping" request to the server.

func (*ClientSession) Prompts

func (cs *ClientSession) Prompts(ctx context.Context, params *ListPromptsParams) iter.Seq2[*Prompt, error]

Prompts provides an iterator for all prompts available on the server, automatically fetching pages and managing cursors. The params argument can set the initial cursor. Iteration stops at the first encountered error, which will be yielded.

func (*ClientSession) ReadResource

func (cs *ClientSession) ReadResource(ctx context.Context, params *ReadResourceParams) (*ReadResourceResult, error)

ReadResource asks the server to read a resource and return its contents.

func (*ClientSession) ResourceTemplates

ResourceTemplates provides an iterator for all resource templates available on the server, automatically fetching pages and managing cursors. The `params` argument can set the initial cursor. Iteration stops at the first encountered error, which will be yielded.

func (*ClientSession) Resources

func (cs *ClientSession) Resources(ctx context.Context, params *ListResourcesParams) iter.Seq2[*Resource, error]

Resources provides an iterator for all resources available on the server, automatically fetching pages and managing cursors. The params argument can set the initial cursor. Iteration stops at the first encountered error, which will be yielded.

func (*ClientSession) SetLoggingLevel added in v0.3.0

func (cs *ClientSession) SetLoggingLevel(ctx context.Context, params *SetLoggingLevelParams) error

func (*ClientSession) Subscribe added in v0.3.0

func (cs *ClientSession) Subscribe(ctx context.Context, params *SubscribeParams) error

Subscribe sends a "resources/subscribe" request to the server, asking for notifications when the specified resource changes.

func (*ClientSession) Tools

func (cs *ClientSession) Tools(ctx context.Context, params *ListToolsParams) iter.Seq2[*Tool, error]

Tools provides an iterator for all tools available on the server, automatically fetching pages and managing cursors. The params argument can set the initial cursor. Iteration stops at the first encountered error, which will be yielded.

func (*ClientSession) Unsubscribe added in v0.3.0

func (cs *ClientSession) Unsubscribe(ctx context.Context, params *UnsubscribeParams) error

Unsubscribe sends a "resources/unsubscribe" request to the server, cancelling a previous subscription.

func (*ClientSession) Wait

func (cs *ClientSession) Wait() error

Wait waits for the connection to be closed by the server. Generally, clients should be responsible for closing the connection.

type ClientSessionOptions added in v0.3.0

type ClientSessionOptions struct{}

ClientSessionOptions is reserved for future use.

type CommandTransport

type CommandTransport struct {
	Command *exec.Cmd
	// TerminateDuration controls how long Close waits after closing stdin
	// for the process to exit before sending SIGTERM.
	// If zero or negative, the default of 5s is used.
	TerminateDuration time.Duration
}

A CommandTransport is a Transport that runs a command and communicates with it over stdin/stdout, using newline-delimited JSON.

func (*CommandTransport) Connect

func (t *CommandTransport) Connect(ctx context.Context) (Connection, error)

Connect starts the command, and connects to it over stdin/stdout.

type CompleteContext

type CompleteContext struct {
	// Previously-resolved variables in a URI template or prompt.
	Arguments map[string]string `json:"arguments,omitempty"`
}

CompleteContext represents additional, optional context for completions.

type CompleteParams

type CompleteParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The argument's information
	Argument CompleteParamsArgument `json:"argument"`
	Context  *CompleteContext       `json:"context,omitempty"`
	Ref      *CompleteReference     `json:"ref"`
}

type CompleteParamsArgument

type CompleteParamsArgument struct {
	// The name of the argument
	Name string `json:"name"`
	// The value of the argument to use for completion matching.
	Value string `json:"value"`
}

type CompleteReference

type CompleteReference struct {
	Type string `json:"type"`
	// Name is relevant when Type is "ref/prompt".
	Name string `json:"name,omitempty"`
	// URI is relevant when Type is "ref/resource".
	URI string `json:"uri,omitempty"`
}

CompleteReference represents a completion reference type (ref/prompt ref/resource). The Type field determines which other fields are relevant.

func (*CompleteReference) MarshalJSON

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

func (*CompleteReference) UnmarshalJSON

func (r *CompleteReference) UnmarshalJSON(data []byte) error

type CompleteRequest added in v0.3.0

type CompleteRequest = ServerRequest[*CompleteParams]

type CompleteResult

type CompleteResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta       `json:"_meta,omitempty"`
	Completion CompletionResultDetails `json:"completion"`
}

The server's response to a completion/complete request

type CompletionCapabilities added in v0.3.0

type CompletionCapabilities struct{}

Present if the server supports argument autocompletion suggestions.

type CompletionResultDetails

type CompletionResultDetails struct {
	HasMore bool     `json:"hasMore,omitempty"`
	Total   int      `json:"total,omitempty"`
	Values  []string `json:"values"`
}

type Connection

type Connection interface {
	// Read reads the next message to process off the connection.
	//
	// Connections must allow Read to be called concurrently with Close. In
	// particular, calling Close should unblock a Read waiting for input.
	Read(context.Context) (jsonrpc.Message, error)

	// Write writes a new message to the connection.
	//
	// Write may be called concurrently, as calls or reponses may occur
	// concurrently in user code.
	Write(context.Context, jsonrpc.Message) error

	// Close closes the connection. It is implicitly called whenever a Read or
	// Write fails.
	//
	// Close may be called multiple times, potentially concurrently.
	Close() error

	// TODO(#148): remove SessionID from this interface.
	SessionID() string
}

A Connection is a logical bidirectional JSON-RPC connection.

type Content

type Content interface {
	MarshalJSON() ([]byte, error)
	// contains filtered or unexported methods
}

A Content is a TextContent, ImageContent, AudioContent, ResourceLink, or EmbeddedResource.

type CreateMessageParams

type CreateMessageParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// A request to include context from one or more MCP servers (including the
	// caller), to be attached to the prompt. The client may ignore this request.
	IncludeContext string `json:"includeContext,omitempty"`
	// The maximum number of tokens to sample, as requested by the server. The
	// client may choose to sample fewer tokens than requested.
	MaxTokens int64              `json:"maxTokens"`
	Messages  []*SamplingMessage `json:"messages"`
	// Optional metadata to pass through to the LLM provider. The format of this
	// metadata is provider-specific.
	Metadata any `json:"metadata,omitempty"`
	// The server's preferences for which model to select. The client may ignore
	// these preferences.
	ModelPreferences *ModelPreferences `json:"modelPreferences,omitempty"`
	StopSequences    []string          `json:"stopSequences,omitempty"`
	// An optional system prompt the server wants to use for sampling. The client
	// may modify or omit this prompt.
	SystemPrompt string  `json:"systemPrompt,omitempty"`
	Temperature  float64 `json:"temperature,omitempty"`
}

func (*CreateMessageParams) GetProgressToken

func (x *CreateMessageParams) GetProgressToken() any

func (*CreateMessageParams) SetProgressToken

func (x *CreateMessageParams) SetProgressToken(t any)

type CreateMessageRequest added in v0.3.0

type CreateMessageRequest = ClientRequest[*CreateMessageParams]

type CreateMessageResult

type CreateMessageResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content"`
	// The name of the model that generated the message.
	Model string `json:"model"`
	Role  Role   `json:"role"`
	// The reason why sampling stopped, if known.
	StopReason string `json:"stopReason,omitempty"`
}

The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it.

func (*CreateMessageResult) UnmarshalJSON added in v0.3.0

func (r *CreateMessageResult) UnmarshalJSON(data []byte) error

type ElicitParams added in v0.3.0

type ElicitParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The message to present to the user.
	Message string `json:"message"`
	// A restricted subset of JSON Schema.
	// Only top-level properties are allowed, without nesting.
	RequestedSchema *jsonschema.Schema `json:"requestedSchema"`
}

A request from the server to elicit additional information from the user via the client.

func (*ElicitParams) GetProgressToken added in v0.3.0

func (x *ElicitParams) GetProgressToken() any

func (*ElicitParams) SetProgressToken added in v0.3.0

func (x *ElicitParams) SetProgressToken(t any)

type ElicitRequest added in v0.3.0

type ElicitRequest = ClientRequest[*ElicitParams]

type ElicitResult added in v0.3.0

type ElicitResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The user action in response to the elicitation.
	// - "accept": User submitted the form/confirmed the action
	// - "decline": User explicitly declined the action
	// - "cancel": User dismissed without making an explicit choice
	Action string `json:"action"`
	// The submitted form data, only present when action is "accept".
	// Contains values matching the requested schema.
	Content map[string]any `json:"content,omitempty"`
}

The client's response to an elicitation/create request from the server.

type ElicitationCapabilities

type ElicitationCapabilities struct{}

ElicitationCapabilities describes the capabilities for elicitation.

type EmbeddedResource

type EmbeddedResource struct {
	Resource    *ResourceContents
	Meta        Meta
	Annotations *Annotations
}

EmbeddedResource contains embedded resources.

func (*EmbeddedResource) MarshalJSON

func (c *EmbeddedResource) MarshalJSON() ([]byte, error)

type Event added in v0.3.0

type Event struct {
	Name string // the "event" field
	ID   string // the "id" field
	Data []byte // the "data" field
}

An Event is a server-sent event. See https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#fields.

func (Event) Empty added in v0.3.0

func (e Event) Empty() bool

Empty reports whether the Event is empty.

type EventStore added in v0.3.0

type EventStore interface {
	// Open prepares the event store for a given stream. It ensures that the
	// underlying data structure for the stream is initialized, making it
	// ready to store event streams.
	Open(_ context.Context, sessionID string, streamID StreamID) error

	// Append appends data for an outgoing event to given stream, which is part of the
	// given session.
	Append(_ context.Context, sessionID string, _ StreamID, data []byte) error

	// After returns an iterator over the data for the given session and stream, beginning
	// just after the given index.
	// Once the iterator yields a non-nil error, it will stop.
	// After's iterator must return an error immediately if any data after index was
	// dropped; it must not return partial results.
	// The stream must have been opened previously (see [EventStore.Open]).
	After(_ context.Context, sessionID string, _ StreamID, index int) iter.Seq2[[]byte, error]

	// SessionClosed informs the store that the given session is finished, along
	// with all of its streams.
	// A store cannot rely on this method being called for cleanup. It should institute
	// additional mechanisms, such as timeouts, to reclaim storage.
	//
	SessionClosed(_ context.Context, sessionID string) error
}

An EventStore tracks data for SSE streams. A single EventStore suffices for all sessions, since session IDs are globally unique. So one EventStore can be created per process, for all Servers in the process. Such a store is able to bound resource usage for the entire process.

All of an EventStore's methods must be safe for use by multiple goroutines.

type GetPromptParams

type GetPromptParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// Arguments to use for templating the prompt.
	Arguments map[string]string `json:"arguments,omitempty"`
	// The name of the prompt or prompt template.
	Name string `json:"name"`
}

func (*GetPromptParams) GetProgressToken

func (x *GetPromptParams) GetProgressToken() any

func (*GetPromptParams) SetProgressToken

func (x *GetPromptParams) SetProgressToken(t any)

type GetPromptRequest added in v0.3.0

type GetPromptRequest = ServerRequest[*GetPromptParams]

type GetPromptResult

type GetPromptResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An optional description for the prompt.
	Description string           `json:"description,omitempty"`
	Messages    []*PromptMessage `json:"messages"`
}

The server's response to a prompts/get request from the client.

type ImageContent

type ImageContent struct {
	Meta        Meta
	Annotations *Annotations
	Data        []byte // base64-encoded
	MIMEType    string
}

ImageContent contains base64-encoded image data.

func (*ImageContent) MarshalJSON

func (c *ImageContent) MarshalJSON() ([]byte, error)

type Implementation added in v0.2.0

type Implementation struct {
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	Title   string `json:"title,omitempty"`
	Version string `json:"version"`
}

An Implementation describes the name and version of an MCP implementation, with an optional title for UI representation.

type InMemoryTransport

type InMemoryTransport struct {
	// contains filtered or unexported fields
}

An InMemoryTransport is a Transport that communicates over an in-memory network connection, using newline-delimited JSON.

func (*InMemoryTransport) Connect

Connect implements the Transport interface.

type InitializeParams

type InitializeParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta         `json:"_meta,omitempty"`
	Capabilities *ClientCapabilities `json:"capabilities"`
	ClientInfo   *Implementation     `json:"clientInfo"`
	// The latest version of the Model Context Protocol that the client supports.
	// The client may decide to support older versions as well.
	ProtocolVersion string `json:"protocolVersion"`
}

func (*InitializeParams) GetProgressToken

func (x *InitializeParams) GetProgressToken() any

func (*InitializeParams) SetProgressToken

func (x *InitializeParams) SetProgressToken(t any)

type InitializeRequest added in v0.3.0

type InitializeRequest = ClientRequest[*InitializeParams]

type InitializeResult

type InitializeResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta         `json:"_meta,omitempty"`
	Capabilities *ServerCapabilities `json:"capabilities"`
	// Instructions describing how to use the server and its features.
	//
	// This can be used by clients to improve the LLM's understanding of available
	// tools, resources, etc. It can be thought of like a "hint" to the model. For
	// example, this information may be added to the system prompt.
	Instructions string `json:"instructions,omitempty"`
	// The version of the Model Context Protocol that the server wants to use. This
	// may not match the version that the client requested. If the client cannot
	// support this version, it must disconnect.
	ProtocolVersion string          `json:"protocolVersion"`
	ServerInfo      *Implementation `json:"serverInfo"`
}

After receiving an initialize request from the client, the server sends this response.

type InitializedParams

type InitializedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
}

func (*InitializedParams) GetProgressToken

func (x *InitializedParams) GetProgressToken() any

func (*InitializedParams) SetProgressToken

func (x *InitializedParams) SetProgressToken(t any)

type InitializedRequest added in v0.3.0

type InitializedRequest = ServerRequest[*InitializedParams]

type ListPromptsParams

type ListPromptsParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An opaque token representing the current pagination position. If provided,
	// the server should return results starting after this cursor.
	Cursor string `json:"cursor,omitempty"`
}

func (*ListPromptsParams) GetProgressToken

func (x *ListPromptsParams) GetProgressToken() any

func (*ListPromptsParams) SetProgressToken

func (x *ListPromptsParams) SetProgressToken(t any)

type ListPromptsRequest added in v0.3.0

type ListPromptsRequest = ServerRequest[*ListPromptsParams]

type ListPromptsResult

type ListPromptsResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An opaque token representing the pagination position after the last returned
	// result. If present, there may be more results available.
	NextCursor string    `json:"nextCursor,omitempty"`
	Prompts    []*Prompt `json:"prompts"`
}

The server's response to a prompts/list request from the client.

type ListResourceTemplatesParams

type ListResourceTemplatesParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An opaque token representing the current pagination position. If provided,
	// the server should return results starting after this cursor.
	Cursor string `json:"cursor,omitempty"`
}

func (*ListResourceTemplatesParams) GetProgressToken

func (x *ListResourceTemplatesParams) GetProgressToken() any

func (*ListResourceTemplatesParams) SetProgressToken

func (x *ListResourceTemplatesParams) SetProgressToken(t any)

type ListResourceTemplatesRequest added in v0.3.0

type ListResourceTemplatesRequest = ServerRequest[*ListResourceTemplatesParams]

type ListResourceTemplatesResult

type ListResourceTemplatesResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An opaque token representing the pagination position after the last returned
	// result. If present, there may be more results available.
	NextCursor        string              `json:"nextCursor,omitempty"`
	ResourceTemplates []*ResourceTemplate `json:"resourceTemplates"`
}

The server's response to a resources/templates/list request from the client.

type ListResourcesParams

type ListResourcesParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An opaque token representing the current pagination position. If provided,
	// the server should return results starting after this cursor.
	Cursor string `json:"cursor,omitempty"`
}

func (*ListResourcesParams) GetProgressToken

func (x *ListResourcesParams) GetProgressToken() any

func (*ListResourcesParams) SetProgressToken

func (x *ListResourcesParams) SetProgressToken(t any)

type ListResourcesRequest added in v0.3.0

type ListResourcesRequest = ServerRequest[*ListResourcesParams]

type ListResourcesResult

type ListResourcesResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An opaque token representing the pagination position after the last returned
	// result. If present, there may be more results available.
	NextCursor string      `json:"nextCursor,omitempty"`
	Resources  []*Resource `json:"resources"`
}

The server's response to a resources/list request from the client.

type ListRootsParams

type ListRootsParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
}

func (*ListRootsParams) GetProgressToken

func (x *ListRootsParams) GetProgressToken() any

func (*ListRootsParams) SetProgressToken

func (x *ListRootsParams) SetProgressToken(t any)

type ListRootsRequest added in v0.3.0

type ListRootsRequest = ClientRequest[*ListRootsParams]

type ListRootsResult

type ListRootsResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta  `json:"_meta,omitempty"`
	Roots []*Root `json:"roots"`
}

The client's response to a roots/list request from the server. This result contains an array of Root objects, each representing a root directory or file that the server can operate on.

type ListToolsParams

type ListToolsParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An opaque token representing the current pagination position. If provided,
	// the server should return results starting after this cursor.
	Cursor string `json:"cursor,omitempty"`
}

func (*ListToolsParams) GetProgressToken

func (x *ListToolsParams) GetProgressToken() any

func (*ListToolsParams) SetProgressToken

func (x *ListToolsParams) SetProgressToken(t any)

type ListToolsRequest added in v0.3.0

type ListToolsRequest = ServerRequest[*ListToolsParams]

type ListToolsResult

type ListToolsResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An opaque token representing the pagination position after the last returned
	// result. If present, there may be more results available.
	NextCursor string  `json:"nextCursor,omitempty"`
	Tools      []*Tool `json:"tools"`
}

The server's response to a tools/list request from the client.

type LoggingCapabilities added in v0.3.0

type LoggingCapabilities struct{}

Present if the server supports sending log messages to the client.

type LoggingHandler

type LoggingHandler struct {
	// contains filtered or unexported fields
}

A LoggingHandler is a slog.Handler for MCP.

func NewLoggingHandler

func NewLoggingHandler(ss *ServerSession, opts *LoggingHandlerOptions) *LoggingHandler

NewLoggingHandler creates a LoggingHandler that logs to the given ServerSession using a slog.JSONHandler.

func (*LoggingHandler) Enabled

func (h *LoggingHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled implements slog.Handler.Enabled by comparing level to the ServerSession's level.

func (*LoggingHandler) Handle

func (h *LoggingHandler) Handle(ctx context.Context, r slog.Record) error

Handle implements slog.Handler.Handle by writing the Record to a JSONHandler, then calling [ServerSession.LoggingMessage] with the result.

func (*LoggingHandler) WithAttrs

func (h *LoggingHandler) WithAttrs(as []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.WithAttrs.

func (*LoggingHandler) WithGroup

func (h *LoggingHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler.WithGroup.

type LoggingHandlerOptions

type LoggingHandlerOptions struct {
	// The value for the "logger" field of logging notifications.
	LoggerName string
	// Limits the rate at which log messages are sent.
	// If zero, there is no rate limiting.
	MinInterval time.Duration
}

LoggingHandlerOptions are options for a LoggingHandler.

type LoggingLevel

type LoggingLevel string

The severity of a log message.

These map to syslog message severities, as specified in RFC-5424: https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1

type LoggingMessageParams

type LoggingMessageParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The data to be logged, such as a string message or an object. Any JSON
	// serializable type is allowed here.
	Data any `json:"data"`
	// The severity of this log message.
	Level LoggingLevel `json:"level"`
	// An optional name of the logger issuing this message.
	Logger string `json:"logger,omitempty"`
}

func (*LoggingMessageParams) GetProgressToken

func (x *LoggingMessageParams) GetProgressToken() any

func (*LoggingMessageParams) SetProgressToken

func (x *LoggingMessageParams) SetProgressToken(t any)

type LoggingMessageRequest added in v0.3.0

type LoggingMessageRequest = ClientRequest[*LoggingMessageParams]

type LoggingTransport

type LoggingTransport struct {
	Transport Transport
	Writer    io.Writer
}

A LoggingTransport is a Transport that delegates to another transport, writing RPC logs to an io.Writer.

func (*LoggingTransport) Connect

func (t *LoggingTransport) Connect(ctx context.Context) (Connection, error)

Connect connects the underlying transport, returning a Connection that writes logs to the configured destination.

type MemoryEventStore added in v0.3.0

type MemoryEventStore struct {
	// contains filtered or unexported fields
}

A MemoryEventStore is an EventStore backed by memory.

func NewMemoryEventStore added in v0.3.0

func NewMemoryEventStore(opts *MemoryEventStoreOptions) *MemoryEventStore

NewMemoryEventStore creates a MemoryEventStore with the default value for MaxBytes.

func (*MemoryEventStore) After added in v0.3.0

func (s *MemoryEventStore) After(_ context.Context, sessionID string, streamID StreamID, index int) iter.Seq2[[]byte, error]

After implements [EventStore.After].

func (*MemoryEventStore) Append added in v0.3.0

func (s *MemoryEventStore) Append(_ context.Context, sessionID string, streamID StreamID, data []byte) error

Append implements [EventStore.Append] by recording data in memory.

func (*MemoryEventStore) MaxBytes added in v0.3.0

func (s *MemoryEventStore) MaxBytes() int

MaxBytes returns the maximum number of bytes that the store will retain before purging data.

func (*MemoryEventStore) Open added in v0.3.1

func (s *MemoryEventStore) Open(_ context.Context, sessionID string, streamID StreamID) error

Open implements [EventStore.Open]. It ensures that the underlying data structures for the given session are initialized and ready for use.

func (*MemoryEventStore) SessionClosed added in v0.3.0

func (s *MemoryEventStore) SessionClosed(_ context.Context, sessionID string) error

SessionClosed implements [EventStore.SessionClosed].

func (*MemoryEventStore) SetMaxBytes added in v0.3.0

func (s *MemoryEventStore) SetMaxBytes(n int)

SetMaxBytes sets the maximum number of bytes the store will retain before purging data. The argument must not be negative. If it is zero, a suitable default will be used. SetMaxBytes can be called at any time. The size of the store will be adjusted immediately.

type MemoryEventStoreOptions added in v0.3.0

type MemoryEventStoreOptions struct{}

MemoryEventStoreOptions are options for a MemoryEventStore.

type Meta

type Meta map[string]any

Meta is additional metadata for requests, responses and other types.

func (Meta) GetMeta

func (m Meta) GetMeta() map[string]any

GetMeta returns metadata from a value.

func (*Meta) SetMeta

func (m *Meta) SetMeta(x map[string]any)

SetMeta sets the metadata on a value.

type MethodHandler

type MethodHandler func(ctx context.Context, method string, req Request) (result Result, err error)

A MethodHandler handles MCP messages. For methods, exactly one of the return values must be nil. For notifications, both must be nil.

type Middleware

type Middleware func(MethodHandler) MethodHandler

Middleware is a function from MethodHandler to MethodHandler.

type ModelHint

type ModelHint struct {
	// A hint for a model name.
	//
	// The client should treat this as a substring of a model name; for example: -
	// `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` - `sonnet`
	// should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. -
	// `claude` should match any Claude model
	//
	// The client may also map the string to a different provider's model name or a
	// different model family, as long as it fills a similar niche; for example: -
	// `gemini-1.5-flash` could match `claude-3-haiku-20240307`
	Name string `json:"name,omitempty"`
}

Hints to use for model selection.

Keys not declared here are currently left unspecified by the spec and are up to the client to interpret.

type ModelPreferences

type ModelPreferences struct {
	// How much to prioritize cost when selecting a model. A value of 0 means cost
	// is not important, while a value of 1 means cost is the most important factor.
	CostPriority float64 `json:"costPriority,omitempty"`
	// Optional hints to use for model selection.
	//
	// If multiple hints are specified, the client must evaluate them in order (such
	// that the first match is taken).
	//
	// The client should prioritize these hints over the numeric priorities, but may
	// still use the priorities to select from ambiguous matches.
	Hints []*ModelHint `json:"hints,omitempty"`
	// How much to prioritize intelligence and capabilities when selecting a model.
	// A value of 0 means intelligence is not important, while a value of 1 means
	// intelligence is the most important factor.
	IntelligencePriority float64 `json:"intelligencePriority,omitempty"`
	// How much to prioritize sampling speed (latency) when selecting a model. A
	// value of 0 means speed is not important, while a value of 1 means speed is
	// the most important factor.
	SpeedPriority float64 `json:"speedPriority,omitempty"`
}

The server's preferences for model selection, requested of the client during sampling.

Because LLMs can vary along multiple dimensions, choosing the "best" model is rarely straightforward. Different models excel in different areas—some are faster but less capable, others are more capable but more expensive, and so on. This interface allows servers to express their priorities across multiple dimensions to help clients make an appropriate selection for their use case.

These preferences are always advisory. The client may ignore them. It is also up to the client to decide how to interpret these preferences and how to balance them against other considerations.

type Params

type Params interface {

	// GetMeta returns metadata from a value.
	GetMeta() map[string]any
	// SetMeta sets the metadata on a value.
	SetMeta(map[string]any)
	// contains filtered or unexported methods
}

Params is a parameter (input) type for an MCP call or notification.

type PingParams

type PingParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
}

func (*PingParams) GetProgressToken

func (x *PingParams) GetProgressToken() any

func (*PingParams) SetProgressToken

func (x *PingParams) SetProgressToken(t any)

type ProgressNotificationClientRequest added in v0.3.0

type ProgressNotificationClientRequest = ClientRequest[*ProgressNotificationParams]

type ProgressNotificationParams

type ProgressNotificationParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// An optional message describing the current progress.
	Message string `json:"message,omitempty"`
	// The progress thus far. This should increase every time progress is made, even
	// if the total is unknown.
	Progress float64 `json:"progress"`
	// The progress token which was given in the initial request, used to associate
	// this notification with the request that is proceeding.
	ProgressToken any `json:"progressToken"`
	// Total number of items to process (or total progress required), if known.
	Total float64 `json:"total,omitempty"`
}

type ProgressNotificationServerRequest added in v0.3.0

type ProgressNotificationServerRequest = ServerRequest[*ProgressNotificationParams]

type Prompt

type Prompt struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// A list of arguments to use for templating the prompt.
	Arguments []*PromptArgument `json:"arguments,omitempty"`
	// An optional description of what this prompt provides
	Description string `json:"description,omitempty"`
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	Title string `json:"title,omitempty"`
}

A prompt or prompt template that the server offers.

type PromptArgument

type PromptArgument struct {
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	Title string `json:"title,omitempty"`
	// A human-readable description of the argument.
	Description string `json:"description,omitempty"`
	// Whether this argument must be provided.
	Required bool `json:"required,omitempty"`
}

Describes an argument that a prompt can accept.

type PromptCapabilities added in v0.3.0

type PromptCapabilities struct {
	// Whether this server supports notifications for changes to the prompt list.
	ListChanged bool `json:"listChanged,omitempty"`
}

Present if the server offers any prompt templates.

type PromptHandler

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

A PromptHandler handles a call to prompts/get.

type PromptListChangedParams

type PromptListChangedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
}

func (*PromptListChangedParams) GetProgressToken

func (x *PromptListChangedParams) GetProgressToken() any

func (*PromptListChangedParams) SetProgressToken

func (x *PromptListChangedParams) SetProgressToken(t any)

type PromptListChangedRequest added in v0.3.0

type PromptListChangedRequest = ClientRequest[*PromptListChangedParams]

type PromptMessage

type PromptMessage struct {
	Content Content `json:"content"`
	Role    Role    `json:"role"`
}

Describes a message returned as part of a prompt.

This is similar to SamplingMessage, but also supports the embedding of resources from the MCP server.

func (*PromptMessage) UnmarshalJSON

func (m *PromptMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON handles the unmarshalling of content into the Content interface.

type ReadResourceParams

type ReadResourceParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The URI of the resource to read. The URI can use any protocol; it is up to
	// the server how to interpret it.
	URI string `json:"uri"`
}

func (*ReadResourceParams) GetProgressToken

func (x *ReadResourceParams) GetProgressToken() any

func (*ReadResourceParams) SetProgressToken

func (x *ReadResourceParams) SetProgressToken(t any)

type ReadResourceRequest added in v0.3.0

type ReadResourceRequest = ServerRequest[*ReadResourceParams]

type ReadResourceResult

type ReadResourceResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta     `json:"_meta,omitempty"`
	Contents []*ResourceContents `json:"contents"`
}

The server's response to a resources/read request from the client.

type Request added in v0.3.0

type Request interface {
	GetSession() Session
	GetParams() Params
	// GetExtra returns the Extra field for ServerRequests, and nil for ClientRequests.
	GetExtra() *RequestExtra
	// contains filtered or unexported methods
}

A Request is a method request with parameters and additional information, such as the session. Request is implemented by *ClientRequest and *ServerRequest.

type RequestExtra added in v0.3.0

type RequestExtra struct {
	TokenInfo *auth.TokenInfo // bearer token info (e.g. from OAuth) if any
	Header    http.Header     // header from HTTP request, if any
}

RequestExtra is extra information included in requests, typically from the transport layer.

type RequestParams

type RequestParams interface {
	Params

	// GetProgressToken returns the progress token from the params' Meta field, or nil
	// if there is none.
	GetProgressToken() any

	// SetProgressToken sets the given progress token into the params' Meta field.
	// It panics if its argument is not an int or a string.
	SetProgressToken(any)
}

RequestParams is a parameter (input) type for an MCP request.

type Resource

type Resource struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// Optional annotations for the client.
	Annotations *Annotations `json:"annotations,omitempty"`
	// A description of what this resource represents.
	//
	// This can be used by clients to improve the LLM's understanding of available
	// resources. It can be thought of like a "hint" to the model.
	Description string `json:"description,omitempty"`
	// The MIME type of this resource, if known.
	MIMEType string `json:"mimeType,omitempty"`
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// The size of the raw resource content, in bytes (i.e., before base64 encoding
	// or any tokenization), if known.
	//
	// This can be used by Hosts to display file sizes and estimate context window
	// usage.
	Size int64 `json:"size,omitempty"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	//
	// If not provided, the name should be used for display (except for Tool, where
	// Annotations.Title should be given precedence over using name, if
	// present).
	Title string `json:"title,omitempty"`
	// The URI of this resource.
	URI string `json:"uri"`
}

A known resource that the server is capable of reading.

type ResourceCapabilities added in v0.3.0

type ResourceCapabilities struct {
	// Whether this server supports notifications for changes to the resource list.
	ListChanged bool `json:"listChanged,omitempty"`
	// Whether this server supports subscribing to resource updates.
	Subscribe bool `json:"subscribe,omitempty"`
}

Present if the server offers any resources to read.

type ResourceContents

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

ResourceContents contains the contents of a specific resource or sub-resource.

func (ResourceContents) MarshalJSON

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

type ResourceHandler

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

A ResourceHandler is a function that reads a resource. It will be called when the client calls ClientSession.ReadResource. If it cannot find the resource, it should return the result of calling ResourceNotFoundError.

type ResourceLink struct {
	URI         string
	Name        string
	Title       string
	Description string
	MIMEType    string
	Size        *int64
	Meta        Meta
	Annotations *Annotations
}

ResourceLink is a link to a resource

func (*ResourceLink) MarshalJSON

func (c *ResourceLink) MarshalJSON() ([]byte, error)

type ResourceListChangedParams

type ResourceListChangedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
}

func (*ResourceListChangedParams) GetProgressToken

func (x *ResourceListChangedParams) GetProgressToken() any

func (*ResourceListChangedParams) SetProgressToken

func (x *ResourceListChangedParams) SetProgressToken(t any)

type ResourceListChangedRequest added in v0.3.0

type ResourceListChangedRequest = ClientRequest[*ResourceListChangedParams]

type ResourceTemplate

type ResourceTemplate struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// Optional annotations for the client.
	Annotations *Annotations `json:"annotations,omitempty"`
	// A description of what this template is for.
	//
	// This can be used by clients to improve the LLM's understanding of available
	// resources. It can be thought of like a "hint" to the model.
	Description string `json:"description,omitempty"`
	// The MIME type for all resources that match this template. This should only be
	// included if all resources matching this template have the same type.
	MIMEType string `json:"mimeType,omitempty"`
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	//
	// If not provided, the name should be used for display (except for Tool, where
	// Annotations.Title should be given precedence over using name, if
	// present).
	Title string `json:"title,omitempty"`
	// A URI template (according to RFC 6570) that can be used to construct resource
	// URIs.
	URITemplate string `json:"uriTemplate"`
}

A template description for resources available on the server.

type ResourceUpdatedNotificationParams added in v0.3.0

type ResourceUpdatedNotificationParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
	URI string `json:"uri"`
}

A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.

type ResourceUpdatedNotificationRequest added in v0.3.0

type ResourceUpdatedNotificationRequest = ClientRequest[*ResourceUpdatedNotificationParams]

type Result

type Result interface {

	// GetMeta returns metadata from a value.
	GetMeta() map[string]any
	// SetMeta sets the metadata on a value.
	SetMeta(map[string]any)
	// contains filtered or unexported methods
}

Result is a result of an MCP call.

type Role

type Role string

The sender or recipient of messages and data in a conversation.

type Root

type Root struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// An optional name for the root. This can be used to provide a human-readable
	// identifier for the root, which may be useful for display purposes or for
	// referencing the root in other parts of the application.
	Name string `json:"name,omitempty"`
	// The URI identifying the root. This *must* start with file:// for now. This
	// restriction may be relaxed in future versions of the protocol to allow other
	// URI schemes.
	URI string `json:"uri"`
}

Represents a root directory or file that the server can operate on.

type RootsListChangedParams

type RootsListChangedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
}

func (*RootsListChangedParams) GetProgressToken

func (x *RootsListChangedParams) GetProgressToken() any

func (*RootsListChangedParams) SetProgressToken

func (x *RootsListChangedParams) SetProgressToken(t any)

type RootsListChangedRequest added in v0.3.0

type RootsListChangedRequest = ServerRequest[*RootsListChangedParams]

type SSEClientTransport

type SSEClientTransport struct {
	// Endpoint is the SSE endpoint to connect to.
	Endpoint string

	// HTTPClient is the client to use for making HTTP requests. If nil,
	// http.DefaultClient is used.
	HTTPClient *http.Client
}

An SSEClientTransport is a Transport that can communicate with an MCP endpoint serving the SSE transport defined by the 2024-11-05 version of the spec.

https://modelcontextprotocol.io/specification/2024-11-05/basic/transports

func (*SSEClientTransport) Connect

func (c *SSEClientTransport) Connect(ctx context.Context) (Connection, error)

Connect connects through the client endpoint.

type SSEHandler

type SSEHandler struct {
	// contains filtered or unexported fields
}

SSEHandler is an http.Handler that serves SSE-based MCP sessions as defined by the 2024-11-05 version of the MCP spec.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"

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

type AddParams struct {
	X int `json:"x"`
	Y int `json:"y"`
}

func Add(ctx context.Context, req *mcp.CallToolRequest, args AddParams) (*mcp.CallToolResult, any, error) {
	return &mcp.CallToolResult{
		Content: []mcp.Content{
			&mcp.TextContent{Text: fmt.Sprintf("%d", args.X+args.Y)},
		},
	}, nil, nil
}

func main() {
	server := mcp.NewServer(&mcp.Implementation{Name: "adder", Version: "v0.0.1"}, nil)
	mcp.AddTool(server, &mcp.Tool{Name: "add", Description: "add two numbers"}, Add)

	handler := mcp.NewSSEHandler(func(*http.Request) *mcp.Server { return server })
	httpServer := httptest.NewServer(handler)
	defer httpServer.Close()

	ctx := context.Background()
	transport := &mcp.SSEClientTransport{Endpoint: httpServer.URL}
	client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "v1.0.0"}, nil)
	cs, err := client.Connect(ctx, transport, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer cs.Close()

	res, err := cs.CallTool(ctx, &mcp.CallToolParams{
		Name:      "add",
		Arguments: map[string]any{"x": 1, "y": 2},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.Content[0].(*mcp.TextContent).Text)

}
Output:

3

func NewSSEHandler

func NewSSEHandler(getServer func(request *http.Request) *Server) *SSEHandler

NewSSEHandler returns a new SSEHandler that creates and manages MCP sessions created via incoming HTTP requests.

Sessions are created when the client issues a GET request to the server, which must accept text/event-stream responses (server-sent events). For each such request, a new SSEServerTransport is created with a distinct messages endpoint, and connected to the server returned by getServer. The SSEHandler also handles requests to the message endpoints, by delegating them to the relevant server transport.

The getServer function may return a distinct Server for each new request, or reuse an existing server. If it returns nil, the handler will return a 400 Bad Request.

TODO(rfindley): add options.

func (*SSEHandler) ServeHTTP

func (h *SSEHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)

type SSEServerTransport

type SSEServerTransport struct {
	// Endpoint is the endpoint for this session, where the client can POST
	// messages.
	Endpoint string

	// Response is the hanging response body to the incoming GET request.
	Response http.ResponseWriter
	// contains filtered or unexported fields
}

A SSEServerTransport is a logical SSE session created through a hanging GET request.

Use SSEServerTransport.Connect to initiate the flow of messages.

When connected, it returns the following Connection implementation:

  • Writes are SSE 'message' events to the GET response.
  • Reads are received from POSTs to the session endpoint, via SSEServerTransport.ServeHTTP.
  • Close terminates the hanging GET.

The transport is itself an http.Handler. It is the caller's responsibility to ensure that the resulting transport serves HTTP requests on the given session endpoint.

Each SSEServerTransport may be connected (via Server.Connect) at most once, since SSEServerTransport.ServeHTTP serves messages to the connected session.

Most callers should instead use an SSEHandler, which transparently handles the delegation to SSEServerTransports.

func (*SSEServerTransport) Connect

Connect sends the 'endpoint' event to the client. See SSEServerTransport for more details on the Connection implementation.

func (*SSEServerTransport) ServeHTTP

func (t *SSEServerTransport) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP handles POST requests to the transport endpoint.

type SamplingCapabilities

type SamplingCapabilities struct{}

SamplingCapabilities describes the capabilities for sampling.

type SamplingMessage

type SamplingMessage struct {
	Content Content `json:"content"`
	Role    Role    `json:"role"`
}

Describes a message issued to or received from an LLM API.

func (*SamplingMessage) UnmarshalJSON

func (m *SamplingMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON handles the unmarshalling of content into the Content interface.

type Server

type Server struct {
	// contains filtered or unexported fields
}

A Server is an instance of an MCP server.

Servers expose server-side MCP features, which can serve one or more MCP sessions by using Server.Run.

func NewServer

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

NewServer creates a new MCP server. The resulting server has no features: add features using the various Server.AddXXX methods, and the AddTool function.

The server can be connected to one or more MCP clients using Server.Run.

The first argument must not be nil.

If non-nil, the provided options are used to configure the server.

func (*Server) AddPrompt added in v0.2.0

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

AddPrompt adds a Prompt to the server, or replaces one with the same name.

func (*Server) AddReceivingMiddleware

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

AddReceivingMiddleware wraps the current receiving method handler using the provided middleware. Middleware is applied from right to left, so that the first one is executed first.

For example, AddReceivingMiddleware(m1, m2, m3) augments the method handler as m1(m2(m3(handler))).

Receiving middleware is called when a request is received. It is useful for tasks such as authentication, request logging and metrics.

func (*Server) AddResource added in v0.2.0

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

AddResource adds a Resource to the server, or replaces one with the same URI. AddResource panics if the resource URI is invalid or not absolute (has an empty scheme).

func (*Server) AddResourceTemplate added in v0.2.0

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

AddResourceTemplate adds a ResourceTemplate to the server, or replaces one with the same URI. AddResourceTemplate panics if a URI template is invalid or not absolute (has an empty scheme).

func (*Server) AddSendingMiddleware

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

AddSendingMiddleware wraps the current sending method handler using the provided middleware. Middleware is applied from right to left, so that the first one is executed first.

For example, AddSendingMiddleware(m1, m2, m3) augments the method handler as m1(m2(m3(handler))).

Sending middleware is called when a request is sent. It is useful for tasks such as tracing, metrics, and adding progress tokens.

func (*Server) AddTool added in v0.2.0

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

AddTool adds a Tool to the server, or replaces one with the same name. The Tool argument must not be modified after this call.

The tool's input schema must be non-nil and have the type "object". For a tool that takes no input, or one where any input is valid, set [Tool.InputSchema] to &jsonschema.Schema{Type: "object"}.

If present, the output schema must also have type "object".

When the handler is invoked as part of a CallTool request, req.Params.Arguments will be a json.RawMessage.

Unmarshaling the arguments and validating them against the input schema are the caller's responsibility.

Validating the result against the output schema, if any, is the caller's responsibility.

Setting the result's Content, StructuredContent and IsError fields are the caller's responsibility.

Most users should use the top-level function AddTool, which handles all these responsibilities.

func (*Server) Connect

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

Connect connects the MCP server over the given transport and starts handling messages.

It returns a connection object that may be used to terminate the connection (with [Connection.Close]), or await client termination (with [Connection.Wait]).

If opts.State is non-nil, it is the initial state for the server.

func (*Server) RemovePrompts

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

RemovePrompts removes the prompts with the given names. It is not an error to remove a nonexistent prompt.

func (*Server) RemoveResourceTemplates

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

RemoveResourceTemplates removes the resource templates with the given URI templates. It is not an error to remove a nonexistent resource.

func (*Server) RemoveResources

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

RemoveResources removes the resources with the given URIs. It is not an error to remove a nonexistent resource.

func (*Server) RemoveTools

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

RemoveTools removes the tools with the given names. It is not an error to remove a nonexistent tool.

func (*Server) ResourceUpdated added in v0.3.0

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

ResourceUpdated sends a notification to all clients that have subscribed to the resource specified in params. This method is the primary way for a server author to signal that a resource has changed.

func (*Server) Run

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

Run runs the server over the given transport, which must be persistent.

Run blocks until the client terminates the connection or the provided context is cancelled. If the context is cancelled, Run closes the connection.

If tools have been added to the server before this call, then the server will advertise the capability for tools, including the ability to send list-changed notifications. If no tools have been added, the server will not have the tool capability. The same goes for other features like prompts and resources.

Run is a convenience for servers that handle a single session (or one session at a time). It need not be called on servers that are used for multiple concurrent connections, as with StreamableHTTPHandler.

func (*Server) Sessions

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

Sessions returns an iterator that yields the current set of server sessions.

type ServerCapabilities added in v0.3.0

type ServerCapabilities struct {
	// Present if the server supports argument autocompletion suggestions.
	Completions *CompletionCapabilities `json:"completions,omitempty"`
	// Experimental, non-standard capabilities that the server supports.
	Experimental map[string]any `json:"experimental,omitempty"`
	// Present if the server supports sending log messages to the client.
	Logging *LoggingCapabilities `json:"logging,omitempty"`
	// Present if the server offers any prompt templates.
	Prompts *PromptCapabilities `json:"prompts,omitempty"`
	// Present if the server offers any resources to read.
	Resources *ResourceCapabilities `json:"resources,omitempty"`
	// Present if the server offers any tools to call.
	Tools *ToolCapabilities `json:"tools,omitempty"`
}

Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.

type ServerOptions

type ServerOptions struct {
	// Optional instructions for connected clients.
	Instructions string
	// If non-nil, called when "notifications/initialized" is received.
	InitializedHandler func(context.Context, *InitializedRequest)
	// PageSize is the maximum number of items to return in a single page for
	// list methods (e.g. ListTools).
	//
	// If zero, defaults to [DefaultPageSize].
	PageSize int
	// If non-nil, called when "notifications/roots/list_changed" is received.
	RootsListChangedHandler func(context.Context, *RootsListChangedRequest)
	// If non-nil, called when "notifications/progress" is received.
	ProgressNotificationHandler func(context.Context, *ProgressNotificationServerRequest)
	// If non-nil, called when "completion/complete" is received.
	CompletionHandler func(context.Context, *CompleteRequest) (*CompleteResult, error)
	// If non-zero, defines an interval for regular "ping" requests.
	// If the peer fails to respond to pings originating from the keepalive check,
	// the session is automatically closed.
	KeepAlive time.Duration
	// Function called when a client session subscribes to a resource.
	SubscribeHandler func(context.Context, *SubscribeRequest) error
	// Function called when a client session unsubscribes from a resource.
	UnsubscribeHandler func(context.Context, *UnsubscribeRequest) error
	// If true, advertises the prompts capability during initialization,
	// even if no prompts have been registered.
	HasPrompts bool
	// If true, advertises the resources capability during initialization,
	// even if no resources have been registered.
	HasResources bool
	// If true, advertises the tools capability during initialization,
	// even if no tools have been registered.
	HasTools bool
}

ServerOptions is used to configure behavior of the server.

type ServerRequest added in v0.3.0

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

A ServerRequest is a request to a server.

func (*ServerRequest[P]) GetExtra added in v0.3.0

func (r *ServerRequest[P]) GetExtra() *RequestExtra

func (*ServerRequest[P]) GetParams added in v0.3.0

func (r *ServerRequest[P]) GetParams() Params

func (*ServerRequest[P]) GetSession added in v0.3.0

func (r *ServerRequest[P]) GetSession() Session

type ServerSession

type ServerSession struct {
	// contains filtered or unexported fields
}

A ServerSession is a logical connection from a single MCP client. Its methods can be used to send requests or notifications to the client. Create a session by calling Server.Connect.

Call ServerSession.Close to close the connection, or await client termination with ServerSession.Wait.

func (*ServerSession) Close

func (ss *ServerSession) Close() error

Close performs a graceful shutdown of the connection, preventing new requests from being handled, and waiting for ongoing requests to return. Close then terminates the connection.

func (*ServerSession) CreateMessage

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

CreateMessage sends a sampling request to the client.

func (*ServerSession) Elicit added in v0.3.0

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

Elicit sends an elicitation request to the client asking for user input.

func (*ServerSession) ID

func (ss *ServerSession) ID() string

func (*ServerSession) InitializeParams added in v0.3.0

func (ss *ServerSession) InitializeParams() *InitializeParams

func (*ServerSession) ListRoots

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

ListRoots lists the client roots.

func (*ServerSession) Log

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

Log sends a log message to the client. The message is not sent if the client has not called SetLevel, or if its level is below that of the last SetLevel.

func (*ServerSession) NotifyProgress

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

NotifyProgress sends a progress notification from the server to the client associated with this session. This is typically used to report on the status of a long-running request that was initiated by the client.

func (*ServerSession) Ping

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

Ping pings the client.

func (*ServerSession) Wait

func (ss *ServerSession) Wait() error

Wait waits for the connection to be closed by the client.

type ServerSessionOptions added in v0.3.0

type ServerSessionOptions struct {
	State *ServerSessionState
	// contains filtered or unexported fields
}

ServerSessionOptions configures the server session.

type ServerSessionState added in v0.3.0

type ServerSessionState struct {
	// InitializeParams are the parameters from 'initialize'.
	InitializeParams *InitializeParams `json:"initializeParams"`

	// InitializedParams are the parameters from 'notifications/initialized'.
	InitializedParams *InitializedParams `json:"initializedParams"`

	// LogLevel is the logging level for the session.
	LogLevel LoggingLevel `json:"logLevel"`
}

ServerSessionState is the state of a session.

type Session

type Session interface {
	// ID returns the session ID, or the empty string if there is none.
	ID() string
	// contains filtered or unexported methods
}

A Session is either a ClientSession or a ServerSession.

type SetLoggingLevelParams added in v0.3.0

type SetLoggingLevelParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The level of logging that the client wants to receive from the server. The
	// server should send all logs at this level and higher (i.e., more severe) to
	// the client as notifications/message.
	Level LoggingLevel `json:"level"`
}

func (*SetLoggingLevelParams) GetProgressToken added in v0.3.0

func (x *SetLoggingLevelParams) GetProgressToken() any

func (*SetLoggingLevelParams) SetProgressToken added in v0.3.0

func (x *SetLoggingLevelParams) SetProgressToken(t any)

type StdioTransport

type StdioTransport struct{}

A StdioTransport is a Transport that communicates over stdin/stdout using newline-delimited JSON.

func (*StdioTransport) Connect

Connect implements the Transport interface.

type StreamID added in v0.3.0

type StreamID string

A StreamID identifies a stream of SSE events. It is globally unique. ServerSession.

type StreamableClientTransport

type StreamableClientTransport struct {
	Endpoint   string
	HTTPClient *http.Client
	// MaxRetries is the maximum number of times to attempt a reconnect before giving up.
	// It defaults to 5. To disable retries, use a negative number.
	MaxRetries int
}

A StreamableClientTransport is a Transport that can communicate with an MCP endpoint serving the streamable HTTP transport defined by the 2025-03-26 version of the spec.

func (*StreamableClientTransport) Connect

Connect implements the Transport interface.

The resulting Connection writes messages via POST requests to the transport URL with the Mcp-Session-Id header set, and reads messages from hanging requests.

When closed, the connection issues a DELETE request to terminate the logical session.

type StreamableHTTPHandler

type StreamableHTTPHandler struct {
	// contains filtered or unexported fields
}

A StreamableHTTPHandler is an http.Handler that serves streamable MCP sessions, as defined by the MCP spec.

func NewStreamableHTTPHandler

func NewStreamableHTTPHandler(getServer func(*http.Request) *Server, opts *StreamableHTTPOptions) *StreamableHTTPHandler

NewStreamableHTTPHandler returns a new StreamableHTTPHandler.

The getServer function is used to create or look up servers for new sessions. It is OK for getServer to return the same server multiple times. If getServer returns nil, a 400 Bad Request will be served.

func (*StreamableHTTPHandler) ServeHTTP

func (h *StreamableHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)

type StreamableHTTPOptions

type StreamableHTTPOptions struct {
	// GetSessionID provides the next session ID to use for an incoming request.
	// If nil, a default randomly generated ID will be used.
	//
	// Session IDs should be globally unique across the scope of the server,
	// which may span multiple processes in the case of distributed servers.
	//
	// As a special case, if GetSessionID returns the empty string, the
	// Mcp-Session-Id header will not be set.
	GetSessionID func() string

	// Stateless controls whether the session is 'stateless'.
	//
	// A stateless server does not validate the Mcp-Session-Id header, and uses a
	// temporary session with default initialization parameters. Any
	// server->client request is rejected immediately as there's no way for the
	// client to respond. Server->Client notifications may reach the client if
	// they are made in the context of an incoming request, as described in the
	// documentation for [StreamableServerTransport].
	Stateless bool

	// JSONResponse is forwarded to StreamableServerTransport.jsonResponse.
	JSONResponse bool
}

StreamableHTTPOptions configures the StreamableHTTPHandler.

type StreamableServerTransport

type StreamableServerTransport struct {
	// SessionID is the ID of this session.
	//
	// If SessionID is the empty string, this is a 'stateless' session, which has
	// limited ability to communicate with the client. Otherwise, the session ID
	// must be globally unique, that is, different from any other session ID
	// anywhere, past and future. (We recommend using a crypto random number
	// generator to produce one, as with [crypto/rand.Text].)
	SessionID string

	// Stateless controls whether the eventstore is 'Stateless'. Server sessions
	// connected to a stateless transport are disallowed from making outgoing
	// requests.
	//
	// See also [StreamableHTTPOptions.Stateless].
	Stateless bool

	// Storage for events, to enable stream resumption.
	// If nil, a [MemoryEventStore] with the default maximum size will be used.
	EventStore EventStore
	// contains filtered or unexported fields
}

A StreamableServerTransport implements the server side of the MCP streamable transport.

Each StreamableServerTransport must be connected (via Server.Connect) at most once, since StreamableServerTransport.ServeHTTP serves messages to the connected session.

Reads from the streamable server connection receive messages from http POST requests from the client. Writes to the streamable server connection are sent either to the hanging POST response, or to the hanging GET, according to the following rules:

  • JSON-RPC responses to incoming requests are always routed to the appropriate HTTP response.
  • Requests or notifications made with a context.Context value derived from an incoming request handler, are routed to the HTTP response corresponding to that request, unless it has already terminated, in which case they are routed to the hanging GET.
  • Requests or notifications made with a detached context.Context value are routed to the hanging GET.

func (*StreamableServerTransport) Connect

Connect implements the Transport interface.

func (*StreamableServerTransport) ServeHTTP

ServeHTTP handles a single HTTP request for the session.

type SubscribeParams added in v0.3.0

type SubscribeParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The URI of the resource to subscribe to.
	URI string `json:"uri"`
}

Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.

type SubscribeRequest added in v0.3.0

type SubscribeRequest = ServerRequest[*SubscribeParams]

type TextContent

type TextContent struct {
	Text        string
	Meta        Meta
	Annotations *Annotations
}

TextContent is a textual content.

func (*TextContent) MarshalJSON

func (c *TextContent) MarshalJSON() ([]byte, error)

type Tool

type Tool struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// Optional additional tool information.
	//
	// Display name precedence order is: title, annotations.title, then name.
	Annotations *ToolAnnotations `json:"annotations,omitempty"`
	// A human-readable description of the tool.
	//
	// This can be used by clients to improve the LLM's understanding of available
	// tools. It can be thought of like a "hint" to the model.
	Description string `json:"description,omitempty"`
	// A JSON Schema object defining the expected parameters for the tool.
	InputSchema *jsonschema.Schema `json:"inputSchema"`
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// An optional JSON Schema object defining the structure of the tool's output
	// returned in the structuredContent field of a CallToolResult.
	OutputSchema *jsonschema.Schema `json:"outputSchema,omitempty"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	// If not provided, Annotations.Title should be used for display if present,
	// otherwise Name.
	Title string `json:"title,omitempty"`
}

Definition for a tool the client can call.

type ToolAnnotations

type ToolAnnotations struct {
	// If true, the tool may perform destructive updates to its environment. If
	// false, the tool performs only additive updates.
	//
	// (This property is meaningful only when ReadOnlyHint == false.)
	//
	// Default: true
	DestructiveHint *bool `json:"destructiveHint,omitempty"`
	// If true, calling the tool repeatedly with the same arguments will have no
	// additional effect on the its environment.
	//
	// (This property is meaningful only when ReadOnlyHint == false.)
	//
	// Default: false
	IdempotentHint bool `json:"idempotentHint,omitempty"`
	// If true, this tool may interact with an "open world" of external entities. If
	// false, the tool's domain of interaction is closed. For example, the world of
	// a web search tool is open, whereas that of a memory tool is not.
	//
	// Default: true
	OpenWorldHint *bool `json:"openWorldHint,omitempty"`
	// If true, the tool does not modify its environment.
	//
	// Default: false
	ReadOnlyHint bool `json:"readOnlyHint,omitempty"`
	// A human-readable title for the tool.
	Title string `json:"title,omitempty"`
}

Additional properties describing a Tool to clients.

NOTE: all properties in ToolAnnotations are hints. They are not guaranteed to provide a faithful description of tool behavior (including descriptive properties like title).

Clients should never make tool use decisions based on ToolAnnotations received from untrusted servers.

type ToolCapabilities added in v0.3.0

type ToolCapabilities struct {
	// Whether this server supports notifications for changes to the tool list.
	ListChanged bool `json:"listChanged,omitempty"`
}

Present if the server offers any tools to call.

type ToolHandler

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

A ToolHandler handles a call to tools/call.

This is a low-level API, for use with Server.AddTool. It does not do any pre- or post-processing of the request or result: the params contain raw arguments, no input validation is performed, and the result is returned to the user as-is, without any validation of the output.

Most users will write a ToolHandlerFor and install it with the generic AddTool function.

If ToolHandler returns an error, it is treated as a protocol error. By contrast, ToolHandlerFor automatically populates [CallToolResult.IsError] and [CallToolResult.Content] accordingly.

type ToolHandlerFor

type ToolHandlerFor[In, Out any] func(_ context.Context, request *CallToolRequest, input In) (result *CallToolResult, output Out, _ error)

A ToolHandlerFor handles a call to tools/call with typed arguments and results.

Use AddTool to add a ToolHandlerFor to a server.

Unlike ToolHandler, ToolHandlerFor provides significant functionality out of the box, and enforces that the tool conforms to the MCP spec:

  • The In type provides a default input schema for the tool, though it may be overridden in AddTool.
  • The input value is automatically unmarshaled from req.Params.Arguments.
  • The input value is automatically validated against its input schema. Invalid input is rejected before getting to the handler.
  • If the Out type is not the empty interface [any], it provides the default output schema for the tool (which again may be overridden in AddTool).
  • The Out value is used to populate result.StructuredOutput.
  • If [CallToolResult.Content] is unset, it is populated with the JSON content of the output.
  • An error result is treated as a tool error, rather than a protocol error, and is therefore packed into CallToolResult.Content, with [IsError] set.

For these reasons, most users can ignore the CallToolRequest argument and CallToolResult return values entirely. In fact, it is permissible to return a nil CallToolResult, if you only care about returning a output value or error. The effective result will be populated as described above.

type ToolListChangedParams

type ToolListChangedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
}

func (*ToolListChangedParams) GetProgressToken

func (x *ToolListChangedParams) GetProgressToken() any

func (*ToolListChangedParams) SetProgressToken

func (x *ToolListChangedParams) SetProgressToken(t any)

type ToolListChangedRequest added in v0.3.0

type ToolListChangedRequest = ClientRequest[*ToolListChangedParams]

type Transport

type Transport interface {
	// Connect returns the logical JSON-RPC connection..
	//
	// It is called exactly once by [Server.Connect] or [Client.Connect].
	Connect(ctx context.Context) (Connection, error)
}

A Transport is used to create a bidirectional connection between MCP client and server.

Transports should be used for at most one call to Server.Connect or Client.Connect.

type UnsubscribeParams added in v0.3.0

type UnsubscribeParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The URI of the resource to unsubscribe from.
	URI string `json:"uri"`
}

Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.

type UnsubscribeRequest added in v0.3.0

type UnsubscribeRequest = ServerRequest[*UnsubscribeParams]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL