tessl install tessl/golang-mcp-golang@0.16.1An unofficial implementation of the Model Context Protocol in Go
The content system provides rich message content supporting text, images, and embedded resources with comprehensive response types for tools, prompts, and resources.
import mcp "github.com/metoro-io/mcp-golang"type Role string
const (
RoleUser Role = "user"
RoleAssistant Role = "assistant"
)Role constants define message roles in conversations and prompts.
Constants:
RoleUser: Message from the userRoleAssistant: Message from the assistanttype ContentType string
const (
ContentTypeText ContentType = "text"
ContentTypeImage ContentType = "image"
ContentTypeEmbeddedResource ContentType = "resource"
)ContentType constants identify different types of content in messages.
Constants:
ContentTypeText: Plain text contentContentTypeImage: Base64-encoded image dataContentTypeEmbeddedResource: Embedded resource (text or binary)The Content type represents message content that can be text, image, or an embedded resource.
type Content struct {
Type ContentType
TextContent *TextContent
ImageContent *ImageContent
EmbeddedResource *EmbeddedResource
Annotations *Annotations
}Fields:
Type: Content type discriminator (text, image, or resource)TextContent: Text content (present when Type is ContentTypeText)ImageContent: Image content (present when Type is ContentTypeImage)EmbeddedResource: Embedded resource (present when Type is ContentTypeEmbeddedResource)Annotations: Optional annotations for audience and priorityfunc NewTextContent(content string) *ContentCreates text content.
Parameters:
content: The text stringReturns: Content with type ContentTypeText
Example:
content := mcp.NewTextContent("Hello, world!")func NewImageContent(base64EncodedStringData string, mimeType string) *ContentCreates image content from base64-encoded data.
Parameters:
base64EncodedStringData: Base64-encoded image datamimeType: Image MIME type (e.g., "image/png", "image/jpeg")Returns: Content with type ContentTypeImage
Example:
import (
"encoding/base64"
"os"
)
// Read and encode image
imageData, _ := os.ReadFile("photo.jpg")
base64Data := base64.StdEncoding.EncodeToString(imageData)
content := mcp.NewImageContent(base64Data, "image/jpeg")func NewTextResourceContent(uri string, text string, mimeType string) *ContentCreates content with an embedded text resource.
Parameters:
uri: Resource URItext: Text content of the resourcemimeType: Resource MIME type (e.g., "text/plain", "application/json")Returns: Content with type ContentTypeEmbeddedResource containing text
Example:
jsonData := `{"status": "ok", "message": "Success"}`
content := mcp.NewTextResourceContent(
"file:///output/result.json",
jsonData,
"application/json",
)func NewBlobResourceContent(uri string, base64EncodedData string, mimeType string) *ContentCreates content with an embedded binary resource.
Parameters:
uri: Resource URIbase64EncodedData: Base64-encoded binary datamimeType: Resource MIME type (e.g., "application/pdf", "image/png")Returns: Content with type ContentTypeEmbeddedResource containing binary data
Example:
import (
"encoding/base64"
"os"
)
// Read and encode binary file
pdfData, _ := os.ReadFile("document.pdf")
base64Data := base64.StdEncoding.EncodeToString(pdfData)
content := mcp.NewBlobResourceContent(
"file:///docs/document.pdf",
base64Data,
"application/pdf",
)func (c *Content) WithAnnotations(annotations Annotations) *ContentAdds annotations to content for specifying audience and priority.
Parameters:
annotations: Annotations to addReturns: The same Content instance with annotations added
Example:
content := mcp.NewTextContent("Debug information: cache miss on key 'user:123'").
WithAnnotations(mcp.Annotations{
Audience: []mcp.Role{mcp.RoleAssistant}, // Only for assistant
Priority: ptrFloat64(0.2), // Low priority
})func (c Content) MarshalJSON() ([]byte, error)Custom JSON marshaling for Content. Serializes the Content to JSON format based on its Type field. This method is typically called automatically by Go's encoding/json package.
Returns:
[]byte: JSON-encoded contenterror: Error if marshaling failsfunc (c *Content) UnmarshalJSON(b []byte) errorCustom JSON unmarshaling for Content. Deserializes JSON into the appropriate Content type. This method is typically called automatically by Go's encoding/json package.
Parameters:
b: JSON-encoded dataReturns: Error if unmarshaling fails
type TextContent struct {
Text string `json:"text"`
}Plain text content in a message.
Fields:
Text: The text contenttype ImageContent struct {
Data string `json:"data"`
MimeType string `json:"mimeType"`
}Image content in a message.
Fields:
Data: Base64-encoded image dataMimeType: Image MIME type (e.g., "image/png", "image/jpeg", "image/gif")type Annotations struct {
Audience []Role `json:"audience,omitempty"`
Priority *float64 `json:"priority,omitempty"`
}Annotations for content or resources specifying intended audience and importance.
Fields:
Audience: Intended audience(s) for the content (RoleUser, RoleAssistant, or both)Priority: Importance level where 1.0 is highest priority and 0.0 is lowest priorityExample:
// High-priority content for the user
annotations := mcp.Annotations{
Audience: []mcp.Role{mcp.RoleUser},
Priority: ptrFloat64(1.0),
}
// Low-priority debug info for assistant only
debugAnnotations := mcp.Annotations{
Audience: []mcp.Role{mcp.RoleAssistant},
Priority: ptrFloat64(0.1),
}type EmbeddedResource struct {
EmbeddedResourceType embeddedResourceType
TextResourceContents *TextResourceContents
BlobResourceContents *BlobResourceContents
}Resource embedded in a prompt or tool response. Can contain either text or binary data.
Fields:
EmbeddedResourceType: Resource type discriminator (text or blob)TextResourceContents: Text resource contents (present for text resources)BlobResourceContents: Binary resource contents (present for blob resources)func NewTextEmbeddedResource(uri string, text string, mimeType string) *EmbeddedResourceCreates an embedded text resource.
Parameters:
uri: Resource URItext: Text contentmimeType: Resource MIME typeReturns: EmbeddedResource containing text
Example:
resource := mcp.NewTextEmbeddedResource(
"file:///config/settings.json",
`{"theme": "dark", "language": "en"}`,
"application/json",
)func NewBlobEmbeddedResource(uri string, base64EncodedData string, mimeType string) *EmbeddedResourceCreates an embedded binary resource.
Parameters:
uri: Resource URIbase64EncodedData: Base64-encoded binary datamimeType: Resource MIME typeReturns: EmbeddedResource containing binary data
Example:
import (
"encoding/base64"
"os"
)
data, _ := os.ReadFile("logo.png")
base64Data := base64.StdEncoding.EncodeToString(data)
resource := mcp.NewBlobEmbeddedResource(
"file:///assets/logo.png",
base64Data,
"image/png",
)func (c EmbeddedResource) MarshalJSON() ([]byte, error)Custom JSON marshaling for EmbeddedResource. Serializes the resource to JSON format based on its resource type. This method is typically called automatically by Go's encoding/json package.
Returns:
[]byte: JSON-encoded resourceerror: Error if marshaling failsfunc (c *EmbeddedResource) UnmarshalJSON(data []byte) errorCustom JSON unmarshaling for EmbeddedResource. Deserializes JSON into the appropriate resource type. This method is typically called automatically by Go's encoding/json package.
Parameters:
data: JSON-encoded dataReturns: Error if unmarshaling fails
type TextResourceContents struct {
Uri string `json:"uri"`
Text string `json:"text"`
MimeType *string `json:"mimeType,omitempty"`
}Text representation of a resource.
Fields:
Uri: Resource URIText: Text content of the resourceMimeType: Optional MIME type (e.g., "text/plain", "application/json")type BlobResourceContents struct {
Uri string `json:"uri"`
Blob string `json:"blob"`
MimeType *string `json:"mimeType,omitempty"`
}Binary representation of a resource.
Fields:
Uri: Resource URIBlob: Base64-encoded binary dataMimeType: Optional MIME type (e.g., "application/pdf", "image/png")type ToolResponse struct {
Content []*Content `json:"content"`
}Response from a tool execution.
Fields:
Content: Array of content items (text, images, or resources) returned by the toolfunc NewToolResponse(content ...*Content) *ToolResponseCreates a new tool response with the provided content.
Parameters:
content: Variadic content items to include in the responseReturns: ToolResponse containing the content
Example:
// Simple text response
response := mcp.NewToolResponse(
mcp.NewTextContent("Operation completed successfully"),
)
// Multiple content items
response := mcp.NewToolResponse(
mcp.NewTextContent("Processing results:"),
mcp.NewTextResourceContent(
"file:///output/data.json",
`{"result": "success", "count": 42}`,
"application/json",
),
mcp.NewImageContent(base64ChartData, "image/png"),
)type ToolsResponse struct {
Tools []ToolRetType `json:"tools"`
NextCursor *string `json:"nextCursor,omitempty"`
}Server's response to a tools/list request.
Fields:
Tools: Array of available toolsNextCursor: Optional pagination cursor for fetching the next pagetype ToolRetType struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
InputSchema interface{} `json:"inputSchema"`
}Definition for a tool that clients can call.
Fields:
Name: Tool name (unique identifier)Description: Optional human-readable descriptionInputSchema: JSON Schema defining the tool's input parameters (auto-generated from handler argument struct)type PromptResponse struct {
Description *string `json:"description,omitempty"`
Messages []*PromptMessage `json:"messages"`
}Server's response to a prompts/get request containing the rendered prompt.
Fields:
Description: Optional description of the promptMessages: Array of messages forming the prompt conversationfunc NewPromptResponse(description string, messages ...*PromptMessage) *PromptResponseCreates a new prompt response.
Parameters:
description: Prompt descriptionmessages: Variadic prompt messagesReturns: PromptResponse with description and messages
Example:
response := mcp.NewPromptResponse(
"Code review prompt",
mcp.NewPromptMessage(
mcp.NewTextContent("You are an expert code reviewer. Review the following code for bugs, performance issues, and style."),
mcp.RoleAssistant,
),
mcp.NewPromptMessage(
mcp.NewTextContent("func calculate(a, b int) int { return a + b }"),
mcp.RoleUser,
),
)type PromptMessage struct {
Content *Content `json:"content"`
Role Role `json:"role"`
}A single message in a prompt.
Fields:
Content: Message content (text, image, or resource)Role: Message role (RoleUser or RoleAssistant)func NewPromptMessage(content *Content, role Role) *PromptMessageCreates a new prompt message.
Parameters:
content: Message contentrole: Message role (RoleUser or RoleAssistant)Returns: PromptMessage with the specified content and role
Example:
// Assistant message with instructions
systemMsg := mcp.NewPromptMessage(
mcp.NewTextContent("Translate the following text to French."),
mcp.RoleAssistant,
)
// User message with input
userMsg := mcp.NewPromptMessage(
mcp.NewTextContent("Hello, how are you?"),
mcp.RoleUser,
)type ListPromptsResponse struct {
Prompts []*PromptSchema `json:"prompts"`
NextCursor *string `json:"nextCursor,omitempty"`
}Server's response to a prompts/list request.
Fields:
Prompts: Array of available promptsNextCursor: Optional pagination cursor for fetching the next pagetype PromptSchema struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
Arguments []PromptSchemaArgument `json:"arguments,omitempty"`
}A prompt or prompt template offered by the server.
Fields:
Name: Prompt name (unique identifier)Description: Optional human-readable descriptionArguments: Array of template arguments (empty for static prompts)type PromptSchemaArgument struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
Required *bool `json:"required,omitempty"`
}An argument for a prompt template.
Fields:
Name: Argument nameDescription: Optional argument descriptionRequired: Whether the argument is required (nil means optional)type ResourceResponse struct {
Contents []*EmbeddedResource `json:"contents"`
}Response from reading a resource.
Fields:
Contents: Array of embedded resources (typically one, but can be multiple)func NewResourceResponse(contents ...*EmbeddedResource) *ResourceResponseCreates a new resource response.
Parameters:
contents: Variadic embedded resources to include in the responseReturns: ResourceResponse containing the resources
Example:
// Text resource
response := mcp.NewResourceResponse(
mcp.NewTextEmbeddedResource(
"file:///data/config.yaml",
"server:\n port: 8080\n host: localhost",
"text/yaml",
),
)
// Binary resource
imageData, _ := os.ReadFile("chart.png")
base64Data := base64.StdEncoding.EncodeToString(imageData)
response := mcp.NewResourceResponse(
mcp.NewBlobEmbeddedResource(
"file:///output/chart.png",
base64Data,
"image/png",
),
)type ListResourcesResponse struct {
Resources []*ResourceSchema `json:"resources"`
NextCursor *string `json:"nextCursor,omitempty"`
}Server's response to a resources/list request.
Fields:
Resources: Array of available resourcesNextCursor: Optional pagination cursor for fetching the next pagetype ResourceSchema struct {
Uri string `json:"uri"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
MimeType *string `json:"mimeType,omitempty"`
Annotations *Annotations `json:"annotations,omitempty"`
}A resource that the server can read.
Fields:
Uri: Resource URI (unique identifier)Name: Human-readable resource nameDescription: Optional resource descriptionMimeType: Optional MIME type (e.g., "text/plain", "application/json")Annotations: Optional annotations for audience and prioritytype ListResourceTemplatesResponse struct {
Templates []*ResourceTemplateSchema `json:"resourceTemplates"`
NextCursor *string `json:"nextCursor,omitempty"`
}Server's response to a resources/templates/list request.
Fields:
Templates: Array of resource templatesNextCursor: Optional pagination cursor for fetching the next pagetype ResourceTemplateSchema struct {
UriTemplate string `json:"uriTemplate"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
MimeType *string `json:"mimeType,omitempty"`
Annotations *Annotations `json:"annotations,omitempty"`
}A resource template defining a pattern for dynamic resources.
Fields:
UriTemplate: URI template using RFC 6570 syntax (e.g., "file:///users/{userId}/data.json")Name: Human-readable template nameDescription: Optional template descriptionMimeType: Optional MIME type for resources matching this templateAnnotations: Optional annotations for audience and priorityfunc analyzeHandler(args AnalyzeArgs) (*mcp.ToolResponse, error) {
// Return multiple content types
return mcp.NewToolResponse(
mcp.NewTextContent("Analysis complete. Results:"),
mcp.NewTextResourceContent(
"file:///output/analysis.json",
`{"score": 85, "issues": 3}`,
"application/json",
),
mcp.NewImageContent(chartImageBase64, "image/png"),
mcp.NewTextContent("See attached chart for visualization.").
WithAnnotations(mcp.Annotations{
Audience: []mcp.Role{mcp.RoleUser},
Priority: ptrFloat64(0.8),
}),
), nil
}func reviewPromptHandler(args ReviewArgs) (*mcp.PromptResponse, error) {
return mcp.NewPromptResponse(
"Code review conversation",
mcp.NewPromptMessage(
mcp.NewTextContent("You are a senior software engineer performing code reviews."),
mcp.RoleAssistant,
),
mcp.NewPromptMessage(
mcp.NewTextResourceContent(
"file:///code/main.go",
args.SourceCode,
"text/x-go",
),
mcp.RoleUser,
),
mcp.NewPromptMessage(
mcp.NewTextContent("Focus on security vulnerabilities and performance."),
mcp.RoleAssistant,
),
), nil
}// Text resource
func readConfig() (*mcp.ResourceResponse, error) {
data, err := os.ReadFile("config.json")
if err != nil {
return nil, err
}
return mcp.NewResourceResponse(
mcp.NewTextEmbeddedResource(
"file:///config.json",
string(data),
"application/json",
),
), nil
}
// Binary resource
func readLogo() (*mcp.ResourceResponse, error) {
data, err := os.ReadFile("logo.png")
if err != nil {
return nil, err
}
base64Data := base64.StdEncoding.EncodeToString(data)
return mcp.NewResourceResponse(
mcp.NewBlobEmbeddedResource(
"file:///assets/logo.png",
base64Data,
"image/png",
),
), nil
}