Documentation
¶
Index ¶
- Constants
- Variables
- func ResourceNotFoundError(uri string) error
- type CompletionError
- type CompletionFunc
- type CompletionRef
- type CompletionResult
- type ElicitationResult
- type Elicitor
- type Handler
- type MCPRequestContext
- func (r *MCPRequestContext) GetHeaders() http.Header
- func (r *MCPRequestContext) GetIdentifier() string
- func (r *MCPRequestContext) GetMeta() map[string]any
- func (r *MCPRequestContext) GetProgressToken() any
- func (r *MCPRequestContext) GetSession() *capabilities.Session
- func (r *MCPRequestContext) GetTokenInfo() *auth.TokenInfo
- type MCPServer
- type Option
- func WithCompletion(fn CompletionFunc) Option
- func WithHTTPTransport(opts ...mcpwrapper.TransportOptionStreamableHTTP) Option
- func WithName(name string) Option
- func WithPrompt(name, description string, fn PromptFunc) Option
- func WithPromptWithArgs(name, description string, args []*mcp.PromptArgument, fn PromptFunc) Option
- func WithRawTool(name, description string, inputSchema any, fn RawToolFunc, opts ...tool.Option) Option
- func WithResource(uri, description string, fn ResourceFunc) Option
- func WithResourceTemplate(uriTemplate, description string, fn ResourceFunc) Option
- func WithServer(server *mcp.Server) Option
- func WithServerConfig(opts *mcp.ServerOptions) Option
- func WithServerOptions(opts ...mcpwrapper.ServerOption) Option
- func WithTool[TIn, TOut any](name, description string, fn ToolFunc[TIn, TOut], opts ...tool.Option) Option
- func WithTransport(transport mcp.Transport) Option
- func WithTypedPrompt[TArgs any](name, description string, fn TypedPromptFunc[TArgs]) Option
- func WithVersion(version string) Option
- type PromptFunc
- type PromptMessage
- type PromptResult
- type RawToolFunc
- type RequestContext
- type ResourceContent
- type ResourceFunc
- type ToolError
- type ToolFunc
- type TypedPromptFunc
Constants ¶
const ( RefTypePrompt = "ref/prompt" RefTypeResource = "ref/resource" )
MCP completion reference types
const ( ElicitActionAccept = "accept" ElicitActionDecline = "decline" ElicitActionCancel = "cancel" )
Elicitation action constants defined by the MCP specification
const ( ErrorCodeValidation = "VALIDATION_ERROR" // Input validation failures ErrorCodeProcessing = "PROCESSING_ERROR" // Data processing issues ErrorCodeRateLimit = "RATE_LIMITED" // API rate limiting ErrorCodeInsufficientData = "INSUFFICIENT_DATA" // Missing required information ErrorCodeAuthentication = "AUTHENTICATION_ERROR" // Authentication failures ErrorCodeAuthorization = "AUTHORIZATION_ERROR" // Authorization/permission issues ErrorCodeNotFound = "NOT_FOUND" // Resource or entity not found ErrorCodeTimeout = "TIMEOUT" // Operation timeout )
Common tool error codes for categorizing user-facing tool errors
Variables ¶
var ( ErrEmptyValue = errors.New("value cannot be empty") ErrNilValue = errors.New("value cannot be nil") )
Configuration validation errors
var ( ErrInvalidJSONSchema = errors.New("invalid JSON schema") ErrNoSchemaProperties = errors.New("schema has no properties") )
Schema validation errors
var ( ErrInvalidJSON = errors.New("tool returned invalid JSON") ErrSchemaGeneration = errors.New("failed to generate schema") ErrNoContent = errors.New("no content to decode") ErrUnmarshalContent = errors.New("failed to unmarshal content") )
Runtime and operational errors
var ErrElicitationNotSupported = errors.New("client does not support elicitation")
ErrElicitationNotSupported is returned when attempting to elicit user input from a client that doesn't support the elicitation capability. Check capabilities.Session.SupportsElicitation() before calling elicitation functions.
var ErrInvalidTotal = errors.New("total must be 0 (unknown) or >= len(values)")
ErrInvalidTotal is returned when Total is set but is less than the number of Values
var ErrNoCompletions = errors.New("completion handler must return at least one value")
ErrNoCompletions is returned when a completion handler provides no suggestions
var ErrNoSession = errors.New("no session available in context")
ErrNoSession is returned when a session-dependent operation is attempted without an active MCP session in the context. This typically occurs when calling sampling, elicitation, or logging functions outside of a proper tool, prompt, or resource handler execution.
var ErrSamplingNotSupported = errors.New("client does not support sampling")
ErrSamplingNotSupported is returned when attempting to use CreateMessage (sampling) with a client that doesn't support the sampling capability. Check capabilities.Session.SupportsSampling() before calling CreateMessage.
var ErrUnsupportedRefType = errors.New("unsupported completion reference type")
ErrUnsupportedRefType is returned when the reference type is not supported
Functions ¶
func ResourceNotFoundError ¶
ResourceNotFoundError returns a protocol-level error indicating that a resource could not be found. This provides the proper MCP error code (-32002) for resource not found conditions.
Types ¶
type CompletionError ¶
type CompletionError struct {
// contains filtered or unexported fields
}
CompletionError represents a user-facing completion error. Use this for errors that should be returned to the MCP client (e.g., unsupported ref types).
func NewCompletionError ¶
func NewCompletionError(msg string) *CompletionError
NewCompletionError creates a new completion error with the given message
func (*CompletionError) Error ¶
func (e *CompletionError) Error() string
type CompletionFunc ¶
type CompletionFunc func(context.Context, RequestContext, CompletionRef) (*CompletionResult, error)
CompletionFunc is the function signature for user-defined completion handlers. The function receives context, request metadata, completion reference details, and returns completion suggestions with optional metadata.
Example:
func myCompletionHandler(ctx context.Context, reqCtx mcpio.RequestContext, ref CompletionRef) (*CompletionResult, error) {
if ref.Type == mcpio.RefTypePrompt && ref.Name == "greet" {
return &CompletionResult{
Values: []string{"Hello", "Hi", "Greetings"},
}, nil
}
return nil, mcpio.NewCompletionError("unsupported reference type")
}
type CompletionRef ¶
type CompletionRef struct {
// Type indicates what kind of reference this is (e.g., "ref/prompt", "ref/resource")
Type string
// Name is the name of the prompt being completed (used with "ref/prompt")
Name string
// URI is the resource URI being completed (used with "ref/resource")
URI string
// Argument is the specific argument name being completed within a prompt
Argument string
// Value is the current input value for the argument being completed
Value string
// Context contains previously-resolved arguments for dependency-aware completions.
// For example, if completing a "style" argument and the user has already selected
// language="Spanish", Context would contain {"language": "Spanish"}.
Context map[string]string
}
CompletionRef contains information about what is being completed. This maps to mcp.CompleteRequest.Params.Ref with user-friendly field names.
type CompletionResult ¶
type CompletionResult struct {
// Values contains the completion suggestions (required, max recommended: 100)
Values []string
// HasMore indicates if additional completions are available beyond this set (optional)
// Default: false (all completions provided)
HasMore bool
// Total indicates the total number of completions available (optional)
// Use 0 or omit if unknown. When HasMore is true, Total > len(Values)
Total int
// Meta is protocol-reserved metadata for extensibility (optional)
Meta map[string]any
}
CompletionResult represents completion suggestions returned by a completion handler. This provides a simplified, opinionated interface compared to the raw SDK types.
func (*CompletionResult) Validate ¶
func (r *CompletionResult) Validate() error
Validate ensures the CompletionResult is well-formed before returning to the SDK
type ElicitationResult ¶
type ElicitationResult struct {
*mcp.ElicitResult
}
ElicitationResult provides typed access to elicitation results. This wraps the raw MCP ElicitResult with convenience methods.
func ElicitTyped ¶
func ElicitTyped[T any](ctx context.Context, elicitor *Elicitor, message string) (*ElicitationResult, error)
ElicitTyped sends an elicitation request with automatic schema generation from a Go struct. The schema is generated from struct tags, allowing you to specify validation rules, descriptions, and constraints.
Example:
type UserConfig struct {
Name string `json:"name" jsonschema:"Your full name"`
Email string `json:"email" jsonschema:"format=email"`
EnableUI bool `json:"enableUI" jsonschema:"Enable graphical interface"`
}
func myTool(ctx context.Context, toolCtx mcpio.RequestContext, input MyInput) (MyOutput, error) {
elicitor := mcpio.NewElicitor(toolCtx)
result, err := mcpio.ElicitTyped[UserConfig](ctx, elicitor, "Please provide your configuration:")
if err != nil {
return MyOutput{}, err
}
if result.IsAccepted() {
var config UserConfig
if err := result.DecodeContent(&config); err != nil {
return MyOutput{}, err
}
// Use config...
}
return MyOutput{}, nil
}
Schema Tags: Use jsonschema struct tags for validation:
- description: Human-readable field description
- minimum/maximum: Numeric constraints
- enum: Allowed values (enum=option1,enum=option2)
- format: String format (email, uri, etc.)
func WrapElicitResult ¶
func WrapElicitResult(result *mcp.ElicitResult) *ElicitationResult
WrapElicitResult wraps an MCP ElicitResult with convenience methods.
func (*ElicitationResult) DecodeContent ¶
func (r *ElicitationResult) DecodeContent(target any) error
DecodeContent decodes the elicitation content into the target struct. This eliminates the need for manual JSON marshaling/unmarshaling when working with typed elicitation results.
Example usage:
type UserConfig struct {
Name string `json:"name"`
Email string `json:"email"`
}
result, err := ElicitTypedResult[UserConfig](ctx, capability, "Enter config:")
if err != nil {
return err
}
if result.IsAccepted() {
var config UserConfig
if err := result.DecodeContent(&config); err != nil {
return fmt.Errorf("failed to decode config: %w", err)
}
// Use config...
}
The method returns an error if:
- The elicitation was not accepted (content is nil)
- JSON marshaling/unmarshaling fails
- The target is not a valid pointer
func (*ElicitationResult) GetContent ¶
func (r *ElicitationResult) GetContent() map[string]any
GetContent returns the submitted form data when the action is "accept". Returns nil if the user declined or cancelled.
Example:
result, err := ElicitSimple(ctx, capability, "Name:", "name", "Your name")
if err != nil {
return nil, err
}
if content := result.GetContent(); content != nil {
name := content["name"].(string)
// Use name...
} else {
// User declined or cancelled
}
func (*ElicitationResult) IsAccepted ¶
func (r *ElicitationResult) IsAccepted() bool
IsAccepted returns true if the user accepted the elicitation.
Example:
result, err := ElicitTyped[Config](ctx, capability, "Enter configuration:")
if err != nil {
return nil, err
}
if result.IsAccepted() {
// User provided data - process result.Content
data := result.GetContent()
// Convert to your struct...
}
func (*ElicitationResult) IsCancelled ¶
func (r *ElicitationResult) IsCancelled() bool
IsCancelled returns true if the user cancelled/dismissed the elicitation.
Example:
result, err := ElicitTyped[Config](ctx, capability, "Enter config:")
if err != nil {
return nil, err
}
if result.IsCancelled() {
return map[string]any{"status": "cancelled"}, nil
}
func (*ElicitationResult) IsDeclined ¶
func (r *ElicitationResult) IsDeclined() bool
IsDeclined returns true if the user explicitly declined the elicitation.
Example:
result, err := ElicitSimple(ctx, capability, "Continue?", "confirm", "Type yes/no")
if err != nil {
return nil, err
}
if result.IsDeclined() {
return map[string]any{"status": "user_declined"}, nil
}
type Elicitor ¶
type Elicitor struct {
// contains filtered or unexported fields
}
Elicitor provides elicitation functionality for interactive user input. Create via mcpio.NewElicitor(toolCtx) in tool functions.
func NewElicitor ¶
func NewElicitor(toolCtx RequestContext) *Elicitor
NewElicitor creates an Elicitor with the given RequestContext. This allows elicitation to access the session and validate elicitation support.
func (*Elicitor) ElicitSimple ¶
func (e *Elicitor) ElicitSimple(ctx context.Context, message, fieldName, description string) (*ElicitationResult, error)
ElicitSimple is a convenience function for simple string input elicitation. The session is automatically extracted from the context. This creates a schema for a single string field with the specified name and description. It's ideal for quick confirmations, simple text inputs, or collecting single values.
Example:
func myTool(ctx context.Context, input MyInput) (MyOutput, error) {
result, err := mcpio.ElicitSimple(ctx, "Enter your username:", "username", "Your account username")
if err != nil {
return MyOutput{}, err
}
if result.IsAccepted() {
username := result.GetContent()["username"].(string)
// Use username...
}
return MyOutput{}, nil
}
Confirmation Example:
result, err := mcpio.ElicitSimple(ctx,
"Delete all files? This cannot be undone.", "confirm", "Type 'DELETE' to confirm")
if err != nil {
return MyOutput{}, err
}
if result.IsAccepted() {
if confirmation := result.GetContent()["confirm"].(string); confirmation == "DELETE" {
// Proceed with deletion
}
}
The fieldName parameter becomes the key in the returned Content map. The description parameter guides the user on what to enter.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler is the main MCP handler struct
func NewHandler ¶
NewHandler creates a new MCP handler that supports any combination of MCP resources. This is the unified constructor that can handle tools, prompts, resources, and resource templates.
func NewInMemoryPair ¶
NewInMemoryPair creates a Handler and client Transport for in-memory communication. This is useful for testing and integrating mcp-io servers with MCP clients like Google ADK.
The returned handler is configured with an in-memory server transport, and the returned client transport can be used to connect to the server. The handler must be started with Run() before the client transport is used.
Example with Google ADK:
handler, clientTransport, err := mcpio.NewInMemoryPair(ctx,
mcpio.WithTool("weather", "Get weather", getWeather),
)
if err != nil {
log.Fatal(err)
}
// Start server in background
var wg sync.WaitGroup
wg.Go(func() {
if err := handler.Run(ctx); err != nil {
log.Printf("Server error: %v", err)
}
})
defer wg.Wait()
// Use with ADK (requires google.golang.org/adk)
mcpToolSet, err := mcptoolset.New(mcptoolset.Config{
Transport: clientTransport,
})
if err != nil {
log.Fatal(err)
}
agent, err := llmagent.New(llmagent.Config{
Toolsets: []tool.Toolset{mcpToolSet},
})
func (*Handler) GetTransport ¶
GetTransport returns the currently configured transport for this handler. Returns nil if no transport has been set.
This is useful for advanced use cases where access to the underlying transport is needed, such as when integrating with external MCP client libraries like Google ADK.
For common use cases with in-memory transports, consider using NewInMemoryPair() instead, which returns both the handler and client transport in one call.
Example:
handler, _ := mcpio.NewHandler(mcpio.WithTool(...)) transport := handler.GetTransport() // transport can now be used with external MCP clients
func (*Handler) Run ¶
Run starts the MCP server with the configured transport. This is the main entry point for starting the server.
For stdio transport (default), this reads from os.Stdin and writes to os.Stdout. For in-memory transport (from NewInMemoryPair), this connects to the paired client transport. For HTTP transport, use ServeHTTP instead.
func (*Handler) ServeHTTP ¶
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler for Streamable HTTP transport. Delegates to the MCPServer's ServeHTTP method.
func (*Handler) ServeStdio
deprecated
ServeStdio runs the server using stdio transport for command-line tools. Uses os.Stdin and os.Stdout as configured by the MCP SDK.
Deprecated: Use Run() instead. ServeStdio is kept for backward compatibility but Run() is the preferred method as it works with any transport type.
type MCPRequestContext ¶
type MCPRequestContext struct {
// MCPParams contains raw MCP request parameters.
Params mcp.Params
// Session provides access to MCP session capabilities (sampling, elicitation, logging, etc).
// Never nil - always contains a valid session instance.
Session *capabilities.Session
// Identifier is the name or URI for the current request:
// - Tool requests: tool name
// - Prompt requests: prompt name
// - Resource requests: resource URI
Identifier string
// TokenInfo contains OAuth token information when the request includes authentication.
// Nil if no token is present in the request.
TokenInfo *auth.TokenInfo
// Headers contains HTTP headers when the request was made via HTTP transport.
// Never nil - always contains a valid (possibly empty) http.Header map.
Headers http.Header
}
MCPRequestContext holds all MCP request metadata and implements the RequestContext interface. This struct is created once per request and passed directly to the primitives (tool, prompt, resource).
Exported to enable test mocking. Tests construct MCPRequestContext instances with mock sessions when testing elicitation, logging, and other session-dependent functionality.
func (*MCPRequestContext) GetHeaders ¶
func (r *MCPRequestContext) GetHeaders() http.Header
GetHeaders returns all HTTP headers from the request. Never returns nil - returns empty http.Header{} if no headers present.
func (*MCPRequestContext) GetIdentifier ¶
func (r *MCPRequestContext) GetIdentifier() string
GetIdentifier returns the identifier for the current request. For tools, this is the tool name. For prompts, the prompt name. For resources, the URI.
func (*MCPRequestContext) GetMeta ¶
func (r *MCPRequestContext) GetMeta() map[string]any
GetMeta returns MCP request metadata as a map[string]any.
func (*MCPRequestContext) GetProgressToken ¶
func (r *MCPRequestContext) GetProgressToken() any
GetProgressToken returns the progress token from the request params if available. Returns nil if the params don't support progress tokens or no token is present.
func (*MCPRequestContext) GetSession ¶
func (r *MCPRequestContext) GetSession() *capabilities.Session
GetSession returns the MCP session for accessing session capabilities like logging, elicitation, and sampling.
func (*MCPRequestContext) GetTokenInfo ¶
func (r *MCPRequestContext) GetTokenInfo() *auth.TokenInfo
GetTokenInfo returns OAuth token information from the request if available. Returns nil if no token was provided.
type MCPServer ¶
type MCPServer interface {
// Tool registration
AddTool(tool *mcp.Tool, handler mcp.ToolHandler)
// Prompt registration
AddPrompt(prompt *mcp.Prompt, handler mcp.PromptHandler)
// Resource registration
AddResource(resource *mcp.Resource, handler mcp.ResourceHandler)
AddResourceTemplate(template *mcp.ResourceTemplate, handler mcp.ResourceHandler)
// Transport - run the server with configured transport
Run(ctx context.Context) error
// GetTransport returns the currently configured transport
GetTransport() mcp.Transport
// ServeHTTP implements http.Handler for Streamable HTTP transport
ServeHTTP(w http.ResponseWriter, r *http.Request)
// Unwrap returns the underlying SDK server for advanced usage.
// Returns *mcp.Server from github.com/modelcontextprotocol/go-sdk/mcp
// Returns nil if this is a mock implementation.
Unwrap() any
}
MCPServer provides an interface to the concrete MCP SDK server instance.
The Unwrap method provides an escape hatch for power users who need access to features not yet wrapped by mcp-io.
type Option ¶
type Option func(*handlerConfig) error
Option is a functional option for configuring handlers
func WithCompletion ¶
func WithCompletion(fn CompletionFunc) Option
WithCompletion adds a completion handler to the server. The completion handler provides autocomplete suggestions for prompts, resources, or custom reference types.
Only ONE completion handler can be registered per server. Multiple calls to WithCompletion will result in only the last handler being used (SDK limitation).
Example:
mcpio.WithCompletion(func(ctx context.Context, reqCtx mcpio.RequestContext, ref mcpio.CompletionRef) (*mcpio.CompletionResult, error) {
switch ref.Type {
case "ref/prompt":
if ref.Name == "greet" && ref.Argument == "language" {
return &mcpio.CompletionResult{
Values: []string{"English", "Spanish", "French", "German"},
}, nil
}
case "ref/resource":
return &mcpio.CompletionResult{
Values: []string{"file:///data1.txt", "file:///data2.txt"},
}, nil
}
return nil, mcpio.NewCompletionError("unsupported reference type")
})
func WithHTTPTransport ¶
func WithHTTPTransport(opts ...mcpwrapper.TransportOptionStreamableHTTP) Option
WithHTTPTransport configures the Streamable HTTP transport. Accepts variadic TransportOption functions for configuration (e.g., mcp.WithStateless()).
Example:
mcpio.WithHTTPTransport(
mcp.WithStateless(),
mcp.WithJSONResponse(),
)
func WithPrompt ¶
func WithPrompt(name, description string, fn PromptFunc) Option
WithPrompt adds a prompt to the handler
func WithPromptWithArgs ¶
func WithPromptWithArgs(name, description string, args []*mcp.PromptArgument, fn PromptFunc) Option
WithPromptWithArgs adds a prompt with argument definitions
func WithRawTool ¶
func WithRawTool(name, description string, inputSchema any, fn RawToolFunc, opts ...tool.Option) Option
WithRawTool adds a tool with manual JSON handling and explicit schema. Use this when you need direct control over JSON processing or dynamic schemas. Optional metadata can be provided via functional options from primitives/tool package.
Examples:
rawFunc := func(ctx context.Context, input []byte) ([]byte, error) { return input, nil }
WithRawTool("process", "Process JSON", `{"type":"object"}`, rawFunc)
// With metadata (recommended import alias: import toolOption "github.com/robbyt/mcp-io/primitives/tool")
WithRawTool("process", "Process JSON", inputSchema, rawFunc,
toolOption.WithTitle("JSON Processor"),
toolOption.WithReadOnly(),
)
func WithResource ¶
func WithResource(uri, description string, fn ResourceFunc) Option
WithResource adds a resource to the handler
func WithResourceTemplate ¶
func WithResourceTemplate(uriTemplate, description string, fn ResourceFunc) Option
WithResourceTemplate adds a resource template to the handler
func WithServer ¶
WithServer allows injecting a custom server for testing
func WithServerConfig ¶
func WithServerConfig(opts *mcp.ServerOptions) Option
WithServerConfig sets the complete MCP server options struct. Use this for advanced configurations requiring handler functions. For simple configurations, prefer WithServerOptions with functional options.
func WithServerOptions ¶
func WithServerOptions(opts ...mcpwrapper.ServerOption) Option
WithServerOptions configures MCP server options using functional options. Accepts variadic ServerOption functions for configuration.
Example:
mcpio.WithServerOptions(
mcp.WithInstructions("Use this server for data processing"),
mcp.WithPageSize(50),
mcp.WithCapabilityPrompts(),
)
func WithTool ¶
func WithTool[TIn, TOut any](name, description string, fn ToolFunc[TIn, TOut], opts ...tool.Option) Option
WithTool adds a type-safe tool with automatic schema generation from Go types.
The InputSchema is automatically generated from the TIn type parameter. Optional metadata can be provided using functional options from the primitives/tool package.
Examples:
// Simple case: Auto-generated schemas only
WithTool("to_upper", "Convert text to uppercase", toUpperFunc)
// With metadata options (recommended import alias: import toolOption "github.com/robbyt/mcp-io/primitives/tool")
WithTool("to_upper", "Convert text to uppercase", toUpperFunc,
toolOption.WithTitle("Text Uppercaser"),
toolOption.WithReadOnly(),
toolOption.WithIdempotent(),
)
func WithTransport ¶
WithTransport sets a custom transport for the handler. By default, handlers use StdioTransport. This option allows using in-memory or HTTP transports for testing or integration scenarios.
This is primarily useful for:
- Testing with in-memory transports
- Integration with external libraries like Google ADK
- Custom transport implementations
For most use cases, consider using NewInMemoryPair() instead, which handles transport setup automatically.
Example with custom transport:
serverTransport, clientTransport := mcp.NewInMemoryTransports()
handler, _ := mcpio.NewHandler(
mcpio.WithTransport(serverTransport),
mcpio.WithTool("echo", "Echo tool", echoFunc),
)
// Start server with handler.Run(ctx)
// Connect client using clientTransport
func WithTypedPrompt ¶
func WithTypedPrompt[TArgs any](name, description string, fn TypedPromptFunc[TArgs]) Option
WithTypedPrompt adds a type-safe prompt with automatic schema generation
type PromptFunc ¶
type PromptFunc func(context.Context, RequestContext, map[string]any) (*PromptResult, error)
PromptFunc is the function signature for user-defined prompt handlers. The function receives a context, request context with metadata, and a map of arguments, and returns a PromptResult with an optional error.
type PromptMessage ¶
type PromptMessage struct {
Role string `json:"role"` // "user", "assistant", "system"
Content string `json:"content"`
}
PromptMessage represents a single message in a prompt
type PromptResult ¶
type PromptResult struct {
Messages []PromptMessage `json:"messages"`
Description string `json:"description,omitempty"`
}
PromptResult represents the result of prompt generation
type RawToolFunc ¶
RawToolFunc is the function signature for raw JSON tools. The function receives a context, RequestContext for accessing session/metadata, and raw JSON bytes as input, and returns JSON bytes as output. Schema must be provided explicitly when using WithRawTool.
type RequestContext ¶
type RequestContext interface {
// GetSession returns the MCP session for accessing session capabilities like
// logging, elicitation, and sampling.
GetSession() *capabilities.Session
// GetIdentifier returns the identifier for the current request.
// For tools: tool name, for prompts: prompt name, for resources: URI.
GetIdentifier() string
// GetTokenInfo returns OAuth token information if present, nil otherwise.
GetTokenInfo() *auth.TokenInfo
// GetHeaders returns HTTP headers from the request.
GetHeaders() http.Header
// GetProgressToken returns the progress token from the request params if present.
// Progress tokens are opaque identifiers (int or string per MCP specification) that
// associate progress notifications with their originating request, enabling proper
// concurrent request tracking. The token must be echoed back exactly as received
// for client-side matching to work correctly. Returns nil if no token is present.
GetProgressToken() any
// contains filtered or unexported methods
}
RequestContext provides access to MCP request metadata and session capabilities. RequestContext implements this interface and is passed directly to tool functions, eliminating the need for context storage and retrieval.
type ResourceContent ¶
type ResourceContent struct {
Content []byte `json:"content"`
MIMEType string `json:"mimeType,omitempty"`
}
ResourceContent represents the content of a resource
type ResourceFunc ¶
type ResourceFunc func(context.Context, RequestContext) (*ResourceContent, error)
ResourceFunc is the function signature for user-defined resource handlers. The function receives a context, request context with metadata, and returns ResourceContent with an optional error. The URI can be accessed via reqCtx.GetIdentifier().
type ToolError ¶
ToolError represents a user-facing tool execution error that becomes visible to LLMs. When returned from tool functions, the MCP SDK automatically wraps these in CallToolResult with IsError=true, allowing LLMs to see the error and potentially retry or self-correct.
func NewToolError ¶
NewToolError creates a new tool error with the given message.
Tool errors are user-facing errors that become visible to LLMs in the CallToolResult. When returned from tool functions, the MCP SDK automatically:
- Sets CallToolResult.IsError = true
- Includes the error message in CallToolResult.Content
- Allows the LLM to see the error and potentially retry or self-correct
Use tool errors for validation failures, input problems, or other issues that the LLM should be aware of and can potentially fix.
For system-level errors (authentication, network, etc.) that should be hidden from the LLM, return regular Go errors instead.
func NewToolErrorWithCode ¶
NewToolErrorWithCode creates a new tool error with message and error code.
The error code provides categorization for different types of tool errors, which can be useful for client-side error handling, analytics, and structured error responses. Use the ErrorCode* constants for common error types.
Like NewToolError, these become visible to LLMs through CallToolResult.
func ProcessingError ¶
ProcessingError is a convenience function for creating processing tool errors
func ValidationError ¶
ValidationError is a convenience function for creating validation tool errors
type ToolFunc ¶
type ToolFunc[TIn, TOut any] func(context.Context, RequestContext, TIn) (TOut, error)
ToolFunc is the function signature for typed tools with automatic schema generation. The function receives a context, RequestContext for accessing session/metadata, typed input, and returns typed output with an optional error. Schema generation is handled automatically based on the TIn and TOut types.
type TypedPromptFunc ¶
type TypedPromptFunc[TArgs any] func(context.Context, RequestContext, TArgs) (*PromptResult, error)
TypedPromptFunc is the function signature for typed prompts with automatic schema generation. The function receives a context, request context with metadata, and typed arguments, and returns a PromptResult with an optional error. Schema generation is handled automatically based on the TArgs type.
Example:
type DocumentArgs struct {
DocumentType string `json:"document_type" jsonschema:"description:Type of document"`
Topic string `json:"topic" jsonschema:"description:Main topic"`
}
func myPrompt(ctx context.Context, reqCtx mcpio.RequestContext, args DocumentArgs) (*PromptResult, error) { ... }
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
sampling
Package sampling provides options for configuring LLM sampling requests.
|
Package sampling provides options for configuring LLM sampling requests. |
|
examples
|
|
|
cli_agent
command
|
|
|
cli_completion
command
|
|
|
cli_elicitation
command
|
|
|
cli_prompt
command
|
|
|
cli_resource
command
|
|
|
cli_simple
command
|
|
|
http_multistep
command
|
|
|
mixed_resources
command
|
|
|
schema_flexibility
command
|
|
|
simple_dungeon_master
command
|
|
|
internal
|
|
|
Package mcpwrapper provides a wrapper around the MCP SDK server to simplify transport configuration and provide a consistent interface for both stdio and HTTP transports.
|
Package mcpwrapper provides a wrapper around the MCP SDK server to simplify transport configuration and provide a consistent interface for both stdio and HTTP transports. |
|
primitives
|
|
|
tool
Package tool provides constructors for MCP Tool primitives using functional options.
|
Package tool provides constructors for MCP Tool primitives using functional options. |