package mcp

Import Path
	github.com/mark3labs/mcp-go/mcp (on go.dev)

Dependency Relation
	imports 12 packages, and imported by 3 packages

Involved Source Files consts.go errors.go prompts.go resources.go tasks.go tools.go typed_tools.go Package mcp defines the core types and interfaces for the Model Context Protocol (MCP). MCP is a protocol for communication between LLM-powered applications and their supporting services. utils.go
Package-Level Type Names (total 151)
/* sort by: | */
Annotated is the base for objects that include optional annotations for the client. The client can use annotations to inform how objects are used or displayed Annotations *Annotations
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., `["user", "assistant"]`). ISO 8601 formatted timestamp (e.g., "2025-01-12T15:00:58Z") 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 ranges from 0.0 to 1.0 (1 = most important, 0 = least important). func ParseAnnotations(data map[string]any) *Annotations
ArgumentOption is a function that configures a PromptArgument. It allows for flexible configuration of prompt arguments using the functional options pattern. func ArgumentDescription(desc string) ArgumentOption func RequiredArgument() ArgumentOption func WithArgument(name string, opts ...ArgumentOption) PromptOption
AudioContent represents the contents of audio, embedded into a prompt or tool call result. It must have Type set to "audio". Annotated Annotated Annotated.Annotations *Annotations The base64-encoded image data. The MIME type of the image. Different providers may support different image types. Meta is a metadata object that is reserved by MCP for storing additional information. // Must be "image" AudioContent : Content func AsAudioContent(content any) (*AudioContent, bool) func NewAudioContent(data, mimeType string) AudioContent
A base64-encoded string representing the binary data of the item. The MIME type of this resource, if known. Raw per‑resource metadata; pass‑through as defined by MCP. Not the same as mcp.Meta. Allows _meta to be used for MCP-UI features for example. Does not assume any specific format. The URI of this resource. BlobResourceContents : ResourceContents func AsBlobResourceContents(content any) (*BlobResourceContents, bool)
Arguments any Meta *Meta Name string Task *TaskParams
CallToolRequest is used by the client to invoke a tool provided by the server. // HTTP headers from the original request Params CallToolParams Request Request Request.Method string BindArguments unmarshals the Arguments into the provided struct This is useful for working with strongly-typed arguments GetArguments returns the Arguments as map[string]any for backward compatibility If Arguments is not a map, it returns an empty map GetBool returns a bool argument by key, or the default value if not found GetBoolSlice returns a bool slice argument by key, or the default value if not found GetFloat returns a float64 argument by key, or the default value if not found GetFloatSlice returns a float64 slice argument by key, or the default value if not found GetInt returns an int argument by key, or the default value if not found GetIntSlice returns an int slice argument by key, or the default value if not found GetRawArguments returns the Arguments as-is without type conversion This allows users to access the raw arguments in any format GetString returns a string argument by key, or the default value if not found GetStringSlice returns a string slice argument by key, or the default value if not found RequireBool returns a bool argument by key, or an error if not found or not convertible to bool RequireBoolSlice returns a bool slice argument by key, or an error if not found or not convertible to bool slice RequireFloat returns a float64 argument by key, or an error if not found or not convertible to float64 RequireFloatSlice returns a float64 slice argument by key, or an error if not found or not convertible to float64 slice RequireInt returns an int argument by key, or an error if not found or not convertible to int RequireIntSlice returns an int slice argument by key, or an error if not found or not convertible to int slice RequireString returns a string argument by key, or an error if not found or not a string RequireStringSlice returns a string slice argument by key, or an error if not found or not convertible to string slice func ParseArgument(request CallToolRequest, key string, defaultVal any) any func ParseBoolean(request CallToolRequest, key string, defaultValue bool) bool func ParseFloat32(request CallToolRequest, key string, defaultValue float32) float32 func ParseFloat64(request CallToolRequest, key string, defaultValue float64) float64 func ParseInt(request CallToolRequest, key string, defaultValue int) int func ParseInt16(request CallToolRequest, key string, defaultValue int16) int16 func ParseInt32(request CallToolRequest, key string, defaultValue int32) int32 func ParseInt64(request CallToolRequest, key string, defaultValue int64) int64 func ParseInt8(request CallToolRequest, key string, defaultValue int8) int8 func ParseString(request CallToolRequest, key string, defaultValue string) string func ParseStringMap(request CallToolRequest, key string, defaultValue map[string]any) map[string]any func ParseUInt(request CallToolRequest, key string, defaultValue uint) uint func ParseUInt16(request CallToolRequest, key string, defaultValue uint16) uint16 func ParseUInt32(request CallToolRequest, key string, defaultValue uint32) uint32 func ParseUInt64(request CallToolRequest, key string, defaultValue uint64) uint64 func ParseUInt8(request CallToolRequest, key string, defaultValue uint8) uint8
CallToolResult is the server's response to a tool call. Any errors that originate from the tool SHOULD be reported inside the result object, 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. // Can be TextContent, ImageContent, AudioContent, or EmbeddedResource Whether the tool call ended in an error. If not set, this is assumed to be false (the call was successful). Result Result Result.Meta *Meta Structured content returned as a JSON object in the structuredContent field of a result. For backwards compatibility, a tool that returns structured content SHOULD also return functionally equivalent unstructured content. MarshalJSON implements custom JSON marshaling for CallToolResult UnmarshalJSON implements custom JSON unmarshaling for CallToolResult CallToolResult : github.com/goccy/go-json.Marshaler *CallToolResult : github.com/goccy/go-json.Unmarshaler CallToolResult : encoding/json.Marshaler *CallToolResult : encoding/json.Unmarshaler func FormatNumberResult(value float64) *CallToolResult func NewToolResultAudio(text, audioData, mimeType string) *CallToolResult func NewToolResultError(text string) *CallToolResult func NewToolResultErrorf(format string, a ...any) *CallToolResult func NewToolResultErrorFromErr(text string, err error) *CallToolResult func NewToolResultImage(text, imageData, mimeType string) *CallToolResult func NewToolResultJSON[T](data T) (*CallToolResult, error) func NewToolResultResource(text string, resource ResourceContents) *CallToolResult func NewToolResultStructured(structured any, fallbackText string) *CallToolResult func NewToolResultStructuredOnly(structured any) *CallToolResult func NewToolResultText(text string) *CallToolResult func ParseCallToolResult(rawMessage *json.RawMessage) (*CallToolResult, error)
CancelledNotification can be sent by either side to indicate that it is cancelling a previously-issued request. The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. This notification indicates that the result will be unused, so any associated processing SHOULD cease. A client MUST NOT attempt to cancel its `initialize` request. Notification Notification Notification.Method string Params CancelledNotificationParams
An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. The ID of the request to cancel. This MUST correspond to the ID of a request previously issued in the same direction.
TaskId string
CancelTaskRequest cancels an in-progress task. Header http.Header Params CancelTaskParams Request Request Request.Method string
CancelTaskResult returns the cancelled task state. Result Result Result.Meta *Meta Task Task ISO 8601 timestamp when the task was created. ISO 8601 timestamp when the task was last updated. Suggested time in milliseconds between status checks. Current state of the task execution. Optional human-readable message describing the current state. Time in milliseconds from creation before task may be deleted. If null, the task has no expiration. Unique identifier for the task. GetName returns the task ID, implementing the Named interface for pagination. CancelTaskResult : Named func NewCancelTaskResult(task Task) CancelTaskResult func ParseCancelTaskResult(rawMessage *json.RawMessage) (*CancelTaskResult, error)
ClientCapabilities represents 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. Present if the client supports elicitation requests from the server. Experimental, non-standard capabilities that the client supports. Optional, present if the client is advertising extension support. Present if the client supports listing roots. Present if the client supports sampling from an LLM. Present if the client supports task-based execution. func github.com/mark3labs/mcp-go/server.(*InProcessSession).GetClientCapabilities() ClientCapabilities func github.com/mark3labs/mcp-go/server.SessionWithClientInfo.GetClientCapabilities() ClientCapabilities func github.com/mark3labs/mcp-go/server.(*InProcessSession).SetClientCapabilities(clientCapabilities ClientCapabilities) func github.com/mark3labs/mcp-go/server.SessionWithClientInfo.SetClientCapabilities(clientCapabilities ClientCapabilities)
ClientNotification represents any notification that can be sent from client to server.
ClientRequest represents any request that can be sent from client to server.
ClientResult represents any result that can be sent from client to server.
CompleteArgument is an argument to a completion request The name of the argument The value of the argument to use for completion matching. func github.com/mark3labs/mcp-go/server.(*DefaultPromptCompletionProvider).CompletePromptArgument(ctx context.Context, promptName string, argument CompleteArgument, context CompleteContext) (*Completion, error) func github.com/mark3labs/mcp-go/server.(*DefaultResourceCompletionProvider).CompleteResourceArgument(ctx context.Context, uri string, argument CompleteArgument, context CompleteContext) (*Completion, error) func github.com/mark3labs/mcp-go/server.PromptCompletionProvider.CompletePromptArgument(ctx context.Context, promptName string, argument CompleteArgument, context CompleteContext) (*Completion, error) func github.com/mark3labs/mcp-go/server.ResourceCompletionProvider.CompleteResourceArgument(ctx context.Context, uri string, argument CompleteArgument, context CompleteContext) (*Completion, error)
CompleteContext is the context about already-resolved arguments Arguments map[string]string func github.com/mark3labs/mcp-go/server.(*DefaultPromptCompletionProvider).CompletePromptArgument(ctx context.Context, promptName string, argument CompleteArgument, context CompleteContext) (*Completion, error) func github.com/mark3labs/mcp-go/server.(*DefaultResourceCompletionProvider).CompleteResourceArgument(ctx context.Context, uri string, argument CompleteArgument, context CompleteContext) (*Completion, error) func github.com/mark3labs/mcp-go/server.PromptCompletionProvider.CompletePromptArgument(ctx context.Context, promptName string, argument CompleteArgument, context CompleteContext) (*Completion, error) func github.com/mark3labs/mcp-go/server.ResourceCompletionProvider.CompleteResourceArgument(ctx context.Context, uri string, argument CompleteArgument, context CompleteContext) (*Completion, error)
CompleteParams are the parameters for a completion/complete request Argument CompleteArgument Context CompleteContext // Can be PromptReference or ResourceReference (*CompleteParams) UnmarshalJSON(data []byte) error *CompleteParams : github.com/goccy/go-json.Unmarshaler *CompleteParams : encoding/json.Unmarshaler
CompleteRequest is a request from the client to the server, to ask for completion options. Header http.Header Params CompleteParams Request Request Request.Method string
CompleteResult is the server's response to a completion/complete request Completion Completion Result Result Result.Meta *Meta
Completion is the server's response to a completion/complete request Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. The total number of completion options available. This can exceed the number of values actually sent in the response. An array of completion values. Must not exceed 100 items. func github.com/mark3labs/mcp-go/server.(*DefaultPromptCompletionProvider).CompletePromptArgument(ctx context.Context, promptName string, argument CompleteArgument, context CompleteContext) (*Completion, error) func github.com/mark3labs/mcp-go/server.(*DefaultResourceCompletionProvider).CompleteResourceArgument(ctx context.Context, uri string, argument CompleteArgument, context CompleteContext) (*Completion, error) func github.com/mark3labs/mcp-go/server.PromptCompletionProvider.CompletePromptArgument(ctx context.Context, promptName string, argument CompleteArgument, context CompleteContext) (*Completion, error) func github.com/mark3labs/mcp-go/server.ResourceCompletionProvider.CompleteResourceArgument(ctx context.Context, uri string, argument CompleteArgument, context CompleteContext) (*Completion, error)
AudioContent EmbeddedResource ImageContent ResourceLink TextContent func ParseContent(contentMap map[string]any) (Content, error) func UnmarshalContent(data []byte) (Content, error) func MarshalContent(content Content) ([]byte, error) func NewPromptMessage(role Role, content Content) PromptMessage
CreateMessageRequest is a request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. CreateMessageParams CreateMessageParams CreateMessageParams.IncludeContext string CreateMessageParams.MaxTokens int CreateMessageParams.Messages []SamplingMessage CreateMessageParams.Metadata any CreateMessageParams.ModelPreferences *ModelPreferences CreateMessageParams.StopSequences []string CreateMessageParams.SystemPrompt string CreateMessageParams.Temperature float64 Request Request Request.Method string Request.Params RequestParams func github.com/mark3labs/mcp-go/server.(*InProcessSession).RequestSampling(ctx context.Context, request CreateMessageRequest) (*CreateMessageResult, error) func github.com/mark3labs/mcp-go/server.(*MCPServer).RequestSampling(ctx context.Context, request CreateMessageRequest) (*CreateMessageResult, error) func github.com/mark3labs/mcp-go/server.SamplingHandler.CreateMessage(ctx context.Context, request CreateMessageRequest) (*CreateMessageResult, error) func github.com/mark3labs/mcp-go/server.SessionWithSampling.RequestSampling(ctx context.Context, request CreateMessageRequest) (*CreateMessageResult, error)
CreateMessageResult is 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. The name of the model that generated the message. Result Result Result.Meta *Meta SamplingMessage SamplingMessage // Can be TextContent, ImageContent or AudioContent SamplingMessage.Role Role The reason why sampling stopped, if known. func github.com/mark3labs/mcp-go/server.(*InProcessSession).RequestSampling(ctx context.Context, request CreateMessageRequest) (*CreateMessageResult, error) func github.com/mark3labs/mcp-go/server.(*MCPServer).RequestSampling(ctx context.Context, request CreateMessageRequest) (*CreateMessageResult, error) func github.com/mark3labs/mcp-go/server.SamplingHandler.CreateMessage(ctx context.Context, request CreateMessageRequest) (*CreateMessageResult, error) func github.com/mark3labs/mcp-go/server.SessionWithSampling.RequestSampling(ctx context.Context, request CreateMessageRequest) (*CreateMessageResult, error)
CreateTaskResult is returned immediately when a task-augmented request is accepted. It contains task metadata rather than the actual operation result. Content []Content IsError bool Result Result Result.Meta *Meta StructuredContent any Task Task func NewCreateTaskResult(task Task) CreateTaskResult
Cursor is an opaque token used to represent a cursor for pagination. func NewListPromptsResult(prompts []Prompt, nextCursor Cursor) *ListPromptsResult func NewListResourcesResult(resources []Resource, nextCursor Cursor) *ListResourcesResult func NewListResourceTemplatesResult(templates []ResourceTemplate, nextCursor Cursor) *ListResourceTemplatesResult func NewListToolsResult(tools []Tool, nextCursor Cursor) *ListToolsResult
ElicitationCapability represents the elicitation capabilities of a client or server. // Supports form mode // Supports URL mode
ElicitationParams contains the parameters for an elicitation request. ElicitationID is a unique identifier for the elicitation request. A human-readable message explaining what information is being requested and why. Meta *Meta Mode specifies the type of elicitation: "form" or "url". Defaults to "form". A JSON Schema defining the expected structure of the user's response. URL is the URL to be opened by the user. Validate checks if the elicitation parameters are valid.
ElicitationRequest is a request from the server to the client to request additional information from the user during an interaction. Params ElicitationParams Request Request Request.Method string func github.com/mark3labs/mcp-go/server.ElicitationHandler.Elicit(ctx context.Context, request ElicitationRequest) (*ElicitationResult, error) func github.com/mark3labs/mcp-go/server.(*InProcessSession).RequestElicitation(ctx context.Context, request ElicitationRequest) (*ElicitationResult, error) func github.com/mark3labs/mcp-go/server.(*MCPServer).RequestElicitation(ctx context.Context, request ElicitationRequest) (*ElicitationResult, error) func github.com/mark3labs/mcp-go/server.SessionWithElicitation.RequestElicitation(ctx context.Context, request ElicitationRequest) (*ElicitationResult, error)
ElicitationResponse represents the user's response to an elicitation request. Action indicates whether the user accepted, declined, or cancelled. Content contains the user's response data if they accepted. Should conform to the requestedSchema from the ElicitationRequest.
ElicitationResponseAction indicates how the user responded to an elicitation request. const ElicitationResponseActionAccept const ElicitationResponseActionCancel const ElicitationResponseActionDecline
ElicitationResult represents the result of an elicitation request. ElicitationResponse ElicitationResponse Action indicates whether the user accepted, declined, or cancelled. Content contains the user's response data if they accepted. Should conform to the requestedSchema from the ElicitationRequest. Result Result Result.Meta *Meta func github.com/mark3labs/mcp-go/server.ElicitationHandler.Elicit(ctx context.Context, request ElicitationRequest) (*ElicitationResult, error) func github.com/mark3labs/mcp-go/server.(*InProcessSession).RequestElicitation(ctx context.Context, request ElicitationRequest) (*ElicitationResult, error) func github.com/mark3labs/mcp-go/server.(*MCPServer).RequestElicitation(ctx context.Context, request ElicitationRequest) (*ElicitationResult, error) func github.com/mark3labs/mcp-go/server.(*MCPServer).RequestURLElicitation(ctx context.Context, session server.ClientSession, elicitationID string, url string, message string) (*ElicitationResult, error) func github.com/mark3labs/mcp-go/server.SessionWithElicitation.RequestElicitation(ctx context.Context, request ElicitationRequest) (*ElicitationResult, error)
EmbeddedResource represents the contents of a resource, embedded into a prompt or tool call result. It is up to the client how best to render embedded resources for the benefit of the LLM and/or the user. Annotated Annotated Annotated.Annotations *Annotations Meta is a metadata object that is reserved by MCP for storing additional information. Resource ResourceContents Type string EmbeddedResource : Content func AsEmbeddedResource(content any) (*EmbeddedResource, bool) func NewEmbeddedResource(resource ResourceContents) EmbeddedResource
EmptyResult represents a response that indicates success but carries no data. Meta *Meta
Arguments to use for templating the prompt. The name of the prompt or prompt template.
GetPromptRequest is used by the client to get a prompt provided by the server. Header http.Header Params GetPromptParams Request Request Request.Method string
GetPromptResult is the server's response to a prompts/get request from the client. An optional description for the prompt. Messages []PromptMessage Result Result Result.Meta *Meta func NewGetPromptResult(description string, messages []PromptMessage) *GetPromptResult func ParseGetPromptResult(rawMessage *json.RawMessage) (*GetPromptResult, error)
TaskId string
GetTaskRequest retrieves the current status of a task. Header http.Header Params GetTaskParams Request Request Request.Method string
GetTaskResult returns the current state of a task. Result Result Result.Meta *Meta Task Task ISO 8601 timestamp when the task was created. ISO 8601 timestamp when the task was last updated. Suggested time in milliseconds between status checks. Current state of the task execution. Optional human-readable message describing the current state. Time in milliseconds from creation before task may be deleted. If null, the task has no expiration. Unique identifier for the task. GetName returns the task ID, implementing the Named interface for pagination. GetTaskResult : Named func NewGetTaskResult(task Task) GetTaskResult func ParseGetTaskResult(rawMessage *json.RawMessage) (*GetTaskResult, error)
Icon represents a visual identifier for MCP entities. Security considerations: - Clients MUST support at least image/png and image/jpeg MIME types - Clients SHOULD support image/svg+xml and image/webp - Icons should be treated as untrusted input - URI scheme validation (HTTPS or data URI only) - Size/dimension limits to prevent resource exhaustion Optional MIME type (e.g., "image/png", "image/svg+xml") Optional size specifications (e.g., ["48x48"], ["any"] for SVG) URI pointing to the icon resource (HTTPS URL or data URI) func WithPromptIcons(icons ...Icon) PromptOption func WithResourceIcons(icons ...Icon) ResourceOption func WithTemplateIcons(icons ...Icon) ResourceTemplateOption func WithToolIcons(icons ...Icon) ToolOption func github.com/mark3labs/mcp-go/server.WithIcons(icons ...Icon) server.ServerOption
ImageContent represents an image provided to or from an LLM. It must have Type set to "image". Annotated Annotated Annotated.Annotations *Annotations The base64-encoded image data. The MIME type of the image. Different providers may support different image types. Meta is a metadata object that is reserved by MCP for storing additional information. // Must be "image" ImageContent : Content func AsImageContent(content any) (*ImageContent, bool) func NewImageContent(data, mimeType string) ImageContent
Implementation describes the name and version of an MCP implementation. Description string Icons provides visual identifiers for the implementation Name string Title string Version string WebsiteURL string func github.com/mark3labs/mcp-go/server.(*InProcessSession).GetClientInfo() Implementation func github.com/mark3labs/mcp-go/server.SessionWithClientInfo.GetClientInfo() Implementation func NewInitializeResult(protocolVersion string, capabilities ServerCapabilities, serverInfo Implementation, instructions string) *InitializeResult func github.com/mark3labs/mcp-go/server.(*InProcessSession).SetClientInfo(clientInfo Implementation) func github.com/mark3labs/mcp-go/server.SessionWithClientInfo.SetClientInfo(clientInfo Implementation)
InitializedNotification is sent from the client to the server after initialization has finished. Notification Notification Notification.Method string Notification.Params NotificationParams
Capabilities ClientCapabilities ClientInfo Implementation The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
InitializeRequest is sent from the client to the server when it first connects, asking it to begin initialization. Header http.Header Params InitializeParams Request Request Request.Method string
InitializeResult is sent after receiving an initialize request from the client. Capabilities ServerCapabilities 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. 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. Result Result Result.Meta *Meta ServerInfo Implementation func NewInitializeResult(protocolVersion string, capabilities ServerCapabilities, serverInfo Implementation, instructions string) *InitializeResult
JSONRPCError represents a non-successful (error) response to a request. Error JSONRPCErrorDetails ID RequestId JSONRPC string func NewJSONRPCError(id RequestId, code int, message string, data any) JSONRPCError func URLElicitationRequiredError.JSONRPCError() JSONRPCError
JSONRPCErrorDetails represents a JSON-RPC error for Go error handling. This is separate from the JSONRPCError type which represents the full JSON-RPC error response structure. The error type that occurred. Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). A short description of the error. The message SHOULD be limited to a concise single sentence. AsError maps JSONRPCErrorDetails to a Go error. Returns sentinel errors wrapped with custom messages for known codes. Defaults to a generic error with the original message when the code is not mapped. func NewJSONRPCErrorDetails(code int, message string, data any) JSONRPCErrorDetails
JSONRPCMessage represents either a JSONRPCRequest, JSONRPCNotification, JSONRPCResponse, or JSONRPCError func github.com/mark3labs/mcp-go/server.(*MCPServer).HandleMessage(ctx context.Context, message json.RawMessage) JSONRPCMessage
JSONRPCNotification represents a notification which does not expect a response. JSONRPC string Notification Notification Notification.Method string Notification.Params NotificationParams func NewElicitationCompleteNotification(elicitationID string) JSONRPCNotification func github.com/mark3labs/mcp-go/server.ClientSession.NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.(*InProcessSession).NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.SessionWithClientInfo.NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.SessionWithElicitation.NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.SessionWithLogging.NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.SessionWithResources.NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.SessionWithResourceTemplates.NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.SessionWithRoots.NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.SessionWithSampling.NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.SessionWithStreamableHTTPConfig.NotificationChannel() chan<- JSONRPCNotification func github.com/mark3labs/mcp-go/server.SessionWithTools.NotificationChannel() chan<- JSONRPCNotification
JSONRPCRequest represents a request that expects a response. ID RequestId JSONRPC string Params any Request Request Request.Method string
JSONRPCResponse represents a successful (non-error) response to a request. ID RequestId JSONRPC string Result any func NewJSONRPCResponse(id RequestId, result Result) JSONRPCResponse func NewJSONRPCResultResponse(id RequestId, result any) JSONRPCResponse
ListPromptsRequest is sent from the client to request a list of prompts and prompt templates the server has. Header http.Header PaginatedRequest PaginatedRequest PaginatedRequest.Params PaginatedParams PaginatedRequest.Request Request PaginatedRequest.Request.Method string
ListPromptsResult is the server's response to a prompts/list request from the client. PaginatedResult PaginatedResult An opaque token representing the pagination position after the last returned result. If present, there may be more results available. PaginatedResult.Result Result PaginatedResult.Result.Meta *Meta Prompts []Prompt func NewListPromptsResult(prompts []Prompt, nextCursor Cursor) *ListPromptsResult
ListResourcesRequest is sent from the client to request a list of resources the server has. Header http.Header PaginatedRequest PaginatedRequest PaginatedRequest.Params PaginatedParams PaginatedRequest.Request Request PaginatedRequest.Request.Method string
ListResourcesResult is the server's response to a resources/list request from the client. PaginatedResult PaginatedResult An opaque token representing the pagination position after the last returned result. If present, there may be more results available. PaginatedResult.Result Result PaginatedResult.Result.Meta *Meta Resources []Resource func NewListResourcesResult(resources []Resource, nextCursor Cursor) *ListResourcesResult
ListResourceTemplatesRequest is sent from the client to request a list of resource templates the server has. Header http.Header PaginatedRequest PaginatedRequest PaginatedRequest.Params PaginatedParams PaginatedRequest.Request Request PaginatedRequest.Request.Method string
ListResourceTemplatesResult is the server's response to a resources/templates/list request from the client. PaginatedResult PaginatedResult An opaque token representing the pagination position after the last returned result. If present, there may be more results available. PaginatedResult.Result Result PaginatedResult.Result.Meta *Meta ResourceTemplates []ResourceTemplate func NewListResourceTemplatesResult(templates []ResourceTemplate, nextCursor Cursor) *ListResourceTemplatesResult
ListRootsRequest is sent from the server to request a list of root URIs from the client. Roots allow servers to ask for specific directories or files to operate on. A common example for roots is providing a set of repositories or directories a server should operate on. This request is typically used when the server needs to understand the file system structure or access specific locations that the client has permission to read from. Request Request Request.Method string Request.Params RequestParams func github.com/mark3labs/mcp-go/server.(*InProcessSession).ListRoots(ctx context.Context, request ListRootsRequest) (*ListRootsResult, error) func github.com/mark3labs/mcp-go/server.(*MCPServer).RequestRoots(ctx context.Context, request ListRootsRequest) (*ListRootsResult, error) func github.com/mark3labs/mcp-go/server.RootsHandler.ListRoots(ctx context.Context, request ListRootsRequest) (*ListRootsResult, error) func github.com/mark3labs/mcp-go/server.SessionWithRoots.ListRoots(ctx context.Context, request ListRootsRequest) (*ListRootsResult, error)
ListRootsResult is 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. Result Result Result.Meta *Meta Roots []Root func github.com/mark3labs/mcp-go/server.(*InProcessSession).ListRoots(ctx context.Context, request ListRootsRequest) (*ListRootsResult, error) func github.com/mark3labs/mcp-go/server.(*MCPServer).RequestRoots(ctx context.Context, request ListRootsRequest) (*ListRootsResult, error) func github.com/mark3labs/mcp-go/server.RootsHandler.ListRoots(ctx context.Context, request ListRootsRequest) (*ListRootsResult, error) func github.com/mark3labs/mcp-go/server.SessionWithRoots.ListRoots(ctx context.Context, request ListRootsRequest) (*ListRootsResult, error)
ListTasksResult returns a list of tasks. PaginatedResult PaginatedResult An opaque token representing the pagination position after the last returned result. If present, there may be more results available. PaginatedResult.Result Result PaginatedResult.Result.Meta *Meta Tasks []Task func NewListTasksResult(tasks []Task) ListTasksResult func ParseListTasksResult(rawMessage *json.RawMessage) (*ListTasksResult, error)
ListToolsRequest is sent from the client to request a list of tools the server has. Header http.Header PaginatedRequest PaginatedRequest PaginatedRequest.Params PaginatedParams PaginatedRequest.Request Request PaginatedRequest.Request.Method string
ListToolsResult is the server's response to a tools/list request from the client. PaginatedResult PaginatedResult An opaque token representing the pagination position after the last returned result. If present, there may be more results available. PaginatedResult.Result Result PaginatedResult.Result.Meta *Meta Tools []Tool func NewListToolsResult(tools []Tool, nextCursor Cursor) *ListToolsResult
LoggingLevel represents 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 ( LoggingLevel) ShouldSendTo(minLevel LoggingLevel) bool func github.com/mark3labs/mcp-go/server.(*InProcessSession).GetLogLevel() LoggingLevel func github.com/mark3labs/mcp-go/server.SessionWithLogging.GetLogLevel() LoggingLevel func NewLoggingMessageNotification(level LoggingLevel, logger string, data any) LoggingMessageNotification func LoggingLevel.ShouldSendTo(minLevel LoggingLevel) bool func github.com/mark3labs/mcp-go/server.(*InProcessSession).SetLogLevel(level LoggingLevel) func github.com/mark3labs/mcp-go/server.SessionWithLogging.SetLogLevel(level LoggingLevel) const LoggingLevelAlert const LoggingLevelCritical const LoggingLevelDebug const LoggingLevelEmergency const LoggingLevelError const LoggingLevelInfo const LoggingLevelNotice const LoggingLevelWarning
LoggingMessageNotification is a notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. Notification Notification Notification.Method string Params LoggingMessageNotificationParams func NewLoggingMessageNotification(level LoggingLevel, logger string, data any) LoggingMessageNotification func github.com/mark3labs/mcp-go/server.(*MCPServer).SendLogMessageToClient(ctx context.Context, notification LoggingMessageNotification) error func github.com/mark3labs/mcp-go/server.(*MCPServer).SendLogMessageToSpecificClient(sessionID string, notification LoggingMessageNotification) error
The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. The severity of this log message. An optional name of the logger issuing this message.
func github.com/mark3labs/mcp-go/server.(*UnparsableMessageError).GetMethod() MCPMethod const MethodCompletionComplete const MethodElicitationCreate const MethodInitialize const MethodListRoots const MethodNotificationElicitationComplete const MethodPing const MethodPromptsGet const MethodPromptsList const MethodResourcesList const MethodResourcesRead const MethodResourcesTemplatesList const MethodSamplingCreateMessage const MethodSetLogLevel const MethodTasksCancel const MethodTasksGet const MethodTasksList const MethodTasksResult const MethodToolsCall const MethodToolsList
Meta is metadata attached to a request's parameters. This can include fields formally defined by the protocol or other arbitrary data. AdditionalFields are any fields present in the Meta that are not otherwise defined in the protocol. If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. (*Meta) MarshalJSON() ([]byte, error) (*Meta) UnmarshalJSON(data []byte) error *Meta : github.com/goccy/go-json.Marshaler *Meta : github.com/goccy/go-json.Unmarshaler *Meta : encoding/json.Marshaler *Meta : encoding/json.Unmarshaler func NewMetaFromMap(m map[string]any) *Meta func WithModelImmediateResponse(message string) *Meta func WithRelatedTask(taskID string) *Meta
ModelHint represents 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. 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`
ModelPreferences represents the server's preferences for model selection, requested of the client during sampling. Because LLMs can vary along multiple dimensions, choosing the "best" modelis 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. 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. 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. 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. 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.
( Named) GetName() string CancelTaskResult GetTaskResult Prompt Resource ResourceTemplate Task TaskStatusNotificationParams Tool *github.com/apache/arrow-go/v18/parquet/internal/gen-go/parquet.SchemaElement *github.com/polarsignals/frostdb/gen/proto/go/frostdb/schema/v1alpha1.Column *github.com/polarsignals/frostdb/gen/proto/go/frostdb/schema/v1alpha1.Schema *github.com/polarsignals/frostdb/gen/proto/go/frostdb/schema/v1alpha1.SortingColumn *github.com/polarsignals/frostdb/gen/proto/go/frostdb/schema/v1alpha2.Group *github.com/polarsignals/frostdb/gen/proto/go/frostdb/schema/v1alpha2.Leaf *github.com/polarsignals/frostdb/gen/proto/go/frostdb/snapshot/v1alpha1.Table *github.com/prometheus/client_model/go.LabelPair *github.com/prometheus/client_model/go.MetricFamily *go.opentelemetry.io/proto/otlp/common/v1.InstrumentationScope *go.opentelemetry.io/proto/otlp/trace/v1.Span *go.opentelemetry.io/proto/otlp/trace/v1.Span_Event *google.golang.org/protobuf/types/descriptorpb.DescriptorProto *google.golang.org/protobuf/types/descriptorpb.EnumDescriptorProto *google.golang.org/protobuf/types/descriptorpb.EnumValueDescriptorProto *google.golang.org/protobuf/types/descriptorpb.FieldDescriptorProto *google.golang.org/protobuf/types/descriptorpb.FileDescriptorProto *google.golang.org/protobuf/types/descriptorpb.MethodDescriptorProto *google.golang.org/protobuf/types/descriptorpb.OneofDescriptorProto *google.golang.org/protobuf/types/descriptorpb.ServiceDescriptorProto *gorm.io/gorm/schema.CheckConstraint *gorm.io/gorm/schema.Constraint gorm.io/gorm/schema.ConstraintInterface (interface) *gorm.io/gorm/schema.UniqueConstraint
Method string Params NotificationParams
Additional fields can be added to this map This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications. MarshalJSON implements custom JSON marshaling UnmarshalJSON implements custom JSON unmarshaling NotificationParams : github.com/goccy/go-json.Marshaler *NotificationParams : github.com/goccy/go-json.Unmarshaler NotificationParams : encoding/json.Marshaler *NotificationParams : encoding/json.Unmarshaler
An opaque token representing the current pagination position. If provided, the server should return results starting after this cursor.
An opaque token representing the pagination position after the last returned result. If present, there may be more results available. Result Result Result.Meta *Meta
type Params (map)
PingRequest represents a ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. Header http.Header Request Request Request.Method string Request.Params RequestParams
ProgressNotification is an out-of-band notification used to inform the receiver of a progress update for a long-running request. Notification Notification Notification.Method string Params ProgressNotificationParams func NewProgressNotification(token ProgressToken, progress float64, total *float64, message *string) ProgressNotification
Message related to progress. This should provide relevant human-readable progress information. The progress thus far. This should increase every time progress is made, even if the total is unknown. The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. Total number of items to process (or total progress required), if known.
ProgressToken is used to associate progress notifications with the original request. func NewProgressNotification(token ProgressToken, progress float64, total *float64, message *string) ProgressNotification
Prompt represents a prompt or prompt template that the server offers. If Arguments is non-nil and non-empty, this indicates the prompt is a template that requires argument values to be provided when calling prompts/get. If Arguments is nil or empty, this is a static prompt that takes no arguments. A list of arguments to use for templating the prompt. The presence of arguments indicates this is a template prompt. An optional description of what this prompt provides Icons provides visual identifiers for the prompt Meta is a metadata object that is reserved by MCP for storing additional information. The name of the prompt or prompt template. GetName returns the name of the prompt. Prompt : Named func NewPrompt(name string, opts ...PromptOption) Prompt func NewListPromptsResult(prompts []Prompt, nextCursor Cursor) *ListPromptsResult func github.com/mark3labs/mcp-go/server.(*MCPServer).AddPrompt(prompt Prompt, handler server.PromptHandlerFunc)
PromptArgument describes an argument that a prompt template can accept. When a prompt includes arguments, clients must provide values for all required arguments when making a prompts/get request. A human-readable description of the argument. The name of the argument. Whether this argument must be provided. If true, clients must include this argument when calling prompts/get.
PromptListChangedNotification is an optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. Notification Notification Notification.Method string Notification.Params NotificationParams
PromptMessage 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. // Can be TextContent, ImageContent, AudioContent or EmbeddedResource Role Role func NewPromptMessage(role Role, content Content) PromptMessage func NewGetPromptResult(description string, messages []PromptMessage) *GetPromptResult
PromptOption is a function that configures a Prompt. It provides a flexible way to set various properties of a Prompt using the functional options pattern. func WithArgument(name string, opts ...ArgumentOption) PromptOption func WithPromptDescription(description string) PromptOption func WithPromptIcons(icons ...Icon) PromptOption func NewPrompt(name string, opts ...PromptOption) Prompt
PromptReference identifies a prompt. The name of the prompt or prompt template Type string
PropertyOption is a function that configures a property in a Tool's input schema. It allows for flexible configuration of JSON Schema properties using the functional options pattern. func AdditionalProperties(schema any) PropertyOption func DefaultArray[T](value []T) PropertyOption func DefaultBool(value bool) PropertyOption func DefaultNumber(value float64) PropertyOption func DefaultString(value string) PropertyOption func Description(desc string) PropertyOption func Enum(values ...string) PropertyOption func Items(schema any) PropertyOption func Max(max float64) PropertyOption func MaxItems(max int) PropertyOption func MaxLength(max int) PropertyOption func MaxProperties(max int) PropertyOption func Min(min float64) PropertyOption func MinItems(min int) PropertyOption func MinLength(min int) PropertyOption func MinProperties(min int) PropertyOption func MultipleOf(value float64) PropertyOption func Pattern(pattern string) PropertyOption func Properties(props map[string]any) PropertyOption func PropertyNames(schema map[string]any) PropertyOption func Required() PropertyOption func Title(title string) PropertyOption func UniqueItems(unique bool) PropertyOption func WithBooleanItems(opts ...PropertyOption) PropertyOption func WithNumberItems(opts ...PropertyOption) PropertyOption func WithStringEnumItems(values []string) PropertyOption func WithStringItems(opts ...PropertyOption) PropertyOption func WithAny(name string, opts ...PropertyOption) ToolOption func WithArray(name string, opts ...PropertyOption) ToolOption func WithBoolean(name string, opts ...PropertyOption) ToolOption func WithBooleanItems(opts ...PropertyOption) PropertyOption func WithNumber(name string, opts ...PropertyOption) ToolOption func WithNumberItems(opts ...PropertyOption) PropertyOption func WithObject(name string, opts ...PropertyOption) ToolOption func WithString(name string, opts ...PropertyOption) ToolOption func WithStringItems(opts ...PropertyOption) PropertyOption
Arguments to pass to the resource handler The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
ReadResourceRequest is sent from the client to the server, to read a specific resource URI. Header http.Header Params ReadResourceParams Request Request Request.Method string
ReadResourceResult is the server's response to a resources/read request from the client. // Can be TextResourceContents or BlobResourceContents Result Result Result.Meta *Meta func NewReadResourceResult(text string) *ReadResourceResult func ParseReadResourceResult(rawMessage *json.RawMessage) (*ReadResourceResult, error)
Method string Params RequestParams
RequestId is a uniquely identifying ID for a request in JSON-RPC. It can be any JSON-serializable value, typically a number or string. IsNil returns true if the RequestId is nil ( RequestId) MarshalJSON() ([]byte, error) String returns a string representation of the RequestId (*RequestId) UnmarshalJSON(data []byte) error Value returns the underlying value of the RequestId RequestId : github.com/goccy/go-json.Marshaler *RequestId : github.com/goccy/go-json.Unmarshaler RequestId : encoding/json.Marshaler *RequestId : encoding/json.Unmarshaler RequestId : expvar.Var RequestId : fmt.Stringer func NewRequestId(value any) RequestId func NewJSONRPCError(id RequestId, code int, message string, data any) JSONRPCError func NewJSONRPCResponse(id RequestId, result Result) JSONRPCResponse func NewJSONRPCResultResponse(id RequestId, result any) JSONRPCResponse
Meta *Meta
Resource represents a known resource that the server is capable of reading. Annotated Annotated Annotated.Annotations *Annotations 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. Icons provides visual identifiers for the resource The MIME type of this resource, if known. Meta is a metadata object that is reserved by MCP for storing additional information. A human-readable name for this resource. This can be used by clients to populate UI elements. The URI of this resource. GetName returns the name of the resource. Resource : Named func NewResource(uri string, name string, opts ...ResourceOption) Resource func NewListResourcesResult(resources []Resource, nextCursor Cursor) *ListResourcesResult func github.com/mark3labs/mcp-go/server.(*MCPServer).AddResource(resource Resource, handler server.ResourceHandlerFunc) func github.com/mark3labs/mcp-go/server.(*MCPServer).AddSessionResource(sessionID string, resource Resource, handler server.ResourceHandlerFunc) error
ResourceContents represents the contents of a specific resource or sub- resource. BlobResourceContents TextResourceContents func ParseResourceContents(contentMap map[string]any) (ResourceContents, error) func NewEmbeddedResource(resource ResourceContents) EmbeddedResource func NewToolResultResource(text string, resource ResourceContents) *CallToolResult
ResourceListChangedNotification is an optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. Notification Notification Notification.Method string Notification.Params NotificationParams
ResourceOption is a function that configures a Resource. It provides a flexible way to set various properties of a Resource using the functional options pattern. func WithAnnotations(audience []Role, priority float64, lastModified string) ResourceOption func WithLastModified(timestamp string) ResourceOption func WithMIMEType(mimeType string) ResourceOption func WithResourceDescription(description string) ResourceOption func WithResourceIcons(icons ...Icon) ResourceOption func NewResource(uri string, name string, opts ...ResourceOption) Resource
ResourceReference is a reference to a resource or resource template definition. Type string The URI or URI template of the resource.
ResourceTemplate represents a template description for resources available on the server. Annotated Annotated Annotated.Annotations *Annotations 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. Icons provides visual identifiers for the resource template 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. Meta is a metadata object that is reserved by MCP for storing additional information. A human-readable name for the type of resource this template refers to. This can be used by clients to populate UI elements. A URI template (according to RFC 6570) that can be used to construct resource URIs. GetName returns the name of the resourceTemplate. ResourceTemplate : Named func NewResourceTemplate(uriTemplate string, name string, opts ...ResourceTemplateOption) ResourceTemplate func NewListResourceTemplatesResult(templates []ResourceTemplate, nextCursor Cursor) *ListResourceTemplatesResult func github.com/mark3labs/mcp-go/server.(*MCPServer).AddResourceTemplate(template ResourceTemplate, handler server.ResourceTemplateHandlerFunc) func github.com/mark3labs/mcp-go/server.(*MCPServer).AddSessionResourceTemplate(sessionID string, template ResourceTemplate, handler server.ResourceTemplateHandlerFunc) error
ResourceTemplateOption is a function that configures a ResourceTemplate. It provides a flexible way to set various properties of a ResourceTemplate using the functional options pattern. func WithTemplateAnnotations(audience []Role, priority float64, lastModified string) ResourceTemplateOption func WithTemplateDescription(description string) ResourceTemplateOption func WithTemplateIcons(icons ...Icon) ResourceTemplateOption func WithTemplateMIMEType(mimeType string) ResourceTemplateOption func NewResourceTemplate(uriTemplate string, name string, opts ...ResourceTemplateOption) ResourceTemplate
ResourceUpdatedNotification is 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. Notification Notification Notification.Method string Params ResourceUpdatedNotificationParams
The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
Meta *Meta func NewJSONRPCResponse(id RequestId, result Result) JSONRPCResponse
Role represents the sender or recipient of messages and data in a conversation. func NewPromptMessage(role Role, content Content) PromptMessage func WithAnnotations(audience []Role, priority float64, lastModified string) ResourceOption func WithTemplateAnnotations(audience []Role, priority float64, lastModified string) ResourceTemplateOption const RoleAssistant const RoleUser
Root represents a root directory or file that the server can operate on. Meta is a metadata object that is reserved by MCP for storing additional information. 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. 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.
RootsListChangedNotification is a notification from the client to the server, informing it that the list of roots has changed. This notification should be sent whenever the client adds, removes, or modifies any root. The server should then request an updated list of roots using the ListRootsRequest. Notification Notification Notification.Method string Notification.Params NotificationParams
SamplingMessage describes a message issued to or received from an LLM API. // Can be TextContent, ImageContent or AudioContent Role Role
ServerCapabilities represents 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. Present if the server supports completions requests to the client. Present if the server supports elicitation requests to the client. Experimental, non-standard capabilities that the server supports. Optional, present if the server is advertising extension support. Present if the server supports sending log messages to the client. Present if the server offers any prompt templates. Present if the server offers any resources to read. Present if the server supports roots requests to the client. Present if the server supports sending sampling requests to clients. Present if the server supports task-based execution. Present if the server offers any tools to call. func NewInitializeResult(protocolVersion string, capabilities ServerCapabilities, serverInfo Implementation, instructions string) *InitializeResult
ServerNotification represents any notification that can be sent from server to client.
ServerRequest represents any request that can be sent from server to client.
ServerResult represents any result that can be sent from server to client.
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/logging/message.
SetLevelRequest is a request from the client to the server, to enable or adjust logging. Header http.Header Params SetLevelParams Request Request Request.Method string
Type Parameters: TArgs: any TResult: any StructuredToolHandlerFunc is a function that handles a tool call with typed arguments and returns structured output func NewStructuredToolHandler[TArgs, TResult](handler StructuredToolHandlerFunc[TArgs, TResult]) func(ctx context.Context, request CallToolRequest) (*CallToolResult, error)
The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
SubscribeRequest is sent from the client to request resources/updated notifications from the server whenever a particular resource changes. Header http.Header Params SubscribeParams Request Request Request.Method string
Task represents the execution state of a request. ISO 8601 timestamp when the task was created. ISO 8601 timestamp when the task was last updated. Suggested time in milliseconds between status checks. Current state of the task execution. Optional human-readable message describing the current state. Time in milliseconds from creation before task may be deleted. If null, the task has no expiration. Unique identifier for the task. GetName returns the task ID, implementing the Named interface for pagination. Task : Named func NewTask(taskId string, opts ...TaskOption) Task func NewCancelTaskResult(task Task) CancelTaskResult func NewCreateTaskResult(task Task) CreateTaskResult func NewGetTaskResult(task Task) GetTaskResult func NewListTasksResult(tasks []Task) ListTasksResult func NewTaskStatusNotification(task Task) TaskStatusNotification
TaskOption is a function that configures a Task. It provides a flexible way to set various properties of a Task using the functional options pattern. func WithTaskCreatedAt(createdAt string) TaskOption func WithTaskPollInterval(intervalMs int64) TaskOption func WithTaskStatus(status TaskStatus) TaskOption func WithTaskStatusMessage(message string) TaskOption func WithTaskTTL(ttlMs int64) TaskOption func NewTask(taskId string, opts ...TaskOption) Task
TaskParams represents the task metadata included when augmenting a request. Requested duration in milliseconds to retain task from creation. func NewTaskParams(ttlMs *int64) TaskParams
TaskRequestsCapability indicates which request types support task augmentation. Elicitation-related capabilities. Sampling-related capabilities. Tool-related capabilities.
TaskId string
TaskResultRequest retrieves the result of a completed task. Header http.Header Params TaskResultParams Request Request Request.Method string
TaskResultResult contains the actual operation result. For task-augmented tool calls, this embeds the CallToolResult fields. Tool call result fields (for task-augmented tool calls) IsError bool Result Result Result.Meta *Meta StructuredContent any func ParseTaskResultResult(rawMessage *json.RawMessage) (*TaskResultResult, error)
TasksCapability represents the task capabilities that a client or server may support. Tasks enable long-running, asynchronous operations with status polling. Whether the party supports the tasks/cancel operation. Whether the party supports the tasks/list operation. Requests that can be augmented with task metadata. func NewTasksCapability() *TasksCapability func NewTasksCapabilityWithToolsOnly() *TasksCapability
TaskStatus represents the execution state of a task. IsTerminal returns true if the task status is terminal (completed, failed, or cancelled). func WithTaskStatus(status TaskStatus) TaskOption const TaskStatusCancelled const TaskStatusCompleted const TaskStatusFailed const TaskStatusInputRequired const TaskStatusWorking
TaskStatusNotification is sent when a task's status changes. Notification Notification Notification.Method string Params TaskStatusNotificationParams func NewTaskStatusNotification(task Task) TaskStatusNotification
Task Task ISO 8601 timestamp when the task was created. ISO 8601 timestamp when the task was last updated. Suggested time in milliseconds between status checks. Current state of the task execution. Optional human-readable message describing the current state. Time in milliseconds from creation before task may be deleted. If null, the task has no expiration. Unique identifier for the task. GetName returns the task ID, implementing the Named interface for pagination. TaskStatusNotificationParams : Named
TaskSupport indicates how a tool supports task augmentation. func WithTaskSupport(support TaskSupport) ToolOption const TaskSupportForbidden const TaskSupportOptional const TaskSupportRequired
TextContent represents text provided to or from an LLM. It must have Type set to "text". Annotated Annotated Annotated.Annotations *Annotations Meta is a metadata object that is reserved by MCP for storing additional information. The text content of the message. // Must be "text" TextContent : Content func AsTextContent(content any) (*TextContent, bool) func NewTextContent(text string) TextContent
The MIME type of this resource, if known. Raw per‑resource metadata; pass‑through as defined by MCP. Not the same as mcp.Meta. Allows _meta to be used for MCP-UI features for example. Does not assume any specific format. The text of the item. This must only be set if the item can actually be represented as text (not binary data). The URI of this resource. TextResourceContents : ResourceContents func AsTextResourceContents(content any) (*TextResourceContents, bool)
Tool represents the definition for a tool the client can call. Optional properties describing tool behavior Support for deferred loading A human-readable description of the tool. Execution describes execution behavior for the tool Icons provides visual identifiers for the tool A JSON Schema object defining the expected parameters for the tool. Meta is a metadata object that is reserved by MCP for storing additional information. The name of the tool. A JSON Schema object defining the expected output returned by the tool . Alternative to InputSchema - allows arbitrary JSON Schema to be provided // Hide this from JSON marshaling Optional JSON Schema defining expected output structure // Hide this from JSON marshaling GetName returns the name of the tool. MarshalJSON implements the json.Marshaler interface for Tool. It handles marshaling either InputSchema or RawInputSchema based on which is set. Tool : Named Tool : github.com/goccy/go-json.Marshaler Tool : encoding/json.Marshaler func NewTool(name string, opts ...ToolOption) Tool func NewToolWithRawSchema(name, description string, schema json.RawMessage) Tool func NewListToolsResult(tools []Tool, nextCursor Cursor) *ListToolsResult func github.com/mark3labs/mcp-go/server.(*MCPServer).AddSessionTool(sessionID string, tool Tool, handler server.ToolHandlerFunc) error func github.com/mark3labs/mcp-go/server.(*MCPServer).AddTaskTool(tool Tool, handler server.TaskToolHandlerFunc) func github.com/mark3labs/mcp-go/server.(*MCPServer).AddTool(tool Tool, handler server.ToolHandlerFunc)
If true, the tool may perform destructive updates If true, repeated calls with same args have no additional effect If true, tool interacts with external entities If true, the tool does not modify its environment Human-readable title for the tool func WithToolAnnotation(annotation ToolAnnotation) ToolOption
ToolArgumentsSchema represents a JSON Schema for tool arguments. AdditionalProperties any Defs map[string]any Properties map[string]any Required []string Type string MarshalJSON implements the json.Marshaler interface for ToolArgumentsSchema. UnmarshalJSON implements the json.Unmarshaler interface for ToolArgumentsSchema. ToolArgumentsSchema : github.com/goccy/go-json.Marshaler *ToolArgumentsSchema : github.com/goccy/go-json.Unmarshaler ToolArgumentsSchema : encoding/json.Marshaler *ToolArgumentsSchema : encoding/json.Unmarshaler
ToolExecution describes execution behavior for a tool. TaskSupport indicates whether the tool supports task augmentation.
AdditionalProperties any Defs map[string]any Properties map[string]any Required []string Type string MarshalJSON implements the json.Marshaler interface for ToolInputSchema. UnmarshalJSON implements the json.Unmarshaler interface for ToolInputSchema. ToolInputSchema : github.com/goccy/go-json.Marshaler *ToolInputSchema : github.com/goccy/go-json.Unmarshaler ToolInputSchema : encoding/json.Marshaler *ToolInputSchema : encoding/json.Unmarshaler
ToolListChangedNotification is an optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. Notification Notification Notification.Method string Notification.Params NotificationParams
ToolOption is a function that configures a Tool. It provides a flexible way to set various properties of a Tool using the functional options pattern. func WithAny(name string, opts ...PropertyOption) ToolOption func WithArray(name string, opts ...PropertyOption) ToolOption func WithBoolean(name string, opts ...PropertyOption) ToolOption func WithDeferLoading(deferLoading bool) ToolOption func WithDescription(description string) ToolOption func WithDestructiveHintAnnotation(value bool) ToolOption func WithIdempotentHintAnnotation(value bool) ToolOption func WithInputSchema[T]() ToolOption func WithNumber(name string, opts ...PropertyOption) ToolOption func WithObject(name string, opts ...PropertyOption) ToolOption func WithOpenWorldHintAnnotation(value bool) ToolOption func WithOutputSchema[T]() ToolOption func WithRawInputSchema(schema json.RawMessage) ToolOption func WithRawOutputSchema(schema json.RawMessage) ToolOption func WithReadOnlyHintAnnotation(value bool) ToolOption func WithSchemaAdditionalProperties(schema any) ToolOption func WithString(name string, opts ...PropertyOption) ToolOption func WithTaskSupport(support TaskSupport) ToolOption func WithTitleAnnotation(title string) ToolOption func WithToolAnnotation(annotation ToolAnnotation) ToolOption func WithToolIcons(icons ...Icon) ToolOption func NewTool(name string, opts ...ToolOption) Tool
AdditionalProperties any Defs map[string]any Properties map[string]any Required []string Type string MarshalJSON implements the json.Marshaler interface for ToolOutputSchema. UnmarshalJSON implements the json.Unmarshaler interface for ToolOutputSchema. ToolOutputSchema : github.com/goccy/go-json.Marshaler *ToolOutputSchema : github.com/goccy/go-json.Unmarshaler ToolOutputSchema : encoding/json.Marshaler *ToolOutputSchema : encoding/json.Unmarshaler
Type Parameters: T: any TypedToolHandlerFunc is a function that handles a tool call with typed arguments func NewTypedToolHandler[T](handler TypedToolHandlerFunc[T]) func(ctx context.Context, request CallToolRequest) (*CallToolResult, error)
The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
UnsubscribeRequest is sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. Header http.Header Params UnsubscribeParams Request Request Request.Method string
UnsupportedProtocolVersionError is returned when the server responds with a protocol version that the client doesn't support. Version string ( UnsupportedProtocolVersionError) Error() string Is implements the errors.Is interface for better error handling UnsupportedProtocolVersionError : error
Template *uritemplate.Template Expand returns a URI reference corresponding to the template expanded using the passed variables. (*URITemplate) MarshalJSON() ([]byte, error) ( URITemplate) Match(expansion string) uritemplate.Values Raw returns a raw URI template passed to New in string. Regexp converts the template to regexp and returns compiled *regexp.Regexp. (*URITemplate) UnmarshalJSON(data []byte) error Varnames returns variable names used in the template. *URITemplate : github.com/goccy/go-json.Marshaler *URITemplate : github.com/goccy/go-json.Unmarshaler *URITemplate : encoding/json.Marshaler *URITemplate : encoding/json.Unmarshaler
URLElicitationRequiredError is returned when the server requires URL elicitation to proceed. Elicitations []ElicitationParams ( URLElicitationRequiredError) Error() string Is implements the errors.Is interface for better error handling ( URLElicitationRequiredError) JSONRPCError() JSONRPCError URLElicitationRequiredError : error
Package-Level Functions (total 160)
AdditionalProperties specifies whether additional properties are allowed in the object or defines a schema for additional properties
ArgumentDescription adds a description to a prompt argument. The description should explain the purpose and expected values of the argument.
AsAudioContent attempts to cast the given interface to AudioContent
AsBlobResourceContents attempts to cast the given interface to BlobResourceContents
AsEmbeddedResource attempts to cast the given interface to EmbeddedResource
AsImageContent attempts to cast the given interface to ImageContent
AsTextContent attempts to cast the given interface to TextContent
AsTextResourceContents attempts to cast the given interface to TextResourceContents
Type Parameters: T: any DefaultArray sets the default value for an array property. This value will be used if the property is not explicitly provided.
DefaultBool sets the default value for a boolean property. This value will be used if the property is not explicitly provided.
DefaultNumber sets the default value for a number property. This value will be used if the property is not explicitly provided.
DefaultString sets the default value for a string property. This value will be used if the property is not explicitly provided.
Description adds a description to a property in the JSON Schema. The description should explain the purpose and expected values of the property.
Enum specifies a list of allowed values for a string property. The property value must be one of the specified enum values.
func ExtractMap(data map[string]any, key string) map[string]any
func ExtractString(data map[string]any, key string) string
FormatNumberResult Helper for formatting numbers in tool results
GetTextFromContent extracts text from a Content interface that might be a TextContent struct or a map[string]any that was unmarshaled from JSON. This is useful when dealing with content that comes from different transport layers that may handle JSON differently. This function uses fallback behavior for non-text content - it returns a string representation via fmt.Sprintf for any content that cannot be extracted as text. This is a lossy operation intended for convenience in logging and display scenarios. For strict type validation, use ParseContent() instead, which returns an error for invalid content.
IsUnsupportedProtocolVersion checks if an error is an UnsupportedProtocolVersionError
Items defines the schema for array items. Accepts any schema definition for maximum flexibility. Example: Items(map[string]any{ "type": "object", "properties": map[string]any{ "name": map[string]any{"type": "string"}, "age": map[string]any{"type": "number"}, }, }) For simple types, use ItemsString(), ItemsNumber(), ItemsBoolean() instead.
MarshalJSON implements custom JSON marshaling for Content interface
Max sets the maximum value for a number property. The number value must not exceed this maximum.
MaxItems sets the maximum number of items for an array
MaxLength sets the maximum length for a string property. The string value must not exceed this length.
MaxProperties sets the maximum number of properties for an object
Min sets the minimum value for a number property. The number value must not be less than this minimum.
MinItems sets the minimum number of items for an array
MinLength sets the minimum length for a string property. The string value must be at least this length.
MinProperties sets the minimum number of properties for an object
MultipleOf specifies that a number must be a multiple of the given value. The number value must be divisible by this value.
Helper function to create a new AudioContent
NewCancelTaskResult creates a CancelTaskResult from a Task.
NewCreateTaskResult creates a CreateTaskResult with the given task.
NewElicitationCompleteNotification creates a new elicitation complete notification.
Helper function to create a new EmbeddedResource
NewGetPromptResult creates a new GetPromptResult
NewGetTaskResult creates a GetTaskResult from a Task.
NewImageContent Helper function to create a new ImageContent
NewInitializeResult creates a new InitializeResult
NewJSONRPCError creates a new JSONRPCResponse with the given id, code, and message
NewJSONRPCErrorDetails creates a new JSONRPCErrorDetails with the given code, message, and data.
NewJSONRPCResponse creates a new JSONRPCResponse with the given id and result. NOTE: This function expects a Result struct, but JSONRPCResponse.Result is typed as `any`. The Result struct wraps the actual result data with optional metadata. For direct result assignment, use NewJSONRPCResultResponse instead.
NewJSONRPCResultResponse creates a new JSONRPCResponse with the given id and result. This function accepts any type for the result, matching the JSONRPCResponse.Result field type.
NewListPromptsResult creates a new ListPromptsResult
NewListResourcesResult creates a new ListResourcesResult
NewListResourceTemplatesResult creates a new ListResourceTemplatesResult
NewListTasksResult creates a ListTasksResult with the given tasks.
NewListToolsResult creates a new ListToolsResult
NewLoggingMessageNotification Helper function for creating a logging message notification
NewProgressNotification Helper function for creating a progress notification
NewPrompt creates a new Prompt with the given name and options. The prompt will be configured based on the provided options. Options are applied in order, allowing for flexible prompt configuration.
NewPromptMessage Helper function to create a new PromptMessage
NewReadResourceResult creates a new ReadResourceResult with text content
NewRequestId creates a new RequestId with the given value
NewResource creates a new Resource with the given URI, name and options. The resource will be configured based on the provided options. Options are applied in order, allowing for flexible resource configuration.
NewResourceTemplate creates a new ResourceTemplate with the given URI template, name and options. The template will be configured based on the provided options. Options are applied in order, allowing for flexible template configuration.
Type Parameters: TArgs: any TResult: any NewStructuredToolHandler creates a ToolHandlerFunc that automatically binds arguments to a typed struct and returns structured output. It automatically creates both structured and text content (from the structured output) for backwards compatibility.
NewTask creates a new Task with the given ID and options. The task will be configured based on the provided options. Options are applied in order, allowing for flexible task configuration.
NewTaskParams creates TaskParams with the given TTL.
NewTasksCapability creates a TasksCapability with all operations enabled.
NewTasksCapabilityWithToolsOnly creates a TasksCapability with only tool call support. List and Cancel operations are not enabled with this capability.
NewTaskStatusNotification creates a notification for a task status change.
NewTextContent Helper function to create a new TextContent
NewTool creates a new Tool with the given name and options. The tool will have an object-type input schema with configurable properties. Options are applied in order, allowing for flexible tool configuration.
NewToolResultAudio creates a new CallToolResult with both text and audio content
NewToolResultError creates a new CallToolResult with an error message. Any errors that originate from the tool SHOULD be reported inside the result object.
NewToolResultErrorf creates a new CallToolResult with an error message. The error message is formatted using the fmt package. Any errors that originate from the tool SHOULD be reported inside the result object.
NewToolResultErrorFromErr creates a new CallToolResult with an error message. If an error is provided, its details will be appended to the text message. Any errors that originate from the tool SHOULD be reported inside the result object.
NewToolResultImage creates a new CallToolResult with both text and image content
Type Parameters: T: any NewToolResultJSON creates a new CallToolResult with a JSON content.
NewToolResultResource creates a new CallToolResult with an embedded resource
NewToolResultStructured creates a new CallToolResult with structured content. It includes both the structured content and a text representation for backward compatibility.
NewToolResultStructuredOnly creates a new CallToolResult with structured content and creates a JSON string fallback for backwards compatibility. This is useful when you want to provide structured data without any specific text fallback.
NewToolResultText creates a new CallToolResult with a text content
NewToolWithRawSchema creates a new Tool with the given name and a raw JSON Schema. This allows for arbitrary JSON Schema to be used for the tool's input schema. NOTE a [Tool] built in such a way is incompatible with the [ToolOption] and runtime errors will result from supplying a [ToolOption] to a [Tool] built with this function.
Type Parameters: T: any NewTypedToolHandler creates a ToolHandlerFunc that automatically binds arguments to a typed struct
ParseAnnotations parses priority, audience, and lastModified fields from the provided map and returns an Annotations struct populated with any valid values found. If data is nil, ParseAnnotations returns nil. Priority is set when a numeric value can be parsed and is stored as a *float64. Audience is populated from string values and includes only RoleUser and RoleAssistant entries. LastModified is set when the value is a string.
func ParseArgument(request CallToolRequest, key string, defaultVal any) any
ParseBoolean extracts and converts a boolean parameter from a CallToolRequest. If the key is not found in the Arguments map, the defaultValue is returned. The function uses cast.ToBool for conversion which handles various string representations such as "true", "yes", "1", etc.
ParseCancelTaskResult parses a JSON message and converts it to a CancelTaskResult.
ParseContent parses a generic map into a strongly-typed Content value. It extracts annotations and _meta fields from the map and sets them on the returned content type.
ParseFloat32 extracts and converts a float32 parameter from a CallToolRequest.
ParseFloat64 extracts and converts a float64 parameter from a CallToolRequest.
ParseGetTaskResult parses a JSON message and converts it to a GetTaskResult.
ParseInt extracts and converts an int parameter from a CallToolRequest.
ParseInt16 extracts and converts an int16 parameter from a CallToolRequest.
ParseInt32 extracts and converts an int32 parameter from a CallToolRequest.
ParseInt64 extracts and converts an int64 parameter from a CallToolRequest. If the key is not found in the Arguments map, the defaultValue is returned.
ParseInt8 extracts and converts an int8 parameter from a CallToolRequest.
ParseListTasksResult parses a JSON message and converts it to a ListTasksResult.
ParseString extracts and converts a string parameter from a CallToolRequest.
ParseStringMap extracts and converts a string map parameter from a CallToolRequest.
ParseTaskResultResult parses a JSON message and converts it to a TaskResultResult.
ParseUInt extracts and converts an uint parameter from a CallToolRequest.
ParseUInt16 extracts and converts an uint16 parameter from a CallToolRequest.
ParseUInt32 extracts and converts an uint32 parameter from a CallToolRequest.
ParseUInt64 extracts and converts an uint64 parameter from a CallToolRequest.
ParseUInt8 extracts and converts an uint8 parameter from a CallToolRequest.
Pattern sets a regex pattern that a string property must match. The string value must conform to the specified regular expression.
Properties sets the "properties" map for an object schema. The returned PropertyOption stores the provided map under the schema's "properties" key.
PropertyNames defines a schema for property names in an object
RelatedTaskMeta creates the metadata for associating a message with a task. The returned map contains a "taskId" field with the provided task ID.
Required marks a property as required in the tool's input schema. Required properties must be provided when using the tool.
RequiredArgument marks an argument as required in the prompt. Required arguments must be provided when getting the prompt.
Title adds a display-friendly title to a property in the JSON Schema. This title can be used by UI components to show a more readable property name.
ToBoolPtr returns a pointer to the given boolean value
ToInt64Ptr returns a pointer to the given int64 value
UniqueItems specifies whether array items must be unique
UnmarshalContent implements custom JSON unmarshaling for Content interface
ValidateISO8601Timestamp verifies that timestamp is a valid ISO 8601 timestamp using the RFC3339 layout. An empty string is considered valid. It returns nil when the timestamp is valid, or the parsing error when it is not.
WithAnnotations returns a ResourceOption that sets the resource's Annotations fields. It initializes Annotations if nil, sets Audience to the provided slice, stores Priority as a pointer to the provided value, and sets LastModified to the provided timestamp.
WithAny adds an input property named name with no predefined JSON Schema type to the Tool's input schema. The returned ToolOption applies the provided PropertyOption functions to the property's schema, moves a property-level `required` flag into the Tool's InputSchema.Required list if present, and stores the resulting schema under InputSchema.Properties[name].
WithArgument adds an argument to the prompt's argument list. The argument will be configured based on the provided options.
WithArray returns a ToolOption that adds an array-typed property with the given name to a Tool's input schema. It applies provided PropertyOption functions to configure the property's schema, moves a `required` flag from the property schema into the Tool's InputSchema.Required slice when present, and registers the resulting schema under InputSchema.Properties[name].
WithBoolean adds a boolean property to the tool schema. It accepts property options to configure the boolean property's behavior and constraints.
WithBooleanItems configures an array's items to be of type boolean. Supported options: Description(), DefaultBool() Note: Options like Required() are not valid for item schemas and will be ignored. Examples: mcp.WithArray("flags", mcp.WithBooleanItems()) mcp.WithArray("permissions", mcp.WithBooleanItems(mcp.Description("User permissions"))) Limitations: Only supports simple boolean arrays. Use Items() for complex objects.
WithDeferLoading sets the defer_loading flag for the tool. This is used to implement dynamic tool loading/searching patterns.
WithDescription adds a description to the Tool. The description should provide a clear, human-readable explanation of what the tool does.
WithDestructiveHintAnnotation sets the DestructiveHint field of the Tool's Annotations. If true, it indicates the tool may perform destructive updates.
WithIdempotentHintAnnotation sets the IdempotentHint field of the Tool's Annotations. If true, it indicates repeated calls with the same arguments have no additional effect.
Type Parameters: T: any WithInputSchema creates a ToolOption that sets the input schema for a tool. It accepts any Go type, usually a struct, and automatically generates a JSON schema from it.
WithLastModified returns a ResourceOption that sets the resource's Annotations.LastModified to the provided timestamp. If the resource's Annotations is nil, it will be initialized. The timestamp is expected to be an ISO 8601 (RFC3339) formatted string (e.g., "2025-01-12T15:00:58Z").
WithMIMEType sets the MIME type for the Resource. This should indicate the format of the resource's contents.
WithModelImmediateResponse creates Meta with an immediate response message for the model. This allows the model to continue processing while the task executes asynchronously. The message parameter is a human-readable string that will be shown to the model. Example: return &mcp.CreateTaskResult{ Task: task, Result: mcp.Result{ Meta: mcp.WithModelImmediateResponse("Processing your request. This may take a few minutes."), }, }
WithNumber adds a number property to the tool schema. It accepts property options to configure the number property's behavior and constraints.
WithNumberItems configures an array's items to be of type number. Supported options: Description(), DefaultNumber(), Min(), Max(), MultipleOf() Note: Options like Required() are not valid for item schemas and will be ignored. Examples: mcp.WithArray("scores", mcp.WithNumberItems(mcp.Min(0), mcp.Max(100))) mcp.WithArray("prices", mcp.WithNumberItems(mcp.Min(0))) Limitations: Only supports simple number arrays. Use Items() for complex objects.
WithObject adds an object property to the tool schema. It accepts property options to configure the object property's behavior and constraints.
WithOpenWorldHintAnnotation sets the OpenWorldHint field of the Tool's Annotations. If true, it indicates the tool interacts with external entities.
Type Parameters: T: any WithOutputSchema creates a ToolOption that sets the output schema for a tool. It accepts any Go type, usually a struct, and automatically generates a JSON schema from it.
WithPromptDescription adds a description to the Prompt. The description should provide a clear, human-readable explanation of what the prompt does.
WithPromptIcons adds icons to the Prompt. Icons provide visual identifiers for the prompt.
WithRawInputSchema sets a raw JSON schema for the tool's input. Use this when you need full control over the schema or when working with complex schemas that can't be generated from Go types. The jsonschema library can handle complex schemas and provides nice extension points, so be sure to check that out before using this.
WithRawOutputSchema sets a raw JSON schema for the tool's output. Use this when you need full control over the schema or when working with complex schemas that can't be generated from Go types. The jsonschema library can handle complex schemas and provides nice extension points, so be sure to check that out before using this.
WithReadOnlyHintAnnotation sets the ReadOnlyHint field of the Tool's Annotations. If true, it indicates the tool does not modify its environment.
WithRelatedTask returns a Meta with the related task ID set. This is useful for associating task results with their originating task.
WithResourceDescription adds a description to the Resource. The description should provide a clear, human-readable explanation of what the resource represents.
WithResourceIcons adds icons to the Resource. Icons provide visual identifiers for the resource.
WithSchemaAdditionalProperties sets the additionalProperties field on the tool's input schema. It accepts false (disallow extra properties), true (allow any), or a schema map to validate additional properties against.
WithString adds a string property to the tool schema. It accepts property options to configure the string property's behavior and constraints.
WithStringEnumItems configures an array's items to be of type string with a specified enum. Example: mcp.WithArray("priority", mcp.WithStringEnumItems([]string{"low", "medium", "high"})) Limitations: Only supports string enums. Use WithStringItems(Enum(...)) for more flexibility.
WithStringItems configures an array's items to be of type string. Supported options: Description(), DefaultString(), Enum(), MaxLength(), MinLength(), Pattern() Note: Options like Required() are not valid for item schemas and will be ignored. Examples: mcp.WithArray("tags", mcp.WithStringItems()) mcp.WithArray("colors", mcp.WithStringItems(mcp.Enum("red", "green", "blue"))) mcp.WithArray("names", mcp.WithStringItems(mcp.MinLength(1), mcp.MaxLength(50))) Limitations: Only supports simple string arrays. Use Items() for complex objects.
WithTaskCreatedAt sets a specific creation timestamp for the task. By default, NewTask uses the current time.
WithTaskPollInterval sets the suggested polling interval in milliseconds.
WithTaskStatus sets the status of the task.
WithTaskStatusMessage sets a human-readable status message for the task.
WithTaskSupport sets the task support mode for the tool. It configures whether the tool can be invoked as a task (asynchronously). Valid values are TaskSupportForbidden (default), TaskSupportOptional, or TaskSupportRequired.
WithTaskTTL sets the time-to-live for the task in milliseconds. After this duration from creation, the task may be deleted.
WithTemplateAnnotations returns a ResourceTemplateOption that sets the template's Annotations field, initializing it if nil, and setting Audience, Priority, and LastModified.
WithTemplateDescription adds a description to the ResourceTemplate. The description should provide a clear, human-readable explanation of what resources this template represents.
WithTemplateIcons adds icons to the ResourceTemplate. Icons provide visual identifiers for the resource template.
WithTemplateMIMEType sets the MIME type for the ResourceTemplate. This should only be set if all resources matching this template will have the same type.
WithTitleAnnotation sets the Title field of the Tool's Annotations. It provides a human-readable title for the tool.
WithToolAnnotation adds optional hints about the Tool.
WithToolIcons adds icons to the Tool. Icons provide visual identifiers for the tool.
Package-Level Variables (total 8)
ErrInternalError indicates an internal JSON-RPC error (code: INTERNAL_ERROR).
ErrInvalidParams indicates invalid method parameters (code: INVALID_PARAMS).
ErrInvalidRequest indicates an invalid JSON-RPC request (code: INVALID_REQUEST).
ErrMethodNotFound indicates the requested method does not exist (code: METHOD_NOT_FOUND).
ErrParseError indicates a JSON parsing error (code: PARSE_ERROR).
ErrRequestInterrupted indicates a request was cancelled or timed out (code: REQUEST_INTERRUPTED).
ErrResourceNotFound indicates a requested resource was not found (code: RESOURCE_NOT_FOUND).
ValidProtocolVersions lists all known valid MCP protocol versions.
Package-Level Constants (total 65)
const ContentTypeAudio = "audio"
const ContentTypeImage = "image"
const ContentTypeResource = "resource"
const ContentTypeText = "text"
const ElicitationModeForm = "form"
const ElicitationModeURL = "url"
ElicitationResponseActionAccept indicates the user provided the requested information.
ElicitationResponseActionCancel indicates the user cancelled without making a choice.
ElicitationResponseActionDecline indicates the user explicitly declined to provide information.
INTERNAL_ERROR indicates internal JSON-RPC error.
INVALID_PARAMS indicates invalid method parameter(s).
INVALID_REQUEST indicates the JSON sent is not a valid Request object.
JSONRPC_VERSION is the version of JSON-RPC used by MCP.
LATEST_PROTOCOL_VERSION is the most recent version of the MCP protocol.
const LoggingLevelEmergency LoggingLevel = "emergency"
METHOD_NOT_FOUND indicates the method does not exist/is not available.
MethodCompletionComplete returns completion suggestions for a given argument https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/completion
MethodElicitationCreate requests additional information from the user during interactions. https://modelcontextprotocol.io/docs/concepts/elicitation
MethodInitialize initiates connection and negotiates protocol capabilities. https://modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization
MethodListRoots requests roots list from the client during interactions. https://modelcontextprotocol.io/specification/2025-06-18/client/roots
MethodNotificationElicitationComplete notifies when a URL mode elicitation completes.
MethodNotificationPromptsListChanged notifies when the list of available prompt templates changes. https://modelcontextprotocol.io/specification/2025-03-26/server/prompts#list-changed-notification
MethodNotificationResourcesListChanged notifies when the list of available resources changes. https://modelcontextprotocol.io/specification/2025-03-26/server/resources#list-changed-notification
const MethodNotificationResourceUpdated = "notifications/resources/updated"
MethodNotificationRootsListChanged notifies when the list of available roots changes. https://modelcontextprotocol.io/specification/2025-06-18/client/roots#root-list-changes
MethodNotificationTasksStatus notifies when a task's status changes. https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks
MethodNotificationToolsListChanged notifies when the list of available tools changes. https://modelcontextprotocol.io/specification/2025-06-18/server/tools#list-changed-notification
MethodPing verifies connection liveness between client and server. https://modelcontextprotocol.io/specification/2024-11-05/basic/utilities/ping/
MethodPromptsGet retrieves a specific prompt template with filled parameters. https://modelcontextprotocol.io/specification/2024-11-05/server/prompts/
MethodPromptsList lists all available prompt templates. https://modelcontextprotocol.io/specification/2024-11-05/server/prompts/
MethodResourcesList lists all available server resources. https://modelcontextprotocol.io/specification/2024-11-05/server/resources/
MethodResourcesRead retrieves content of a specific resource by URI. https://modelcontextprotocol.io/specification/2024-11-05/server/resources/
MethodResourcesTemplatesList provides URI templates for constructing resource URIs. https://modelcontextprotocol.io/specification/2024-11-05/server/resources/
MethodSamplingCreateMessage allows servers to request LLM completions from clients
MethodSetLogLevel configures the minimum log level for client https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/logging
MethodTasksCancel cancels an in-progress task. https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks
MethodTasksGet retrieves the current status of a task. https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks
MethodTasksList lists all tasks for the current session. https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks
MethodTasksResult retrieves the result of a completed task. https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks
MethodToolsCall invokes a specific tool with provided parameters. https://modelcontextprotocol.io/specification/2024-11-05/server/tools/
MethodToolsList lists all available executable tools. https://modelcontextprotocol.io/specification/2024-11-05/server/tools/
ModelImmediateResponseMetaKey is the metadata key for providing an immediate response to the model. Servers can use this optional key in the _meta field of CreateTaskResult to provide a string that should be passed as an immediate tool result to the model while the task continues executing asynchronously in the background.
PARSE_ERROR indicates invalid JSON was received by the server.
RelatedTaskMetaKey is the metadata key for associating a message with a task.
REQUEST_INTERRUPTED indicates a request was cancelled or timed out.
RESOURCE_NOT_FOUND indicates that the requested resource was not found.
const RoleAssistant Role = "assistant"
const RoleUser Role = "user"
TaskStatusCancelled indicates the request was cancelled before completion.
TaskStatusCompleted indicates the request completed successfully.
TaskStatusFailed indicates the request did not complete successfully.
TaskStatusInputRequired indicates the receiver needs input from the requestor. NOTE: This status is defined by the spec but not yet implemented in this SDK. The input_required flow requires integration with elicitation which is planned for a future release.
TaskStatusWorking indicates the request is currently being processed.
TaskSupportForbidden means the tool cannot be invoked as a task (default).
TaskSupportOptional means the tool can be invoked as a task or normally.
TaskSupportRequired means the tool must be invoked as a task.
URL_ELICITATION_REQUIRED is the error code for when URL elicitation is required.