mcp

package
v0.0.0-...-9268282 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mcp serves the Model Context Protocol revision 2026-07-28 through its stateless Streamable HTTP binding.

Server accepts one JSON-RPC request or notification per POST. Protocol version, method, tool name and selected resource name are mirrored in HTTP headers and checked against the JSON body. Registry keeps tools in registration order, validates their JSON Schema subset, and invokes each Handler with an authenticated actor and request context. Tool failures are returned as execution results; transport and validation failures use JSON-RPC errors.

Index

Constants

View Source
const (
	HeaderProtocolVersion = "MCP-Protocol-Version"
	HeaderMethod          = "Mcp-Method"
	HeaderName            = "Mcp-Name"
)

Header names mirrored from the JSON-RPC body so intermediaries can route without parsing it. Comparison of names is case-insensitive; values are case-sensitive.

View Source
const (
	MetaProtocolVersion    = "io.modelcontextprotocol/protocolVersion"
	MetaClientCapabilities = "io.modelcontextprotocol/clientCapabilities"
	MetaClientInfo         = "io.modelcontextprotocol/clientInfo"
	MetaServerInfo         = "io.modelcontextprotocol/serverInfo"
)

Reserved _meta keys carried on every request and result.

View Source
const (
	CodeParse                      = -32700
	CodeInvalidRequest             = -32600
	CodeMethodNotFound             = -32601
	CodeInvalidParams              = -32602
	CodeInternal                   = -32603
	CodeHeaderMismatch             = -32020
	CodeMissingClientCapability    = -32021
	CodeUnsupportedProtocolVersion = -32022
)

JSON-RPC error codes. The -32020 to -32099 range is reserved for the MCP specification and only the defined codes may be emitted.

View Source
const (
	OutcomeOK           = "ok"
	OutcomeInvalid      = "invalid"
	OutcomeUnauthorized = "unauthorized"
	OutcomeError        = "error"
)
View Source
const Version = "2026-07-28"

Version is the protocol revision this package implements.

Variables

View Source
var SupportedVersions = []string{Version}

SupportedVersions lists the protocol revisions the server accepts.

Functions

func DecodeHeaderValue

func DecodeHeaderValue(value string) (string, error)

DecodeHeaderValue reverses EncodeHeaderValue. Plain values must consist of visible ASCII, space and horizontal tab.

func EncodeHeaderValue

func EncodeHeaderValue(value string) string

EncodeHeaderValue renders a body value for the Mcp-Name or Mcp-Param headers. Values outside the safe ASCII set, with surrounding whitespace, or that already look like the sentinel are Base64 encoded.

func Object

func Object(properties map[string]any, required ...string) map[string]any

Object builds a closed object schema. Properties are sorted when listed so the schema serializes deterministically.

func Validate

func Validate(schema map[string]any, value any) error

Validate checks a value against the subset of JSON Schema 2020-12 the tool tables use: type, properties, required, additionalProperties, enum, not, pattern, minimum, maximum, minLength, maxLength, minProperties and items.

Types

type Call

type Call struct {
	Actor     string
	Name      string
	Arguments map[string]any
	Request   *http.Request
}

Call carries the validated arguments of a tools/call request together with the authenticated actor.

func (Call) Int

func (c Call) Int(key string) int

Int returns an integer argument or 0.

func (Call) String

func (c Call) String(key string) string

String returns a string argument or "".

type Content

type Content struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
}

Content is one unstructured content block of a tool result.

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
	Status  int    `json:"-"`
}

Error is a JSON-RPC error object. Status is the HTTP status the transport answers with and is never serialized.

func (*Error) Error

func (e *Error) Error() string

type Handler

type Handler func(ctx context.Context, call Call) (Result, error)

Handler executes a tool. A returned error is reported to the client as a tool execution error the model can act on; protocol errors are raised by the transport before the handler runs.

type Implementation

type Implementation struct {
	Name    string `json:"name"`
	Version string `json:"version,omitempty"`
}

Implementation names a client or server.

type Observation

type Observation struct {
	Method  string
	Tool    string
	Outcome string
	Status  int
}

Observation summarizes one handled request for telemetry. It never carries the caller's identity.

type Registry

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

Registry is an ordered tool table. Tools list in the order they were added so clients can cache the list.

func (*Registry) Add

func (r *Registry) Add(tool Tool) error

Add registers a tool. Names must be unique and header safe.

func (*Registry) Lookup

func (r *Registry) Lookup(name string) (Tool, bool)

Lookup finds a tool by name.

func (*Registry) Tools

func (r *Registry) Tools() []Tool

Tools returns the table in registration order.

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id,omitempty"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

Request is an incoming JSON-RPC request or notification. ID is nil for a notification.

func (Request) Notification

func (r Request) Notification() bool

Notification reports whether the message carries no id and therefore expects no response.

type Response

type Response struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id,omitempty"`
	Result  any             `json:"result,omitempty"`
	Error   *Error          `json:"error,omitempty"`
}

Response is an outgoing JSON-RPC result or error.

type Result

type Result struct {
	Content           []Content `json:"content"`
	StructuredContent any       `json:"structuredContent,omitempty"`
	IsError           bool      `json:"isError,omitempty"`
}

Result is what a tool returns. StructuredContent is mirrored into a text block when Content is empty so every client sees the same data.

func Failure

func Failure(message string, structured any) Result

Failure builds a tool execution error. Structured data, when given, helps the client correct the call.

func Value

func Value(value any) Result

Value builds a successful result from a JSON value.

type Server

type Server struct {
	// Tools is the tool table served by tools/list and tools/call.
	Tools *Registry
	// Info identifies this server in every result's _meta.
	Info Implementation
	// Instructions is optional guidance returned by server/discover.
	Instructions string
	// Authenticate resolves the caller from the request and its body. An
	// error answers 401 with Challenge in WWW-Authenticate.
	Authenticate func(r *http.Request, body []byte) (string, error)
	// Challenge is the WWW-Authenticate value sent with 401.
	Challenge string
	// Origin returns the origin this endpoint is served from. A request whose
	// Origin header names another origin is refused with 403.
	Origin func(r *http.Request) string
	// MaxBodyBytes bounds the request body. Zero means one megabyte.
	MaxBodyBytes int64
}

Server serves the MCP endpoint. Every request is authenticated, validated against its mirrored headers and routed independently; no state survives between requests.

func (*Server) Handle

func (s *Server) Handle(w http.ResponseWriter, r *http.Request) Observation

Handle serves the request and reports what happened.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles one POST to the MCP endpoint.

type Tool

type Tool struct {
	Name         string         `json:"name"`
	Title        string         `json:"title,omitempty"`
	Description  string         `json:"description"`
	InputSchema  map[string]any `json:"inputSchema"`
	OutputSchema map[string]any `json:"outputSchema,omitempty"`
	Annotations  map[string]any `json:"annotations,omitempty"`
	Handler      Handler        `json:"-"`
}

Tool is one entry in a server's tool table.

Jump to

Keyboard shortcuts

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