mcp

package
v0.34.0 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2025 License: BSD-3-Clause Imports: 31 Imported by: 0

README

MCP SDK prototype

PkgGoDev

Contents

  1. Installation
  2. Quickstart
  3. Design
  4. Testing
  5. Code of Conduct
  6. License

The mcp package provides a software development kit (SDK) for writing clients and servers of the model context protocol. It is unstable, and will change in breaking ways in the future. As of writing, it is a prototype to explore the design space of client/server transport and binding.

Installation

The mcp package is currently internal and cannot be imported using go get.

Quickstart

Here's an example that creates a client that talks to an MCP server running as a sidecar process:

package main

import (
	"context"
	"log"
	"os/exec"

	"golang.org/x/tools/internal/mcp"
)

func main() {
	ctx := context.Background()
	// Create a new client, with no features.
	client := mcp.NewClient("mcp-client", "v1.0.0", nil)
	// Connect to a server over stdin/stdout
	transport := mcp.NewCommandTransport(exec.Command("myserver"))
	session, err := client.Connect(ctx, transport)
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()
	// Call a tool on the server.
	params := &mcp.CallToolParams[map[string]any]{
		Name:      "greet",
		Arguments: map[string]any{"name": "you"},
	}
	if res, err := mcp.CallTool(ctx, session, params); err != nil {
		log.Printf("CallTool failed: %v", err)
	} else {
		if res.IsError {
			log.Print("tool failed")
		}
		for _, c := range res.Content {
			log.Print(c.Text)
		}
	}
}

Here is an example of the corresponding server, connected over stdin/stdout:

package main

import (
	"context"

	"golang.org/x/tools/internal/mcp"
)

type HiParams struct {
	Name string `json:"name"`
}

func SayHi(ctx context.Context, cc *mcp.ServerSession, params *mcp.CallToolParams[HiParams]) (*mcp.CallToolResult, error) {
	return &mcp.CallToolResult{
		Content: []*mcp.Content{mcp.NewTextContent("Hi " + params.Name)},
	}, nil
}

func main() {
	// Create a server with a single tool.
	server := mcp.NewServer("greeter", "v1.0.0", nil)
	server.AddTools(mcp.NewTool("greet", "say hi", SayHi))
	// Run the server over stdin/stdout, until the client disconnects
	_ = server.Run(context.Background(), mcp.NewStdIOTransport())
}

Design

See design.md for the SDK design. That document is canonical: given any divergence between the design doc and this prototype, the doc reflects the latest design.

Testing

To test your client or server using stdio transport, you can use an in-memory transport. See example.

To test your client or server using sse transport, you can use the httptest package. See example.

Code of Conduct

This project follows the Go Community Code of Conduct. If you encounter a conduct-related issue, please mail conduct@golang.org.

License

Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file.

Upon a potential move to the modelcontextprotocol organization, the license will be updated to the MIT License, and the license header will reflect the Go MCP SDK Authors.

Documentation

Overview

The mcp package provides an SDK for writing model context protocol clients and servers.

To get started, create either a Client or Server, and connect it to a peer using a Transport. The diagram below illustrates how this works:

Client                                                   Server
 ⇅                          (jsonrpc2)                     ⇅
ClientSession ⇄ Client Transport ⇄ Server Transport ⇄ ServerSession

A Client is an MCP client, which can be configured with various client capabilities. Clients may be connected to a Server instance using the Client.Connect method.

Similarly, a Server is an MCP server, which can be configured with various server capabilities. Servers may be connected to one or more Client instances using the Server.Connect method, which creates a ServerSession.

A Transport connects a bidirectional Stream of jsonrpc2 messages. In practice, transports in the MCP spec are are either client transports or server transports. For example, the StdIOTransport is a server transport that communicates over stdin/stdout, and its counterpart is a CommandTransport that communicates with a subprocess over its stdin/stdout.

Some transports may hide more complicated details, such as an SSEClientTransport, which reads messages via server-sent events on a hanging GET request, and writes them to a POST endpoint. Users of this SDK may define their own custom Transports by implementing the Transport interface.

TODO

  • Support all content types.
  • Support pagination.
  • Support completion.
  • Support oauth.
  • Support all client/server operations.
  • Pass the client connection in the context.
  • Support streamable HTTP transport.
  • Support multiple versions of the spec.
  • Implement full JSON schema support, with both client-side and server-side validation.
Example (ProgressMiddleware)

This middleware function adds a progress token to every outgoing request from the client.

package main

import (
	"context"
	"sync/atomic"

	"golang.org/x/tools/internal/mcp"
)

var nextProgressToken atomic.Int64

// This middleware function adds a progress token to every outgoing request
// from the client.
func main() {
	c := mcp.NewClient("test", "v1", nil)
	c.AddSendingMiddleware(addProgressToken[*mcp.ClientSession])
	_ = c
}

func addProgressToken[S mcp.Session](h mcp.MethodHandler[S]) mcp.MethodHandler[S] {
	return func(ctx context.Context, s S, method string, params mcp.Params) (result mcp.Result, err error) {
		params.GetMeta().ProgressToken = nextProgressToken.Add(1)
		return h(ctx, s, method, params)
	}
}

Index

Examples

Constants

View Source
const (
	LevelDebug     = slog.LevelDebug
	LevelInfo      = slog.LevelInfo
	LevelNotice    = (slog.LevelInfo + slog.LevelWarn) / 2
	LevelWarning   = slog.LevelWarn
	LevelError     = slog.LevelError
	LevelCritical  = slog.LevelError + 4
	LevelAlert     = slog.LevelError + 8
	LevelEmergency = slog.LevelError + 12
)

Logging levels.

View Source
const (
	// The error code to return when a resource isn't found.
	// See https://modelcontextprotocol.io/specification/2025-03-26/server/resources#error-handling
	// However, the code they chose is in the wrong space
	// (see https://github.com/modelcontextprotocol/modelcontextprotocol/issues/509).
	// so we pick a different one, arbitrarily for now (until they fix it).
	// The immediate problem is that jsonprc2 defines -32002 as "server closing".
	CodeResourceNotFound = -31002
	// The error code if the method exists and was called properly, but the peer does not support it.
	CodeUnsupportedMethod = -31001
)

Error codes

View Source
const DefaultPageSize = 1000

Variables

View Source
var ErrConnectionClosed = errors.New("connection closed")

ErrConnectionClosed is returned when sending a message to a connection that is closed or in the process of closing.

Functions

func NewInMemoryTransports added in v0.34.0

func NewInMemoryTransports() (*InMemoryTransport, *InMemoryTransport)

NewInMemoryTransports returns two InMemoryTransports that connect to each other.

func ResourceNotFoundError added in v0.34.0

func ResourceNotFoundError(uri string) error

ResourceNotFoundError returns an error indicating that a resource being read could not be found.

Types

type Annotations added in v0.34.0

type Annotations struct {
	// 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"]`).
	Audience []Role `json:"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"`
}

Optional annotations for the client. The client can use annotations to inform how objects are used or displayed

type CallToolParams added in v0.34.0

type CallToolParams[TArgs any] struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta      Meta   `json:"_meta,omitempty"`
	Arguments TArgs  `json:"arguments,omitempty"`
	Name      string `json:"name"`
}

func (*CallToolParams[TArgs]) GetMeta added in v0.34.0

func (x *CallToolParams[TArgs]) GetMeta() *Meta

type CallToolResult added in v0.34.0

type CallToolResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta    Meta       `json:"_meta,omitempty"`
	Content []*Content `json:"content"`
	// Whether the tool call ended in an error.
	//
	// If not set, this is assumed to be false (the call was successful).
	IsError bool `json:"isError,omitempty"`
}

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.

func CallTool added in v0.34.0

func CallTool[TArgs any](ctx context.Context, cs *ClientSession, params *CallToolParams[TArgs]) (*CallToolResult, error)

CallTool is a helper to call a tool with any argument type. It returns an error if params.Arguments fails to marshal to JSON.

func (*CallToolResult) GetMeta added in v0.34.0

func (x *CallToolResult) GetMeta() *Meta

type CancelledParams added in v0.34.0

type CancelledParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// An optional string describing the reason for the cancellation. This MAY be
	// logged or presented to the user.
	Reason string `json:"reason,omitempty"`
	// The ID of the request to cancel.
	//
	// This MUST correspond to the ID of a request previously issued in the same
	// direction.
	RequestID any `json:"requestId"`
}

func (*CancelledParams) GetMeta added in v0.34.0

func (x *CancelledParams) GetMeta() *Meta

type Client

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

A Client is an MCP client, which may be connected to an MCP server using the Client.Connect method.

func NewClient

func NewClient(name, version string, opts *ClientOptions) *Client

NewClient creates a new Client.

Use Client.Connect to connect it to an MCP server.

If non-nil, the provided options configure the Client.

func (*Client) AddReceivingMiddleware added in v0.34.0

func (c *Client) AddReceivingMiddleware(middleware ...Middleware[*ClientSession])

AddReceivingMiddleware wraps the current receiving method handler using the provided middleware. Middleware is applied from right to left, so that the first one is executed first.

For example, AddReceivingMiddleware(m1, m2, m3) augments the method handler as m1(m2(m3(handler))).

Receiving middleware is called when a request is received. It is useful for tasks such as authentication, request logging and metrics.

func (*Client) AddRoots added in v0.34.0

func (c *Client) AddRoots(roots ...*Root)

AddRoots adds the given roots to the client, replacing any with the same URIs, and notifies any connected servers.

func (*Client) AddSendingMiddleware added in v0.34.0

func (c *Client) AddSendingMiddleware(middleware ...Middleware[*ClientSession])

AddSendingMiddleware wraps the current sending method handler using the provided middleware. Middleware is applied from right to left, so that the first one is executed first.

For example, AddSendingMiddleware(m1, m2, m3) augments the method handler as m1(m2(m3(handler))).

Sending middleware is called when a request is sent. It is useful for tasks such as tracing, metrics, and adding progress tokens.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, t Transport) (cs *ClientSession, err error)

Connect begins an MCP session by connecting to a server over the given transport, and initializing the session.

Typically, it is the responsibility of the client to close the connection when it is no longer needed. However, if the connection is closed by the server, calls or notifications will return an error wrapping ErrConnectionClosed.

func (*Client) RemoveRoots added in v0.34.0

func (c *Client) RemoveRoots(uris ...string)

RemoveRoots removes the roots with the given URIs, and notifies any connected servers if the list has changed. It is not an error to remove a nonexistent root. TODO: notification

type ClientCapabilities added in v0.34.0

type ClientCapabilities struct {
	// Experimental, non-standard capabilities that the client supports.
	Experimental map[string]struct {
	} `json:"experimental,omitempty"`
	// Present if the client supports listing roots.
	Roots struct {
		// Whether the client supports notifications for changes to the roots list.
		ListChanged bool `json:"listChanged,omitempty"`
	} `json:"roots,omitempty"`
	// Present if the client supports sampling from an LLM.
	Sampling *SamplingCapabilities `json:"sampling,omitempty"`
}

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.

type ClientOptions

type ClientOptions struct {
	// Handler for sampling.
	// Called when a server calls CreateMessage.
	CreateMessageHandler func(context.Context, *ClientSession, *CreateMessageParams) (*CreateMessageResult, error)
	// Handlers for notifications from the server.
	ToolListChangedHandler     func(context.Context, *ClientSession, *ToolListChangedParams)
	PromptListChangedHandler   func(context.Context, *ClientSession, *PromptListChangedParams)
	ResourceListChangedHandler func(context.Context, *ClientSession, *ResourceListChangedParams)
	LoggingMessageHandler      func(context.Context, *ClientSession, *LoggingMessageParams)
}

ClientOptions configures the behavior of the client.

type ClientSession added in v0.34.0

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

A ClientSession is a logical connection with an MCP server. Its methods can be used to send requests or notifications to the server. Create a session by calling Client.Connect.

Call ClientSession.Close to close the connection, or await client termination with ServerSession.Wait.

func (*ClientSession) CallTool added in v0.34.0

CallTool calls the tool with the given name and arguments. Pass a [CallToolOptions] to provide additional request fields.

func (*ClientSession) Close added in v0.34.0

func (cs *ClientSession) Close() error

Close performs a graceful close of the connection, preventing new requests from being handled, and waiting for ongoing requests to return. Close then terminates the connection.

func (*ClientSession) GetPrompt added in v0.34.0

func (cs *ClientSession) GetPrompt(ctx context.Context, params *GetPromptParams) (*GetPromptResult, error)

GetPrompt gets a prompt from the server.

func (*ClientSession) ListPrompts added in v0.34.0

func (cs *ClientSession) ListPrompts(ctx context.Context, params *ListPromptsParams) (*ListPromptsResult, error)

ListPrompts lists prompts that are currently available on the server.

func (*ClientSession) ListResources added in v0.34.0

func (cs *ClientSession) ListResources(ctx context.Context, params *ListResourcesParams) (*ListResourcesResult, error)

ListResources lists the resources that are currently available on the server.

func (*ClientSession) ListTools added in v0.34.0

func (cs *ClientSession) ListTools(ctx context.Context, params *ListToolsParams) (*ListToolsResult, error)

ListTools lists tools that are currently available on the server.

func (*ClientSession) Ping added in v0.34.0

func (cs *ClientSession) Ping(ctx context.Context, params *PingParams) error

Ping makes an MCP "ping" request to the server.

func (*ClientSession) Prompts added in v0.34.0

func (cs *ClientSession) Prompts(ctx context.Context, params *ListPromptsParams) iter.Seq2[Prompt, error]

Prompts provides an iterator for all prompts available on the server, automatically fetching pages and managing cursors. The `params` argument can set the initial cursor. Iteration stops at the first encountered error, which will be yielded.

func (*ClientSession) ReadResource added in v0.34.0

func (cs *ClientSession) ReadResource(ctx context.Context, params *ReadResourceParams) (*ReadResourceResult, error)

ReadResource ask the server to read a resource and return its contents.

func (*ClientSession) Resources added in v0.34.0

func (cs *ClientSession) Resources(ctx context.Context, params *ListResourcesParams) iter.Seq2[Resource, error]

Resources provides an iterator for all resources available on the server, automatically fetching pages and managing cursors. The `params` argument can set the initial cursor. Iteration stops at the first encountered error, which will be yielded.

func (*ClientSession) SetLevel added in v0.34.0

func (cs *ClientSession) SetLevel(ctx context.Context, params *SetLevelParams) error

func (*ClientSession) Tools added in v0.34.0

func (cs *ClientSession) Tools(ctx context.Context, params *ListToolsParams) iter.Seq2[Tool, error]

Tools provides an iterator for all tools available on the server, automatically fetching pages and managing cursors. The `params` argument can set the initial cursor. Iteration stops at the first encountered error, which will be yielded.

func (*ClientSession) Wait added in v0.34.0

func (cs *ClientSession) Wait() error

Wait waits for the connection to be closed by the server. Generally, clients should be responsible for closing the connection.

type CommandTransport

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

A CommandTransport is a Transport that runs a command and communicates with it over stdin/stdout, using newline-delimited JSON.

func NewCommandTransport

func NewCommandTransport(cmd *exec.Cmd) *CommandTransport

NewCommandTransport returns a CommandTransport that runs the given command and communicates with it over stdin/stdout.

The resulting transport takes ownership of the command, starting it during CommandTransport.Connect, and stopping it when the connection is closed.

func (*CommandTransport) Connect

func (t *CommandTransport) Connect(ctx context.Context) (Stream, error)

Connect starts the command, and connects to it over stdin/stdout.

type Content

type Content struct {
	Type        string            `json:"type"`
	Text        string            `json:"text,omitempty"`
	MIMEType    string            `json:"mimeType,omitempty"`
	Data        []byte            `json:"data,omitempty"`
	Resource    *ResourceContents `json:"resource,omitempty"`
	Annotations *Annotations      `json:"annotations,omitempty"`
}

Content is the wire format for content. It represents the protocol types TextContent, ImageContent, AudioContent and EmbeddedResource. Use NewTextContent, NewImageContent, NewAudioContent or NewResourceContent to create one.

The Type field must be one of "text", "image", "audio" or "resource". The constructors above populate this field appropriately. Although at most one of Text, Data, and Resource should be non-zero, consumers of Content use the Type field to determine which value to use; values in the other fields are ignored.

func NewAudioContent added in v0.34.0

func NewAudioContent(data []byte, mimeType string) *Content

NewAudioContent creates a Content with audio data.

func NewImageContent added in v0.34.0

func NewImageContent(data []byte, mimeType string) *Content

NewImageContent creates a Content with image data.

func NewResourceContent added in v0.34.0

func NewResourceContent(resource *ResourceContents) *Content

NewResourceContent creates a Content with an embedded resource.

func NewTextContent added in v0.34.0

func NewTextContent(text string) *Content

NewTextContent creates a Content with text.

func (*Content) UnmarshalJSON added in v0.34.0

func (c *Content) UnmarshalJSON(data []byte) error

type CreateMessageParams added in v0.34.0

type CreateMessageParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// A request to include context from one or more MCP servers (including the
	// caller), to be attached to the prompt. The client MAY ignore this request.
	IncludeContext string `json:"includeContext,omitempty"`
	// The maximum number of tokens to sample, as requested by the server. The
	// client MAY choose to sample fewer tokens than requested.
	MaxTokens int64              `json:"maxTokens"`
	Messages  []*SamplingMessage `json:"messages"`
	// Optional metadata to pass through to the LLM provider. The format of this
	// metadata is provider-specific.
	Metadata struct {
	} `json:"metadata,omitempty"`
	// The server's preferences for which model to select. The client MAY ignore
	// these preferences.
	ModelPreferences *ModelPreferences `json:"modelPreferences,omitempty"`
	StopSequences    []string          `json:"stopSequences,omitempty"`
	// An optional system prompt the server wants to use for sampling. The client
	// MAY modify or omit this prompt.
	SystemPrompt string  `json:"systemPrompt,omitempty"`
	Temperature  float64 `json:"temperature,omitempty"`
}

func (*CreateMessageParams) GetMeta added in v0.34.0

func (x *CreateMessageParams) GetMeta() *Meta

type CreateMessageResult added in v0.34.0

type CreateMessageResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta    Meta     `json:"_meta,omitempty"`
	Content *Content `json:"content"`
	// The name of the model that generated the message.
	Model string `json:"model"`
	Role  Role   `json:"role"`
	// The reason why sampling stopped, if known.
	StopReason string `json:"stopReason,omitempty"`
}

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.

func (*CreateMessageResult) GetMeta added in v0.34.0

func (x *CreateMessageResult) GetMeta() *Meta

type GetPromptParams added in v0.34.0

type GetPromptParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// Arguments to use for templating the prompt.
	Arguments map[string]string `json:"arguments,omitempty"`
	// The name of the prompt or prompt template.
	Name string `json:"name"`
}

func (*GetPromptParams) GetMeta added in v0.34.0

func (x *GetPromptParams) GetMeta() *Meta

type GetPromptResult added in v0.34.0

type GetPromptResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// An optional description for the prompt.
	Description string           `json:"description,omitempty"`
	Messages    []*PromptMessage `json:"messages"`
}

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

func (*GetPromptResult) GetMeta added in v0.34.0

func (x *GetPromptResult) GetMeta() *Meta

type InMemoryTransport added in v0.34.0

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

An InMemoryTransport is a Transport that communicates over an in-memory network connection, using newline-delimited JSON.

func (*InMemoryTransport) Connect added in v0.34.0

func (t *InMemoryTransport) Connect(context.Context) (Stream, error)

type InitializeParams added in v0.34.0

type InitializeParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta         Meta                `json:"_meta,omitempty"`
	Capabilities *ClientCapabilities `json:"capabilities"`
	ClientInfo   *implementation     `json:"clientInfo"`
	// The latest version of the Model Context Protocol that the client supports.
	// The client MAY decide to support older versions as well.
	ProtocolVersion string `json:"protocolVersion"`
}

func (*InitializeParams) GetMeta added in v0.34.0

func (x *InitializeParams) GetMeta() *Meta

type InitializeResult added in v0.34.0

type InitializeResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta         Meta                `json:"_meta,omitempty"`
	Capabilities *serverCapabilities `json:"capabilities"`
	// 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.
	Instructions string `json:"instructions,omitempty"`
	// 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.
	ProtocolVersion string          `json:"protocolVersion"`
	ServerInfo      *implementation `json:"serverInfo"`
}

After receiving an initialize request from the client, the server sends this response.

func (*InitializeResult) GetMeta added in v0.34.0

func (x *InitializeResult) GetMeta() *Meta

type InitializedParams added in v0.34.0

type InitializedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
}

func (*InitializedParams) GetMeta added in v0.34.0

func (x *InitializedParams) GetMeta() *Meta

type ListPromptsParams added in v0.34.0

type ListPromptsParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// An opaque token representing the current pagination position. If provided,
	// the server should return results starting after this cursor.
	Cursor string `json:"cursor,omitempty"`
}

func (*ListPromptsParams) GetMeta added in v0.34.0

func (x *ListPromptsParams) GetMeta() *Meta

type ListPromptsResult added in v0.34.0

type ListPromptsResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// An opaque token representing the pagination position after the last returned
	// result. If present, there may be more results available.
	NextCursor string    `json:"nextCursor,omitempty"`
	Prompts    []*Prompt `json:"prompts"`
}

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

func (*ListPromptsResult) GetMeta added in v0.34.0

func (x *ListPromptsResult) GetMeta() *Meta

type ListResourcesParams added in v0.34.0

type ListResourcesParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// An opaque token representing the current pagination position. If provided,
	// the server should return results starting after this cursor.
	Cursor string `json:"cursor,omitempty"`
}

func (*ListResourcesParams) GetMeta added in v0.34.0

func (x *ListResourcesParams) GetMeta() *Meta

type ListResourcesResult added in v0.34.0

type ListResourcesResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// An opaque token representing the pagination position after the last returned
	// result. If present, there may be more results available.
	NextCursor string      `json:"nextCursor,omitempty"`
	Resources  []*Resource `json:"resources"`
}

The server's response to a resources/list request from the client.

func (*ListResourcesResult) GetMeta added in v0.34.0

func (x *ListResourcesResult) GetMeta() *Meta

type ListRootsParams added in v0.34.0

type ListRootsParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
}

func (*ListRootsParams) GetMeta added in v0.34.0

func (x *ListRootsParams) GetMeta() *Meta

type ListRootsResult added in v0.34.0

type ListRootsResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta  Meta    `json:"_meta,omitempty"`
	Roots []*Root `json:"roots"`
}

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.

func (*ListRootsResult) GetMeta added in v0.34.0

func (x *ListRootsResult) GetMeta() *Meta

type ListToolsParams added in v0.34.0

type ListToolsParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// An opaque token representing the current pagination position. If provided,
	// the server should return results starting after this cursor.
	Cursor string `json:"cursor,omitempty"`
}

func (*ListToolsParams) GetMeta added in v0.34.0

func (x *ListToolsParams) GetMeta() *Meta

type ListToolsResult added in v0.34.0

type ListToolsResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// An opaque token representing the pagination position after the last returned
	// result. If present, there may be more results available.
	NextCursor string  `json:"nextCursor,omitempty"`
	Tools      []*Tool `json:"tools"`
}

The server's response to a tools/list request from the client.

func (*ListToolsResult) GetMeta added in v0.34.0

func (x *ListToolsResult) GetMeta() *Meta

type LoggingHandler added in v0.34.0

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

A LoggingHandler is a slog.Handler for MCP.

func NewLoggingHandler added in v0.34.0

func NewLoggingHandler(ss *ServerSession, opts *LoggingHandlerOptions) *LoggingHandler

NewLoggingHandler creates a LoggingHandler that logs to the given ServerSession using a slog.JSONHandler.

func (*LoggingHandler) Enabled added in v0.34.0

func (h *LoggingHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled implements slog.Handler.Enabled by comparing level to the ServerSession's level.

func (*LoggingHandler) Handle added in v0.34.0

func (h *LoggingHandler) Handle(ctx context.Context, r slog.Record) error

Handle implements slog.Handler.Handle by writing the Record to a JSONHandler, then calling [ServerSession.LoggingMesssage] with the result.

func (*LoggingHandler) WithAttrs added in v0.34.0

func (h *LoggingHandler) WithAttrs(as []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.WithAttrs.

func (*LoggingHandler) WithGroup added in v0.34.0

func (h *LoggingHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler.WithGroup.

type LoggingHandlerOptions added in v0.34.0

type LoggingHandlerOptions struct {
	// The value for the "logger" field of logging notifications.
	LoggerName string
	// Limits the rate at which log messages are sent.
	// If zero, there is no rate limiting.
	MinInterval time.Duration
}

LoggingHandlerOptions are options for a LoggingHandler.

type LoggingLevel added in v0.34.0

type LoggingLevel string

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

type LoggingMessageParams added in v0.34.0

type LoggingMessageParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// The data to be logged, such as a string message or an object. Any JSON
	// serializable type is allowed here.
	Data any `json:"data"`
	// The severity of this log message.
	Level LoggingLevel `json:"level"`
	// An optional name of the logger issuing this message.
	Logger string `json:"logger,omitempty"`
}

func (*LoggingMessageParams) GetMeta added in v0.34.0

func (x *LoggingMessageParams) GetMeta() *Meta

type LoggingTransport added in v0.34.0

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

A LoggingTransport is a Transport that delegates to another transport, writing RPC logs to an io.Writer.

func NewLoggingTransport added in v0.34.0

func NewLoggingTransport(delegate Transport, w io.Writer) *LoggingTransport

NewLoggingTransport creates a new LoggingTransport that delegates to the provided transport, writing RPC logs to the provided io.Writer.

func (*LoggingTransport) Connect added in v0.34.0

func (t *LoggingTransport) Connect(ctx context.Context) (Stream, error)

Connect connects the underlying transport, returning a Stream that writes logs to the configured destination.

type Meta added in v0.34.0

type Meta struct {
	Data map[string]any `json:",omitempty"`
	// For params, the progress token can be nil, a string or an integer.
	// It should be nil for results.
	ProgressToken any `json:"progressToken,omitempty"`
}

func (Meta) MarshalJSON added in v0.34.0

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

func (*Meta) UnmarshalJSON added in v0.34.0

func (m *Meta) UnmarshalJSON(data []byte) error

type MethodHandler added in v0.34.0

type MethodHandler[S Session] func(
	ctx context.Context, _ S, method string, params Params) (result Result, err error)

A MethodHandler handles MCP messages. For methods, exactly one of the return values must be nil. For notifications, both must be nil.

type Middleware added in v0.34.0

type Middleware[S Session] func(MethodHandler[S]) MethodHandler[S]

Middleware is a function from MethodHandlers to MethodHandlers.

type ModelHint added in v0.34.0

type ModelHint struct {
	// 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`
	Name string `json:"name,omitempty"`
}

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.

type ModelPreferences added in v0.34.0

type ModelPreferences struct {
	// 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.
	CostPriority float64 `json:"costPriority,omitempty"`
	// 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.
	Hints []*ModelHint `json:"hints,omitempty"`
	// 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.
	IntelligencePriority float64 `json:"intelligencePriority,omitempty"`
	// 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.
	SpeedPriority float64 `json:"speedPriority,omitempty"`
}

The server's preferences for model selection, requested of the client during sampling.

Because LLMs can vary along multiple dimensions, choosing the "best" model is 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.

type Params added in v0.34.0

type Params interface {
	// Returns a pointer to the params's Meta field.
	GetMeta() *Meta
}

Params is a parameter (input) type for an MCP call or notification.

type PingParams added in v0.34.0

type PingParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
}

func (*PingParams) GetMeta added in v0.34.0

func (x *PingParams) GetMeta() *Meta

type Prompt

type Prompt struct {
	// A list of arguments to use for templating the prompt.
	Arguments []*PromptArgument `json:"arguments,omitempty"`
	// An optional description of what this prompt provides
	Description string `json:"description,omitempty"`
	// The name of the prompt or prompt template.
	Name string `json:"name"`
}

A prompt or prompt template that the server offers.

type PromptArgument added in v0.34.0

type PromptArgument struct {
	// A human-readable description of the argument.
	Description string `json:"description,omitempty"`
	// The name of the argument.
	Name string `json:"name"`
	// Whether this argument must be provided.
	Required bool `json:"required,omitempty"`
}

Describes an argument that a prompt can accept.

type PromptHandler

A PromptHandler handles a call to prompts/get.

type PromptListChangedParams added in v0.34.0

type PromptListChangedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
}

func (*PromptListChangedParams) GetMeta added in v0.34.0

func (x *PromptListChangedParams) GetMeta() *Meta

type PromptMessage added in v0.34.0

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

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.

type PromptOption

type PromptOption interface {
	// contains filtered or unexported methods
}

A PromptOption configures the behavior of a Prompt.

func Argument

func Argument(name string, opts ...SchemaOption) PromptOption

Argument configures the 'schema' of a prompt argument. If the argument does not exist, it is added.

Since prompt arguments are not a full JSON schema, Argument only accepts Required and Description, and panics when encountering any other option.

type ReadResourceParams added in v0.34.0

type ReadResourceParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// The URI of the resource to read. The URI can use any protocol; it is up to
	// the server how to interpret it.
	URI string `json:"uri"`
}

func (*ReadResourceParams) GetMeta added in v0.34.0

func (x *ReadResourceParams) GetMeta() *Meta

type ReadResourceResult added in v0.34.0

type ReadResourceResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta     Meta                `json:"_meta,omitempty"`
	Contents []*ResourceContents `json:"contents"`
}

The server's response to a resources/read request from the client.

func (*ReadResourceResult) GetMeta added in v0.34.0

func (x *ReadResourceResult) GetMeta() *Meta

type Resource

type Resource struct {
	// Optional annotations for the client.
	Annotations *Annotations `json:"annotations,omitempty"`
	// 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.
	Description string `json:"description,omitempty"`
	// The MIME type of this resource, if known.
	MIMEType string `json:"mimeType,omitempty"`
	// A human-readable name for this resource.
	//
	// This can be used by clients to populate UI elements.
	Name string `json:"name"`
	// The size of the raw resource content, in bytes (i.e., before base64 encoding
	// or any tokenization), if known.
	//
	// This can be used by Hosts to display file sizes and estimate context window
	// usage.
	Size int64 `json:"size,omitempty"`
	// The URI of this resource.
	URI string `json:"uri"`
}

A known resource that the server is capable of reading.

type ResourceContents added in v0.34.0

type ResourceContents struct {
	URI      string `json:"uri"` // resource location; must not be empty
	MIMEType string `json:"mimeType,omitempty"`
	Text     string `json:"text"`
	Blob     []byte `json:"blob,omitempty"` // if nil, then text; else blob
}

A ResourceContents is either a TextResourceContents or a BlobResourceContents. Use NewTextResourceContents or [NextBlobResourceContents] to create one.

func NewBlobResourceContents added in v0.34.0

func NewBlobResourceContents(uri, mimeType string, blob []byte) *ResourceContents

NewBlobResourceContents returns a ResourceContents containing a byte slice.

func NewTextResourceContents added in v0.34.0

func NewTextResourceContents(uri, mimeType, text string) *ResourceContents

NewTextResourceContents returns a ResourceContents containing text.

func (ResourceContents) MarshalJSON added in v0.34.0

func (r ResourceContents) MarshalJSON() ([]byte, error)

type ResourceHandler added in v0.34.0

A ResourceHandler is a function that reads a resource. If it cannot find the resource, it should return the result of calling ResourceNotFoundError.

type ResourceListChangedParams added in v0.34.0

type ResourceListChangedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
}

func (*ResourceListChangedParams) GetMeta added in v0.34.0

func (x *ResourceListChangedParams) GetMeta() *Meta

type Result added in v0.34.0

type Result interface {
	// Returns a pointer to the result's Meta field.
	GetMeta() *Meta
}

Result is a result of an MCP call.

type Role added in v0.34.0

type Role string

The sender or recipient of messages and data in a conversation.

type Root added in v0.34.0

type Root struct {
	// 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.
	Name string `json:"name,omitempty"`
	// 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.
	URI string `json:"uri"`
}

Represents a root directory or file that the server can operate on.

type RootsListChangedParams added in v0.34.0

type RootsListChangedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
}

func (*RootsListChangedParams) GetMeta added in v0.34.0

func (x *RootsListChangedParams) GetMeta() *Meta

type SSEClientTransport

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

An SSEClientTransport is a Transport that can communicate with an MCP endpoint serving the SSE transport defined by the 2024-11-05 version of the spec.

https://modelcontextprotocol.io/specification/2024-11-05/basic/transports

func NewSSEClientTransport

func NewSSEClientTransport(baseURL string) *SSEClientTransport

NewSSEClientTransport returns a new client transport that connects to the SSE server at the provided URL.

NewSSEClientTransport panics if the given URL is invalid.

func (*SSEClientTransport) Connect

func (c *SSEClientTransport) Connect(ctx context.Context) (Stream, error)

Connect connects through the client endpoint.

type SSEHandler

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

SSEHandler is an http.Handler that serves SSE-based MCP sessions as defined by the 2024-11-05 version of the MCP protocol:

https://modelcontextprotocol.io/specification/2024-11-05/basic/transports

Example
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"

	"golang.org/x/tools/internal/mcp"
)

type AddParams struct {
	X, Y int
}

func Add(ctx context.Context, cc *mcp.ServerSession, params *mcp.CallToolParams[AddParams]) (*mcp.CallToolResult, error) {
	return &mcp.CallToolResult{
		Content: []*mcp.Content{mcp.NewTextContent(fmt.Sprintf("%d", params.Arguments.X+params.Arguments.Y))},
	}, nil
}

func main() {
	server := mcp.NewServer("adder", "v0.0.1", nil)
	server.AddTools(mcp.NewTool("add", "add two numbers", Add))

	handler := mcp.NewSSEHandler(func(*http.Request) *mcp.Server { return server })
	httpServer := httptest.NewServer(handler)
	defer httpServer.Close()

	ctx := context.Background()
	transport := mcp.NewSSEClientTransport(httpServer.URL)
	client := mcp.NewClient("test", "v1.0.0", nil)
	cs, err := client.Connect(ctx, transport)
	if err != nil {
		log.Fatal(err)
	}
	defer cs.Close()

	res, err := mcp.CallTool(ctx, cs, &mcp.CallToolParams[map[string]any]{
		Name:      "add",
		Arguments: map[string]any{"x": 1, "y": 2},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.Content[0].Text)

}
Output:

3

func NewSSEHandler

func NewSSEHandler(getServer func(request *http.Request) *Server) *SSEHandler

NewSSEHandler returns a new SSEHandler that creates and manages MCP sessions created via incoming HTTP requests.

Sessions are created when the client issues a GET request to the server, which must accept text/event-stream responses (server-sent events). For each such request, a new SSEServerTransport is created with a distinct messages endpoint, and connected to the server returned by getServer. It is up to the user whether getServer returns a distinct Server for each new request, or reuses an existing server.

The SSEHandler also handles requests to the message endpoints, by delegating them to the relevant server transport.

func (*SSEHandler) ServeHTTP

func (h *SSEHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)

type SSEServerTransport added in v0.34.0

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

A SSEServerTransport is a logical SSE session created through a hanging GET request.

When connected, it returns the following Stream implementation:

  • Writes are SSE 'message' events to the GET response.
  • Reads are received from POSTs to the session endpoint, via SSEServerTransport.ServeHTTP.
  • Close terminates the hanging GET.

func NewSSEServerTransport added in v0.34.0

func NewSSEServerTransport(endpoint string, w http.ResponseWriter) *SSEServerTransport

NewSSEServerTransport creates a new SSE transport for the given messages endpoint, and hanging GET response.

Use SSEServerTransport.Connect to initiate the flow of messages.

The transport is itself an http.Handler. It is the caller's responsibility to ensure that the resulting transport serves HTTP requests on the given session endpoint.

Most callers should instead use an SSEHandler, which transparently handles the delegation to SSEServerTransports.

func (*SSEServerTransport) Connect added in v0.34.0

Connect sends the 'endpoint' event to the client. See SSEServerTransport for more details on the Stream implementation.

func (*SSEServerTransport) ServeHTTP added in v0.34.0

func (t *SSEServerTransport) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP handles POST requests to the transport endpoint.

type SamplingCapabilities added in v0.34.0

type SamplingCapabilities struct {
}

Present if the client supports sampling from an LLM.

type SamplingMessage added in v0.34.0

type SamplingMessage struct {
	Content *Content `json:"content"`
	Role    Role     `json:"role"`
}

Describes a message issued to or received from an LLM API.

type SchemaOption

type SchemaOption interface {
	// contains filtered or unexported methods
}

A SchemaOption configures a jsonschema.Schema.

func Description

func Description(desc string) SchemaOption

Description sets the provided schema description.

func Enum

func Enum(values ...any) SchemaOption

Enum sets the provided values as the "enum" value of the schema.

func Property

func Property(name string, opts ...SchemaOption) SchemaOption

Property configures the schema for the property of the given name. If there is no such property in the schema, it is created.

func Required

func Required(v bool) SchemaOption

Required sets whether the associated property is required. It is only valid when used in a Property option: using Required outside of Property panics.

func Schema

func Schema(schema *jsonschema.Schema) SchemaOption

Schema overrides the inferred schema with a shallow copy of the given schema.

type Server

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

A Server is an instance of an MCP server.

Servers expose server-side MCP features, which can serve one or more MCP sessions by using [Server.Start] or Server.Run.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"golang.org/x/tools/internal/mcp"
)

type SayHiParams struct {
	Name string `json:"name"`
}

func SayHi(ctx context.Context, cc *mcp.ServerSession, params *mcp.CallToolParams[SayHiParams]) (*mcp.CallToolResult, error) {
	return &mcp.CallToolResult{
		Content: []*mcp.Content{
			mcp.NewTextContent("Hi " + params.Arguments.Name),
		},
	}, nil
}

func main() {
	ctx := context.Background()
	clientTransport, serverTransport := mcp.NewInMemoryTransports()

	server := mcp.NewServer("greeter", "v0.0.1", nil)
	server.AddTools(mcp.NewTool("greet", "say hi", SayHi))

	serverSession, err := server.Connect(ctx, serverTransport)
	if err != nil {
		log.Fatal(err)
	}

	client := mcp.NewClient("client", "v0.0.1", nil)
	clientSession, err := client.Connect(ctx, clientTransport)
	if err != nil {
		log.Fatal(err)
	}

	res, err := mcp.CallTool(ctx, clientSession, &mcp.CallToolParams[map[string]any]{
		Name:      "greet",
		Arguments: map[string]any{"name": "user"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.Content[0].Text)

	clientSession.Close()
	serverSession.Wait()

}
Output:

Hi user

func NewServer

func NewServer(name, version string, opts *ServerOptions) *Server

NewServer creates a new MCP server. The resulting server has no features: add features using Server.AddTools, Server.AddPrompts and Server.AddResources.

The server can be connected to one or more MCP clients using [Server.Start] or Server.Run.

If non-nil, the provided options is used to configure the server.

func (*Server) AddPrompts

func (s *Server) AddPrompts(prompts ...*ServerPrompt)

AddPrompts adds the given prompts to the server, replacing any with the same names.

func (*Server) AddReceivingMiddleware added in v0.34.0

func (s *Server) AddReceivingMiddleware(middleware ...Middleware[*ServerSession])

AddReceivingMiddleware wraps the current receiving method handler using the provided middleware. Middleware is applied from right to left, so that the first one is executed first.

For example, AddReceivingMiddleware(m1, m2, m3) augments the method handler as m1(m2(m3(handler))).

Receiving middleware is called when a request is received. It is useful for tasks such as authentication, request logging and metrics.

func (*Server) AddResources added in v0.34.0

func (s *Server) AddResources(resources ...*ServerResource)

AddResources adds the given resource to the server and associates it with a ResourceHandler, which will be called when the client calls ClientSession.ReadResource. If a resource with the same URI already exists, this one replaces it. AddResource panics if a resource URI is invalid or not absolute (has an empty scheme).

func (*Server) AddSendingMiddleware added in v0.34.0

func (s *Server) AddSendingMiddleware(middleware ...Middleware[*ServerSession])

AddSendingMiddleware wraps the current sending method handler using the provided middleware. Middleware is applied from right to left, so that the first one is executed first.

For example, AddSendingMiddleware(m1, m2, m3) augments the method handler as m1(m2(m3(handler))).

Sending middleware is called when a request is sent. It is useful for tasks such as tracing, metrics, and adding progress tokens.

func (*Server) AddTools

func (s *Server) AddTools(tools ...*ServerTool)

AddTools adds the given tools to the server, replacing any with the same names.

func (*Server) Connect

func (s *Server) Connect(ctx context.Context, t Transport) (*ServerSession, error)

Connect connects the MCP server over the given transport and starts handling messages.

It returns a connection object that may be used to terminate the connection (with [Connection.Close]), or await client termination (with [Connection.Wait]).

func (*Server) RemovePrompts added in v0.34.0

func (s *Server) RemovePrompts(names ...string)

RemovePrompts removes the prompts with the given names. It is not an error to remove a nonexistent prompt.

func (*Server) RemoveResources added in v0.34.0

func (s *Server) RemoveResources(uris ...string)

RemoveResources removes the resources with the given URIs. It is not an error to remove a nonexistent resource.

func (*Server) RemoveTools added in v0.34.0

func (s *Server) RemoveTools(names ...string)

RemoveTools removes the tools with the given names. It is not an error to remove a nonexistent tool.

func (*Server) Run

func (s *Server) Run(ctx context.Context, t Transport) error

Run runs the server over the given transport, which must be persistent.

Run blocks until the client terminates the connection.

func (*Server) Sessions added in v0.34.0

func (s *Server) Sessions() iter.Seq[*ServerSession]

Sessions returns an iterator that yields the current set of server sessions.

type ServerOptions

type ServerOptions struct {
	// Optional instructions for connected clients.
	Instructions string
	// If non-nil, called when "notifications/initialized" is received.
	InitializedHandler func(context.Context, *ServerSession, *InitializedParams)
	// PageSize is the maximum number of items to return in a single page for
	// list methods (e.g. ListTools).
	PageSize int
	// If non-nil, called when "notifications/roots/list_changed" is received.
	RootsListChangedHandler func(context.Context, *ServerSession, *RootsListChangedParams)
}

ServerOptions is used to configure behavior of the server.

type ServerPrompt added in v0.34.0

type ServerPrompt struct {
	Prompt  *Prompt
	Handler PromptHandler
}

A Prompt is a prompt definition bound to a prompt handler.

func NewPrompt added in v0.34.0

func NewPrompt[TReq any](name, description string, handler func(context.Context, *ServerSession, TReq, *GetPromptParams) (*GetPromptResult, error), opts ...PromptOption) *ServerPrompt

NewPrompt is a helper that uses reflection to create a prompt for the given handler.

The arguments for the prompt are extracted from the request type for the handler. The handler request type must be a struct consisting only of fields of type string or *string. The argument names for the resulting prompt definition correspond to the JSON names of the request fields, and any fields that are not marked "omitempty" are considered required.

The handler is passed GetPromptParams so it can have access to prompt parameters other than name and arguments. At present, there are no such parameters.

type ServerResource added in v0.34.0

type ServerResource struct {
	Resource *Resource
	Handler  ResourceHandler
}

A ServerResource associates a Resource with its handler.

type ServerSession added in v0.34.0

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

A ServerSession is a logical connection from a single MCP client. Its methods can be used to send requests or notifications to the client. Create a session by calling Server.Connect.

Call ServerSession.Close to close the connection, or await client termination with ServerSession.Wait.

func (*ServerSession) Close added in v0.34.0

func (ss *ServerSession) Close() error

Close performs a graceful shutdown of the connection, preventing new requests from being handled, and waiting for ongoing requests to return. Close then terminates the connection.

func (*ServerSession) CreateMessage added in v0.34.0

func (ss *ServerSession) CreateMessage(ctx context.Context, params *CreateMessageParams) (*CreateMessageResult, error)

CreateMessage sends a sampling request to the client.

func (*ServerSession) ListRoots added in v0.34.0

func (ss *ServerSession) ListRoots(ctx context.Context, params *ListRootsParams) (*ListRootsResult, error)

ListRoots lists the client roots.

func (*ServerSession) LoggingMessage added in v0.34.0

func (ss *ServerSession) LoggingMessage(ctx context.Context, params *LoggingMessageParams) error

LoggingMessage sends a logging message to the client. The message is not sent if the client has not called SetLevel, or if its level is below that of the last SetLevel.

func (*ServerSession) Ping added in v0.34.0

func (ss *ServerSession) Ping(ctx context.Context, params *PingParams) error

Ping pings the client.

func (*ServerSession) Wait added in v0.34.0

func (ss *ServerSession) Wait() error

Wait waits for the connection to be closed by the client.

type ServerTool added in v0.34.0

type ServerTool struct {
	Tool    *Tool
	Handler ToolHandler[json.RawMessage]
}

A Tool is a tool definition that is bound to a tool handler.

func NewTool added in v0.34.0

func NewTool[TReq any](name, description string, handler ToolHandler[TReq], opts ...ToolOption) *ServerTool

NewTool is a helper to make a tool using reflection on the given handler.

If provided, variadic ToolOption values may be used to customize the tool.

The input schema for the tool is extracted from the request type for the handler, and used to unmmarshal and validate requests to the handler. This schema may be customized using the Input option.

The handler request type must translate to a valid schema, as documented by jsonschema.ForType; otherwise, NewTool panics.

TODO: just have the handler return a CallToolResult: returning []Content is going to be inconsistent with other server features.

type Session added in v0.34.0

type Session interface {
	*ClientSession | *ServerSession
	// contains filtered or unexported methods
}

A Session is either a ClientSession or a ServerSession.

type SetLevelParams added in v0.34.0

type SetLevelParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
	// 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/message.
	Level LoggingLevel `json:"level"`
}

func (*SetLevelParams) GetMeta added in v0.34.0

func (x *SetLevelParams) GetMeta() *Meta

type StdIOTransport added in v0.34.0

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

A StdIOTransport is a Transport that communicates over stdin/stdout using newline-delimited JSON.

func NewStdIOTransport

func NewStdIOTransport() *StdIOTransport

NewStdIOTransport constructs a transport that communicates over stdin/stdout.

func (*StdIOTransport) Connect added in v0.34.0

func (t *StdIOTransport) Connect(context.Context) (Stream, error)

type Stream

type Stream interface {
	jsonrpc2.Reader
	jsonrpc2.Writer
	io.Closer
}

A Stream is a bidirectional jsonrpc2 Stream.

type Tool

type Tool struct {
	// Optional additional tool information.
	Annotations *ToolAnnotations `json:"annotations,omitempty"`
	// A human-readable description of the tool.
	//
	// This can be used by clients to improve the LLM's understanding of available
	// tools. It can be thought of like a "hint" to the model.
	Description string `json:"description,omitempty"`
	// A JSON Schema object defining the expected parameters for the tool.
	InputSchema *jsonschema.Schema `json:"inputSchema"`
	// The name of the tool.
	Name string `json:"name"`
}

Definition for a tool the client can call.

type ToolAnnotations added in v0.34.0

type ToolAnnotations struct {
	// If true, the tool may perform destructive updates to its environment. If
	// false, the tool performs only additive updates.
	//
	// (This property is meaningful only when `readOnlyHint == false`)
	//
	// Default: true
	DestructiveHint bool `json:"destructiveHint,omitempty"`
	// If true, calling the tool repeatedly with the same arguments will have no
	// additional effect on the its environment.
	//
	// (This property is meaningful only when `readOnlyHint == false`)
	//
	// Default: false
	IdempotentHint bool `json:"idempotentHint,omitempty"`
	// If true, this tool may interact with an "open world" of external entities. If
	// false, the tool's domain of interaction is closed. For example, the world of
	// a web search tool is open, whereas that of a memory tool is not.
	//
	// Default: true
	OpenWorldHint bool `json:"openWorldHint,omitempty"`
	// If true, the tool does not modify its environment.
	//
	// Default: false
	ReadOnlyHint bool `json:"readOnlyHint,omitempty"`
	// A human-readable title for the tool.
	Title string `json:"title,omitempty"`
}

Additional properties describing a Tool to clients.

NOTE: all properties in ToolAnnotations are **hints**. They are not guaranteed to provide a faithful description of tool behavior (including descriptive properties like `title`).

Clients should never make tool use decisions based on ToolAnnotations received from untrusted servers.

type ToolHandler

type ToolHandler[TArgs any] func(context.Context, *ServerSession, *CallToolParams[TArgs]) (*CallToolResult, error)

A ToolHandler handles a call to tools/call.

type ToolListChangedParams added in v0.34.0

type ToolListChangedParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta Meta `json:"_meta,omitempty"`
}

func (*ToolListChangedParams) GetMeta added in v0.34.0

func (x *ToolListChangedParams) GetMeta() *Meta

type ToolOption

type ToolOption interface {
	// contains filtered or unexported methods
}

A ToolOption configures the behavior of a Tool.

func Input

func Input(opts ...SchemaOption) ToolOption

Input applies the provided SchemaOption configuration to the tool's input schema.

type Transport

type Transport interface {
	// Connect returns the logical stream.
	//
	// It is called exactly once by [Connect].
	Connect(ctx context.Context) (Stream, error)
}

A Transport is used to create a bidirectional connection between MCP client and server.

Transports should be used for at most one call to Server.Connect or [Client.Start].

Directories

Path Synopsis
examples
sse
internal
!+
!+
Package jsonschema is an implementation of the [JSON Schema specification], a JSON-based format for describing the structure of JSON data.
Package jsonschema is an implementation of the [JSON Schema specification], a JSON-based format for describing the structure of JSON data.

Jump to

Keyboard shortcuts

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