mcp_golang

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2024 License: MIT Imports: 12 Imported by: 82

README

Statusphere logo

GitHub stars GitHub forks GitHub issues GitHub pull requests GitHub license GitHub contributors GitHub last commit GoDoc Go Report Card Tests

mcp-golang

mcp-golang is an unofficial implementation of the Model Context Protocol in Go.

Write MCP servers in golang with a few lines of code.

Docs at https://mcpgolang.com

Highlights

  • 🛡️Type safety - Define your tool arguments as native go structs, have mcp-golang handle the rest. Automatic schema generation, deserialization, error handling etc.
  • 🚛 Custom transports - Use the built-in transports or write your own.
  • Low boilerplate - mcp-golang generates all the MCP endpoints for you apart from your tools, prompts and resources.
  • 🧩 Modular - The library is split into three components: transport, protocol and server. Use them all or take what you need.

Example Usage

package main

import (
	"fmt"
	"github.com/metoro-io/mcp-golang"
	"github.com/metoro-io/mcp-golang/transport/stdio"
)

// Tool arguments are just structs, annotated with jsonschema tags
// More at https://mcpgolang.com/tools#schema-generation
type Content struct {
	Title       string  `json:"title" jsonschema:"required,description=The title to submit"`
	Description *string `json:"description" jsonschema:"description=The description to submit"`
}
type MyFunctionsArguments struct {
	Submitter string  `json:"submitter" jsonschema:"required,description=The name of the thing calling this tool (openai, google, claude, etc)"`
	Content   Content `json:"content" jsonschema:"required,description=The content of the message"`
}

func main() {
	done := make(chan struct{})

	server := mcp_golang.NewServer(stdio.NewStdioServerTransport())
	err := server.RegisterTool("hello", "Say hello to a person", func(arguments MyFunctionsArguments) (*mcp_golang.ToolResponse, error) {
		return mcp_golang.NewToolResponse(mcp_golang.NewTextContent(fmt.Sprintf("Hello, %server!", arguments.Submitter))), nil
	})
	if err != nil {
		panic(err)
	}

	err = server.RegisterPrompt("promt_test", "This is a test prompt", func(arguments Content) (*mcp_golang.PromptResponse, error) {
		return mcp_golang.NewPromptResponse("description", mcp_golang.NewPromptMessage(mcp_golang.NewTextContent(fmt.Sprintf("Hello, %server!", arguments.Title)), mcp_golang.RoleUser)), nil
	})
	if err != nil {
		panic(err)
	}

	err = server.RegisterResource("test://resource", "resource_test", "This is a test resource", "application/json", func() (*mcp_golang.ResourceResponse, error) {
		return mcp_golang.NewResourceResponse(mcp_golang.NewTextEmbeddedResource("test://resource", "This is a test resource", "application/json")), nil
	})

	err = server.Serve()
	if err != nil {
		panic(err)
	}

	<-done
}

This will start a server using the stdio transport (used by claude desktop), host a tool called "hello" that will say hello to the user who submitted it.

You can use raw go structs as the input to your tools, the library handles generating the messages, deserialization, etc.

Contributions

Contributions are more than welcome! Please check out our contribution guidelines.

Discord

Got any suggestions, have a question on the api or usage? Ask on the discord server. A maintainer will be happy to help you out.

Examples

Some more extensive examples using the library found here:

  • Metoro - Query and interact with kubernetes environments monitored by Metoro

Open a PR to add your own projects!

Server Feature Implementation

Tools
  • Tool Calls
  • Native go structs as arguments
  • Programatically generated tool list endpoint
  • Change notifications
  • Pagination
Prompts
  • Prompt Calls
  • Programatically generated prompt list endpoint
  • Change notifications
  • Pagination
Resources
  • Resource Calls
  • Programatically generated resource list endpoint
  • Change notifications
  • Pagination
Transports
  • Stdio
  • SSE
  • Custom transport support
  • HTTPS with custom auth support - in progress. Not currently part of the spec but we'll be adding experimental support for it.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Annotations

type Annotations struct {
	// Describes who the intended customer of this object or data is.
	//
	// It can include multiple entries to indicate ToolResponse useful for multiple
	// audiences (e.g., `["user", "assistant"]`).
	Audience []Role `json:"audience,omitempty" yaml:"audience,omitempty" mapstructure:"audience,omitempty"`

	// Describes how important this data is for operating the server.
	//
	// A value of 1 means "most important," and indicates that the data is
	// effectively required, while 0 means "least important," and indicates that
	// the data is entirely optional.
	Priority *float64 `json:"priority,omitempty" yaml:"priority,omitempty" mapstructure:"priority,omitempty"`
}

type BlobResourceContents

type BlobResourceContents struct {
	// A base64-encoded string representing the binary data of the item.
	Blob string `json:"blob" yaml:"blob" mapstructure:"blob"`

	// The MIME type of this resource, if known.
	MimeType *string `json:"mimeType,omitempty" yaml:"mimeType,omitempty" mapstructure:"mimeType,omitempty"`

	// The URI of this resource.
	Uri string `json:"uri" yaml:"uri" mapstructure:"uri"`
}

type Content

type Content struct {
	Type             ContentType
	TextContent      *TextContent
	ImageContent     *ImageContent
	EmbeddedResource *EmbeddedResource
	Annotations      *Annotations
}

func NewBlobResourceContent

func NewBlobResourceContent(uri string, base64EncodedData string, mimeType string) *Content

NewBlobResourceContent creates a new ToolResponse that is a blob of binary data. The given data is base64-encoded; the client will decode it. The client will render this as a blob; it will not be human-readable.

func NewImageContent

func NewImageContent(base64EncodedStringData string, mimeType string) *Content

NewImageContent creates a new ToolResponse that is an image. The given data is base64-encoded

func NewTextContent

func NewTextContent(content string) *Content

NewTextContent creates a new ToolResponse that is a simple text string. The client will render this as a single string.

func NewTextResourceContent

func NewTextResourceContent(uri string, text string, mimeType string) *Content

NewTextResourceContent creates a new ToolResponse that is an embedded resource of type "text". The given text is embedded in the response as a TextResourceContents, which contains the given MIME type and URI. The text is not base64-encoded.

func (Content) MarshalJSON

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

Custom JSON marshaling for ToolResponse Content

func (*Content) WithAnnotations

func (c *Content) WithAnnotations(annotations Annotations) *Content

type ContentType

type ContentType string
const (
	// The value is the value of the "type" field in the Content so do not change
	ContentTypeText             ContentType = "text"
	ContentTypeImage            ContentType = "image"
	ContentTypeEmbeddedResource ContentType = "resource"
)

type EmbeddedResource

type EmbeddedResource struct {
	EmbeddedResourceType embeddedResourceType
	TextResourceContents *TextResourceContents
	BlobResourceContents *BlobResourceContents
}

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.

func NewBlobEmbeddedResource

func NewBlobEmbeddedResource(uri string, base64EncodedData string, mimeType string) *EmbeddedResource

func NewTextEmbeddedResource

func NewTextEmbeddedResource(uri string, text string, mimeType string) *EmbeddedResource

func (EmbeddedResource) MarshalJSON

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

Custom JSON marshaling for EmbeddedResource

type ImageContent

type ImageContent struct {
	// The base64-encoded image data.
	Data string `json:"data" yaml:"data" mapstructure:"data"`

	// The MIME type of the image. Different providers may support different image
	// types.
	MimeType string `json:"mimeType" yaml:"mimeType" mapstructure:"mimeType"`
}

An image provided to or from an LLM.

type PromptMessage

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

func NewPromptMessage

func NewPromptMessage(content *Content, role Role) *PromptMessage

type PromptResponse

type PromptResponse struct {
	// An optional description for the prompt.
	Description *string `json:"description,omitempty" yaml:"description,omitempty" mapstructure:"description,omitempty"`

	// Messages corresponds to the JSON schema field "messages".
	Messages []*PromptMessage `json:"messages" yaml:"messages" mapstructure:"messages"`
}

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

func NewPromptResponse

func NewPromptResponse(description string, messages ...*PromptMessage) *PromptResponse

type ResourceResponse

type ResourceResponse struct {
	Contents []*EmbeddedResource `json:"contents"`
}

func NewResourceResponse

func NewResourceResponse(contents ...*EmbeddedResource) *ResourceResponse

type Role

type Role string
const RoleAssistant Role = "assistant"
const RoleUser Role = "user"

type Server

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

func NewServer

func NewServer(transport transport.Transport, options ...ServerOptions) *Server

func (*Server) CheckPromptRegistered added in v0.2.0

func (s *Server) CheckPromptRegistered(name string) bool

func (*Server) CheckResourceRegistered added in v0.2.0

func (s *Server) CheckResourceRegistered(uri string) bool

func (*Server) CheckToolRegistered added in v0.2.0

func (s *Server) CheckToolRegistered(name string) bool

func (*Server) DeregisterPrompt added in v0.2.0

func (s *Server) DeregisterPrompt(name string) error

func (*Server) DeregisterResource added in v0.2.0

func (s *Server) DeregisterResource(uri string) error

func (*Server) DeregisterTool added in v0.2.0

func (s *Server) DeregisterTool(name string) error

func (*Server) RegisterPrompt

func (s *Server) RegisterPrompt(name string, description string, handler any) error

func (*Server) RegisterResource

func (s *Server) RegisterResource(uri string, name string, description string, mimeType string, handler any) error

func (*Server) RegisterTool

func (s *Server) RegisterTool(name string, description string, handler any) error

RegisterTool registers a new tool with the server

func (*Server) Serve

func (s *Server) Serve() error

type ServerOptions added in v0.3.0

type ServerOptions func(*Server)

func WithPaginationLimit added in v0.3.0

func WithPaginationLimit(limit int) ServerOptions

Beware: As of 2024-12-13, it looks like Claude does not support pagination yet

func WithProtocol added in v0.3.0

func WithProtocol(protocol *protocol.Protocol) ServerOptions

type TextContent

type TextContent struct {
	// The text ToolResponse of the message.
	Text string `json:"text" yaml:"text" mapstructure:"text"`
}

Text provided to or from an LLM.

type TextResourceContents

type TextResourceContents struct {
	// The MIME type of this resource, if known.
	MimeType *string `json:"mimeType,omitempty" yaml:"mimeType,omitempty" mapstructure:"mimeType,omitempty"`

	// The text of the item. This must only be set if the item can actually be
	// represented as text (not binary data).
	Text string `json:"text" yaml:"text" mapstructure:"text"`

	// The URI of this resource.
	Uri string `json:"uri" yaml:"uri" mapstructure:"uri"`
}

type ToolResponse

type ToolResponse struct {
	Content []*Content
}

This is a union type of all the different ToolResponse that can be sent back to the client. We allow creation through constructors only to make sure that the ToolResponse is valid.

func NewToolResponse added in v0.2.0

func NewToolResponse(content ...*Content) *ToolResponse

Directories

Path Synopsis
examples
internal
protocol
This file implements the core protocol layer for JSON-RPC communication in the MCP SDK.
This file implements the core protocol layer for JSON-RPC communication in the MCP SDK.
sse
sse/internal/sse
/* Package mcp implements Server-Sent Events (SSE) transport for JSON-RPC communication.
/* Package mcp implements Server-Sent Events (SSE) transport for JSON-RPC communication.
stdio/internal/stdio
This file implements the stdio transport layer for JSON-RPC communication.
This file implements the stdio transport layer for JSON-RPC communication.

Jump to

Keyboard shortcuts

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