mcp

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package mcp is a small, standalone Model Context Protocol client. It does not depend on an MCP SDK or on other PiG packages.

The package provides a transport-neutral client core, stdio and Streamable HTTP transports, and an in-memory transport for tests (package mcptest). A transport owns framing and I/O and delivers individual JSON-RPC messages to Client; the client owns request correlation, initialization, timeouts, cancellation, server requests, and protocol-level helpers.

Async mapping from upstream: an awaited Promise is a blocking call that returns its value and error; an AbortSignal is a context.Context; every intentionally unawaited Promise is a goroutine the client or transport owns and drains on Close.

Index

Constants

View Source
const (
	JSONRPCParseError     = -32700
	JSONRPCInvalidRequest = -32600
	JSONRPCMethodNotFound = -32601
	JSONRPCInvalidParams  = -32602
	JSONRPCInternalError  = -32603
)

JSON-RPC error codes, the members of upstream JSON_RPC_ERROR_CODES (jsonrpc.ts:37).

View Source
const DefaultMaxMessageBytes = 16 * 1024 * 1024

DefaultMaxMessageBytes bounds one message on a transport.

View Source
const LatestProtocolVersion = "2025-11-25"

LatestProtocolVersion is the protocol version the client requests.

Variables

View Source
var JSONRPCErrorCodes = struct {
	ParseError     int
	InvalidRequest int
	MethodNotFound int
	InvalidParams  int
	InternalError  int
}{JSONRPCParseError, JSONRPCInvalidRequest, JSONRPCMethodNotFound, JSONRPCInvalidParams, JSONRPCInternalError}

JSONRPCErrorCodes is upstream JSON_RPC_ERROR_CODES: the object whose members name the standard JSON-RPC error codes (`JSON_RPC_ERROR_CODES.invalidRequest`). The mcp package and its callers read the codes through it.

View Source
var SupportedProtocolVersions = []SupportedProtocolVersion{LatestProtocolVersion, "2025-06-18", "2025-03-26", "2024-11-05"}

SupportedProtocolVersions are the versions the client accepts from a server. Servers that do not support the requested version answer with their own latest one, so older versions stay accepted for servers built on older SDKs.

Functions

func ConsumeSSEStream

func ConsumeSSEStream(r io.Reader, options ConsumeSSEOptions) error

ConsumeSSEStream reads a server-sent event stream to its end. It fails as soon as an event grows past the limit, before the stream ends.

func IsJSONRPCNotification

func IsJSONRPCNotification(message any) bool

IsJSONRPCNotification is upstream isJsonRpcNotification (protocol/jsonrpc.ts): a JSON-RPC 2.0 object with a string method and no id member (an id of null still counts as an id member). message takes the same values as IsJSONRPCRequest.

func IsJSONRPCRequest

func IsJSONRPCRequest(message any) bool

IsJSONRPCRequest is upstream isJsonRpcRequest (protocol/jsonrpc.ts): a JSON-RPC 2.0 object with a string or finite-number id and a string method. message is a parsed JSONRPCMessage or a decoded JSON object (map[string]any); any other value is no request.

func IsJSONRPCResponse

func IsJSONRPCResponse(message any) bool

IsJSONRPCResponse is upstream isJsonRpcResponse (protocol/jsonrpc.ts): a JSON-RPC 2.0 object with a valid id that carries a result and no error, or an error object with a numeric code and a string message. message takes the same values as IsJSONRPCRequest.

func KillLiveProcessGroups

func KillLiveProcessGroups()

KillLiveProcessGroups sends SIGTERM to the process group of every stdio server still running. A host calls it as it exits without closing its transports (upstream's process "exit" hook).

Types

type AuthProvider

type AuthProvider interface {
	// Token returns the current access token, or "" for none.
	Token(ctx context.Context) (string, error)
}

AuthProvider supplies bearer tokens to an MCP HTTP transport.

type CallToolResult

type CallToolResult struct {
	Content []ContentBlock `json:"content"`
	// StructuredContent is any JSON value, including an array and `null` (MCP 2026-07-28; earlier revisions allowed only objects).
	StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
	IsError           *bool           `json:"isError,omitempty"`
	Meta              json.RawMessage `json:"_meta,omitempty"`

	// Raw is the result object as the server sent it, with `content` defaulted
	// to an empty list. A host that passes the whole result on, as upstream's
	// codemode bridge does, uses it to keep the server's members and their order.
	Raw json.RawMessage `json:"-"`
}

CallToolResult is the result of tools/call.

func (*CallToolResult) UnmarshalJSON

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

UnmarshalJSON reads a tools/call result as upstream's client does: `content` is a list of blocks, `isError` is read for its JavaScript truthiness (client.ts passes the server's value through and tools.ts tests `result.isError`), and no member is rejected for its type.

type CancelledNotification

type CancelledNotification struct {
	RequestID JSONRPCID `json:"requestId"`
	Reason    string    `json:"reason,omitempty"`
}

CancelledNotification is the params of notifications/cancelled.

type Client

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

Client is an MCP client over a Transport. It is safe for concurrent use.

func NewClient

func NewClient(options ClientOptions) *Client

NewClient returns an idle client.

func (*Client) CallTool

func (c *Client) CallTool(ctx context.Context, name string, args any, options RequestOptions) (*CallToolResult, error)

CallTool calls a tool. A nil args omits the arguments member; args may be a map, a struct, or json.RawMessage.

func (*Client) Close

func (c *Client) Close() error

Close rejects in-flight requests, closes the transport, and waits for the goroutines the client started for server requests.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, transport Transport) (*InitializeResult, error)

Connect starts the transport, initializes the connection, and returns the server's initialize result. On failure the client is closed. The context bounds the wait for the server's answer; per the spec, initialize is not cancelled on the server.

func (*Client) ConnectionState

func (c *Client) ConnectionState() ClientState

ConnectionState is the current state.

func (*Client) Instructions

func (c *Client) Instructions() *string

Instructions are the server's instructions, or nil.

func (*Client) ListResourceTemplates

func (c *Client) ListResourceTemplates(ctx context.Context, options RequestOptions) ([]ResourceTemplate, error)

ListResourceTemplates returns every resource template, following nextCursor through all pages.

func (*Client) ListResourceTemplatesPage

func (c *Client) ListResourceTemplatesPage(ctx context.Context, cursor *string, options RequestOptions) (*ListResourceTemplatesResult, error)

ListResourceTemplatesPage returns one page of resource templates.

func (*Client) ListResources

func (c *Client) ListResources(ctx context.Context, options RequestOptions) ([]Resource, error)

ListResources returns every resource, following nextCursor through all pages.

func (*Client) ListResourcesPage

func (c *Client) ListResourcesPage(ctx context.Context, cursor *string, options RequestOptions) (*ListResourcesResult, error)

ListResourcesPage returns one page of resources, starting at cursor.

func (*Client) ListTools

func (c *Client) ListTools(ctx context.Context, options RequestOptions) ([]Tool, error)

ListTools returns every tool, following nextCursor through all pages.

func (*Client) Notify

func (c *Client) Notify(method string, params any) error

Notify sends a notification.

func (*Client) OnClose

func (c *Client) OnClose(listener CloseListener) (dispose func())

OnClose registers a listener called once when the connection closes, whether the transport dropped or Close was called.

func (*Client) OnError

func (c *Client) OnError(listener ErrorListener) (dispose func())

OnError registers a listener for errors that do not fail a request.

func (*Client) OnNotification

func (c *Client) OnNotification(method string, listener NotificationListener) (dispose func())

OnNotification registers a listener for one notification method.

func (*Client) Options

func (c *Client) Options() ClientOptions

Options returns the options the client was created with.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context, options RequestOptions) error

Ping sends a ping request.

func (*Client) ProtocolVersion

func (c *Client) ProtocolVersion() string

ProtocolVersion is the negotiated protocol version, or "".

func (*Client) ReadResource

func (c *Client) ReadResource(ctx context.Context, uri string, options RequestOptions) (*ReadResourceResult, error)

ReadResource reads a resource.

func (*Client) Request

func (c *Client) Request(ctx context.Context, method string, params any, options RequestOptions) (json.RawMessage, error)

Request sends a request and waits for its result. It fails with McpAbortError when ctx ends first and with McpTimeoutError when the timeout passes without a response or progress notification.

func (*Client) ServerCapabilities

func (c *Client) ServerCapabilities() *ServerCapabilities

ServerCapabilities are the server's capabilities, after connect.

func (*Client) ServerInfo

func (c *Client) ServerInfo() *Implementation

ServerInfo is the server's implementation, after connect.

func (*Client) SetRequestHandler

func (c *Client) SetRequestHandler(method string, handler RequestHandler) (dispose func())

SetRequestHandler installs the handler for a server request method. The returned function removes it unless a later handler replaced it.

type ClientCapabilities

type ClientCapabilities struct {
	Experimental map[string]any         `json:"experimental,omitempty"`
	Roots        *ListChangedCapability `json:"roots,omitempty"`
	Sampling     map[string]any         `json:"sampling,omitempty"`
	Elicitation  map[string]any         `json:"elicitation,omitempty"`
}

ClientCapabilities are the capabilities the client declares in initialize.

func (ClientCapabilities) MarshalJSON

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

MarshalJSON emits a non-nil empty map as an empty object: `{sampling: {}}` declares the capability, and encoding/json's omitempty would drop it.

type ClientOptions

type ClientOptions struct {
	Implementation
	Capabilities    *ClientCapabilities
	ProtocolVersion string
	// RequestTimeoutMs is the default request timeout. Zero selects 30000;
	// a negative value disables the timeout. (Go mechanic: upstream tells
	// "unset" from an explicit 0 with undefined.)
	RequestTimeoutMs int
	// Roots are the roots offered to servers. A non-nil slice, even an empty
	// one, answers roots/list and declares the roots capability.
	Roots []Root
	// RootsFunc computes the roots on each roots/list request. It takes
	// precedence over Roots.
	RootsFunc func(ctx context.Context) ([]Root, error)
}

ClientOptions configure a Client.

type ClientState

type ClientState string

ClientState is the connection state of a Client.

const (
	ClientStateIdle       ClientState = "idle"
	ClientStateConnecting ClientState = "connecting"
	ClientStateConnected  ClientState = "connected"
	ClientStateClosed     ClientState = "closed"
)

Connection states. A client moves idle, connecting, connected, closed and never back.

type CloseListener

type CloseListener func()

CloseListener is called once when the transport closes.

type ConsumeSSEOptions

type ConsumeSSEOptions struct {
	// MaxEventBytes bounds one event. Zero selects DefaultMaxMessageBytes.
	MaxEventBytes int
	OnEvent       func(event SSEEvent)
	// OnID is called for every `id` field, including events without data (for
	// example resumption priming events).
	OnID func(id string)
	// OnRetry is called for every valid `retry` field, in milliseconds.
	OnRetry func(delayMs int)
}

ConsumeSSEOptions configure ConsumeSSEStream.

type ContentAnnotations

type ContentAnnotations struct {
	Audience     []string `json:"audience,omitempty"`
	Priority     *float64 `json:"priority,omitempty"`
	LastModified string   `json:"lastModified,omitempty"`
}

ContentAnnotations are the annotations of a content block.

type ContentBlock

type ContentBlock struct {
	Type     ContentBlockType
	Text     string
	Data     string
	MimeType string
	URI      string
	Name     string
	Title    string
	// HasTitle is set when the server sent a non-null `title`, possibly empty. A title of a block built in Go is
	// present when it is not empty.
	HasTitle    bool
	Description string
	Size        *float64
	Resource    *ResourceContents
	Annotations *ContentAnnotations
	Meta        json.RawMessage
	// contains filtered or unexported fields
}

ContentBlock is one block of a tool result. Type selects the variant: "text" uses Text; "image" and "audio" use Data and MimeType; "resource_link" uses URI, Name, Title, Description, MimeType, and Size; "resource" uses Resource. A block decoded from JSON keeps its original bytes, so a server's block reaches a script exactly as sent.

func (ContentBlock) MarshalJSON

func (b ContentBlock) MarshalJSON() ([]byte, error)

MarshalJSON writes the bytes the block was decoded from, or builds the block from its fields.

func (*ContentBlock) UnmarshalJSON

func (b *ContentBlock) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a block and keeps its bytes. Upstream's client passes a server's block through unchecked (client.ts validateCallToolResult), so a member of another JSON type, an absent member and a block that is not an object are not decode errors: the typed fields take the members that have the declared type, and the kept bytes carry every member for ToLLMContent.

type ContentBlockType

type ContentBlockType string

ContentBlockType is the "type" of a ContentBlock: the closed union of protocol/content.ts ContentBlock. A block decoded from JSON keeps whatever type the server sent.

const (
	ContentText         ContentBlockType = "text"
	ContentImage        ContentBlockType = "image"
	ContentAudio        ContentBlockType = "audio"
	ContentResourceLink ContentBlockType = "resource_link"
	ContentResource     ContentBlockType = "resource"
)

The ContentBlock types.

type ErrorListener

type ErrorListener func(err error)

ErrorListener receives transport errors that do not close the connection.

type Implementation

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

Implementation names a client or server implementation.

type InitializeParams

type InitializeParams struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ClientCapabilities `json:"capabilities"`
	ClientInfo      Implementation     `json:"clientInfo"`
}

InitializeParams are the params of the initialize request.

type InitializeResult

type InitializeResult struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ServerCapabilities `json:"capabilities"`
	ServerInfo      Implementation     `json:"serverInfo"`
	Instructions    *string            `json:"instructions,omitempty"`
}

InitializeResult is the result of the initialize request.

type JSONRPCErrorObject

type JSONRPCErrorObject struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

JSONRPCErrorObject is the error member of a JSON-RPC error response.

type JSONRPCErrorResponse

type JSONRPCErrorResponse struct {
	JSONRPC string
	ID      JSONRPCID
	Error   JSONRPCErrorObject
}

JSONRPCErrorResponse is jsonrpc.ts:28-32 JsonRpcErrorResponse.

func (JSONRPCErrorResponse) ResponseID

func (r JSONRPCErrorResponse) ResponseID() JSONRPCID

ResponseID returns the response's id.

type JSONRPCID

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

JSONRPCID is a JSON-RPC request id: a string or a finite number.

func NumberID

func NumberID(n float64) JSONRPCID

NumberID returns a numeric id.

func StringID

func StringID(s string) JSONRPCID

StringID returns a string id.

func (JSONRPCID) IsSet

func (id JSONRPCID) IsSet() bool

IsSet reports whether the id holds a value.

func (JSONRPCID) IsString

func (id JSONRPCID) IsString() bool

IsString reports whether the id is a string.

func (JSONRPCID) MarshalJSON

func (id JSONRPCID) MarshalJSON() ([]byte, error)

MarshalJSON writes the id as JSON.stringify does: a JSON string, or the number as Number.prototype.toString renders it.

func (JSONRPCID) String

func (id JSONRPCID) String() string

String is the id as JavaScript's String(id) renders it.

func (*JSONRPCID) UnmarshalJSON

func (id *JSONRPCID) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a string or number; any other JSON value is an error.

type JSONRPCMessage

type JSONRPCMessage struct {
	JSONRPC string
	ID      *JSONRPCID
	Method  string
	Params  json.RawMessage
	// Result is the raw result of a success response. A response whose result
	// is JSON null has Result "null"; HasResult reports presence.
	Result json.RawMessage
	Error  *JSONRPCErrorObject
	// contains filtered or unexported fields
}

JSONRPCMessage is a request, a notification, or a response. Use JSONRPCMessage.IsRequest, JSONRPCMessage.IsNotification, and JSONRPCMessage.IsResponse to tell them apart.

func NewErrorResponse

func NewErrorResponse(id JSONRPCID, code int, message string, data json.RawMessage) JSONRPCMessage

NewErrorResponse builds an error response.

func NewNotification

func NewNotification(method string, params json.RawMessage) JSONRPCMessage

NewNotification builds a notification message.

func NewRequest

func NewRequest(id JSONRPCID, method string, params json.RawMessage) JSONRPCMessage

NewRequest builds a request message.

func NewResult

func NewResult(id JSONRPCID, result json.RawMessage) JSONRPCMessage

NewResult builds a success response.

func ParseJSONRPCMessage

func ParseJSONRPCMessage(data []byte) (JSONRPCMessage, error)

ParseJSONRPCMessage decodes one JSON-RPC message and validates its shape as upstream parseJsonRpcMessage does. It returns *McpError with the invalid request code for anything else.

func (JSONRPCMessage) AsResponse

func (m JSONRPCMessage) AsResponse() (response JSONRPCResponse, ok bool)

AsResponse is the JsonRpcResponse form of the message: ok is true exactly when JSONRPCMessage.IsResponse holds, and the result is a JSONRPCSuccessResponse or, for an error response, a JSONRPCErrorResponse.

func (JSONRPCMessage) HasResult

func (m JSONRPCMessage) HasResult() bool

HasResult reports whether the message carries a result member.

func (JSONRPCMessage) IsNotification

func (m JSONRPCMessage) IsNotification() bool

IsNotification is upstream isJsonRpcNotification.

func (JSONRPCMessage) IsRequest

func (m JSONRPCMessage) IsRequest() bool

IsRequest is upstream isJsonRpcRequest.

func (JSONRPCMessage) IsResponse

func (m JSONRPCMessage) IsResponse() bool

IsResponse is upstream isJsonRpcResponse.

func (JSONRPCMessage) MarshalJSON

func (m JSONRPCMessage) MarshalJSON() ([]byte, error)

MarshalJSON writes the message with its members in wire order.

type JSONRPCResponse

type JSONRPCResponse interface {
	// ResponseID is the id of the request the response answers.
	ResponseID() JSONRPCID
	// contains filtered or unexported methods
}

JSONRPCResponse is jsonrpc.ts:34 JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse: a response always has its id and carries either a result or an error object, never both. JSONRPCSuccessResponse and JSONRPCErrorResponse are its two forms; JSONRPCMessage.AsResponse produces one from a message for which JSONRPCMessage.IsResponse holds, and the client's handleResponse takes it (client.ts:476).

type JSONRPCSuccessResponse

type JSONRPCSuccessResponse struct {
	JSONRPC string
	ID      JSONRPCID
	// Result is the raw result; JSON null is the raw "null".
	Result json.RawMessage
}

JSONRPCSuccessResponse is jsonrpc.ts:22-26 JsonRpcSuccessResponse.

func (JSONRPCSuccessResponse) ResponseID

func (r JSONRPCSuccessResponse) ResponseID() JSONRPCID

ResponseID returns the response's id.

type LLMContent

type LLMContent struct {
	Type     LLMContentType
	Text     string
	Data     string
	MimeType string
}

LLMContent is tool result content in the shape LLM APIs accept: text and base64 images. It matches the text and image content of package ai.

func ToLLMContent

func ToLLMContent(result CallToolResult) []LLMContent

ToLLMContent converts a tool result to text and image content for a model. Text and images pass through, embedded text resources become text, embedded image resources become images, and other blocks (audio, resource links, binary resources) become a short text placeholder. A result without content blocks but with structuredContent becomes its indented JSON, since servers should, but do not always, mirror structured results as text.

type LLMContentType

type LLMContentType string

LLMContentType is the discriminator of LLMContent: upstream's `"text" | "image"`.

const (
	LLMContentTypeText  LLMContentType = "text"
	LLMContentTypeImage LLMContentType = "image"
)

type ListChangedCapability

type ListChangedCapability struct {
	ListChanged *bool `json:"listChanged,omitempty"`
}

ListChangedCapability is a capability with an optional listChanged flag.

type ListResourceTemplatesResult

type ListResourceTemplatesResult struct {
	ResourceTemplates []ResourceTemplate `json:"resourceTemplates"`
	NextCursor        string             `json:"nextCursor,omitempty"`
	// HasNextCursor reports that the page has a cursor, which may be the empty string: Pi's resource listing shows any cursor that is not undefined.
	// The client sets it only for a non-empty cursor, as Pi's client drops a null or empty one (packages/mcp/src/client.ts:104).
	HasNextCursor bool            `json:"-"`
	Meta          json.RawMessage `json:"_meta,omitempty"`
}

ListResourceTemplatesResult is one page of resources/templates/list.

type ListResourcesResult

type ListResourcesResult struct {
	Resources  []Resource `json:"resources"`
	NextCursor string     `json:"nextCursor,omitempty"`
	// HasNextCursor reports that the page has a cursor, which may be the empty string: Pi's resource listing shows any cursor that is not undefined.
	// The client sets it only for a non-empty cursor, as Pi's client drops a null or empty one (packages/mcp/src/client.ts:104).
	HasNextCursor bool            `json:"-"`
	Meta          json.RawMessage `json:"_meta,omitempty"`
}

ListResourcesResult is one page of resources/list.

type ListToolsResult

type ListToolsResult struct {
	Tools      []Tool          `json:"tools"`
	NextCursor string          `json:"nextCursor,omitempty"`
	Meta       json.RawMessage `json:"_meta,omitempty"`
}

ListToolsResult is one page of tools/list.

type McpAbortError

type McpAbortError struct {
	Message string
}

McpAbortError reports a request whose context ended.

func NewMcpAbortError

func NewMcpAbortError(message string) *McpAbortError

NewMcpAbortError is `new McpAbortError(message)`; an empty message is upstream's default "MCP request aborted".

func (*McpAbortError) Cause

func (e *McpAbortError) Cause() error

Cause is the `cause` property. No upstream constructor sets one, so it is always nil.

func (*McpAbortError) Error

func (e *McpAbortError) Error() string

func (*McpAbortError) Name

func (e *McpAbortError) Name() string

Name is the `name` property, upstream's "AbortError".

type McpAuthRequiredError

type McpAuthRequiredError struct {
	McpHttpError
	// WWWAuthenticate is the challenge header; HasWWWAuthenticate is false
	// when the response had none.
	WWWAuthenticate    string
	HasWWWAuthenticate bool
}

McpAuthRequiredError is a 401 response.

func NewMcpAuthRequiredError

func NewMcpAuthRequiredError(response *http.Response, body string) *McpAuthRequiredError

NewMcpAuthRequiredError is `new McpAuthRequiredError(response, body)`.

func (*McpAuthRequiredError) Name

func (e *McpAuthRequiredError) Name() string

Name is the `name` property, "McpAuthRequiredError".

func (*McpAuthRequiredError) Unwrap

func (e *McpAuthRequiredError) Unwrap() error

Unwrap lets errors.As find the *McpHttpError.

type McpConnectionClosedError

type McpConnectionClosedError struct {
	Message string
}

McpConnectionClosedError reports a closed connection.

func NewMcpConnectionClosedError

func NewMcpConnectionClosedError(message string) *McpConnectionClosedError

NewMcpConnectionClosedError is `new McpConnectionClosedError(message)`; an empty message is upstream's default "MCP connection closed".

func (*McpConnectionClosedError) Cause

func (e *McpConnectionClosedError) Cause() error

Cause is the `cause` property. No upstream constructor sets one, so it is always nil.

func (*McpConnectionClosedError) Error

func (e *McpConnectionClosedError) Error() string

func (*McpConnectionClosedError) Name

func (e *McpConnectionClosedError) Name() string

Name is the `name` property, "McpConnectionClosedError".

type McpError

type McpError struct {
	Code    int
	Message string
	Data    json.RawMessage
}

McpError is a JSON-RPC error reported by the peer or by validation.

func NewMcpError

func NewMcpError(code int, message string, data json.RawMessage) *McpError

NewMcpError is `new McpError(code, message, data)`.

func (*McpError) Cause

func (e *McpError) Cause() error

Cause is the `cause` property. No upstream constructor sets one, so it is always nil.

func (*McpError) Error

func (e *McpError) Error() string

func (*McpError) Name

func (e *McpError) Name() string

Name is the `name` property, "McpError".

type McpFetch

type McpFetch interface {
	Do(request *http.Request) (*http.Response, error)
}

McpFetch performs one HTTP request. *http.Client implements it. Injecting one lets a host add proxying or custom networking.

type McpHttpError

type McpHttpError struct {
	Status  int
	Message string
	Body    string
}

McpHttpError is a failed HTTP exchange.

func NewMcpHttpError

func NewMcpHttpError(status int, message string, body string) *McpHttpError

NewMcpHttpError is `new McpHttpError(status, message, body)`.

func (*McpHttpError) Cause

func (e *McpHttpError) Cause() error

Cause is the `cause` property. No upstream constructor sets one, so it is always nil.

func (*McpHttpError) Error

func (e *McpHttpError) Error() string

func (*McpHttpError) Name

func (e *McpHttpError) Name() string

Name is the `name` property, "McpHttpError".

type McpSessionExpiredError

type McpSessionExpiredError struct{ McpHttpError }

McpSessionExpiredError is a 404 response for an established session.

func NewMcpSessionExpiredError

func NewMcpSessionExpiredError(body string) *McpSessionExpiredError

NewMcpSessionExpiredError is `new McpSessionExpiredError(body)`.

func (*McpSessionExpiredError) Name

func (e *McpSessionExpiredError) Name() string

Name is the `name` property, "McpSessionExpiredError".

func (*McpSessionExpiredError) Unwrap

func (e *McpSessionExpiredError) Unwrap() error

Unwrap lets errors.As find the *McpHttpError.

type McpTimeoutError

type McpTimeoutError struct {
	TimeoutMs int
}

McpTimeoutError reports a request that exceeded its timeout.

func NewMcpTimeoutError

func NewMcpTimeoutError(timeoutMs int) *McpTimeoutError

NewMcpTimeoutError is `new McpTimeoutError(timeoutMs)`.

func (*McpTimeoutError) Cause

func (e *McpTimeoutError) Cause() error

Cause is the `cause` property. No upstream constructor sets one, so it is always nil.

func (*McpTimeoutError) Error

func (e *McpTimeoutError) Error() string

func (*McpTimeoutError) Message

func (e *McpTimeoutError) Message() string

Message is the `message` property, the text of Error.

func (*McpTimeoutError) Name

func (e *McpTimeoutError) Name() string

Name is the `name` property, "McpTimeoutError".

type MessageListener

type MessageListener func(message JSONRPCMessage)

MessageListener receives each JSON-RPC message a transport reads.

type NotificationListener

type NotificationListener func(params json.RawMessage)

NotificationListener receives the params of one notification method.

type OrderedSender

type OrderedSender interface {
	SendOrdered(ctx context.Context, message JSONRPCMessage, placed func()) error
}

OrderedSender is implemented by a transport whose Send writes messages in the order the writes took their place, such as a stdio pipe or an in-process queue. SendOrdered calls placed once every later Send is written after message, and otherwise behaves as Send. The client uses it to write requests in id order; a transport without it (HTTP, where Send waits for the reply) gets concurrent Sends in no fixed order.

type ProgressNotification

type ProgressNotification struct {
	ProgressToken JSONRPCID `json:"progressToken"`
	Progress      float64   `json:"progress"`
	Total         *float64  `json:"total,omitempty"`
	Message       string    `json:"message,omitempty"`
}

ProgressNotification is the params of notifications/progress.

type ProtocolVersionSetter

type ProtocolVersionSetter interface {
	SetProtocolVersion(version string)
}

ProtocolVersionSetter is implemented by transports that send the negotiated protocol version with later requests.

type ReadResourceResult

type ReadResourceResult struct {
	Contents []ResourceContents `json:"contents"`
	Meta     json.RawMessage    `json:"_meta,omitempty"`
}

ReadResourceResult is the result of resources/read.

type RequestHandler

type RequestHandler func(ctx context.Context, params json.RawMessage) (any, error)

RequestHandler answers a request from the server. The context ends when the server cancels the request or the connection closes. A nil result is sent as an empty object.

type RequestOptions

type RequestOptions struct {
	// TimeoutMs overrides the client's timeout. Zero uses the client's;
	// a negative value disables the timeout.
	TimeoutMs  int
	OnProgress func(ProgressNotification)
	// OnIssued runs once the client gave the request its id, in id order, so a caller that orders its requests can hand
	// the next one on. It does not run when the request fails before it has an id.
	OnIssued func()
}

RequestOptions are per-request options. Cancellation comes from the context passed to the request.

type Resource

type Resource struct {
	URI         string              `json:"uri"`
	Name        string              `json:"name"`
	Title       string              `json:"title,omitempty"`
	Description string              `json:"description,omitempty"`
	MimeType    string              `json:"mimeType,omitempty"`
	Size        *float64            `json:"size,omitempty"`
	Annotations *ContentAnnotations `json:"annotations,omitempty"`
	Meta        json.RawMessage     `json:"_meta,omitempty"`
	// Raw is the list entry as the server sent it, with `name` defaulted to the URI; empty for a Resource built in Go.
	Raw json.RawMessage `json:"-"`
}

Resource is a resource a server lists in resources/list.

type ResourceContents

type ResourceContents struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType,omitempty"`
	// HasMimeType reports that the server sent a string mimeType, which may be empty: Pi keeps an empty mimeType where it defaults an absent one.
	HasMimeType bool            `json:"-"`
	Text        *string         `json:"text,omitempty"`
	Blob        *string         `json:"blob,omitempty"`
	Meta        json.RawMessage `json:"_meta,omitempty"`
	// Raw is the entry of resources/read as the server sent it; empty for contents built in Go.
	Raw json.RawMessage `json:"-"`
}

ResourceContents is the contents of a resource: text when Text is non-nil, otherwise a base64 blob.

type ResourceTemplate

type ResourceTemplate struct {
	URITemplate string              `json:"uriTemplate"`
	Name        string              `json:"name"`
	Title       string              `json:"title,omitempty"`
	Description string              `json:"description,omitempty"`
	MimeType    string              `json:"mimeType,omitempty"`
	Annotations *ContentAnnotations `json:"annotations,omitempty"`
	Meta        json.RawMessage     `json:"_meta,omitempty"`
	// Raw is the list entry as the server sent it, with `name` defaulted to the URI template; empty for a
	// ResourceTemplate built in Go.
	Raw json.RawMessage `json:"-"`
}

ResourceTemplate is a family of resources addressed by an RFC 6570 URI template, from resources/templates/list.

type ResourcesCapability

type ResourcesCapability struct {
	Subscribe   *bool `json:"subscribe,omitempty"`
	ListChanged *bool `json:"listChanged,omitempty"`
}

ResourcesCapability is the server's resources capability.

type Root

type Root struct {
	URI  string `json:"uri"`
	Name string `json:"name,omitempty"`
}

Root is a filesystem root the client offers to servers.

type SSEEvent

type SSEEvent struct {
	Event string
	Data  string
	ID    string
}

SSEEvent is one dispatched server-sent event.

type ServerCapabilities

type ServerCapabilities struct {
	Experimental map[string]any         `json:"experimental,omitempty"`
	Logging      map[string]any         `json:"logging,omitempty"`
	Prompts      *ListChangedCapability `json:"prompts,omitempty"`
	Resources    *ResourcesCapability   `json:"resources,omitempty"`
	Tools        *ListChangedCapability `json:"tools,omitempty"`
	Completions  map[string]any         `json:"completions,omitempty"`
}

ServerCapabilities are the capabilities a server declares. A non-nil field means the server declared the capability, even as an empty object.

type StdioTransport

type StdioTransport struct {
	TransportEvents
	// contains filtered or unexported fields
}

StdioTransport talks to a server process over newline-delimited JSON on its stdin and stdout. The process runs in its own process group, and closing the transport shuts down the whole group per the spec: close stdin, then SIGTERM, then SIGKILL.

func NewStdioTransport

func NewStdioTransport(options StdioTransportOptions) *StdioTransport

NewStdioTransport returns a transport that has not started its process.

func (*StdioTransport) Close

func (t *StdioTransport) Close() error

Close shuts the server down: it closes stdin and lets the server exit, then sends SIGTERM to its process group, then SIGKILL. It returns after the server exited and the transport notified its close listeners.

func (*StdioTransport) Options

Options returns the transport's options.

func (*StdioTransport) PID

func (t *StdioTransport) PID() int

PID is the process id of the running server, or 0.

func (*StdioTransport) Send

func (t *StdioTransport) Send(ctx context.Context, message JSONRPCMessage) error

Send writes one message as a line on the server's stdin. Like Pi's stdio send (stdio.ts:143) it ignores the send signal (ctx): a line is written at once.

func (*StdioTransport) SendOrdered

func (t *StdioTransport) SendOrdered(_ context.Context, message JSONRPCMessage, placed func()) error

SendOrdered is Send that calls placed, if not nil, once the write holds its place: a later Send writes after it.

func (*StdioTransport) Start

func (t *StdioTransport) Start() error

Start spawns the server.

func (*StdioTransport) Stderr

func (t *StdioTransport) Stderr() string

Stderr is the tail of the server's stderr.

type StdioTransportOptions

type StdioTransportOptions struct {
	Command string
	Args    []string
	Cwd     string
	// Env is added to the inherited environment, or replaces it when
	// InheritEnv is false. Go mechanic: a map has no insertion order, so
	// entries are applied in sorted key order.
	Env map[string]string
	// InheritEnv is true by default.
	InheritEnv *bool
	// Stderr is "pipe" (the default) or "inherit".
	Stderr          string
	OnStderr        func(chunk string)
	MaxMessageBytes int
	MaxStderrBytes  int
	// CloseTimeoutMs is the time to wait for the server to exit after SIGTERM
	// before sending SIGKILL. Default: 2000.
	CloseTimeoutMs int
}

StdioTransportOptions configure a StdioTransport.

type StreamableHTTPReconnectOptions

type StreamableHTTPReconnectOptions struct {
	// InitialDelayMs is the delay before the first reconnection attempt,
	// unless the server sent a `retry` field. Default: 1000.
	InitialDelayMs int
	// MaxDelayMs bounds the exponential backoff. Default: 30000.
	MaxDelayMs int
	// MaxRetries is the number of consecutive failed attempts before giving up
	// on a stream. Default: 5.
	MaxRetries int
}

StreamableHTTPReconnectOptions control reconnection of dropped SSE streams (the GET stream, and response streams that carry event IDs). Zero fields select the defaults.

type StreamableHTTPTransport

type StreamableHTTPTransport struct {
	TransportEvents
	URL *url.URL
	// contains filtered or unexported fields
}

StreamableHTTPTransport implements the MCP Streamable HTTP transport: JSON and SSE responses to POSTed messages, sessions, the server-to-client GET stream with reconnection, and resumption of dropped response streams with Last-Event-ID.

func NewStreamableHTTPTransport

func NewStreamableHTTPTransport(options StreamableHTTPTransportOptions) (*StreamableHTTPTransport, error)

NewStreamableHTTPTransport returns a transport for options.URL. It returns an error when the URL does not parse.

func (*StreamableHTTPTransport) Close

func (t *StreamableHTTPTransport) Close() error

Close aborts every in-flight request and stream, ends the session with a DELETE when the server assigned one, and waits for the transport's goroutines.

func (*StreamableHTTPTransport) Options

Options returns the transport's options.

func (*StreamableHTTPTransport) Send

Send POSTs one message. A response to a request arrives as JSON, which is delivered before Send returns, or as an SSE stream, which a goroutine delivers. Once ctx ends the message is not dispatched (Pi streamable-http.ts:231-240, the send signal).

func (*StreamableHTTPTransport) SessionID

func (t *StreamableHTTPTransport) SessionID() string

SessionID is the session the server assigned, or "".

func (*StreamableHTTPTransport) SetProtocolVersion

func (t *StreamableHTTPTransport) SetProtocolVersion(version string)

SetProtocolVersion sets the MCP-Protocol-Version header for later requests.

func (*StreamableHTTPTransport) Start

func (t *StreamableHTTPTransport) Start() error

Start marks the transport started. It opens no connection.

type StreamableHTTPTransportOptions

type StreamableHTTPTransportOptions struct {
	URL     string
	Headers map[string]string
	Fetch   McpFetch
	// OpenGetStream opens the server-to-client GET stream after
	// initialization. Default: true.
	OpenGetStream   *bool
	MaxMessageBytes int
	AuthProvider    AuthProvider
	Reconnect       StreamableHTTPReconnectOptions
}

StreamableHTTPTransportOptions configure a StreamableHTTPTransport.

type SupportedProtocolVersion

type SupportedProtocolVersion string

SupportedProtocolVersion is one of SupportedProtocolVersions (types.ts:10).

type Tool

type Tool struct {
	Name  string `json:"name"`
	Title string `json:"title,omitempty"`
	// HasTitle is set when the server sent a non-null `title`, possibly empty. A title of a tool built in Go is present
	// when it is not empty.
	HasTitle     bool             `json:"-"`
	Description  string           `json:"description,omitempty"`
	InputSchema  json.RawMessage  `json:"inputSchema"`
	OutputSchema json.RawMessage  `json:"outputSchema,omitempty"`
	Annotations  *ToolAnnotations `json:"annotations,omitempty"`
	Execution    *ToolExecution   `json:"execution,omitempty"`
	Meta         json.RawMessage  `json:"_meta,omitempty"`
}

Tool is a tool a server lists in tools/list. Fields the protocol does not define are not kept.

func (*Tool) UnmarshalJSON

func (t *Tool) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a tool and records whether the server sent a `title`.

type ToolAnnotations

type ToolAnnotations struct {
	Title           string
	ReadOnlyHint    *bool
	DestructiveHint *bool
	IdempotentHint  *bool
	OpenWorldHint   *bool
}

ToolAnnotations are a tool's hints. A hint that the server sent with a non-boolean value is left nil.

func (ToolAnnotations) MarshalJSON

func (a ToolAnnotations) MarshalJSON() ([]byte, error)

MarshalJSON writes the annotations that are set.

func (*ToolAnnotations) UnmarshalJSON

func (a *ToolAnnotations) UnmarshalJSON(data []byte) error

UnmarshalJSON reads the annotations and drops hints that are not booleans.

type ToolExecution

type ToolExecution struct {
	TaskSupport string `json:"taskSupport,omitempty"`
}

ToolExecution is a tool's execution metadata.

type Transport

type Transport interface {
	Start() error
	Send(ctx context.Context, message JSONRPCMessage) error
	Close() error
	OnMessage(listener MessageListener) (dispose func())
	OnError(listener ErrorListener) (dispose func())
	OnClose(listener CloseListener) (dispose func())
}

Transport owns framing and I/O for one connection. It delivers individual JSON-RPC messages to listeners, in order, from goroutines it owns.

Send may block until the peer answers at the HTTP level, so a caller that must not wait (the client) calls it from its own goroutine; a Transport therefore accepts concurrent Send calls. Close ends every goroutine the transport started before it returns.

Send's ctx is Pi's McpTransportSendOptions.signal (transport.ts:9-16): it ends once the sender no longer waits for a reply (the request was cancelled, timed out, answered, or the client closed). A transport must not dispatch the message after that, for example when retrying it after an authorization refresh. It does not undo a message already dispatched. A transport that writes at once (stdio, in-memory) ignores it, as Pi's do.

type TransportEvents

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

TransportEvents is listener bookkeeping shared by transports. EmitClose fires at most once per transport. Listeners run on the emitting goroutine, in registration order, outside the internal lock.

func (*TransportEvents) EmitClose

func (t *TransportEvents) EmitClose()

EmitClose notifies the close listeners, once.

func (*TransportEvents) EmitError

func (t *TransportEvents) EmitError(err error)

EmitError delivers an error to the listeners.

func (*TransportEvents) EmitMessage

func (t *TransportEvents) EmitMessage(message JSONRPCMessage)

EmitMessage delivers a message to the listeners.

func (*TransportEvents) OnClose

func (t *TransportEvents) OnClose(listener CloseListener) func()

OnClose registers a close listener.

func (*TransportEvents) OnError

func (t *TransportEvents) OnError(listener ErrorListener) func()

OnError registers an error listener.

func (*TransportEvents) OnMessage

func (t *TransportEvents) OnMessage(listener MessageListener) func()

OnMessage registers a message listener.

type UnauthorizedContext

type UnauthorizedContext struct {
	// Response is the 401 response, or a 403 response whose challenge reports
	// insufficient_scope.
	Response  *http.Response
	ServerURL *url.URL
	Fetch     McpFetch
	// Token is the access token the rejected request carried, if any. A
	// different current token means another request already refreshed it.
	Token string
}

UnauthorizedContext describes a rejected request.

type UnauthorizedHandler

type UnauthorizedHandler interface {
	OnUnauthorized(ctx context.Context, unauthorized UnauthorizedContext) error
}

UnauthorizedHandler is implemented by an AuthProvider that can refresh credentials after a 401 response. The transport retries the request once with whatever credentials the handler left behind.

Directories

Path Synopsis
Package mcptest holds test doubles for package mcp.
Package mcptest holds test doubles for package mcp.
Package oauth is the MCP OAuth client subset: protected-resource and authorization-server discovery, the PKCE authorization code flow, dynamic client registration, token refresh (one refresh shared by concurrent 401s), and step-up authorization for insufficient_scope.
Package oauth is the MCP OAuth client subset: protected-resource and authorization-server discovery, the PKCE authorization code flow, dynamic client registration, token refresh (one refresh shared by concurrent 401s), and step-up authorization for insufficient_scope.

Jump to

Keyboard shortcuts

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