op

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: AGPL-3.0 Imports: 41 Imported by: 0

Documentation

Overview

Example (Cancellation)
package main

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	// For this example, we're going to be collecting observations from the
	// server and client.
	var clientResult, serverResult string
	var wg sync.WaitGroup
	wg.Add(2)

	// Create a server with a single slow tool.
	// When the client cancels its request, the server should observe
	// cancellation.
	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
	started := make(chan struct{}, 1) // signals that the server started handling the tool call
	mcp.AddTool(server, &mcp.Tool{Name: "slow"}, func(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
		started <- struct{}{}
		defer wg.Done()
		select {
		case <-time.After(5 * time.Second):
			serverResult = "tool done"
		case <-ctx.Done():
			serverResult = "tool canceled"
		}
		return &mcp.CallToolResult{}, nil, nil
	})

	// Connect a client to the server.
	client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
	ctx := context.Background()
	t1, t2 := mcp.NewInMemoryTransports()
	if _, err := server.Connect(ctx, t1, nil); err != nil {
		log.Fatal(err)
	}
	session, err := client.Connect(ctx, t2, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	// Make a tool call, asynchronously.
	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		defer wg.Done()
		_, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "slow"})
		clientResult = fmt.Sprintf("%v", err)
	}()

	// As soon as the server has started handling the call, cancel it from the
	// client side.
	<-started
	cancel()
	wg.Wait()

	fmt.Println(clientResult)
	fmt.Println(serverResult)
}
Output:
context canceled
tool canceled
Example (Lifecycle)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	ctx := context.Background()

	// Create a client and server.
	// Wait for the client to initialize the session.
	client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, &mcp.ServerOptions{
		InitializedHandler: func(context.Context, *mcp.InitializedRequest) {
			fmt.Println("initialized!")
		},
	})

	// Connect the server and client using in-memory transports.
	//
	// Connect the server first so that it's ready to receive initialization
	// messages from the client.
	t1, t2 := mcp.NewInMemoryTransports()
	serverSession, err := server.Connect(ctx, t1, nil)
	if err != nil {
		log.Fatal(err)
	}
	clientSession, err := client.Connect(ctx, t2, nil)
	if err != nil {
		log.Fatal(err)
	}

	// Now shut down the session by closing the client, and waiting for the
	// server session to end.
	if err := clientSession.Close(); err != nil {
		log.Fatal(err)
	}
	if err := serverSession.Wait(); err != nil {
		log.Fatal(err)
	}
}
Output:
initialized!
Example (Progress)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
	mcp.AddTool(server, &mcp.Tool{Name: "makeProgress"}, func(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
		if token := req.Params.GetProgressToken(); token != nil {
			for i := range 3 {
				params := &mcp.ProgressNotificationParams{
					Message:       "frobbing widgets",
					ProgressToken: token,
					Progress:      float64(i),
					Total:         2,
				}
				req.Session.NotifyProgress(ctx, params) // ignore error
			}
		}
		return &mcp.CallToolResult{}, nil, nil
	})
	client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, &mcp.ClientOptions{
		ProgressNotificationHandler: func(_ context.Context, req *mcp.ProgressNotificationClientRequest) {
			fmt.Printf("%s %.0f/%.0f\n", req.Params.Message, req.Params.Progress, req.Params.Total)
		},
	})
	ctx := context.Background()
	t1, t2 := mcp.NewInMemoryTransports()
	if _, err := server.Connect(ctx, t1, nil); err != nil {
		log.Fatal(err)
	}

	session, err := client.Connect(ctx, t2, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()
	if _, err := session.CallTool(ctx, &mcp.CallToolParams{
		Name: "makeProgress",
		Meta: mcp.Meta{"progressToken": "abc123"},
	}); err != nil {
		log.Fatal(err)
	}
}
Output:
frobbing widgets 0/2
frobbing widgets 1/2
frobbing widgets 2/2

Index

Examples

Constants

View Source
const (
	SystoolModeDefault   = "default"
	SystoolModeAllowlist = "allowlist"
	SystoolModeDisabled  = "disabled"
)
View Source
const (
	EnvLocal = "local"
	EnvCloud = "cloud"

	LocalUser = "local"
)
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 (
	ThreadEntryTypeMessageAppend = "message_append"
	ThreadEntryTypeMessageUpdate = "message_update"
	ThreadEntryTypeMessageAck    = "message_ack"
)
View Source
const (
	ThreadEntryWindowModeTail   = "tail"
	ThreadEntryWindowModeBefore = "before"
	ThreadEntryWindowModeAfter  = "after"
)
View Source
const (
	ThreadEntryTypeQueueEnqueue = "queue_enqueue"
	ThreadEntryTypeQueueDequeue = "queue_dequeue"
	ThreadEntryTypeQueueRemove  = "queue_remove"
	ThreadEntryTypeQueuePromote = "queue_promote"
)
View Source
const DefaultPageSize = 1000

DefaultPageSize is the default for ServerOptions.PageSize.

View Source
const ThreadEntryTypeCanonicalMessage = "canonical_message"
View Source
const ThreadEntryTypeMetaUpdate = "thread_meta_update"

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.

View Source
var ErrEventsPurged = errors.New("data purged")

ErrEventsPurged is the error that EventStore.After should return if the event just after the index is no longer available.

View Source
var ErrSessionMissing = errors.New("session not found")

ErrSessionMissing is returned when a Streamable HTTP server reports that the current MCP session is no longer present.

The MCP Streamable HTTP transport requires clients to reestablish a session after a 404 response for a request carrying an Mcp-Session-Id header.

View Source
var SystoolNames = []string{
	"shell",
	"read",
	"write",
	"edit",
	"agent_task",
	"message_publish",
	"message_update",
	"message_read",
	"message_subscribe",
	"message_ack",
}

Functions

func AddTool

func AddTool[In, Out any](s *Server, t *Tool, h ToolHandlerFor[In, Out])

AddTool adds a tool and typed tool handler to the server.

If the tool's input schema is nil, it is set to the schema inferred from the In type parameter. Types are inferred from Go types, and property descriptions are read from the 'jsonschema' struct tag. Internally, the SDK uses the github.com/google/jsonschema-go package for inference and validation. The In type argument must be a map or a struct, so that its inferred JSON Schema has type "object", as required by the spec. As a special case, if the In type is 'any', the tool's input schema is set to an empty object schema value.

If the tool's output schema is nil, and the Out type is not 'any', the output schema is set to the schema inferred from the Out type argument, which must also be a map or struct. If the Out type is 'any', the output schema is omitted.

Unlike Server.AddTool, AddTool does a lot automatically, and forces tools to conform to the MCP spec. See ToolHandlerFor for a detailed description of this automatic behavior.

Example (ComplexSchema)
package main

import (
	"context"
	"fmt"
	"log"
	"reflect"
	"time"

	"github.com/google/jsonschema-go/jsonschema"
	"github.com/modelcontextprotocol/go-sdk/mcp"
)

type Location struct {
	Name      string   `json:"name"`
	Latitude  *float64 `json:"latitude,omitempty"`
	Longitude *float64 `json:"longitude,omitempty"`
}

type Forecast struct {
	Forecast string      `json:"forecast" jsonschema:"description of the day's weather"`
	Type     WeatherType `json:"type" jsonschema:"type of weather"`
	Rain     float64     `json:"rain" jsonschema:"probability of rain, between 0 and 1"`
	High     float64     `json:"high" jsonschema:"high temperature"`
	Low      float64     `json:"low" jsonschema:"low temperature"`
}

type WeatherType string

const (
	Sunny        WeatherType = "sun"
	PartlyCloudy WeatherType = "partly_cloudy"
	Cloudy       WeatherType = "clouds"
	Rainy        WeatherType = "rain"
	Snowy        WeatherType = "snow"
)

type Probability float64

type WeatherInput struct {
	Location Location `json:"location" jsonschema:"user location"`
	Days     int      `json:"days" jsonschema:"number of days to forecast"`
}

type WeatherOutput struct {
	Summary       string      `json:"summary" jsonschema:"a summary of the weather forecast"`
	Confidence    Probability `json:"confidence" jsonschema:"confidence, between 0 and 1"`
	AsOf          time.Time   `json:"asOf" jsonschema:"the time the weather was computed"`
	DailyForecast []Forecast  `json:"dailyForecast" jsonschema:"the daily forecast"`
	Source        string      `json:"source,omitempty" jsonschema:"the organization providing the weather forecast"`
}

func WeatherTool(ctx context.Context, req *mcp.CallToolRequest, in WeatherInput) (*mcp.CallToolResult, WeatherOutput, error) {
	perfectWeather := WeatherOutput{
		Summary:    "perfect",
		Confidence: 1.0,
		AsOf:       time.Now(),
	}
	for range in.Days {
		perfectWeather.DailyForecast = append(perfectWeather.DailyForecast, Forecast{
			Forecast: "another perfect day",
			Type:     Sunny,
			Rain:     0.0,
			High:     72.0,
			Low:      72.0,
		})
	}
	return nil, perfectWeather, nil
}

func main() {
	// This example demonstrates a tool with a more 'realistic' input and output
	// schema. We use a combination of techniques to tune our input and output
	// schemas.

	// !+customschemas

	// Distinguished Go types allow custom schemas to be reused during inference.
	customSchemas := map[reflect.Type]*jsonschema.Schema{
		reflect.TypeFor[Probability](): {Type: "number", Minimum: jsonschema.Ptr(0.0), Maximum: jsonschema.Ptr(1.0)},
		reflect.TypeFor[WeatherType](): {Type: "string", Enum: []any{Sunny, PartlyCloudy, Cloudy, Rainy, Snowy}},
	}
	opts := &jsonschema.ForOptions{TypeSchemas: customSchemas}
	in, err := jsonschema.For[WeatherInput](opts)
	if err != nil {
		log.Fatal(err)
	}

	// Furthermore, we can tweak the inferred schema, in this case limiting
	// forecasts to 0-10 days.
	daysSchema := in.Properties["days"]
	daysSchema.Minimum = jsonschema.Ptr(0.0)
	daysSchema.Maximum = jsonschema.Ptr(10.0)

	// Output schema inference can reuse our custom schemas from input inference.
	out, err := jsonschema.For[WeatherOutput](opts)
	if err != nil {
		log.Fatal(err)
	}

	// Now add our tool to a server. Since we've customized the schemas, we need
	// to override the default schema inference.
	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
	mcp.AddTool(server, &mcp.Tool{
		Name:         "weather",
		InputSchema:  in,
		OutputSchema: out,
	}, WeatherTool)

	// !-customschemas

	ctx := context.Background()
	session, err := connect(ctx, server) // create an in-memory connection
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	// Check that the client observes the correct schemas.
	for t, err := range session.Tools(ctx, nil) {
		if err != nil {
			log.Fatal(err)
		}
		// Formatting the entire schemas would be too much output.
		// Just check that our customizations were effective.
		fmt.Println("max days:", jsonPath(t.InputSchema, "properties", "days", "maximum"))
		fmt.Println("max confidence:", jsonPath(t.OutputSchema, "properties", "confidence", "maximum"))
		fmt.Println("weather types:", jsonPath(t.OutputSchema, "properties", "dailyForecast", "items", "properties", "type", "enum"))
	}
}

func connect(ctx context.Context, server *mcp.Server) (*mcp.ClientSession, error) {
	t1, t2 := mcp.NewInMemoryTransports()
	if _, err := server.Connect(ctx, t1, nil); err != nil {
		return nil, err
	}
	client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
	return client.Connect(ctx, t2, nil)
}

func jsonPath(s any, path ...string) any {
	if len(path) == 0 {
		return s
	}
	return jsonPath(s.(map[string]any)[path[0]], path[1:]...)
}
Output:
max days: 10
max confidence: 1
weather types: [sun partly_cloudy clouds rain snow]
Example (CustomMarshalling)
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"reflect"
	"time"

	"github.com/google/jsonschema-go/jsonschema"
	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	// Sometimes when you want to customize the input or output schema for a
	// tool, you need to customize the schema of a single helper type that's used
	// in several places.
	//
	// For example, suppose you had a type that marshals/unmarshals like a
	// time.Time, and that type was used multiple times in your tool input.
	type MyDate struct {
		time.Time
	}
	type Input struct {
		Query string `json:"query,omitempty"`
		Start MyDate `json:"start,omitempty"`
		End   MyDate `json:"end,omitempty"`
	}

	// In this case, you can use jsonschema.For along with jsonschema.ForOptions
	// to customize the schema inference for your custom type.
	inputSchema, err := jsonschema.For[Input](&jsonschema.ForOptions{
		TypeSchemas: map[reflect.Type]*jsonschema.Schema{
			reflect.TypeFor[MyDate](): {Type: "string"},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
	toolHandler := func(context.Context, *mcp.CallToolRequest, Input) (*mcp.CallToolResult, any, error) {
		panic("not implemented")
	}
	mcp.AddTool(server, &mcp.Tool{Name: "my_tool", InputSchema: inputSchema}, toolHandler)

	ctx := context.Background()
	session, err := connect(ctx, server) // create an in-memory connection
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	for t, err := range session.Tools(ctx, nil) {
		if err != nil {
			log.Fatal(err)
		}
		schemaJSON, err := json.MarshalIndent(t.InputSchema, "", "\t")
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(t.Name, string(schemaJSON))
	}
}

func connect(ctx context.Context, server *mcp.Server) (*mcp.ClientSession, error) {
	t1, t2 := mcp.NewInMemoryTransports()
	if _, err := server.Connect(ctx, t1, nil); err != nil {
		return nil, err
	}
	client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
	return client.Connect(ctx, t2, nil)
}
Output:
my_tool {
	"additionalProperties": false,
	"properties": {
		"end": {
			"type": "string"
		},
		"query": {
			"type": "string"
		},
		"start": {
			"type": "string"
		}
	},
	"type": "object"
}

func BuildNodeID

func BuildNodeID(uid, hostID string, kind NodeKind, uri string, env string) string

BuildNodeID builds id in `kind-uuidv5` format from uid/hostID/kind/uri.

func BuildNodeIdentity

func BuildNodeIdentity(uid, hostID, kind, uri string, env string) string

func ComputeNodeID

func ComputeNodeID(identity string) string

ComputeNodeID returns a deterministic UUIDv5 suffix from identity.

func EstimateMessageTokens

func EstimateMessageTokens(m Message) int64

EstimateMessageTokens approximates token usage with a chars/4 heuristic. Includes Content, ReasoningContent (thinking), ContentParts, ToolCalls, text + thinking + toolCall blocks.

func EstimateMessagesTokens

func EstimateMessagesTokens(msgs []Message) int64

func GenerateFileID

func GenerateFileID() string

func GenerateMessageID

func GenerateMessageID() string

func GenerateThreadID

func GenerateThreadID() string

func GenerateTurnID

func GenerateTurnID() string

func GetUserTaskID

func GetUserTaskID() string

func NewInMemoryTransports

func NewInMemoryTransports() (*InMemoryTransport, *InMemoryTransport)

NewInMemoryTransports returns two InMemoryTransport objects that connect to each other.

The resulting transports are symmetrical: use either to connect to a server, and then the other to connect to a client. Servers must be connected before clients, as the client initializes the MCP session during connection.

func NormalizeNodeKind

func NormalizeNodeKind(kind string) string

func PathToURI

func PathToURI(path string, isDir ...bool) string

PathToURI converts a local path to a file:// URI. Optional isDir controls whether a trailing slash is appended.

func ResourceNotFoundError

func ResourceNotFoundError(uri string) error

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

func SerializeMessagesForSummary

func SerializeMessagesForSummary(msgs []Message) string

func URIToDir

func URIToDir(uri string) string

URIToDir extracts a local directory path from a file URI. For file paths that point to a file, its parent directory is returned.

func URIToPath

func URIToPath(uri string) string

URIToPath extracts the local path from a file:// URI. Returns empty string if URI is not a file:// URI.

Types

type AgentListChangedParams

type AgentListChangedParams struct {
	Meta `json:"_meta,omitempty"`
}

type AgentMeta

type AgentMeta struct {
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	Avatar      string   `json:"avatar,omitempty"`
	MaxToken    int64    `json:"maxToken,omitempty"`
	BindAgentID string   `json:"bindAgentID,omitempty"` // optional bind target agent node ID
	ToolServers []string `json:"toolServers,omitempty"` // tool server OpNode IDs
	SysTools    []string `json:"sysTools,omitempty"`    // allowlisted built-in systool names when SysToolMode=allowlist
	SysToolMode string   `json:"sysToolMode,omitempty"` // default | allowlist | disabled
	Skills      []string `json:"skills,omitempty"`      // skill OpNode IDs
	SubAgents   []string `json:"subAgents,omitempty"`   // agent OpNode IDs
	Model       string   `json:"model,omitempty"`       // local models.json modelKey
}

type Annotations

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., []Role{"user", "assistant"}).
	Audience []Role `json:"audience,omitempty"`
	// The moment the resource was last modified, as an ISO 8601 formatted string.
	//
	// Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z").
	//
	// Examples: last activity timestamp in an open file, timestamp when the
	// resource was attached, etc.
	LastModified string `json:"lastModified,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 AudioContent

type AudioContent struct {
	Data        []byte
	MIMEType    string
	Annotations *Annotations
}

AudioContent contains base64-encoded audio data.

func (AudioContent) MarshalJSON

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

type AuthConfig

type AuthConfig struct {
	BaseURL       string `json:"baseURL,omitempty" mapstructure:"baseURL"`
	Gateway       string `json:"gateway,omitempty" mapstructure:"gateway"`
	AIGateway     string `json:"aiGateway,omitempty" mapstructure:"aiGateway"`
	Token         string `json:"token,omitempty" mapstructure:"token"`
	UID           string `json:"uid,omitempty" mapstructure:"uid"`
	Email         string `json:"email,omitempty" mapstructure:"email"`
	ActiveOrgID   string `json:"activeOrgID,omitempty" mapstructure:"activeOrgID"`
	ActiveOrgName string `json:"activeOrgName,omitempty" mapstructure:"activeOrgName"`
	UpdatedAt     int64  `json:"updatedAt,omitempty" mapstructure:"updatedAt"`
}

type CallAgentHandler

type CallAgentHandler func(context.Context, *CallAgentRequest) (*CallAgentResult, error)

type CallAgentParams

type CallAgentParams struct {
	AgentID string `json:"agentID"`
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content,omitempty"`
}

func (*CallAgentParams) UnmarshalJSON

func (p *CallAgentParams) UnmarshalJSON(data []byte) error

type CallAgentRequest

type CallAgentRequest = ServerRequest[*CallAgentParams]

type CallAgentResult

type CallAgentResult struct {
	AgentID string `json:"agentID"`
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content"`
}

func (*CallAgentResult) UnmarshalJSON

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

type CallNodeParams

type CallNodeParams struct {
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content,omitempty"`
}

func (*CallNodeParams) UnmarshalJSON

func (p *CallNodeParams) UnmarshalJSON(data []byte) error

type CallNodeResult

type CallNodeResult struct {
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content"`
}

func (*CallNodeResult) UnmarshalJSON

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

type CallToolParams

type CallToolParams struct {
	// Meta is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// Name is the name of the tool to call.
	Name string `json:"name"`
	// Arguments holds the tool arguments. It can hold any value that can be
	// marshaled to JSON.
	Arguments any `json:"arguments,omitempty"`
}

CallToolParams is used by clients to call a tool.

func (*CallToolParams) GetProgressToken

func (x *CallToolParams) GetProgressToken() any

func (*CallToolParams) SetProgressToken

func (x *CallToolParams) SetProgressToken(t any)

type CallToolParamsRaw

type CallToolParamsRaw struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// Name is the name of the tool being called.
	Name string `json:"name"`
	// Arguments is the raw arguments received over the wire from the client. It
	// is the responsibility of the tool handler to unmarshal and validate the
	// Arguments (see [AddTool]).
	Arguments json.RawMessage `json:"arguments,omitempty"`
}

CallToolParamsRaw is passed to tool handlers on the server. Its arguments are not yet unmarshaled (hence "raw"), so that the handlers can perform unmarshaling themselves.

func (*CallToolParamsRaw) GetProgressToken

func (x *CallToolParamsRaw) GetProgressToken() any

func (*CallToolParamsRaw) SetProgressToken

func (x *CallToolParamsRaw) SetProgressToken(t any)

type CallToolRequest

type CallToolRequest = ServerRequest[*CallToolParamsRaw]

type CallToolResult

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

	// A list of content objects that represent the unstructured result of the tool
	// call.
	//
	// When using a [ToolHandlerFor] with structured output, if Content is unset
	// it will be populated with JSON text content corresponding to the
	// structured output value.
	Content []Content `json:"content"`

	// StructuredContent is an optional value that represents the structured
	// result of the tool call. It must marshal to a JSON object.
	//
	// When using a [ToolHandlerFor] with structured output, you should not
	// populate this field. It will be automatically populated with the typed Out
	// value.
	StructuredContent any `json:"structuredContent,omitempty"`

	// IsError reports whether the tool call ended in an error.
	//
	// If not set, this is assumed to be false (the call was successful).
	//
	// Any errors that originate from the tool should be reported inside the
	// Content field, 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.
	//
	// When using a [ToolHandlerFor], this field is automatically set when the
	// tool handler returns an error, and the error string is included as text in
	// the Content field.
	IsError bool `json:"isError,omitempty"`
	// contains filtered or unexported fields
}

A CallToolResult is the server's response to a tool call.

The ToolHandler and ToolHandlerFor handler functions return this result, though ToolHandlerFor populates much of it automatically as documented at each field.

func (*CallToolResult) UnmarshalJSON

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

UnmarshalJSON handles the unmarshalling of content into the Content interface.

type CancelledParams

type CancelledParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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) GetProgressToken

func (x *CancelledParams) GetProgressToken() any

func (*CancelledParams) SetProgressToken

func (x *CancelledParams) SetProgressToken(t any)

type CanonicalToolCall

type CanonicalToolCall struct {
	ID               string          `json:"id"`
	Name             string          `json:"name"`
	Arguments        map[string]any  `json:"arguments,omitempty"`
	RawArguments     string          `json:"rawArguments,omitempty"`
	ThoughtSignature string          `json:"thoughtSignature,omitempty"`
	Raw              json.RawMessage `json:"raw,omitempty"`
}

type CanonicalToolResult

type CanonicalToolResult struct {
	ToolCallID    string          `json:"toolCallID"`
	ToolName      string          `json:"toolName,omitempty"`
	IsError       bool            `json:"isError,omitempty"`
	OutputText    string          `json:"outputText,omitempty"`
	OutputContent []ContentBlock  `json:"outputContent,omitempty"`
	Raw           json.RawMessage `json:"raw,omitempty"`
}

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(impl *Implementation, opts *ClientOptions) *Client

NewClient creates a new Client.

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

The first argument must not be nil.

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

func (*Client) AddReceivingMiddleware

func (c *Client) AddReceivingMiddleware(middleware ...Middleware)

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

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

func (c *Client) AddSendingMiddleware(middleware ...Middleware)

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, _ *ClientSessionOptions) (cs *ClientSession, err error)

Connect begins an MCP session by connecting to a server over the given transport. The resulting session is initialized, and ready to use.

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

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.

type ClientCapabilities

type ClientCapabilities struct {
	// Experimental, non-standard capabilities that the client supports.
	Experimental map[string]any `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"`
	// Present if the client supports elicitation from the server.
	Elicitation *ElicitationCapabilities `json:"elicitation,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 {
	// CreateMessageHandler handles incoming requests for sampling/createMessage.
	//
	// Setting CreateMessageHandler to a non-nil value causes the client to
	// advertise the sampling capability.
	CreateMessageHandler func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error)
	// OpAgentHandler handles incoming requests for agents/op.
	OpAgentHandler func(context.Context, *OpAgentRequest) (*OpAgentResult, error)
	OpNodeHandler  func(context.Context, *OpNodeRequest) (*OpNodeResult, error)
	// Setting ElicitationHandler to a non-nil value causes the client to
	// advertise the elicitation capability.
	ElicitationHandler func(context.Context, *ElicitRequest) (*ElicitResult, error)
	// Handlers for notifications from the server.
	ToolListChangedHandler      func(context.Context, *ToolListChangedRequest)
	PromptListChangedHandler    func(context.Context, *PromptListChangedRequest)
	ResourceListChangedHandler  func(context.Context, *ResourceListChangedRequest)
	ResourceUpdatedHandler      func(context.Context, *ResourceUpdatedNotificationRequest)
	LoggingMessageHandler       func(context.Context, *LoggingMessageRequest)
	ProgressNotificationHandler func(context.Context, *ProgressNotificationClientRequest)
	InfoNotificationHandler     func(context.Context, *InfoNotificationClientRequest)
	// If non-zero, defines an interval for regular "ping" requests.
	// If the peer fails to respond to pings originating from the keepalive check,
	// the session is automatically closed.
	KeepAlive time.Duration
}

ClientOptions configures the behavior of the client.

type ClientRequest

type ClientRequest[P Params] struct {
	Session *ClientSession
	Params  P
}

A ClientRequest is a request to a client.

func (*ClientRequest[P]) GetExtra

func (r *ClientRequest[P]) GetExtra() *RequestExtra

func (*ClientRequest[P]) GetParams

func (r *ClientRequest[P]) GetParams() Params

func (*ClientRequest[P]) GetSession

func (r *ClientRequest[P]) GetSession() Session

type ClientSession

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 server termination with ClientSession.Wait.

func (*ClientSession) CallAgent

func (cs *ClientSession) CallAgent(ctx context.Context, params *CallAgentParams) (*CallAgentResult, error)

func (*ClientSession) CallNode

func (cs *ClientSession) CallNode(ctx context.Context, params *CallNodeParams) (*CallNodeResult, error)

func (*ClientSession) CallTool

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

CallTool calls the tool with the given parameters.

The params.Arguments can be any value that marshals into a JSON object.

func (*ClientSession) Close

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.

Close is idempotent and concurrency safe.

func (*ClientSession) Complete

func (cs *ClientSession) Complete(ctx context.Context, params *CompleteParams) (*CompleteResult, error)

func (*ClientSession) GetPrompt

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

GetPrompt gets a prompt from the server.

func (*ClientSession) ID

func (cs *ClientSession) ID() string

func (*ClientSession) InitializeResult

func (cs *ClientSession) InitializeResult() *InitializeResult

func (*ClientSession) ListPrompts

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

ListPrompts lists prompts that are currently available on the server.

func (*ClientSession) ListResourceTemplates

func (cs *ClientSession) ListResourceTemplates(ctx context.Context, params *ListResourceTemplatesParams) (*ListResourceTemplatesResult, error)

ListResourceTemplates lists the resource templates that are currently available on the server.

func (*ClientSession) ListResources

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

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

ListTools lists tools that are currently available on the server.

func (*ClientSession) NotifyInfo

func (cs *ClientSession) NotifyInfo(ctx context.Context, params *InfoNotificationParams) error

func (*ClientSession) NotifyProgress

func (cs *ClientSession) NotifyProgress(ctx context.Context, params *ProgressNotificationParams) error

NotifyProgress sends a progress notification from the client to the server associated with this session. This can be used if the client is performing a long-running task that was initiated by the server.

func (*ClientSession) OpNode

func (cs *ClientSession) OpNode(ctx context.Context, params *OpNodeParams) (*OpNodeResult, error)

func (*ClientSession) Ping

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

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

func (*ClientSession) Prompts

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

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

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

func (*ClientSession) ResourceTemplates

ResourceTemplates provides an iterator for all resource templates 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) Resources

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) SetLoggingLevel

func (cs *ClientSession) SetLoggingLevel(ctx context.Context, params *SetLoggingLevelParams) error

func (*ClientSession) Subscribe

func (cs *ClientSession) Subscribe(ctx context.Context, params *SubscribeParams) error

Subscribe sends a "resources/subscribe" request to the server, asking for notifications when the specified resource changes.

func (*ClientSession) Tools

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) Unsubscribe

func (cs *ClientSession) Unsubscribe(ctx context.Context, params *UnsubscribeParams) error

Unsubscribe sends a "resources/unsubscribe" request to the server, cancelling a previous subscription.

func (*ClientSession) Wait

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 ClientSessionOptions

type ClientSessionOptions struct{}

ClientSessionOptions is reserved for future use.

type CloudOSConfig

type CloudOSConfig struct {
	BaseURL string `json:"baseURL,omitempty" mapstructure:"baseURL"`
}

HostCloudOSConfig cloud file system access

type CommandTransport

type CommandTransport struct {
	Command *exec.Cmd
	// TerminateDuration controls how long Close waits after closing stdin
	// for the process to exit before sending SIGTERM.
	// If zero or negative, the default of 5s is used.
	TerminateDuration time.Duration
}

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

func (*CommandTransport) Connect

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

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

type CompactionConfig

type CompactionConfig struct {
	// Enabled toggles automatic compaction. Default: true.
	Enabled *bool `json:"enabled,omitempty" mapstructure:"enabled"`
	// ModelID is the model used to generate compaction summaries.
	ModelID string `json:"modelID,omitempty" mapstructure:"modelID"`
	// ReserveTokens is the token headroom reserved for the LLM response.
	// Compaction triggers when contextTokens > contextWindow - ReserveTokens.
	// Default: 16384.
	ReserveTokens int64 `json:"reserveTokens,omitempty" mapstructure:"reserveTokens"`
	// KeepRecentTokens is the number of recent tokens to keep verbatim
	// (not summarized) during compaction. Default: 20000.
	KeepRecentTokens int64 `json:"keepRecentTokens,omitempty" mapstructure:"keepRecentTokens"`
}

HostCompactionConfig controls history compaction behavior. Defaults aligned with pi-mono: reserveTokens=16384, keepRecentTokens=20000.

type CompleteContext

type CompleteContext struct {
	// Previously-resolved variables in a URI template or prompt.
	Arguments map[string]string `json:"arguments,omitempty"`
}

CompleteContext represents additional, optional context for completions.

type CompleteParams

type CompleteParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The argument's information
	Argument CompleteParamsArgument `json:"argument"`
	Context  *CompleteContext       `json:"context,omitempty"`
	Ref      *CompleteReference     `json:"ref"`
}

type CompleteParamsArgument

type CompleteParamsArgument struct {
	// The name of the argument
	Name string `json:"name"`
	// The value of the argument to use for completion matching.
	Value string `json:"value"`
}

type CompleteReference

type CompleteReference struct {
	Type string `json:"type"`
	// Name is relevant when Type is "ref/prompt".
	Name string `json:"name,omitempty"`
	// URI is relevant when Type is "ref/resource".
	URI string `json:"uri,omitempty"`
}

CompleteReference represents a completion reference type (ref/prompt ref/resource). The Type field determines which other fields are relevant.

func (*CompleteReference) MarshalJSON

func (r *CompleteReference) MarshalJSON() ([]byte, error)

func (*CompleteReference) UnmarshalJSON

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

type CompleteRequest

type CompleteRequest = ServerRequest[*CompleteParams]

type CompleteResult

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

The server's response to a completion/complete request

type CompletionCapabilities

type CompletionCapabilities struct{}

Present if the server supports argument autocompletion suggestions.

type CompletionResultDetails

type CompletionResultDetails struct {
	HasMore bool     `json:"hasMore,omitempty"`
	Total   int      `json:"total,omitempty"`
	Values  []string `json:"values"`
}

type Config

type Config struct {
	System      *SystemConfig     `json:"system,omitempty" mapstructure:"system"`
	User        *UserConfig       `json:"user,omitempty" mapstructure:"user"`
	MongoDB     MongoDBConfig     `json:"mongodb,omitempty" mapstructure:"mongodb"`
	Memory      MemoryConfig      `json:"memory,omitempty" mapstructure:"memory"`
	ObjectStore ObjectStoreConfig `json:"objectStore,omitempty" mapstructure:"objectStore"`
	Compaction  CompactionConfig  `json:"compaction,omitempty" mapstructure:"compaction"`
}

type Connection

type Connection interface {
	// Read reads the next message to process off the connection.
	//
	// Connections must allow Read to be called concurrently with Close. In
	// particular, calling Close should unblock a Read waiting for input.
	Read(context.Context) (jsonrpc.Message, error)

	// Write writes a new message to the connection.
	//
	// Write may be called concurrently, as calls or responses may occur
	// concurrently in user code.
	Write(context.Context, jsonrpc.Message) error

	// Close closes the connection. It is implicitly called whenever a Read or
	// Write fails.
	//
	// Close may be called multiple times, potentially concurrently.
	Close() error

	// TODO(#148): remove SessionID from this interface.
	SessionID() string
}

A Connection is a logical bidirectional JSON-RPC connection.

type Content

type Content interface {
	MarshalJSON() ([]byte, error)
	// contains filtered or unexported methods
}

A Content is a TextContent, ImageContent, AudioContent, ResourceLink, or EmbeddedResource.

type ContentBlock

type ContentBlock struct {
	Type                ContentBlockType     `json:"type"`
	Text                string               `json:"text,omitempty"`
	MimeType            string               `json:"mimeType,omitempty"`
	ImageData           string               `json:"imageData,omitempty"`
	TextSignature       string               `json:"textSignature,omitempty"`
	ThinkingReplayField string               `json:"thinkingReplayField,omitempty"`
	ThinkingSignature   string               `json:"thinkingSignature,omitempty"`
	ToolCall            *CanonicalToolCall   `json:"toolCall,omitempty"`
	ToolResult          *CanonicalToolResult `json:"toolResult,omitempty"`
	EncryptedContent    string               `json:"encryptedContent,omitempty"`
	Raw                 json.RawMessage      `json:"raw,omitempty"`
}

type ContentBlockType

type ContentBlockType string
const (
	BlockText       ContentBlockType = "text"
	BlockThinking   ContentBlockType = "thinking"
	BlockImage      ContentBlockType = "image"
	BlockToolCall   ContentBlockType = "tool_call"
	BlockToolResult ContentBlockType = "tool_result"
	BlockCompaction ContentBlockType = "compaction"
)

type ContentPart

type ContentPart struct {
	Type       string    `json:"type"`
	Text       string    `json:"text,omitempty"`
	Name       string    `json:"name,omitempty"`
	DisplayRef string    `json:"display_ref,omitempty"`
	ImageURL   *ImageURL `json:"image_url,omitempty"`
}

ContentPart is a multi-modal message block. We currently only consume text parts in opagent-runtime.

type ContentType

type ContentType string
const (
	ContentTypeText  ContentType = "text"
	ContentTypeImage ContentType = "image"
	ContentTypeAudio ContentType = "audio"
	ContentTypeJson  ContentType = "json"
)

type ConversationMessage

type ConversationMessage struct {
	Role          ConversationRole  `json:"role"`
	Content       []ContentBlock    `json:"content,omitempty"`
	Timestamp     int64             `json:"timestamp,omitempty"`
	ProviderState *ProviderState    `json:"providerState,omitempty"`
	Usage         *MessageUsage     `json:"usage,omitempty"`
	StopReason    MessageStopReason `json:"stopReason,omitempty"`
	Raw           json.RawMessage   `json:"raw,omitempty"`
}

type ConversationRole

type ConversationRole string
const (
	RoleCanonicalSystem     ConversationRole = "system"
	RoleCanonicalDeveloper  ConversationRole = "developer"
	RoleCanonicalUser       ConversationRole = "user"
	RoleCanonicalAssistant  ConversationRole = "assistant"
	RoleCanonicalTool       ConversationRole = "tool_result"
	RoleCanonicalCompaction ConversationRole = "compaction"
)

type CreateMessageParams

type CreateMessageParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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 any `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) GetProgressToken

func (x *CreateMessageParams) GetProgressToken() any

func (*CreateMessageParams) SetProgressToken

func (x *CreateMessageParams) SetProgressToken(t any)

type CreateMessageRequest

type CreateMessageRequest = ClientRequest[*CreateMessageParams]

type CreateMessageResult

type CreateMessageResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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) UnmarshalJSON

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

type EditorCompletionBlock

type EditorCompletionBlock struct {
	Text     string `json:"text,omitempty"`
	Start    int64  `json:"start,omitempty"`
	End      int64  `json:"end,omitempty"`
	Kind     string `json:"kind,omitempty"`
	Language string `json:"language,omitempty"`
}

type EditorCompletionCancelParams

type EditorCompletionCancelParams struct {
	RequestID string `json:"requestID"`
}

type EditorCompletionRequest

type EditorCompletionRequest struct {
	RequestID       string                 `json:"requestID"`
	AgentID         string                 `json:"agentID,omitempty"`
	ModelKey        string                 `json:"modelKey,omitempty"`
	ThinkingLevel   string                 `json:"thinkingLevel,omitempty"`
	EditorKind      string                 `json:"editorKind,omitempty"`
	LanguageID      string                 `json:"languageId,omitempty"`
	DocumentPath    string                 `json:"documentPath,omitempty"`
	CursorOffset    int64                  `json:"cursorOffset"`
	Prefix          string                 `json:"prefix,omitempty"`
	Suffix          string                 `json:"suffix,omitempty"`
	CurrentBlock    *EditorCompletionBlock `json:"currentBlock,omitempty"`
	PreviousBlock   *EditorCompletionBlock `json:"previousBlock,omitempty"`
	NextBlock       *EditorCompletionBlock `json:"nextBlock,omitempty"`
	MaxOutputTokens int64                  `json:"maxOutputTokens,omitempty"`
	Meta            Meta                   `json:"_meta,omitempty"`
}

type EditorCompletionResult

type EditorCompletionResult struct {
	RequestID   string `json:"requestID"`
	InsertText  string `json:"insertText"`
	ReplaceFrom int64  `json:"replaceFrom"`
	ReplaceTo   int64  `json:"replaceTo"`
	StopReason  string `json:"stopReason,omitempty"`
	ModelKey    string `json:"modelKey,omitempty"`
}

type ElicitParams

type ElicitParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The mode of elicitation to use.
	//
	// If unset, will be inferred from the other fields.
	Mode string `json:"mode"`
	// The message to present to the user.
	Message string  `json:"message"`
	Content Content `json:"content"`
	// A JSON schema object defining the requested elicitation schema.
	//
	// From the server, this field may be set to any value that can JSON-marshal
	// to valid JSON schema (including json.RawMessage for raw schema values).
	// Internally, the SDK uses github.com/google/jsonschema-go for validation,
	// which only supports the 2020-12 draft of the JSON schema spec.
	//
	// From the client, this field will use the default JSON marshaling (a
	// map[string]any).
	//
	// Only top-level properties are allowed, without nesting.
	//
	// This is only used for "form" elicitation.
	RequestedSchema any `json:"requestedSchema,omitempty"`
	// The URL to present to the user.
	//
	// This is only used for "url" elicitation.
	URL string `json:"url,omitempty"`
	// The ID of the elicitation.
	//
	// This is only used for "url" elicitation.
	ElicitationID string `json:"elicitationId,omitempty"`
}

A request from the server to elicit additional information from the user via the client.

func (*ElicitParams) GetProgressToken

func (x *ElicitParams) GetProgressToken() any

func (*ElicitParams) SetProgressToken

func (x *ElicitParams) SetProgressToken(t any)

type ElicitRequest

type ElicitRequest = ClientRequest[*ElicitParams]

type ElicitResult

type ElicitResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The user action in response to the elicitation.
	// - "accept": User submitted the form/confirmed the action
	// - "decline": User explicitly declined the action
	// - "cancel": User dismissed without making an explicit choice
	Action string `json:"action"`
	// The submitted form data, only present when action is "accept".
	// Contains values matching the requested schema.
	Content map[string]any `json:"content,omitempty"`
}

The client's response to an elicitation/create request from the server.

type ElicitationCapabilities

type ElicitationCapabilities struct{}

ElicitationCapabilities describes the capabilities for elicitation.

type EmbeddedResource

type EmbeddedResource struct {
	Resource    *ResourceContents
	Annotations *Annotations
}

EmbeddedResource contains embedded resources.

func (*EmbeddedResource) MarshalJSON

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

type Event

type Event struct {
	Name string // the "event" field
	ID   string // the "id" field
	Data []byte // the "data" field
}

An Event is a server-sent event. See https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#fields.

func (Event) Empty

func (e Event) Empty() bool

Empty reports whether the Event is empty.

type EventStore

type EventStore interface {
	// Open is called when a new stream is created. It may be used to ensure that
	// the underlying data structure for the stream is initialized, making it
	// ready to store and replay event streams.
	Open(_ context.Context, sessionID, streamID string) error

	// Append appends data for an outgoing event to given stream, which is part of the
	// given session.
	Append(_ context.Context, sessionID, streamID string, data []byte) error

	// After returns an iterator over the data for the given session and stream, beginning
	// just after the given index.
	//
	// Once the iterator yields a non-nil error, it will stop.
	// After's iterator must return an error immediately if any data after index was
	// dropped; it must not return partial results.
	// The stream must have been opened previously (see [EventStore.Open]).
	After(_ context.Context, sessionID, streamID string, index int) iter.Seq2[[]byte, error]

	// SessionClosed informs the store that the given session is finished, along
	// with all of its streams.
	//
	// A store cannot rely on this method being called for cleanup. It should institute
	// additional mechanisms, such as timeouts, to reclaim storage.
	SessionClosed(_ context.Context, sessionID string) error
}

An EventStore tracks data for SSE streams. A single EventStore suffices for all sessions, since session IDs are globally unique. So one EventStore can be created per process, for all Servers in the process. Such a store is able to bound resource usage for the entire process.

All of an EventStore's methods must be safe for use by multiple goroutines.

type FSObjectStoreConfig

type FSObjectStoreConfig struct {
	// BaseDir: 存放对象的根目录
	BaseDir string `json:"baseDir,omitempty" mapstructure:"baseDir"`
}

type GeneralContent

type GeneralContent struct {
	Content Content `json:"content"`
	Meta    Meta    `json:"meta,omitempty"`
}

func (*GeneralContent) UnmarshalJSON

func (p *GeneralContent) UnmarshalJSON(data []byte) error

type GetPromptParams

type GetPromptParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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) GetProgressToken

func (x *GetPromptParams) GetProgressToken() any

func (*GetPromptParams) SetProgressToken

func (x *GetPromptParams) SetProgressToken(t any)

type GetPromptRequest

type GetPromptRequest = ServerRequest[*GetPromptParams]

type GetPromptResult

type GetPromptResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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.

type HeartbeatConfig

type HeartbeatConfig struct {
	Enabled  *bool  `json:"enabled,omitempty" mapstructure:"enabled"`
	Interval string `json:"interval,omitempty" mapstructure:"interval"`
}

HeartbeatConfig holds heartbeat reporter controls.

type HostSecretGetResponse

type HostSecretGetResponse struct {
	SecretKeyID string            `json:"secretKeyId,omitempty"`
	Value       string            `json:"value,omitempty"`
	Secrets     map[string]string `json:"secrets,omitempty"`
}

type IOTransport

type IOTransport struct {
	Reader io.ReadCloser
	Writer io.WriteCloser
}

An IOTransport is a Transport that communicates over separate io.ReadCloser and io.WriteCloser using newline-delimited JSON.

func (*IOTransport) Connect

func (t *IOTransport) Connect(context.Context) (Connection, error)

Connect implements the Transport interface.

type Icon

type Icon struct {
	// Source is A URI pointing to the icon resource (required). This can be:
	// - An HTTP/HTTPS URL pointing to an image file
	// - A data URI with base64-encoded image data
	Source string `json:"src"`
	// Optional MIME type if the server's type is missing or generic
	MIMEType string `json:"mimeType,omitempty"`
	// Optional size specification (e.g., ["48x48"], ["any"] for scalable formats like SVG, or ["48x48", "96x96"] for multiple sizes)
	Sizes []string `json:"sizes,omitempty"`
	// Optional Theme of the icon, e.g., "light" or "dark"
	Theme string `json:"theme,omitempty"`
}

Icon provides visual identifiers for their resources, tools, prompts, and implementations See [/specification/draft/basic/index#icons] for notes on icons

TODO(iamsurajbobade): update specification url from draft.

type ImageContent

type ImageContent struct {
	Annotations *Annotations
	Data        []byte // base64-encoded
	MIMEType    string
}

ImageContent contains base64-encoded image data.

func (*ImageContent) MarshalJSON

func (c *ImageContent) MarshalJSON() ([]byte, error)

type ImageURL

type ImageURL struct {
	URL    string `json:"url"`
	Detail string `json:"detail,omitempty"`
}

type Implementation

type Implementation struct {
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	Title   string `json:"title,omitempty"`
	Version string `json:"version"`
	// WebsiteURL for the server, if any.
	WebsiteURL string `json:"websiteUrl,omitempty"`
	// Icons for the Server, if any.
	Icons []Icon `json:"icons,omitempty"`
}

An Implementation describes the name and version of an MCP implementation, with an optional title for UI representation.

type InMemoryTransport

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.

InMemoryTransports should be constructed using NewInMemoryTransports, which returns two transports connected to each other.

func (*InMemoryTransport) Connect

Connect implements the Transport interface.

type InfoNotificationClientRequest

type InfoNotificationClientRequest = ClientRequest[*InfoNotificationParams]

type InfoNotificationParams

type InfoNotificationParams struct {
	OpCode  OpCode `json:"opcode"`
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content"`
}

func (*InfoNotificationParams) UnmarshalJSON

func (p *InfoNotificationParams) UnmarshalJSON(data []byte) error

UnmarshalJSON handles the unmarshalling of content into the Content interface.

type InfoNotificationServerRequest

type InfoNotificationServerRequest = ServerRequest[*InfoNotificationParams]

type InitializeParams

type InitializeParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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) GetProgressToken

func (x *InitializeParams) GetProgressToken() any

func (*InitializeParams) SetProgressToken

func (x *InitializeParams) SetProgressToken(t any)

type InitializeRequest

type InitializeRequest = ClientRequest[*InitializeParams]

type InitializeResult

type InitializeResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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.

type InitializedParams

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

func (*InitializedParams) GetProgressToken

func (x *InitializedParams) GetProgressToken() any

func (*InitializedParams) SetProgressToken

func (x *InitializedParams) SetProgressToken(t any)

type InitializedRequest

type InitializedRequest = ServerRequest[*InitializedParams]

type JsonContent

type JsonContent struct {
	Raw json.RawMessage `json:"payload"`
}

func NewJsonContent

func NewJsonContent(data map[string]any) (*JsonContent, error)

func NewJsonContentRaw

func NewJsonContentRaw(data json.RawMessage) *JsonContent

func (*JsonContent) MarshalJSON

func (c *JsonContent) MarshalJSON() ([]byte, error)

func (*JsonContent) Unmarshal

func (c *JsonContent) Unmarshal(v any) error

type ListPromptsParams

type ListPromptsParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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) GetProgressToken

func (x *ListPromptsParams) GetProgressToken() any

func (*ListPromptsParams) SetProgressToken

func (x *ListPromptsParams) SetProgressToken(t any)

type ListPromptsRequest

type ListPromptsRequest = ServerRequest[*ListPromptsParams]

type ListPromptsResult

type ListPromptsResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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.

type ListResourceTemplatesParams

type ListResourceTemplatesParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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 (*ListResourceTemplatesParams) GetProgressToken

func (x *ListResourceTemplatesParams) GetProgressToken() any

func (*ListResourceTemplatesParams) SetProgressToken

func (x *ListResourceTemplatesParams) SetProgressToken(t any)

type ListResourceTemplatesRequest

type ListResourceTemplatesRequest = ServerRequest[*ListResourceTemplatesParams]

type ListResourceTemplatesResult

type ListResourceTemplatesResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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"`
	ResourceTemplates []*ResourceTemplate `json:"resourceTemplates"`
}

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

type ListResourcesParams

type ListResourcesParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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) GetProgressToken

func (x *ListResourcesParams) GetProgressToken() any

func (*ListResourcesParams) SetProgressToken

func (x *ListResourcesParams) SetProgressToken(t any)

type ListResourcesRequest

type ListResourcesRequest = ServerRequest[*ListResourcesParams]

type ListResourcesResult

type ListResourcesResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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.

type ListRootsParams

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

func (*ListRootsParams) GetProgressToken

func (x *ListRootsParams) GetProgressToken() any

func (*ListRootsParams) SetProgressToken

func (x *ListRootsParams) SetProgressToken(t any)

type ListRootsRequest

type ListRootsRequest = ClientRequest[*ListRootsParams]

type ListRootsResult

type ListRootsResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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.

type ListToolsParams

type ListToolsParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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) GetProgressToken

func (x *ListToolsParams) GetProgressToken() any

func (*ListToolsParams) SetProgressToken

func (x *ListToolsParams) SetProgressToken(t any)

type ListToolsRequest

type ListToolsRequest = ServerRequest[*ListToolsParams]

type ListToolsResult

type ListToolsResult struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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.

type LoggingCapabilities

type LoggingCapabilities struct{}

Present if the server supports sending log messages to the client.

type LoggingHandler

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

A LoggingHandler is a slog.Handler for MCP.

func NewLoggingHandler

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

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

func (*LoggingHandler) Enabled

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

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.LoggingMessage] with the result.

func (*LoggingHandler) WithAttrs

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

WithAttrs implements slog.Handler.WithAttrs.

func (*LoggingHandler) WithGroup

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

WithGroup implements slog.Handler.WithGroup.

type LoggingHandlerOptions

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

LoggingHandlerOptions are options for a LoggingHandler.

type LoggingLevel

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

type LoggingMessageParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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) GetProgressToken

func (x *LoggingMessageParams) GetProgressToken() any

func (*LoggingMessageParams) SetProgressToken

func (x *LoggingMessageParams) SetProgressToken(t any)

type LoggingMessageRequest

type LoggingMessageRequest = ClientRequest[*LoggingMessageParams]

type LoggingTransport

type LoggingTransport struct {
	Transport Transport
	Writer    io.Writer
}

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

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"slices"
	"strings"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	ctx := context.Background()
	t1, t2 := mcp.NewInMemoryTransports()
	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
	serverSession, err := server.Connect(ctx, t1, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer serverSession.Close()

	client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
	var b bytes.Buffer
	logTransport := &mcp.LoggingTransport{Transport: t2, Writer: &b}
	clientSession, err := client.Connect(ctx, logTransport, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer clientSession.Close()

	// Sort for stability: reads are concurrent to writes.
	for _, line := range slices.Sorted(strings.SplitSeq(b.String(), "\n")) {
		fmt.Println(line)
	}

}
Output:
read: {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"logging":{}},"protocolVersion":"2025-06-18","serverInfo":{"name":"server","version":"v0.0.1"}}}
write: {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"client","version":"v0.0.1"},"protocolVersion":"2025-06-18","capabilities":{"roots":{"listChanged":true}}}}
write: {"jsonrpc":"2.0","method":"notifications/initialized","params":{}}

func (*LoggingTransport) Connect

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

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

type LoopResult

type LoopResult struct {
	LoopID           string `json:"loopID"`
	LoopName         string `json:"loopName"`
	ThreadID         string `json:"threadID"`
	AgentName        string `json:"agentName"`
	UserInput        string `json:"userInput"`
	TotalSteps       int64  `json:"totalSteps"`
	TotalTokens      int64  `json:"totalTokens"`
	CompletionTokens int64  `json:"completionTokens"`
	PromptTokens     int64  `json:"promptTokens"`
	Status           Status `json:"status"`
	Error            string `json:"error,omitempty"`
	Result           string `json:"result"`
}

type MemoryConfig

type MemoryConfig struct {
	Storage    string `json:"storage" mapstructure:"storage"`
	Cache      string `json:"cache,omitempty" mapstructure:"cache"`
	SQLitePath string `json:"sqlitePath,omitempty" mapstructure:"sqlitePath"`
}

type MemoryEventStore

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

A MemoryEventStore is an EventStore backed by memory.

func NewMemoryEventStore

func NewMemoryEventStore(opts *MemoryEventStoreOptions) *MemoryEventStore

NewMemoryEventStore creates a MemoryEventStore with the default value for MaxBytes.

func (*MemoryEventStore) After

func (s *MemoryEventStore) After(_ context.Context, sessionID, streamID string, index int) iter.Seq2[[]byte, error]

After implements EventStore.After.

func (*MemoryEventStore) Append

func (s *MemoryEventStore) Append(_ context.Context, sessionID, streamID string, data []byte) error

Append implements EventStore.Append by recording data in memory.

func (*MemoryEventStore) MaxBytes

func (s *MemoryEventStore) MaxBytes() int

MaxBytes returns the maximum number of bytes that the store will retain before purging data.

func (*MemoryEventStore) Open

func (s *MemoryEventStore) Open(_ context.Context, sessionID, streamID string) error

Open implements EventStore.Open. It ensures that the underlying data structures for the given session are initialized and ready for use.

func (*MemoryEventStore) SessionClosed

func (s *MemoryEventStore) SessionClosed(_ context.Context, sessionID string) error

SessionClosed implements EventStore.SessionClosed.

func (*MemoryEventStore) SetMaxBytes

func (s *MemoryEventStore) SetMaxBytes(n int)

SetMaxBytes sets the maximum number of bytes the store will retain before purging data. The argument must not be negative. If it is zero, a suitable default will be used. SetMaxBytes can be called at any time. The size of the store will be adjusted immediately.

type MemoryEventStoreOptions

type MemoryEventStoreOptions struct{}

MemoryEventStoreOptions are options for a MemoryEventStore.

type Message

type Message struct {
	Role MessageRole `json:"role"`

	// Content is used by system/developer/user/assistant/tool/function.
	// For assistant tool-call messages, Content is often empty.
	Content string `json:"content,omitempty"`

	// ContentParts enables future multi-modal inputs. If non-empty, it should be
	// treated as the primary content source.
	ContentParts []ContentPart `json:"content_parts,omitempty"`

	// ReasoningContent stores provider-specific "thinking" content for assistant messages.
	// Some providers require this field to be replayed across tool-calls.
	ReasoningContent string `json:"reasoning_content,omitempty"`

	// ReasoningReplayField records which OpenAI-compatible assistant message field
	// originally carried ReasoningContent (for example reasoning_content,
	// reasoning, or reasoning_text). This is replay metadata, not user-visible text,
	// and should only be reused for same-provider continuation.
	ReasoningReplayField string `json:"reasoning_replay_field,omitempty"`

	// ReasoningSignature stores provider-specific reasoning continuation state.
	// Anthropic extended thinking requires this field to be replayed together with
	// reasoning_content on the next turn, otherwise upstream validation fails.
	ReasoningSignature string `json:"reasoning_signature,omitempty"`

	// ToolCalls is only valid for assistant messages that invoke tools.
	ToolCalls []MessageToolCall `json:"tool_calls,omitempty"`

	// ToolCallID links a tool result message to a previous assistant tool call.
	ToolCallID string `json:"tool_call_id,omitempty"`

	// Name is used by "function" and sometimes "tool" messages in OpenAI formats.
	Name string `json:"name,omitempty"`

	// Timestamp is Unix milliseconds. Optional but useful for persistence / UI.
	Timestamp int64 `json:"timestamp,omitempty"`

	// Usage stores LLM-reported token usage. Only populated on assistant messages
	// after an LLM response. Used by hybrid context estimation (pi-mono pattern):
	// real API usage from the last assistant + estimate only trailing messages.
	Usage *MessageUsage `json:"usage,omitempty"`

	// StopReason marks how the assistant turn ended. This is persisted so
	// replay logic can distinguish complete turns from interrupted/error tails.
	StopReason MessageStopReason `json:"stop_reason,omitempty"`

	// ResponseID stores the upstream Responses API response.id for assistant
	// messages generated via /v1/responses.
	ResponseID string `json:"response_id,omitempty"`
}

Message is the strongly typed internal representation for messages. This is the single source-of-truth for: - LLM conversion (OpenAI SDK) - message history persistence (JSONL/Mongo)

func DecodeUserMessageContent

func DecodeUserMessageContent(content Content) (Message, error)

func NewAssistantMessage

func NewAssistantMessage(content string) Message

func NewAssistantMessageWithReasoning

func NewAssistantMessageWithReasoning(content, reasoningContent string) Message

func NewAssistantToolCalls

func NewAssistantToolCalls(calls []MessageToolCall) Message

func NewAssistantToolCallsWithReasoning

func NewAssistantToolCallsWithReasoning(content, reasoningContent string, calls []MessageToolCall) Message

func NewToolResultMessage

func NewToolResultMessage(toolName, toolCallID, content string) Message

func NewUserMessage

func NewUserMessage(content string) Message

func NewUserMessageParts

func NewUserMessageParts(parts []ContentPart) Message

func (Message) Validate

func (m Message) Validate() error

type MessageAckParams

type MessageAckParams struct {
	ChannelID  string   `json:"channelID,omitempty"`
	ThreadID   string   `json:"threadID,omitempty"`
	AgentID    string   `json:"agentID,omitempty"`
	MessageIDs []string `json:"messageIDs,omitempty"`
}

type MessageAckResult

type MessageAckResult struct {
	ChannelID string `json:"channelID"`
	ThreadID  string `json:"threadID"`
	AgentID   string `json:"agentID"`
	Acked     int    `json:"acked"`
}

type MessageAction

type MessageAction struct {
	ID    string            `json:"id"`
	Label string            `json:"label"`
	Tone  MessageActionTone `json:"tone,omitempty"`
}

type MessageActionTone

type MessageActionTone string
const (
	MessageActionTonePrimary MessageActionTone = "primary"
	MessageActionToneDanger  MessageActionTone = "danger"
)

type MessageAnswer

type MessageAnswer struct {
	QuestionID string `json:"questionID"`
	OptionID   string `json:"optionID,omitempty"`
	Label      string `json:"label,omitempty"`
	Other      bool   `json:"other,omitempty"`
	Text       string `json:"text,omitempty"`
}

type MessageArchiveParams

type MessageArchiveParams struct {
	ChannelID           string `json:"channelID,omitempty"`
	MessageID           string `json:"messageID,omitempty"`
	AgentID             string `json:"agentID,omitempty"`
	PendingRequestsOnly bool   `json:"pendingRequestsOnly,omitempty"`
}

type MessageArchiveResult

type MessageArchiveResult struct {
	Archived int `json:"archived"`
}

type MessageChannelSummary

type MessageChannelSummary struct {
	ChannelID       string         `json:"channelID"`
	ThreadID        string         `json:"threadID"`
	AgentID         string         `json:"agentID"`
	Title           string         `json:"title,omitempty"`
	LastMessage     *MessageRecord `json:"lastMessage,omitempty"`
	OpenCount       int            `json:"openCount,omitempty"`
	UnreadUserCount int            `json:"unreadUserCount,omitempty"`
	UpdatedAt       string         `json:"updatedAt,omitempty"`
}

type MessageKind

type MessageKind string
const (
	MessageKindMessage MessageKind = "message"
	MessageKindRequest MessageKind = "request"
	MessageKindStatus  MessageKind = "status"
)

type MessageListParams

type MessageListParams struct {
	ThreadID string `json:"threadID,omitempty"`
	AgentID  string `json:"agentID,omitempty"`
	Limit    int    `json:"limit,omitempty"`
}

type MessageListResult

type MessageListResult struct {
	Channels []MessageChannelSummary `json:"channels,omitempty"`
	Messages []MessageRecord         `json:"messages,omitempty"`
}

type MessagePublishParams

type MessagePublishParams struct {
	ChannelID string            `json:"channelID,omitempty"`
	ThreadID  string            `json:"threadID,omitempty"`
	AgentID   string            `json:"agentID,omitempty"`
	Kind      MessageKind       `json:"kind,omitempty"`
	Title     string            `json:"title,omitempty"`
	Body      string            `json:"body"`
	Actions   []MessageAction   `json:"actions,omitempty"`
	Questions []MessageQuestion `json:"questions,omitempty"`
	Meta      Meta              `json:"meta,omitempty"`
}

type MessagePublishResult

type MessagePublishResult struct {
	MessageID string `json:"messageID"`
	ChannelID string `json:"channelID"`
	ThreadID  string `json:"threadID"`
	Delivered bool   `json:"delivered"`
}

type MessageQuestion

type MessageQuestion struct {
	ID       string                  `json:"id"`
	Question string                  `json:"question"`
	Options  []MessageQuestionOption `json:"options,omitempty"`
}

type MessageQuestionOption

type MessageQuestionOption struct {
	ID    string `json:"id"`
	Label string `json:"label"`
}

type MessageReadParams

type MessageReadParams struct {
	ChannelID   string `json:"channelID,omitempty"`
	ThreadID    string `json:"threadID,omitempty"`
	AgentID     string `json:"agentID,omitempty"`
	PendingOnly bool   `json:"pendingOnly,omitempty"`
	Limit       int    `json:"limit,omitempty"`
}

type MessageReadResult

type MessageReadResult struct {
	ChannelID string          `json:"channelID,omitempty"`
	ThreadID  string          `json:"threadID,omitempty"`
	AgentID   string          `json:"agentID,omitempty"`
	Messages  []MessageRecord `json:"messages,omitempty"`
}

type MessageRecord

type MessageRecord struct {
	ID               string            `json:"id"`
	ChannelID        string            `json:"channelID"`
	ThreadID         string            `json:"threadID"`
	AgentID          string            `json:"agentID"`
	Sender           MessageSender     `json:"sender"`
	Kind             MessageKind       `json:"kind"`
	Status           MessageStatus     `json:"status"`
	Title            string            `json:"title,omitempty"`
	Body             string            `json:"body"`
	Actions          []MessageAction   `json:"actions,omitempty"`
	Questions        []MessageQuestion `json:"questions,omitempty"`
	ReplyToMessageID string            `json:"replyToMessageID,omitempty"`
	ActionID         string            `json:"actionID,omitempty"`
	Answers          []MessageAnswer   `json:"answers,omitempty"`
	CreatedAt        string            `json:"createdAt"`
	UpdatedAt        string            `json:"updatedAt"`
	Meta             Meta              `json:"meta,omitempty"`
}

type MessageReplyDispatch

type MessageReplyDispatch struct {
	Opcode  OpCode `json:"opcode"`
	Meta    Meta   `json:"meta,omitempty"`
	Content string `json:"content"`
}

type MessageReplyParams

type MessageReplyParams struct {
	ChannelID        string          `json:"channelID"`
	ReplyToMessageID string          `json:"replyToMessageID,omitempty"`
	Text             string          `json:"text,omitempty"`
	ActionID         string          `json:"actionID,omitempty"`
	Answers          []MessageAnswer `json:"answers,omitempty"`
}

type MessageReplyResult

type MessageReplyResult struct {
	Record   MessageRecord         `json:"record"`
	Resolved *MessageRecord        `json:"resolved,omitempty"`
	Dispatch *MessageReplyDispatch `json:"dispatch,omitempty"`
	Queue    *ThreadControlAck     `json:"queue,omitempty"`
}

type MessageRole

type MessageRole string

MessageRole is the canonical role for chat messages within opagent host. It intentionally mirrors OpenAI-compatible roles we already convert to.

const (
	RoleSystem    MessageRole = "system"
	RoleDeveloper MessageRole = "developer"
	RoleUser      MessageRole = "user"
	RoleAssistant MessageRole = "assistant"
	RoleTool      MessageRole = "tool"
	RoleFunction  MessageRole = "function"
)

type MessageSender

type MessageSender string
const (
	MessageSenderUser   MessageSender = "user"
	MessageSenderAgent  MessageSender = "agent"
	MessageSenderSystem MessageSender = "system"
)

type MessageStatus

type MessageStatus string
const (
	MessageStatusOpen     MessageStatus = "open"
	MessageStatusResolved MessageStatus = "resolved"
	MessageStatusArchived MessageStatus = "archived"
)

type MessageStopReason

type MessageStopReason string
const (
	StopReasonStop    MessageStopReason = "stop"
	StopReasonLength  MessageStopReason = "length"
	StopReasonToolUse MessageStopReason = "tool_use"
	StopReasonError   MessageStopReason = "error"
	StopReasonAborted MessageStopReason = "aborted"
)

type MessageSubscribeParams

type MessageSubscribeParams struct {
	ChannelID string `json:"channelID,omitempty"`
	ThreadID  string `json:"threadID,omitempty"`
	AgentID   string `json:"agentID,omitempty"`
}

type MessageSubscribeResult

type MessageSubscribeResult struct {
	ChannelID  string `json:"channelID"`
	ThreadID   string `json:"threadID"`
	AgentID    string `json:"agentID"`
	Subscribed bool   `json:"subscribed"`
}

type MessageToolCall

type MessageToolCall struct {
	ID        string         `json:"id"`
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
	// Type is usually "function". Kept for completeness/future compatibility.
	Type string `json:"type,omitempty"`
}

MessageToolCall represents an assistant tool call (OpenAI "tool_calls"). NOTE: host already has a ToolCall type for streaming aggregation; do not reuse the name.

type MessageUpdateParams

type MessageUpdateParams struct {
	MessageID string            `json:"messageID"`
	Body      *string           `json:"body,omitempty"`
	Title     *string           `json:"title,omitempty"`
	Status    MessageStatus     `json:"status,omitempty"`
	Actions   []MessageAction   `json:"actions,omitempty"`
	Questions []MessageQuestion `json:"questions,omitempty"`
	Meta      Meta              `json:"meta,omitempty"`
}

type MessageUsage

type MessageUsage struct {
	InputTokens      int64 `json:"inputTokens,omitempty"`
	OutputTokens     int64 `json:"outputTokens,omitempty"`
	CacheReadTokens  int64 `json:"cacheReadTokens,omitempty"`
	CacheWriteTokens int64 `json:"cacheWriteTokens,omitempty"`
	TotalTokens      int64 `json:"totalTokens,omitempty"`
}

MessageUsage records token usage from an LLM response. InputTokens stores non-cached prompt tokens. CacheReadTokens and CacheWriteTokens store prompt-cache hits and writes when exposed by the provider. TotalTokens typically equals InputTokens + OutputTokens + CacheReadTokens + CacheWriteTokens, but some providers report it independently. For context estimation, TotalTokens is preferred because it includes everything the API saw (system prompt, cache, reasoning).

type Meta

type Meta map[string]any

Meta is additional metadata for requests, responses and other types.

func (Meta) Add

func (m Meta) Add(other Meta) Meta

Add merges metadata and clones JSON-safe values.

func (Meta) Clone

func (m Meta) Clone() Meta

Clone copies metadata and preserves JSON-safe values.

func (Meta) GetMeta

func (m Meta) GetMeta() map[string]any

GetMeta returns metadata from a value.

func (*Meta) SetMeta

func (m *Meta) SetMeta(x map[string]any)

SetMeta sets the metadata on a value.

type MethodHandler

type MethodHandler func(ctx context.Context, method string, req Request) (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

type Middleware func(MethodHandler) MethodHandler

Middleware is a function from MethodHandler to MethodHandler.

type ModelAutoStrategy

type ModelAutoStrategy struct {
	DefaultChatModelID                   string `json:"defaultChatModelID,omitempty" mapstructure:"defaultChatModelID"`
	DefaultChatThinkingLevel             string `json:"defaultChatThinkingLevel,omitempty" mapstructure:"defaultChatThinkingLevel"`
	DefaultInlineCompletionModelID       string `json:"defaultInlineCompletionModelID,omitempty" mapstructure:"defaultInlineCompletionModelID"`
	DefaultInlineCompletionThinkingLevel string `json:"defaultInlineCompletionThinkingLevel,omitempty" mapstructure:"defaultInlineCompletionThinkingLevel"`
}

type ModelConfig

type ModelConfig struct {
	Key              string            `json:"key,omitempty"`
	ID               string            `json:"id"`
	Name             string            `json:"name"`
	Provider         string            `json:"provider"`
	API              string            `json:"api,omitempty"`
	APIKey           string            `json:"apiKey"`
	BaseURL          string            `json:"baseURL,omitempty"`
	Headers          map[string]string `json:"headers,omitempty"`
	ContextWindow    int64             `json:"contextWindow,omitempty"`
	MaxOutputTokens  int64             `json:"maxOutputTokens,omitempty"`
	Reasoning        bool              `json:"reasoning,omitempty"`
	ReasoningControl string            `json:"reasoningControl,omitempty"`
	ReasoningLevels  []string          `json:"reasoningLevels,omitempty"`
	ServiceTiers     []string          `json:"serviceTiers,omitempty"`
	Enabled          bool              `json:"enabled,omitempty"`
	Source           string            `json:"source,omitempty"` // gateway | custom
}

--------------- model --------------------

type ModelHint

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

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 ModelStrategies

type ModelStrategies struct {
	Auto *ModelAutoStrategy `json:"auto,omitempty" mapstructure:"auto"`
}

type MongoDBConfig

type MongoDBConfig struct {
	URI      string `json:"uri,omitempty" mapstructure:"uri"`
	Database string `json:"database,omitempty" mapstructure:"database"`
}

type MongoObjectStoreConfig

type MongoObjectStoreConfig struct {
	// 可选:未配置时会回退使用顶层 mongodb 配置
	URI      string `json:"uri,omitempty" mapstructure:"uri"`
	Database string `json:"database,omitempty" mapstructure:"database"`
	// GridFSBucket: GridFS bucket 名(默认 images)
	GridFSBucket string `json:"gridfsBucket,omitempty" mapstructure:"gridfsBucket"`
}

type NodeKind

type NodeKind string
const (
	NodeKindAgent NodeKind = "agent"
	NodeKindSkill NodeKind = "skill"
	NodeKindTools NodeKind = "tools"
)

func NodeKindFromID

func NodeKindFromID(id string) (NodeKind, bool)

type ObjectStoreConfig

type ObjectStoreConfig struct {
	// Type: fs | s3 | mongodb
	Type    string                 `json:"type,omitempty" mapstructure:"type"`
	FS      FSObjectStoreConfig    `json:"fs,omitempty" mapstructure:"fs"`
	S3      S3ObjectStoreConfig    `json:"s3,omitempty" mapstructure:"s3"`
	MongoDB MongoObjectStoreConfig `json:"mongodb,omitempty" mapstructure:"mongodb"`
}

type OpAgentParams

type OpAgentParams struct {
	OpCode  OpCode `json:"opCode"`
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content,omitempty"`
}

func (*OpAgentParams) UnmarshalJSON

func (p *OpAgentParams) UnmarshalJSON(data []byte) error

type OpAgentRequest

type OpAgentRequest = ClientRequest[*OpAgentParams]

OpAgentClientRequest = ClientRequest[*OpAgentParams]

type OpAgentResult

type OpAgentResult struct {
	OpCode  OpCode `json:"opCode"`
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content"`
}

func (*OpAgentResult) UnmarshalJSON

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

type OpCode

type OpCode string
const (
	// agent
	// Deprecated: thread chat submission should use OpThreadSubmit. Kept as a legacy edge adapter.
	OpAgentCall OpCode = "agent/call"
	// Deprecated: thread chat submission should use OpThreadSubmit. Kept as a legacy edge adapter.
	OpAgentContinue   OpCode = "agent/continue"
	OpAgentLoopCreate OpCode = "agent/loop/create"
	OpPromptGet       OpCode = "prompt/get"
	// OpAgentRoots OpCode = "agents/roots" // list agent roots
	// OpAgentGet   OpCode = "agent/get"
	OpAgentScan OpCode = "agent/scan"

	//node
	// OpNodeScan OpCode = "node/scan"
	OpNodeList OpCode = "node/list"

	//host
	SystemStarted OpCode = "system/started"

	// notify
	NotifyMessage OpCode = "notify/message"

	//config/get
	ConfigGet       OpCode = "config/get"
	ConfigSystemGet OpCode = "config/system/get"

	//thread
	OpThreadCreate           OpCode = "thread/create"
	OpThreadFork             OpCode = "thread/fork"
	OpThreadMetaGet          OpCode = "thread/meta/get"
	OpThreadMetaUpdate       OpCode = "thread/meta/update"
	OpThreadSnapshotGet      OpCode = "thread/snapshot/get"
	OpThreadReviewList       OpCode = "thread/review/list"
	OpThreadReviewResolve    OpCode = "thread/review/resolve"
	OpThreadReviewRollback   OpCode = "thread/review/rollback"
	OpEditorCompletion       OpCode = "editor/completion"
	OpEditorCompletionCancel OpCode = "editor/completion/cancel"
	OpThreadSubmit           OpCode = "thread/submit"
	OpThreadCompact          OpCode = "thread/compact"
	OpThreadInterrupted      OpCode = "thread/interrupted"
	OpThreadSteer            OpCode = "thread/steer"
	OpThreadFollowUp         OpCode = "thread/follow_up"
	OpThreadFollowUpPromote  OpCode = "thread/follow_up/promote"
	OpThreadQueueGet         OpCode = "thread/queue/get"
	OpThreadQueueRemove      OpCode = "thread/queue/remove"
	OpThreadActiveList       OpCode = "thread/active/list"
	OpMessageList            OpCode = "message/list"
	OpMessageRead            OpCode = "message/read"
	OpMessageReply           OpCode = "message/reply"
	OpMessageAck             OpCode = "message/ack"
	OpMessageArchive         OpCode = "message/archive"
)

type OpNode

type OpNode struct {
	ID      string   `json:"id"`                                     // persistent node id, e.g. agent-cm1...
	HostID  string   `json:"hostID,omitempty" mapstructure:"hostID"` // host id
	UID     string   `json:"uid"`                                    // owner/tenant identifier
	OpCodes []OpCode `json:"opCodes,omitempty"`
	Kind    string   `json:"kind"` // agent | skill | tools
	URI     string   `json:"uri"`  // resource locator (file://, cloudos://, ...)
	Cwd     string   `json:"cwd"`  // current working directory
	Tags    []string `json:"tags,omitempty"`
	Run     Run      `json:"run,omitempty"`
	Meta    any      `json:"meta,omitempty"` // AgentMeta | SkillMeta | ToolsMeta
}

func BuildNode

func BuildNode(uid, hostID string, kind NodeKind, uri string, env string, tags []string, run Run, opCodes []OpCode, meta any) *OpNode

type OpNodeParams

type OpNodeParams struct {
	OpCode  OpCode `json:"opCode"`
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content,omitempty"`
}

func (*OpNodeParams) UnmarshalJSON

func (p *OpNodeParams) UnmarshalJSON(data []byte) error

type OpNodeRequest

type OpNodeRequest = ClientRequest[*OpNodeParams]

type OpNodeResult

type OpNodeResult struct {
	OpCode  OpCode `json:"opCode"`
	Meta    `json:"_meta,omitempty"`
	Content Content `json:"content"`
}

func (*OpNodeResult) UnmarshalJSON

func (p *OpNodeResult) UnmarshalJSON(data []byte) error

type Params

type Params interface {
	// GetMeta returns metadata from a value.
	GetMeta() map[string]any
	// SetMeta sets the metadata on a value.
	SetMeta(map[string]any)
	// contains filtered or unexported methods
}

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

type PingParams

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

func (*PingParams) GetProgressToken

func (x *PingParams) GetProgressToken() any

func (*PingParams) SetProgressToken

func (x *PingParams) SetProgressToken(t any)

type ProgressNotificationClientRequest

type ProgressNotificationClientRequest = ClientRequest[*ProgressNotificationParams]

type ProgressNotificationParams

type ProgressNotificationParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The progress token which was given in the initial request, used to associate
	// this notification with the request that is proceeding.
	ProgressToken any `json:"progressToken"`
	// An optional message describing the current progress.
	Message string `json:"message,omitempty"`
	// The progress thus far. This should increase every time progress is made, even
	// if the total is unknown.
	Progress float64 `json:"progress"`
	// Total number of items to process (or total progress required), if known.
	// Zero means unknown.
	Total float64 `json:"total,omitempty"`
}

type ProgressNotificationServerRequest

type ProgressNotificationServerRequest = ServerRequest[*ProgressNotificationParams]

type Prompt

type Prompt struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// 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"`
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	Title string `json:"title,omitempty"`
	// Icons for the prompt, if any.
	Icons []Icon `json:"icons,omitempty"`
}

A prompt or prompt template that the server offers.

type PromptArgument

type PromptArgument struct {
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	Title string `json:"title,omitempty"`
	// A human-readable description of the argument.
	Description string `json:"description,omitempty"`
	// Whether this argument must be provided.
	Required bool `json:"required,omitempty"`
}

Describes an argument that a prompt can accept.

type PromptCapabilities

type PromptCapabilities struct {
	// Whether this server supports notifications for changes to the prompt list.
	ListChanged bool `json:"listChanged,omitempty"`
}

Present if the server offers any prompt templates.

type PromptHandler

type PromptHandler func(context.Context, *GetPromptRequest) (*GetPromptResult, error)

A PromptHandler handles a call to prompts/get.

type PromptListChangedParams

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

func (*PromptListChangedParams) GetProgressToken

func (x *PromptListChangedParams) GetProgressToken() any

func (*PromptListChangedParams) SetProgressToken

func (x *PromptListChangedParams) SetProgressToken(t any)

type PromptListChangedRequest

type PromptListChangedRequest = ClientRequest[*PromptListChangedParams]

type PromptMessage

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.

func (*PromptMessage) UnmarshalJSON

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

UnmarshalJSON handles the unmarshalling of content into the Content interface.

type ProviderState

type ProviderState struct {
	ProviderRef string `json:"providerRef,omitempty"`
	Provider    string `json:"provider,omitempty"`
	API         string `json:"api,omitempty"`
	Model       string `json:"model,omitempty"`
	ResponseID  string `json:"responseID,omitempty"`
}

type ReadResourceParams

type ReadResourceParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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) GetProgressToken

func (x *ReadResourceParams) GetProgressToken() any

func (*ReadResourceParams) SetProgressToken

func (x *ReadResourceParams) SetProgressToken(t any)

type ReadResourceRequest

type ReadResourceRequest = ServerRequest[*ReadResourceParams]

type ReadResourceResult

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

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

type Request

type Request interface {
	GetSession() Session
	GetParams() Params
	// GetExtra returns the Extra field for ServerRequests, and nil for ClientRequests.
	GetExtra() *RequestExtra
	// contains filtered or unexported methods
}

A Request is a method request with parameters and additional information, such as the session. Request is implemented by *ClientRequest and *ServerRequest.

type RequestExtra

type RequestExtra struct {
	TokenInfo *auth.TokenInfo // bearer token info (e.g. from OAuth) if any
	Header    http.Header     // header from HTTP request, if any
}

RequestExtra is extra information included in requests, typically from the transport layer.

type RequestParams

type RequestParams interface {
	Params

	// GetProgressToken returns the progress token from the params' Meta field, or nil
	// if there is none.
	GetProgressToken() any

	// SetProgressToken sets the given progress token into the params' Meta field.
	// It panics if its argument is not an int or a string.
	SetProgressToken(any)
}

RequestParams is a parameter (input) type for an MCP request.

type Resource

type Resource struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// 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"`
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	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"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	//
	// If not provided, the name should be used for display (except for Tool, where
	// Annotations.Title should be given precedence over using name, if
	// present).
	Title string `json:"title,omitempty"`
	// The URI of this resource.
	URI string `json:"uri"`
	// Icons for the resource, if any.
	Icons []Icon `json:"icons,omitempty"`
}

A known resource that the server is capable of reading.

type ResourceCapabilities

type ResourceCapabilities struct {
	// Whether this server supports notifications for changes to the resource list.
	ListChanged bool `json:"listChanged,omitempty"`
	// Whether this server supports subscribing to resource updates.
	Subscribe bool `json:"subscribe,omitempty"`
}

Present if the server offers any resources to read.

type ResourceContents

type ResourceContents struct {
	URI      string `json:"uri"`
	MIMEType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"`
	Blob     []byte `json:"blob,omitempty"`
}

ResourceContents contains the contents of a specific resource or sub-resource.

func (*ResourceContents) MarshalJSON

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

type ResourceHandler

type ResourceHandler func(context.Context, *ReadResourceRequest) (*ReadResourceResult, error)

A ResourceHandler is a function that reads a resource. It will be called when the client calls ClientSession.ReadResource. If it cannot find the resource, it should return the result of calling ResourceNotFoundError.

type ResourceLink struct {
	URI         string
	Name        string
	Title       string
	Description string
	MIMEType    string
	Size        *int64
	Annotations *Annotations
	// Icons for the resource link, if any.
	Icons []Icon `json:"icons,omitempty"`
}

ResourceLink is a link to a resource

func (*ResourceLink) MarshalJSON

func (c *ResourceLink) MarshalJSON() ([]byte, error)

type ResourceListChangedParams

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

func (*ResourceListChangedParams) GetProgressToken

func (x *ResourceListChangedParams) GetProgressToken() any

func (*ResourceListChangedParams) SetProgressToken

func (x *ResourceListChangedParams) SetProgressToken(t any)

type ResourceListChangedRequest

type ResourceListChangedRequest = ClientRequest[*ResourceListChangedParams]

type ResourceTemplate

type ResourceTemplate struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// Optional annotations for the client.
	Annotations *Annotations `json:"annotations,omitempty"`
	// A description of what this template is for.
	//
	// 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 for all resources that match this template. This should only be
	// included if all resources matching this template have the same type.
	MIMEType string `json:"mimeType,omitempty"`
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	//
	// If not provided, the name should be used for display (except for Tool, where
	// Annotations.Title should be given precedence over using name, if
	// present).
	Title string `json:"title,omitempty"`
	// A URI template (according to RFC 6570) that can be used to construct resource
	// URIs.
	URITemplate string `json:"uriTemplate"`
	// Icons for the resource template, if any.
	Icons []Icon `json:"icons,omitempty"`
}

A template description for resources available on the server.

type ResourceUpdatedNotificationParams

type ResourceUpdatedNotificationParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
	URI string `json:"uri"`
}

A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.

type Result

type Result interface {

	// GetMeta returns metadata from a value.
	GetMeta() map[string]any
	// SetMeta sets the metadata on a value.
	SetMeta(map[string]any)
	// contains filtered or unexported methods
}

Result is a result of an MCP call.

type Role

type Role string

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

type Root

type Root struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// 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

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

func (*RootsListChangedParams) GetProgressToken

func (x *RootsListChangedParams) GetProgressToken() any

func (*RootsListChangedParams) SetProgressToken

func (x *RootsListChangedParams) SetProgressToken(t any)

type RootsListChangedRequest

type RootsListChangedRequest = ServerRequest[*RootsListChangedParams]

type Run

type Run struct {
	Command []string          `json:"command,omitempty"`
	URL     string            `json:"url,omitempty"`
	Header  map[string]string `json:"header,omitempty"`
	Daemon  bool              `json:"daemon,omitempty"`
}

func (Run) HasEndpoint

func (r Run) HasEndpoint() bool

func (Run) Validate

func (r Run) Validate() error

Validate checks whether run config is internally consistent.

type RuntimeUpdateConfig

type RuntimeUpdateConfig struct {
	Enabled         *bool  `json:"enabled,omitempty" mapstructure:"enabled"`
	ManifestURL     string `json:"manifestURL,omitempty" mapstructure:"manifestURL"`
	CheckInterval   string `json:"checkInterval,omitempty" mapstructure:"checkInterval"`
	CheckTimeout    string `json:"checkTimeout,omitempty" mapstructure:"checkTimeout"`
	IdleGracePeriod string `json:"idleGracePeriod,omitempty" mapstructure:"idleGracePeriod"`
	DownloadDir     string `json:"downloadDir,omitempty" mapstructure:"downloadDir"`
}

type RuntimeUpdateState

type RuntimeUpdateState struct {
	CurrentVersion string `json:"currentVersion,omitempty"`
	TargetVersion  string `json:"targetVersion,omitempty"`
	StagedVersion  string `json:"stagedVersion,omitempty"`
	Phase          string `json:"phase,omitempty"`
	Downloaded     bool   `json:"downloaded,omitempty"`
	Applying       bool   `json:"applying,omitempty"`
	LastCheckedAt  string `json:"lastCheckedAt,omitempty"`
	LastError      string `json:"lastError,omitempty"`
}

type S3ObjectStoreConfig

type S3ObjectStoreConfig struct {
	Endpoint        string `json:"endpoint,omitempty" mapstructure:"endpoint"`
	Region          string `json:"region,omitempty" mapstructure:"region"`
	Bucket          string `json:"bucket,omitempty" mapstructure:"bucket"`
	Prefix          string `json:"prefix,omitempty" mapstructure:"prefix"`
	AccessKeyID     string `json:"accessKeyId,omitempty" mapstructure:"accessKeyId"`
	SecretAccessKey string `json:"secretAccessKey,omitempty" mapstructure:"secretAccessKey"`
	SessionToken    string `json:"sessionToken,omitempty" mapstructure:"sessionToken"`
	ForcePathStyle  bool   `json:"forcePathStyle,omitempty" mapstructure:"forcePathStyle"`
}

type SSEClientTransport

type SSEClientTransport struct {
	// Endpoint is the SSE endpoint to connect to.
	Endpoint string

	// HTTPClient is the client to use for making HTTP requests. If nil,
	// http.DefaultClient is used.
	HTTPClient *http.Client
}

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 (*SSEClientTransport) Connect

func (c *SSEClientTransport) Connect(ctx context.Context) (Connection, 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 spec.

Example
package main

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

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

type AddParams struct {
	X int `json:"x"`
	Y int `json:"y"`
}

func Add(ctx context.Context, req *mcp.CallToolRequest, args AddParams) (*mcp.CallToolResult, any, error) {
	return &mcp.CallToolResult{
		Content: []mcp.Content{
			&mcp.TextContent{Text: fmt.Sprintf("%d", args.X+args.Y)},
		},
	}, nil, nil
}

func main() {
	server := mcp.NewServer(&mcp.Implementation{Name: "adder", Version: "v0.0.1"}, nil)
	mcp.AddTool(server, &mcp.Tool{Name: "add", Description: "add two numbers"}, Add)

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

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

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

}
Output:
3

func NewSSEHandler

func NewSSEHandler(getServer func(request *http.Request) *Server, opts *SSEOptions) *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. The SSEHandler also handles requests to the message endpoints, by delegating them to the relevant server transport.

The getServer function may return a distinct Server for each new request, or reuse an existing server. If it returns nil, the handler will return a 400 Bad Request.

func (*SSEHandler) ServeHTTP

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

type SSEOptions

type SSEOptions struct{}

SSEOptions specifies options for an SSEHandler. for now, it is empty, but may be extended in future. https://github.com/modelcontextprotocol/go-sdk/issues/507

type SSEServerTransport

type SSEServerTransport struct {
	// Endpoint is the endpoint for this session, where the client can POST
	// messages.
	Endpoint string

	// Response is the hanging response body to the incoming GET request.
	Response http.ResponseWriter
	// contains filtered or unexported fields
}

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

Use SSEServerTransport.Connect to initiate the flow of messages.

When connected, it returns the following Connection 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.

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.

Each SSEServerTransport may be connected (via Server.Connect) at most once, since SSEServerTransport.ServeHTTP serves messages to the connected session.

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

func (*SSEServerTransport) Connect

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

func (*SSEServerTransport) ServeHTTP

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

ServeHTTP handles POST requests to the transport endpoint.

type SamplingCapabilities

type SamplingCapabilities struct{}

SamplingCapabilities describes the capabilities for sampling.

type SamplingMessage

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

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

func (*SamplingMessage) UnmarshalJSON

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

UnmarshalJSON handles the unmarshalling of content into the Content interface.

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.Run.

func NewServer

func NewServer(impl *Implementation, options *ServerOptions) *Server

NewServer creates a new MCP server. The resulting server has no features: add features using the various Server.AddXXX methods, and the AddTool function.

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

The first argument must not be nil.

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

func (*Server) AddAgent

func (s *Server) AddAgent(agent *AgentMeta, h CallAgentHandler)

func (*Server) AddPrompt

func (s *Server) AddPrompt(p *Prompt, h PromptHandler)

AddPrompt adds a Prompt to the server, or replaces one with the same name.

func (*Server) AddReceivingMiddleware

func (s *Server) AddReceivingMiddleware(middleware ...Middleware)

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) AddResource

func (s *Server) AddResource(r *Resource, h ResourceHandler)

AddResource adds a Resource to the server, or replaces one with the same URI. AddResource panics if the resource URI is invalid or not absolute (has an empty scheme).

func (*Server) AddResourceTemplate

func (s *Server) AddResourceTemplate(t *ResourceTemplate, h ResourceHandler)

AddResourceTemplate adds a ResourceTemplate to the server, or replaces one with the same URI. AddResourceTemplate panics if a URI template is invalid or not absolute (has an empty scheme).

func (*Server) AddSendingMiddleware

func (s *Server) AddSendingMiddleware(middleware ...Middleware)

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) AddTool

func (s *Server) AddTool(t *Tool, h ToolHandler)

AddTool adds a Tool to the server, or replaces one with the same name. The Tool argument must not be modified after this call.

The tool's input schema must be non-nil and have the type "object". For a tool that takes no input, or one where any input is valid, set Tool.InputSchema to `{"type": "object"}`, using your preferred library or `json.RawMessage`.

If present, Tool.OutputSchema must also have type "object".

When the handler is invoked as part of a CallTool request, req.Params.Arguments will be a json.RawMessage.

Unmarshaling the arguments and validating them against the input schema are the caller's responsibility.

Validating the result against the output schema, if any, is the caller's responsibility.

Setting the result's Content, StructuredContent and IsError fields are the caller's responsibility.

Most users should use the top-level function AddTool, which handles all these responsibilities.

Example (RawSchema)
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	// In some scenarios, you may want your server to be a pass-through, with
	// JSON schema coming from another source. Or perhaps you want to implement
	// tool validation using a different JSON schema library.
	//
	// For these cases, you can use [mcp.Server.AddTool], which is the "raw" form
	// of the API. Note that it is the caller's responsibility to validate inputs
	// and outputs.
	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
	server.AddTool(&mcp.Tool{
		Name:        "greet",
		InputSchema: json.RawMessage(`{"type":"object","properties":{"user":{"type":"string"}}}`),
	}, func(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
		// Note: no validation!
		var args struct{ User string }
		if err := json.Unmarshal(req.Params.Arguments, &args); err != nil {
			// TODO: we should use a jsonrpc error here, to be consistent with other
			// SDKs.
			return nil, err
		}
		return &mcp.CallToolResult{
			Content: []mcp.Content{&mcp.TextContent{Text: "Hi " + args.User}},
		}, nil
	})

	ctx := context.Background()
	session, err := connect(ctx, server)
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

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

func connect(ctx context.Context, server *mcp.Server) (*mcp.ClientSession, error) {
	t1, t2 := mcp.NewInMemoryTransports()
	if _, err := server.Connect(ctx, t1, nil); err != nil {
		return nil, err
	}
	client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
	return client.Connect(ctx, t2, nil)
}
Output:
Hi you

func (*Server) Connect

func (s *Server) Connect(ctx context.Context, t Transport, opts *ServerSessionOptions) (*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]).

If opts.State is non-nil, it is the initial state for the server.

func (*Server) RemovePrompts

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) RemoveResourceTemplates

func (s *Server) RemoveResourceTemplates(uriTemplates ...string)

RemoveResourceTemplates removes the resource templates with the given URI templates. It is not an error to remove a nonexistent resource.

func (*Server) RemoveResources

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

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) ResourceUpdated

func (s *Server) ResourceUpdated(ctx context.Context, params *ResourceUpdatedNotificationParams) error

ResourceUpdated sends a notification to all clients that have subscribed to the resource specified in params. This method is the primary way for a server author to signal that a resource has changed.

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 or the provided context is cancelled. If the context is cancelled, Run closes the connection.

If tools have been added to the server before this call, then the server will advertise the capability for tools, including the ability to send list-changed notifications. If no tools have been added, the server will not have the tool capability. The same goes for other features like prompts and resources.

Run is a convenience for servers that handle a single session (or one session at a time). It need not be called on servers that are used for multiple concurrent connections, as with StreamableHTTPHandler.

func (*Server) Sessions

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

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

There is no guarantee that the iterator observes sessions that are added or removed during iteration.

type ServerCapabilities

type ServerCapabilities struct {
	// Present if the server supports argument autocompletion suggestions.
	Completions *CompletionCapabilities `json:"completions,omitempty"`
	// Experimental, non-standard capabilities that the server supports.
	Experimental map[string]any `json:"experimental,omitempty"`
	// Present if the server supports sending log messages to the client.
	Logging *LoggingCapabilities `json:"logging,omitempty"`
	// Present if the server offers any prompt templates.
	Prompts *PromptCapabilities `json:"prompts,omitempty"`
	// Present if the server offers any resources to read.
	Resources *ResourceCapabilities `json:"resources,omitempty"`
	// Present if the server offers any tools to call.
	Tools *ToolCapabilities `json:"tools,omitempty"`
}

Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.

type ServerOptions

type ServerOptions struct {
	// Optional instructions for connected clients.
	Instructions string
	// If non-nil, log server activity.
	Logger *slog.Logger
	// If non-nil, handles incoming custom node operations.
	OpNodeHandler func(context.Context, *ServerRequest[*OpNodeParams]) (*OpNodeResult, error)
	// If non-nil, called when "notifications/initialized" is received.
	InitializedHandler func(context.Context, *InitializedRequest)
	// PageSize is the maximum number of items to return in a single page for
	// list methods (e.g. ListTools).
	//
	// If zero, defaults to [DefaultPageSize].
	PageSize int
	// If non-nil, called when "notifications/roots/list_changed" is received.
	RootsListChangedHandler func(context.Context, *RootsListChangedRequest)
	// If non-nil, called when "notifications/progress" is received.
	ProgressNotificationHandler func(context.Context, *ProgressNotificationServerRequest)
	InfoNotificationHandler     func(context.Context, *InfoNotificationServerRequest)
	// If non-nil, called when "completion/complete" is received.
	CompletionHandler func(context.Context, *CompleteRequest) (*CompleteResult, error)
	// If non-zero, defines an interval for regular "ping" requests.
	// If the peer fails to respond to pings originating from the keepalive check,
	// the session is automatically closed.
	KeepAlive time.Duration
	// Function called when a client session subscribes to a resource.
	SubscribeHandler func(context.Context, *SubscribeRequest) error
	// Function called when a client session unsubscribes from a resource.
	UnsubscribeHandler func(context.Context, *UnsubscribeRequest) error
	// If true, advertises the prompts capability during initialization,
	// even if no prompts have been registered.
	HasPrompts bool
	// If true, advertises the resources capability during initialization,
	// even if no resources have been registered.
	HasResources bool
	// If true, advertises the tools capability during initialization,
	// even if no tools have been registered.
	HasTools bool

	// GetSessionID provides the next session ID to use for an incoming request.
	// If nil, a default randomly generated ID will be used.
	//
	// Session IDs should be globally unique across the scope of the server,
	// which may span multiple processes in the case of distributed servers.
	//
	// As a special case, if GetSessionID returns the empty string, the
	// Mcp-Session-Id header will not be set.
	GetSessionID func() string
}

ServerOptions is used to configure behavior of the server.

type ServerRequest

type ServerRequest[P Params] struct {
	Session *ServerSession
	Params  P
	Extra   *RequestExtra
}

A ServerRequest is a request to a server.

func (*ServerRequest[P]) GetExtra

func (r *ServerRequest[P]) GetExtra() *RequestExtra

func (*ServerRequest[P]) GetParams

func (r *ServerRequest[P]) GetParams() Params

func (*ServerRequest[P]) GetSession

func (r *ServerRequest[P]) GetSession() Session

type ServerSession

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

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.

Close is idempotent and concurrency safe.

func (*ServerSession) CreateMessage

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

CreateMessage sends a sampling request to the client.

func (*ServerSession) Elicit

func (ss *ServerSession) Elicit(ctx context.Context, params *ElicitParams) (*ElicitResult, error)

Elicit sends an elicitation request to the client asking for user input.

func (*ServerSession) ID

func (ss *ServerSession) ID() string

func (*ServerSession) InitializeParams

func (ss *ServerSession) InitializeParams() *InitializeParams

InitializeParams returns the InitializeParams provided during the client's initial connection.

func (*ServerSession) ListRoots

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

ListRoots lists the client roots.

func (*ServerSession) Log

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

Log sends a log 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) NotifyInfo

func (ss *ServerSession) NotifyInfo(ctx context.Context, params *InfoNotificationParams) error

func (*ServerSession) NotifyProgress

func (ss *ServerSession) NotifyProgress(ctx context.Context, params *ProgressNotificationParams) error

NotifyProgress sends a progress notification from the server to the client associated with this session. This is typically used to report on the status of a long-running request that was initiated by the client.

func (*ServerSession) OpAgent

func (ss *ServerSession) OpAgent(ctx context.Context, params *OpAgentParams) (*OpAgentResult, error)

func (*ServerSession) OpNode

func (ss *ServerSession) OpNode(ctx context.Context, params *OpNodeParams) (*OpNodeResult, error)

func (*ServerSession) Ping

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

Ping pings the client.

func (*ServerSession) Wait

func (ss *ServerSession) Wait() error

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

type ServerSessionOptions

type ServerSessionOptions struct {
	State *ServerSessionState
	// contains filtered or unexported fields
}

ServerSessionOptions configures the server session.

type ServerSessionState

type ServerSessionState struct {
	// InitializeParams are the parameters from 'initialize'.
	InitializeParams *InitializeParams `json:"initializeParams"`

	// InitializedParams are the parameters from 'notifications/initialized'.
	InitializedParams *InitializedParams `json:"initializedParams"`

	// LogLevel is the logging level for the session.
	LogLevel LoggingLevel `json:"logLevel"`
}

ServerSessionState is the state of a session.

type Session

type Session interface {
	// ID returns the session ID, or the empty string if there is none.
	ID() string
	// contains filtered or unexported methods
}

A Session is either a ClientSession or a ServerSession.

type SetLoggingLevelParams

type SetLoggingLevelParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	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 (*SetLoggingLevelParams) GetProgressToken

func (x *SetLoggingLevelParams) GetProgressToken() any

func (*SetLoggingLevelParams) SetProgressToken

func (x *SetLoggingLevelParams) SetProgressToken(t any)

type SkillMeta

type SkillMeta struct {
	Slug        string   `json:"slug"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Tags        []string `json:"tags,omitempty"`
}

type Status

type Status string
const (
	Status_Init       Status = "init"
	Status_Pending    Status = "pending"
	Status_Started    Status = "started"
	Status_InProgress Status = "in_progress"
	Status_Completed  Status = "completed"
	Status_Failed     Status = "failed"
	Status_Running    Status = "running"
	Status_Cancelled  Status = "cancelled"
	Status_Stopped    Status = "stopped"
)

type StdioTransport

type StdioTransport struct{}

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

func (*StdioTransport) Connect

Connect implements the Transport interface.

type StreamableClientTransport

type StreamableClientTransport struct {
	Endpoint   string
	HTTPClient *http.Client
	// Header contains additional HTTP headers sent on all streamable HTTP
	// requests. MCP protocol headers set by the transport take precedence.
	Header map[string]string
	// OAuthHandler provides bearer auth for outgoing streamable HTTP requests.
	// When set, TokenSource is consulted before each request. If a request
	// returns 401 or 403, Authorize is called and the request is retried once.
	OAuthHandler auth.OAuthHandler
	// MaxRetries is the maximum number of times to attempt a reconnect before giving up.
	// It defaults to 5. To disable retries, use a negative number.
	MaxRetries int
	// contains filtered or unexported fields
}

A StreamableClientTransport is a Transport that can communicate with an MCP endpoint serving the streamable HTTP transport defined by the 2025-03-26 version of the spec.

func (*StreamableClientTransport) Connect

Connect implements the Transport interface.

The resulting Connection writes messages via POST requests to the transport URL with the Mcp-Session-Id header set, and reads messages from hanging requests.

When closed, the connection issues a DELETE request to terminate the logical session.

type StreamableHTTPHandler

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

A StreamableHTTPHandler is an http.Handler that serves streamable MCP sessions, as defined by the MCP spec.

Example

TODO: Until we have a way to clean up abandoned sessions, this test will leak goroutines (see #499)

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	// Create a new streamable handler, using the same MCP server for every request.
	//
	// Here, we configure it to serves application/json responses rather than
	// text/event-stream, just so the output below doesn't use random event ids.
	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.1.0"}, nil)
	handler := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
		return server
	}, &mcp.StreamableHTTPOptions{JSONResponse: true})
	httpServer := httptest.NewServer(handler)
	defer httpServer.Close()

	// The SDK is currently permissive of some missing keys in "params".
	resp := mustPostMessage(`{"jsonrpc": "2.0", "id": 1, "method":"initialize", "params": {}}`, httpServer.URL)
	fmt.Println(resp)
}

func mustPostMessage(msg, url string) string {
	req := orFatal(http.NewRequest("POST", url, strings.NewReader(msg)))
	req.Header["Content-Type"] = []string{"application/json"}
	req.Header["Accept"] = []string{"application/json", "text/event-stream"}
	resp := orFatal(http.DefaultClient.Do(req))
	defer resp.Body.Close()
	body := orFatal(io.ReadAll(resp.Body))
	return string(body)
}

func orFatal[T any](t T, err error) T {
	if err != nil {
		log.Fatal(err)
	}
	return t
}
Output:
{"jsonrpc":"2.0","id":1,"result":{"capabilities":{"logging":{}},"protocolVersion":"2025-06-18","serverInfo":{"name":"server","version":"v0.1.0"}}}
Example (Middleware)
package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.1.0"}, nil)
	handler := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
		return server
	}, &mcp.StreamableHTTPOptions{Stateless: true})
	loggingHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		// Example debugging; you could also capture the response.
		body, err := io.ReadAll(req.Body)
		if err != nil {
			log.Fatal(err)
		}
		req.Body.Close() // ignore error
		req.Body = io.NopCloser(bytes.NewBuffer(body))
		fmt.Println(req.Method, string(body))
		handler.ServeHTTP(w, req)
	})
	httpServer := httptest.NewServer(loggingHandler)
	defer httpServer.Close()

	// The SDK is currently permissive of some missing keys in "params".
	mustPostMessage(`{"jsonrpc": "2.0", "id": 1, "method":"initialize", "params": {}}`, httpServer.URL)
}

func mustPostMessage(msg, url string) string {
	req := orFatal(http.NewRequest("POST", url, strings.NewReader(msg)))
	req.Header["Content-Type"] = []string{"application/json"}
	req.Header["Accept"] = []string{"application/json", "text/event-stream"}
	resp := orFatal(http.DefaultClient.Do(req))
	defer resp.Body.Close()
	body := orFatal(io.ReadAll(resp.Body))
	return string(body)
}

func orFatal[T any](t T, err error) T {
	if err != nil {
		log.Fatal(err)
	}
	return t
}
Output:
POST {"jsonrpc": "2.0", "id": 1, "method":"initialize", "params": {}}

func NewStreamableHTTPHandler

func NewStreamableHTTPHandler(getServer func(*http.Request) *Server, opts *StreamableHTTPOptions) *StreamableHTTPHandler

NewStreamableHTTPHandler returns a new StreamableHTTPHandler.

The getServer function is used to create or look up servers for new sessions. It is OK for getServer to return the same server multiple times. If getServer returns nil, a 400 Bad Request will be served.

func (*StreamableHTTPHandler) ServeHTTP

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

type StreamableHTTPOptions

type StreamableHTTPOptions struct {
	// Stateless controls whether the session is 'stateless'.
	//
	// A stateless server does not validate the Mcp-Session-Id header, and uses a
	// temporary session with default initialization parameters. Any
	// server->client request is rejected immediately as there's no way for the
	// client to respond. Server->Client notifications may reach the client if
	// they are made in the context of an incoming request, as described in the
	// documentation for [StreamableServerTransport].
	Stateless bool

	// JSONResponse causes streamable responses to return application/json rather
	// than text/event-stream ([§2.1.5] of the spec).
	//
	// [§2.1.5]: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#sending-messages-to-the-server
	JSONResponse bool

	// Logger specifies the logger to use.
	// If nil, do not log.
	Logger *slog.Logger

	// EventStore enables stream resumption.
	//
	// If set, EventStore will be used to persist stream events and replay them
	// upon stream resumption.
	EventStore EventStore

	// SessionTimeout configures a timeout for idle sessions.
	//
	// When sessions receive no new HTTP requests from the client for this
	// duration, they are automatically closed.
	//
	// If SessionTimeout is the zero value, idle sessions are never closed.
	SessionTimeout time.Duration
}

StreamableHTTPOptions configures the StreamableHTTPHandler.

type StreamableServerTransport

type StreamableServerTransport struct {
	// SessionID is the ID of this session.
	//
	// If SessionID is the empty string, this is a 'stateless' session, which has
	// limited ability to communicate with the client. Otherwise, the session ID
	// must be globally unique, that is, different from any other session ID
	// anywhere, past and future. (We recommend using a crypto random number
	// generator to produce one, as with [crypto/rand.Text].)
	SessionID string

	// Stateless controls whether the eventstore is 'Stateless'. Server sessions
	// connected to a stateless transport are disallowed from making outgoing
	// requests.
	//
	// See also [StreamableHTTPOptions.Stateless].
	Stateless bool

	// EventStore enables stream resumption.
	//
	// If set, EventStore will be used to persist stream events and replay them
	// upon stream resumption.
	EventStore EventStore
	// contains filtered or unexported fields
}

A StreamableServerTransport implements the server side of the MCP streamable transport.

Each StreamableServerTransport must be connected (via Server.Connect) at most once, since StreamableServerTransport.ServeHTTP serves messages to the connected session.

Reads from the streamable server connection receive messages from http POST requests from the client. Writes to the streamable server connection are sent either to the related stream, or to the standalone SSE stream, according to the following rules:

  • JSON-RPC responses to incoming requests are always routed to the appropriate HTTP response.
  • Requests or notifications made with a context.Context value derived from an incoming request handler, are routed to the HTTP response corresponding to that request, unless it has already terminated, in which case they are routed to the standalone SSE stream.
  • Requests or notifications made with a detached context.Context value are routed to the standalone SSE stream.

func (*StreamableServerTransport) Connect

Connect implements the Transport interface.

func (*StreamableServerTransport) ServeHTTP

ServeHTTP handles a single HTTP request for the session.

type SubscribeParams

type SubscribeParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The URI of the resource to subscribe to.
	URI string `json:"uri"`
}

Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.

type SubscribeRequest

type SubscribeRequest = ServerRequest[*SubscribeParams]

type SystemConfig

type SystemConfig struct {
	HostID        string              `json:"hostID,omitempty" mapstructure:"hostID"`
	HostName      string              `json:"hostName,omitempty" mapstructure:"hostName"`
	Ips           []string            `json:"ips,omitempty" mapstructure:"ips"`
	ConfigFile    string              `json:"configFile,omitempty" mapstructure:"configFile"`
	Heartbeat     HeartbeatConfig     `json:"heartbeat,omitempty" mapstructure:"heartbeat"`
	RuntimeUpdate RuntimeUpdateConfig `json:"runtimeUpdate,omitempty" mapstructure:"runtimeUpdate"`
	ThreadStorage ThreadStorageConfig `json:"threadStorage,omitempty" mapstructure:"threadStorage"`
	Debug         bool                `json:"debug,omitempty" mapstructure:"debug"`
	BaseDir       string              `json:"baseDir,omitempty" mapstructure:"baseDir"`
	Systool       map[string]ToolSpec `json:"systool,omitempty" mapstructure:"systool"`
	Env           string              `json:"env,omitempty" mapstructure:"env"`
	CloudOS       CloudOSConfig       `json:"cloudos,omitempty" mapstructure:"cloudos"`
	ModelIDs      []string            `json:"models,omitempty" mapstructure:"models"` // model ids
}

SystemConfig is process-level startup configuration.

type TextContent

type TextContent struct {
	Text        string
	Annotations *Annotations
}

TextContent is a textual content.

func (*TextContent) MarshalJSON

func (c *TextContent) MarshalJSON() ([]byte, error)

type ThreadActiveList

type ThreadActiveList struct {
	Threads []ThreadRuntimeInfo `json:"threads"`
}

type ThreadCanonicalMessageEntry

type ThreadCanonicalMessageEntry struct {
	ThreadEntryBase
	Message ConversationMessage `json:"message"`
}

type ThreadCompactionEntry

type ThreadCompactionEntry struct {
	ThreadEntryBase
	Summary          string `json:"summary"`
	FirstKeptEntryID string `json:"firstKeptEntryId"`
	TokensBefore     int64  `json:"tokensBefore,omitempty"`
}

type ThreadContinuationReason

type ThreadContinuationReason string
const (
	ThreadContinuationNone           ThreadContinuationReason = ""
	ThreadContinuationUserTail       ThreadContinuationReason = "user_tail"
	ThreadContinuationToolResultTail ThreadContinuationReason = "tool_result_tail"
	ThreadContinuationAssistantTool  ThreadContinuationReason = "assistant_tool_use"
	ThreadContinuationAssistantError ThreadContinuationReason = "assistant_error"
	ThreadContinuationAssistantAbort ThreadContinuationReason = "assistant_aborted"
)

type ThreadControlAck

type ThreadControlAck struct {
	OK             bool                `json:"ok"`
	ThreadID       string              `json:"threadID"`
	OpCode         OpCode              `json:"opcode"`
	QueuedMessages ThreadQueueSnapshot `json:"queuedMessages,omitempty"`
	RemovedItem    *ThreadQueueItem    `json:"removedItem,omitempty"`
}

type ThreadCreateParams

type ThreadCreateParams struct {
	AgentID        string `json:"agentID"`
	CWD            string `json:"cwd,omitempty"`
	ChatPath       string `json:"chatPath,omitempty"`
	FileID         string `json:"fileID,omitempty"`
	Title          string `json:"title"`
	ParentThreadID string `json:"parentThreadID,omitempty"`
}

type ThreadCreateResult

type ThreadCreateResult struct {
	ThreadID       string `json:"threadID"`
	FileID         string `json:"fileID,omitempty"`
	Title          string `json:"title"`
	CWD            string `json:"cwd,omitempty"`
	Path           string `json:"path,omitempty"`
	ChatPath       string `json:"chatPath,omitempty"`
	ThreadFilePath string `json:"threadFilePath,omitempty"`
}

type ThreadEntry

type ThreadEntry struct {
	Type      string          `json:"type,omitempty"`
	ID        string          `json:"id,omitempty"`
	ParentID  *string         `json:"parentId,omitempty"`
	Timestamp string          `json:"timestamp,omitempty"`
	Raw       json.RawMessage `json:"-"`
}

ThreadEntry is a durable JSONL thread entry. It exposes common entry metadata for revision/dedup logic while preserving the original wire object.

func DecodeThreadEntry

func DecodeThreadEntry(raw []byte) (ThreadEntry, error)

func (ThreadEntry) MarshalJSON

func (entry ThreadEntry) MarshalJSON() ([]byte, error)

func (*ThreadEntry) UnmarshalJSON

func (entry *ThreadEntry) UnmarshalJSON(raw []byte) error

type ThreadEntryBase

type ThreadEntryBase struct {
	Type      string  `json:"type"`
	ID        string  `json:"id"`
	ParentID  *string `json:"parentId"`
	Timestamp string  `json:"timestamp"`
}

type ThreadEntryWindow

type ThreadEntryWindow struct {
	Mode      string `json:"mode,omitempty"`
	AnchorID  string `json:"anchorId,omitempty"`
	Limit     int    `json:"limit,omitempty"`
	Start     int    `json:"start"`
	End       int    `json:"end"`
	Total     int    `json:"total"`
	HasBefore bool   `json:"hasBefore"`
	HasAfter  bool   `json:"hasAfter"`
}

type ThreadEntryWindowQuery

type ThreadEntryWindowQuery struct {
	Mode     string `json:"mode,omitempty"`
	AnchorID string `json:"anchorId,omitempty"`
	Limit    int    `json:"limit,omitempty"`
}

type ThreadForkParams

type ThreadForkParams struct {
	SourceThreadID    string `json:"sourceThreadID,omitempty"`
	SourceFileID      string `json:"sourceFileID,omitempty"`
	SourceChatPath    string `json:"sourceChatPath,omitempty"`
	AgentID           string `json:"agentID,omitempty"`
	CWD               string `json:"cwd,omitempty"`
	FileID            string `json:"fileID,omitempty"`
	ChatPath          string `json:"chatPath,omitempty"`
	Title             string `json:"title"`
	PlanPath          string `json:"planPath,omitempty"`
	ExecutionPlanPath string `json:"executionPlanPath,omitempty"`
}

type ThreadHeader

type ThreadHeader struct {
	Type              string `json:"type"`
	Version           int    `json:"version"`
	ID                string `json:"id"`
	Timestamp         string `json:"timestamp"`
	AgentID           string `json:"agentID"`
	CWD               string `json:"cwd"`
	ChatPath          string `json:"chatPath,omitempty"`
	FileID            string `json:"fileID,omitempty"`
	Title             string `json:"title"`
	ParentThreadID    string `json:"parentThreadID,omitempty"`
	PlanPath          string `json:"planPath,omitempty"`
	ExecutionPlanPath string `json:"executionPlanPath,omitempty"`
}

type ThreadMessageAckEntry

type ThreadMessageAckEntry struct {
	ThreadEntryBase
	MessageID string `json:"messageID"`
	Pending   bool   `json:"pending"`
}

type ThreadMessageAppendEntry

type ThreadMessageAppendEntry struct {
	ThreadEntryBase
	Record  MessageRecord `json:"record"`
	Pending bool          `json:"pending"`
}

type ThreadMessageUpdateEntry

type ThreadMessageUpdateEntry struct {
	ThreadEntryBase
	Record MessageRecord `json:"record"`
}

type ThreadMeta

type ThreadMeta struct {
	ThreadID          string `json:"threadID"`
	FileID            string `json:"fileID,omitempty"`
	AgentID           string `json:"agentID"`
	CWD               string `json:"cwd"`
	Path              string `json:"path,omitempty"`
	ChatPath          string `json:"chatPath,omitempty"`
	ThreadFilePath    string `json:"threadFilePath,omitempty"`
	Title             string `json:"title"`
	ParentThreadID    string `json:"parentThreadID,omitempty"`
	PlanPath          string `json:"planPath,omitempty"`
	ExecutionPlanPath string `json:"executionPlanPath,omitempty"`
}

type ThreadMetaQuery

type ThreadMetaQuery struct {
	ThreadID    string                  `json:"threadID,omitempty"`
	FileID      string                  `json:"fileID,omitempty"`
	ChatPath    string                  `json:"chatPath,omitempty"`
	AgentID     string                  `json:"agentID,omitempty"`
	EntryWindow *ThreadEntryWindowQuery `json:"entryWindow,omitempty"`
}

type ThreadMetaUpdateEntry

type ThreadMetaUpdateEntry struct {
	ThreadEntryBase
	Title             string `json:"title,omitempty"`
	ChatPath          string `json:"chatPath,omitempty"`
	FileID            string `json:"fileID,omitempty"`
	PlanPath          string `json:"planPath,omitempty"`
	ExecutionPlanPath string `json:"executionPlanPath,omitempty"`
}

type ThreadMetaUpdateParams

type ThreadMetaUpdateParams struct {
	ThreadID          string `json:"threadID,omitempty"`
	FileID            string `json:"fileID,omitempty"`
	ChatPath          string `json:"chatPath,omitempty"`
	Title             string `json:"title,omitempty"`
	PlanPath          string `json:"planPath,omitempty"`
	ExecutionPlanPath string `json:"executionPlanPath,omitempty"`
}

type ThreadQueueDequeueEntry

type ThreadQueueDequeueEntry struct {
	ThreadEntryBase
	QueueKind ThreadQueueKind `json:"queueKind"`
	ItemID    string          `json:"itemID"`
}

type ThreadQueueEnqueueEntry

type ThreadQueueEnqueueEntry struct {
	ThreadEntryBase
	QueueKind ThreadQueueKind `json:"queueKind"`
	Item      ThreadQueueItem `json:"item"`
}

type ThreadQueueItem

type ThreadQueueItem struct {
	ID                   string   `json:"id"`
	Message              Message  `json:"message"`
	AgentID              string   `json:"agentID,omitempty"`
	AgentName            string   `json:"agentName,omitempty"`
	CWD                  string   `json:"cwd,omitempty"`
	ModelKey             string   `json:"modelKey,omitempty"`
	ThinkingLevel        string   `json:"thinkingLevel,omitempty"`
	ContextWindow        int64    `json:"contextWindow,omitempty"`
	ServiceTier          string   `json:"serviceTier,omitempty"`
	SelectedSkillIDs     []string `json:"selectedSkillIDs,omitempty"`
	SelectedSkillContext Meta     `json:"selectedSkillContext,omitempty"`
	PlanTurn             bool     `json:"planTurn,omitempty"`
}

type ThreadQueueKind

type ThreadQueueKind string
const (
	ThreadQueueKindSteering ThreadQueueKind = "steering"
	ThreadQueueKindFollowUp ThreadQueueKind = "follow_up"
)

type ThreadQueuePromoteEntry

type ThreadQueuePromoteEntry struct {
	ThreadEntryBase
	ItemID string `json:"itemID"`
}

type ThreadQueueRemoveEntry

type ThreadQueueRemoveEntry struct {
	ThreadEntryBase
	QueueKind ThreadQueueKind `json:"queueKind"`
	Item      ThreadQueueItem `json:"item"`
}

type ThreadQueueSnapshot

type ThreadQueueSnapshot struct {
	Steering []ThreadQueueItem `json:"steering,omitempty"`
	FollowUp []ThreadQueueItem `json:"followUp,omitempty"`
}

type ThreadReviewDecision

type ThreadReviewDecision string
const (
	ThreadReviewDecisionApprove    ThreadReviewDecision = "approve"
	ThreadReviewDecisionReject     ThreadReviewDecision = "reject"
	ThreadReviewDecisionApproveAll ThreadReviewDecision = "approveAll"
	ThreadReviewDecisionRejectAll  ThreadReviewDecision = "rejectAll"
)

type ThreadReviewEntry

type ThreadReviewEntry struct {
	ThreadEntryBase
	TurnID string                 `json:"turnID"`
	Status ThreadReviewTurnStatus `json:"status"`
}

type ThreadReviewFile

type ThreadReviewFile struct {
	Path               string                  `json:"path"`
	Status             ThreadReviewFileStatus  `json:"status"`
	MergeState         ThreadReviewMergeState  `json:"mergeState,omitempty"`
	HasUserEdits       bool                    `json:"hasUserEdits,omitempty"`
	CanUndo            bool                    `json:"canUndo,omitempty"`
	ConflictMessage    string                  `json:"conflictMessage,omitempty"`
	Diff               string                  `json:"diff"`
	BaselineExists     bool                    `json:"baselineExists"`
	FirstChangedLine   int                     `json:"firstChangedLine,omitempty"`
	FirstChangedColumn int                     `json:"firstChangedColumn,omitempty"`
	LineCount          int                     `json:"lineCount,omitempty"`
	ChangedRanges      []ThreadReviewLineRange `json:"changedRanges,omitempty"`
	Hunks              []ThreadReviewHunk      `json:"hunks,omitempty"`
}

type ThreadReviewFileStatus

type ThreadReviewFileStatus string
const (
	ThreadReviewFilePending    ThreadReviewFileStatus = "pending"
	ThreadReviewFileApproved   ThreadReviewFileStatus = "approved"
	ThreadReviewFileRejected   ThreadReviewFileStatus = "rejected"
	ThreadReviewFileRolledBack ThreadReviewFileStatus = "rolledBack"
)

type ThreadReviewHunk

type ThreadReviewHunk struct {
	OldStartLine int      `json:"oldStartLine"`
	OldLineCount int      `json:"oldLineCount"`
	NewStartLine int      `json:"newStartLine"`
	NewLineCount int      `json:"newLineCount"`
	RemovedLines []string `json:"removedLines,omitempty"`
	AddedLines   []string `json:"addedLines,omitempty"`
}

type ThreadReviewLineRange

type ThreadReviewLineRange struct {
	StartLine int `json:"startLine"`
	EndLine   int `json:"endLine"`
}

type ThreadReviewListParams

type ThreadReviewListParams struct {
	ThreadID string `json:"threadID,omitempty"`
	ChatPath string `json:"chatPath,omitempty"`
}

type ThreadReviewListResult

type ThreadReviewListResult struct {
	Reviews []ThreadReviewState `json:"reviews,omitempty"`
}

type ThreadReviewMergeState

type ThreadReviewMergeState string
const (
	ThreadReviewMergeClean      ThreadReviewMergeState = "clean"
	ThreadReviewMergeUserEdited ThreadReviewMergeState = "userEdited"
	ThreadReviewMergeUserUndone ThreadReviewMergeState = "userUndone"
	ThreadReviewMergeConflicted ThreadReviewMergeState = "conflicted"
	ThreadReviewMergeMissing    ThreadReviewMergeState = "missing"
)

type ThreadReviewResolveParams

type ThreadReviewResolveParams struct {
	ThreadID string               `json:"threadID,omitempty"`
	ChatPath string               `json:"chatPath,omitempty"`
	TurnID   string               `json:"turnID"`
	Decision ThreadReviewDecision `json:"decision"`
	Path     string               `json:"path,omitempty"`
}

type ThreadReviewResolveResult

type ThreadReviewResolveResult struct {
	Review *ThreadReviewState `json:"review,omitempty"`
}

type ThreadReviewRollbackParams

type ThreadReviewRollbackParams struct {
	ThreadID string                    `json:"threadID,omitempty"`
	ChatPath string                    `json:"chatPath,omitempty"`
	TurnID   string                    `json:"turnID"`
	Scope    ThreadReviewRollbackScope `json:"scope"`
	Path     string                    `json:"path,omitempty"`
}

type ThreadReviewRollbackResult

type ThreadReviewRollbackResult struct {
	Review *ThreadReviewState `json:"review,omitempty"`
}

type ThreadReviewRollbackScope

type ThreadReviewRollbackScope string
const (
	ThreadReviewRollbackFile ThreadReviewRollbackScope = "file"
	ThreadReviewRollbackTurn ThreadReviewRollbackScope = "turn"
)

type ThreadReviewState

type ThreadReviewState struct {
	ThreadID        string                 `json:"threadID"`
	TurnID          string                 `json:"turnID"`
	ChatPath        string                 `json:"chatPath"`
	Status          ThreadReviewTurnStatus `json:"status"`
	CreatedAt       string                 `json:"createdAt"`
	CanReview       bool                   `json:"canReview"`
	CanRollback     bool                   `json:"canRollback"`
	Unresolved      int                    `json:"unresolved"`
	ApprovedCount   int                    `json:"approvedCount"`
	RejectedCount   int                    `json:"rejectedCount"`
	RolledBackCount int                    `json:"rolledBackCount"`
	ConflictCount   int                    `json:"conflictCount,omitempty"`
	Files           []ThreadReviewFile     `json:"files"`
}

type ThreadReviewTurnStatus

type ThreadReviewTurnStatus string
const (
	ThreadReviewTurnPending    ThreadReviewTurnStatus = "pending"
	ThreadReviewTurnResolved   ThreadReviewTurnStatus = "resolved"
	ThreadReviewTurnRolledBack ThreadReviewTurnStatus = "rolledBack"
)

type ThreadRunStatus

type ThreadRunStatus string
const (
	ThreadRunIdle    ThreadRunStatus = "idle"
	ThreadRunRunning ThreadRunStatus = "running"
)

type ThreadRuntimeInfo

type ThreadRuntimeInfo struct {
	ThreadID string `json:"threadID"`
	ChatPath string `json:"chatPath,omitempty"`
}

type ThreadStorageConfig

type ThreadStorageConfig struct {
	MaxThreads int `json:"maxThreads,omitempty" mapstructure:"maxThreads"`
}

type ThreadTailStatus

type ThreadTailStatus string
const (
	ThreadTailEmpty             ThreadTailStatus = "empty"
	ThreadTailComplete          ThreadTailStatus = "complete"
	ThreadTailNeedsContinuation ThreadTailStatus = "needs_continuation"
)

type TokenUsage

type TokenUsage struct {
	Prompt     int    `json:"prompt"`
	Completion int    `json:"completion"`
	Total      int    `json:"total"`
	Content    string `json:"content"`
}

type Tool

type Tool struct {
	// See [specification/2025-06-18/basic/index#general-fields] for notes on _meta
	// usage.
	Meta `json:"_meta,omitempty"`
	// Optional additional tool information.
	// Sampling
	Sampling bool `json:"sampling,omitempty"`
	// Display name precedence order is: title, annotations.title, then name.
	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"`
	// InputSchema holds a JSON Schema object defining the expected parameters
	// for the tool.
	//
	// From the server, this field may be set to any value that JSON-marshals to
	// valid JSON schema (including json.RawMessage). However, for tools added
	// using [AddTool], which automatically validates inputs and outputs, the
	// schema must be in a draft the SDK understands. Currently, the SDK uses
	// github.com/google/jsonschema-go for inference and validation, which only
	// supports the 2020-12 draft of JSON schema. To do your own validation, use
	// [Server.AddTool].
	//
	// From the client, this field will hold the default JSON marshaling of the
	// server's input schema (a map[string]any).
	InputSchema any `json:"inputSchema"`
	// Intended for programmatic or logical use, but used as a display name in past
	// specs or fallback (if title isn't present).
	Name string `json:"name"`
	// OutputSchema holds an optional JSON Schema object defining the structure
	// of the tool's output returned in the StructuredContent field of a
	// CallToolResult.
	//
	// From the server, this field may be set to any value that JSON-marshals to
	// valid JSON schema (including json.RawMessage). However, for tools added
	// using [AddTool], which automatically validates inputs and outputs, the
	// schema must be in a draft the SDK understands. Currently, the SDK uses
	// github.com/google/jsonschema-go for inference and validation, which only
	// supports the 2020-12 draft of JSON schema. To do your own validation, use
	// [Server.AddTool].
	//
	// From the client, this field will hold the default JSON marshaling of the
	// server's output schema (a map[string]any).
	OutputSchema any `json:"outputSchema,omitempty"`
	// Intended for UI and end-user contexts — optimized to be human-readable and
	// easily understood, even by those unfamiliar with domain-specific terminology.
	// If not provided, Annotations.Title should be used for display if present,
	// otherwise Name.
	Title string `json:"title,omitempty"`
	// Icons for the tool, if any.
	Icons []Icon `json:"icons,omitempty"`
}

Definition for a tool the client can call.

type ToolAnnotations

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 ToolCapabilities

type ToolCapabilities struct {
	// Whether this server supports notifications for changes to the tool list.
	ListChanged bool `json:"listChanged,omitempty"`
}

Present if the server offers any tools to call.

type ToolHandler

type ToolHandler func(context.Context, *CallToolRequest) (*CallToolResult, error)

A ToolHandler handles a call to tools/call.

This is a low-level API, for use with Server.AddTool. It does not do any pre- or post-processing of the request or result: the params contain raw arguments, no input validation is performed, and the result is returned to the user as-is, without any validation of the output.

Most users will write a ToolHandlerFor and install it with the generic AddTool function.

If ToolHandler returns an error, it is treated as a protocol error. By contrast, ToolHandlerFor automatically populates CallToolResult.IsError and CallToolResult.Content accordingly.

type ToolHandlerFor

type ToolHandlerFor[In, Out any] func(_ context.Context, request *CallToolRequest, input In) (result *CallToolResult, output Out, _ error)

A ToolHandlerFor handles a call to tools/call with typed arguments and results.

Use AddTool to add a ToolHandlerFor to a server.

Unlike ToolHandler, ToolHandlerFor provides significant functionality out of the box, and enforces that the tool conforms to the MCP spec:

  • The In type provides a default input schema for the tool, though it may be overridden in AddTool.
  • The input value is automatically unmarshaled from req.Params.Arguments.
  • The input value is automatically validated against its input schema. Invalid input is rejected before getting to the handler.
  • If the Out type is not the empty interface [any], it provides the default output schema for the tool (which again may be overridden in AddTool).
  • The Out value is used to populate result.StructuredOutput.
  • If CallToolResult.Content is unset, it is populated with the JSON content of the output.
  • An error result is treated as a tool error, rather than a protocol error, and is therefore packed into CallToolResult.Content, with [IsError] set.

For these reasons, most users can ignore the CallToolRequest argument and CallToolResult return values entirely. In fact, it is permissible to return a nil CallToolResult, if you only care about returning a output value or error. The effective result will be populated as described above.

type ToolListChangedParams

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

func (*ToolListChangedParams) GetProgressToken

func (x *ToolListChangedParams) GetProgressToken() any

func (*ToolListChangedParams) SetProgressToken

func (x *ToolListChangedParams) SetProgressToken(t any)

type ToolListChangedRequest

type ToolListChangedRequest = ClientRequest[*ToolListChangedParams]

type ToolSpec

type ToolSpec struct {
	ServerID    string `json:"serverID"`
	Name        string `json:"name"`
	Sampling    bool   `json:"sampling,omitempty"`
	Description string `json:"description"`
	InputSchema any    `json:"inputSchema,omitempty"`
}

type ToolUse

type ToolUse struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	InputSchema any    `json:"inputSchema,omitempty"`
}

type ToolsMeta

type ToolsMeta struct {
	Name        string      `json:"name"`
	Description string      `json:"description,omitempty"`
	Tools       []*ToolSpec `json:"tools,omitempty"`
}

type Transport

type Transport interface {
	// Connect returns the logical JSON-RPC connection..
	//
	// It is called exactly once by [Server.Connect] or [Client.Connect].
	Connect(ctx context.Context) (Connection, 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.Connect.

type TransportType

type TransportType string
const (
	Stdio          TransportType = "stdio"
	HttpStreamable TransportType = "http_streamable"
)

type TurnResultPayload

type TurnResultPayload struct {
	ThreadID          string                 `json:"threadID"`
	FileID            string                 `json:"fileID,omitempty"`
	TurnID            string                 `json:"turnID"`
	AgentID           string                 `json:"agentID"`
	Path              string                 `json:"path,omitempty"`
	ChatPath          string                 `json:"chatPath,omitempty"`
	Title             string                 `json:"title"`
	ParentThreadID    string                 `json:"parentThreadID,omitempty"`
	PlanTurn          bool                   `json:"planTurn,omitempty"`
	UserMessage       Message                `json:"userMessage"`
	AssistantText     string                 `json:"assistantText,omitempty"`
	ReasoningText     string                 `json:"reasoningText,omitempty"`
	ToolResults       []TurnResultToolResult `json:"toolResults,omitempty"`
	CanonicalMessages json.RawMessage        `json:"canonicalMessages,omitempty"`
}

type TurnResultToolResult

type TurnResultToolResult struct {
	ToolName        string         `json:"toolName"`
	ArgumentsObject map[string]any `json:"argumentsObject,omitempty"`
	ResultText      string         `json:"resultText"`
	IsError         bool           `json:"isError,omitempty"`
}

type UnsubscribeParams

type UnsubscribeParams struct {
	// This property is reserved by the protocol to allow clients and servers to
	// attach additional metadata to their responses.
	Meta `json:"_meta,omitempty"`
	// The URI of the resource to unsubscribe from.
	URI string `json:"uri"`
}

Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.

type UnsubscribeRequest

type UnsubscribeRequest = ServerRequest[*UnsubscribeParams]

type UserConfig

type UserConfig struct {
	DefaultModelKey string            `json:"defaultModelKey,omitempty" mapstructure:"defaultModelKey"`
	Strategies      *ModelStrategies  `json:"strategies,omitempty" mapstructure:"strategies"`
	Profile         *UserProfile      `json:"profile,omitempty" mapstructure:"profile"`
	Auth            *AuthConfig       `json:"auth,omitempty" mapstructure:"auth"`
	Models          []ModelConfig     `json:"models,omitempty" mapstructure:"models"`
	Nodes           map[string]OpNode `json:"nodes,omitempty" mapstructure:"nodes"` // map(nodeID)OpNode
}

type UserProfile

type UserProfile struct {
	UID         string `json:"uid,omitempty" mapstructure:"uid"`
	UserName    string `json:"username,omitempty" mapstructure:"userName"`
	Email       string `json:"email,omitempty" mapstructure:"email"`
	Avatar      string `json:"avatar,omitempty" mapstructure:"avatar"`
	LocalAvatar string `json:"localAvatar,omitempty" mapstructure:"localAvatar"`
	Provider    string `json:"provider,omitempty" mapstructure:"provider"`
	Address     string `json:"address,omitempty" mapstructure:"address"`
	UpdatedAt   int64  `json:"updatedAt,omitempty" mapstructure:"updatedAt"`
}

UserConfig is per-user runtime configuration.

type UserSettings

type UserSettings struct {
	UID            string `json:"uid" bson:"uid"`
	BaseDir        string `json:"baseDir,omitempty" bson:"baseDir,omitempty"`
	DefaultAgentID string `json:"defaultAgentID,omitempty" bson:"defaultAgentID,omitempty"`
	CreatedAt      int64  `json:"createdAt,omitempty" bson:"createdAt,omitempty"`
	UpdatedAt      int64  `json:"updatedAt,omitempty" bson:"updatedAt,omitempty"`
}

UserSettings stores per-user runtime preferences.

type UserTask

type UserTask struct {
	UID       string   `bson:"uid" json:"uid"`
	AppID     string   `bson:"appID,omitempty" json:"appID,omitempty"`
	TaskID    string   `bson:"taskID,omitempty" json:"taskID,omitempty"`
	TaskName  string   `bson:"taskName,omitempty" json:"taskName,omitempty"`
	ThreadIDs []string `bson:"threadIDs,omitempty" json:"threadIDs,omitempty"`
}

Jump to

Keyboard shortcuts

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