Documentation
¶
Index ¶
- Constants
- Variables
- func ContextWithSession(ctx context.Context, notify NotifyFunc, request RequestFunc, ...) context.Context
- func EmitLog(ctx context.Context, level LogLevel, logger string, data any)
- func EmitProgress(ctx context.Context, token any, progress, total float64, message string)
- func HasScope(ctx context.Context, scope string) bool
- func IsJSONRPCResponse(data []byte) bool
- func MarshalNotification(method string, params any) (json.RawMessage, error)
- func Notify(ctx context.Context, method string, params any) bool
- func ParseWWWAuthenticate(header string) (resourceMetadata string, scopes []string, err error)
- type AuthError
- type AuthValidator
- type Claims
- type ClaimsProvider
- type ClientCapabilities
- type ClientInfo
- type CompletionArgument
- type CompletionHandler
- type CompletionRef
- type CompletionResult
- type Content
- type CreateMessageRequest
- type CreateMessageResult
- type ElicitationRequest
- type ElicitationResult
- type Error
- type Extension
- type ExtensionProvider
- type LogLevel
- type LogMessage
- type ModelHint
- type ModelPreferences
- type NotificationHandler
- type NotifyFunc
- type ProgressNotification
- type PromptArgument
- type PromptDef
- type PromptHandler
- type PromptMessage
- type PromptRequest
- type PromptResult
- type Request
- type RequestFunc
- type ResourceContent
- type ResourceDef
- type ResourceHandler
- type ResourceReadContent
- type ResourceRequest
- type ResourceResult
- type ResourceTemplate
- type ResourceUpdatedNotification
- type Response
- type RootsCap
- type SamplingMessage
- type ScopeAwareTokenSource
- type ServerInfo
- type ServerRequestHandler
- type Stability
- type TemplateHandler
- type TokenSource
- type ToolDef
- type ToolHandler
- type ToolRequest
- type ToolResult
- type Transport
Constants ¶
const ( ErrCodeParse = -32700 ErrCodeInvalidRequest = -32600 ErrCodeMethodNotFound = -32601 ErrCodeInvalidParams = -32602 ErrCodeInternal = -32603 // ErrCodeServerError is the base code for custom server errors (-32000 to -32099). // Use this for application-specific errors that are not covered by standard codes. ErrCodeServerError = -32000 )
Standard JSON-RPC 2.0 error codes (https://www.jsonrpc.org/specification#error_object).
Reserved ranges:
-32700 Parse error (invalid JSON) -32600 Invalid Request (not a valid JSON-RPC request) -32601 Method not found -32602 Invalid params -32603 Internal error -32000 to -32099 Server error (implementation-defined)
const StreamableHTTPAccept = "application/json, text/event-stream"
StreamableHTTPAccept is the Accept header value for Streamable HTTP requests. Per MCP spec: clients MUST include both application/json and text/event-stream.
Variables ¶
var ErrElicitationNotSupported = errors.New("client does not support elicitation")
Sentinel errors for elicitation.
var ErrNoRequestFunc = errors.New("server-to-client requests not available in this context")
ErrNoRequestFunc is returned when Sample() or Elicit() is called outside a session context where server-to-client requests are not available (e.g., no transport wired, or stateless mode).
var ErrSamplingNotSupported = errors.New("client does not support sampling")
Sentinel errors for sampling.
Functions ¶
func ContextWithSession ¶
func ContextWithSession(ctx context.Context, notify NotifyFunc, request RequestFunc, logLevel *atomic.Pointer[LogLevel], clientCaps *ClientCapabilities, claims *Claims) context.Context
ContextWithSession returns a context carrying the session's notification state, request sender, client capabilities, and authenticated claims. Exported for use by the server sub-package; tool handlers should use EmitLog, Sample, Elicit, AuthClaims instead.
func EmitLog ¶
EmitLog sends a notifications/message to the connected client if the session's log level allows it. Safe to call even if no session context is present (no-op).
level is the severity of the message. logger is an optional logger name (typically the tool or subsystem name). data is the log payload (string, map, etc.).
Usage in a tool handler:
func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
mcpkit.EmitLog(ctx, mcpkit.LogInfo, "my-tool", "processing started")
// ... do work ...
return mcpkit.TextResult("done"), nil
}
func EmitProgress ¶
EmitProgress sends a notifications/progress to the connected client. Safe to call even if no session context is present or if token is nil (both are no-ops).
token is the ProgressToken from the ToolRequest — pass req.ProgressToken directly. progress is the current progress value, total is the expected total (0 for indeterminate). message is an optional human-readable status string.
Usage in a tool handler:
func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
mcpkit.EmitProgress(ctx, req.ProgressToken, 0, 100, "starting")
// ... do work ...
mcpkit.EmitProgress(ctx, req.ProgressToken, 50, 100, "halfway")
// ... more work ...
mcpkit.EmitProgress(ctx, req.ProgressToken, 100, 100, "done")
return mcpkit.TextResult("complete"), nil
}
func HasScope ¶
HasScope checks if the context's authenticated claims include the given scope. Returns false if no claims are present.
func IsJSONRPCResponse ¶
isJSONRPCResponse detects whether raw JSON is a JSON-RPC response (not a request). A response has an "id" field and either "result" or "error", but no "method" field. Used by transports to route incoming client messages that are responses to server-to-client requests (sampling/createMessage, elicitation/create).
func MarshalNotification ¶
func MarshalNotification(method string, params any) (json.RawMessage, error)
MarshalNotification builds a JSON-RPC notification (no id field). Exported for use by the server transport sub-package.
func Notify ¶
Notify sends an arbitrary server-to-client JSON-RPC notification. Returns false if no notification sender is available in the context. This is the low-level API; prefer EmitLog for logging notifications.
func ParseWWWAuthenticate ¶
ParseWWWAuthenticate extracts the resource_metadata URL and scopes from a WWW-Authenticate: Bearer header value. Used by MCP clients to discover the PRM endpoint after receiving a 401, and to parse required scopes from a 403 insufficient_scope response.
Per MCP spec (2025-11-25): clients MUST use resource_metadata from WWW-Authenticate when present.
Types ¶
type AuthError ¶
type AuthError struct {
Code int
Message string
WWWAuthenticate string // optional WWW-Authenticate header value
}
AuthError is returned when authentication fails.
type AuthValidator ¶
AuthValidator validates an HTTP request and returns claims on success.
type Claims ¶
type Claims struct {
// Subject is the authenticated principal (user ID or client ID).
Subject string `json:"sub"`
// Issuer identifies the authorization server that issued the token.
Issuer string `json:"iss"`
// Audience lists the intended recipients of the token (RFC 8707).
Audience []string `json:"aud"`
// Scopes lists the granted scopes.
Scopes []string `json:"scope"`
// Extra holds additional claims not covered by the standard fields.
Extra map[string]any `json:"extra,omitempty"`
}
Claims holds the authenticated identity extracted from a validated request. Populated by AuthValidators that also implement ClaimsProvider.
func AuthClaims ¶
AuthClaims returns the authenticated identity from the context, or nil if no auth was configured or the validator does not provide claims.
Usage in a tool handler:
func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
claims := mcpkit.AuthClaims(ctx)
if claims != nil {
log.Printf("called by %s", claims.Subject)
}
// ...
}
type ClaimsProvider ¶
ClaimsProvider is an optional interface for AuthValidators that can extract identity claims from a validated request. Called only after Validate succeeds.
Validators that only perform pass/fail checks (like bearerTokenValidator) do not need to implement this interface.
type ClientCapabilities ¶
type ClientCapabilities struct {
Sampling *struct{} `json:"sampling,omitempty"`
Roots *RootsCap `json:"roots,omitempty"`
Elicitation *struct{} `json:"elicitation,omitempty"`
}
ClientCapabilities describes features the client supports.
type ClientInfo ¶
ClientInfo identifies an MCP client from the initialize request.
type CompletionArgument ¶
type CompletionArgument struct {
// Name is the argument name being completed.
Name string `json:"name"`
// Value is the partial input the user has typed so far.
Value string `json:"value"`
}
CompletionArgument describes the argument being completed and the partial input so far.
type CompletionHandler ¶
type CompletionHandler func(ctx context.Context, ref CompletionRef, arg CompletionArgument) (CompletionResult, error)
CompletionHandler provides autocompletion suggestions for a specific reference. ref identifies the prompt or resource being completed, arg contains the argument name and partial value. Return matching suggestions.
type CompletionRef ¶
type CompletionRef struct {
// Type is "ref/prompt" for prompt argument completion or "ref/resource" for resource URI completion.
Type string `json:"type"`
// Name is the prompt name (when Type is "ref/prompt").
Name string `json:"name,omitempty"`
// URI is the resource URI template (when Type is "ref/resource").
URI string `json:"uri,omitempty"`
}
CompletionRef identifies what is being completed — a prompt argument or resource URI.
type CompletionResult ¶
type CompletionResult struct {
// Values is the list of completion suggestions.
Values []string `json:"values"`
// Total is the total number of available completions (may be larger than len(Values)).
Total int `json:"total,omitempty"`
// HasMore indicates there are additional completions beyond what was returned.
HasMore bool `json:"hasMore"`
}
CompletionResult is the server's response with completion suggestions.
type Content ¶
type Content struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Data string `json:"data,omitempty"`
Resource *ResourceContent `json:"resource,omitempty"`
}
Content is a single content item in a tool result. Supports text, image, audio, and embedded resource types per MCP spec.
type CreateMessageRequest ¶
type CreateMessageRequest struct {
Messages []SamplingMessage `json:"messages"`
SystemPrompt string `json:"systemPrompt,omitempty"`
IncludeContext string `json:"includeContext,omitempty"` // "none", "thisServer", "allServers"
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens int `json:"maxTokens"`
ModelPreferences *ModelPreferences `json:"modelPreferences,omitempty"`
StopSequences []string `json:"stopSequences,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
CreateMessageRequest is the params for a sampling/createMessage server-to-client request. The server sends this to ask the client to perform LLM inference.
type CreateMessageResult ¶
type CreateMessageResult struct {
Model string `json:"model"`
StopReason string `json:"stopReason,omitempty"`
Role string `json:"role"`
Content Content `json:"content"`
}
CreateMessageResult is the client's response to a sampling/createMessage request.
func Sample ¶
func Sample(ctx context.Context, req CreateMessageRequest) (CreateMessageResult, error)
Sample sends a sampling/createMessage request to the connected client and blocks until the client responds with an LLM inference result.
Returns ErrNoRequestFunc if called outside a session context (e.g., no transport). Returns ErrSamplingNotSupported if the client did not declare sampling capability. Returns context.DeadlineExceeded if the context expires before the client responds.
Usage in a tool handler:
func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
result, err := mcpkit.Sample(ctx, mcpkit.CreateMessageRequest{
Messages: []mcpkit.SamplingMessage{{Role: "user", Content: mcpkit.Content{Type: "text", Text: "summarize this"}}},
MaxTokens: 1000,
})
if err != nil {
return mcpkit.ErrorResult(err.Error()), nil
}
return mcpkit.TextResult(result.Content.Text), nil
}
type ElicitationRequest ¶
type ElicitationRequest struct {
Message string `json:"message"`
RequestedSchema json.RawMessage `json:"requestedSchema,omitempty"`
}
ElicitationRequest is the params for an elicitation/create server-to-client request. The server sends this to ask the client to collect structured user input.
type ElicitationResult ¶
type ElicitationResult struct {
Action string `json:"action"` // "accept", "decline", or "cancel"
Content map[string]any `json:"content,omitempty"`
}
ElicitationResult is the client's response to an elicitation/create request.
func Elicit ¶
func Elicit(ctx context.Context, req ElicitationRequest) (ElicitationResult, error)
Elicit sends an elicitation/create request to the connected client and blocks until the client responds with user input.
Returns ErrNoRequestFunc if called outside a session context (e.g., no transport). Returns ErrElicitationNotSupported if the client did not declare elicitation capability. Returns context.DeadlineExceeded if the context expires before the client responds.
Usage in a tool handler:
func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
result, err := mcpkit.Elicit(ctx, mcpkit.ElicitationRequest{
Message: "Which database should I connect to?",
RequestedSchema: json.RawMessage(`{
"type": "object",
"properties": {"database": {"type": "string", "enum": ["prod", "staging", "dev"]}}
}`),
})
if err != nil {
return mcpkit.ErrorResult(err.Error()), nil
}
if result.Action != "accept" {
return mcpkit.TextResult("User declined"), nil
}
return mcpkit.TextResult(fmt.Sprintf("Selected: %v", result.Content["database"])), nil
}
type Error ¶
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
Error is a JSON-RPC 2.0 error object.
type Extension ¶
type Extension struct {
// ID is the extension identifier (e.g., "io.mcpkit/auth").
ID string `json:"id"`
// SpecVersion is the version of the spec this extension implements.
SpecVersion string `json:"specVersion"`
// Stability indicates the maturity of this extension.
Stability Stability `json:"stability"`
// Config holds extension-specific configuration, if any.
Config map[string]any `json:"config,omitempty"`
}
Extension describes a protocol extension with maturity metadata. Extensions are advertised in the initialize response under capabilities.extensions.
type ExtensionProvider ¶
type ExtensionProvider interface {
Extension() Extension
}
ExtensionProvider is implemented by sub-modules to declare their extension. This is how mcpkit/auth registers itself without the core module knowing about auth.
type LogLevel ¶
type LogLevel int
LogLevel represents MCP log severity levels (syslog-based, ascending severity). Used with logging/setLevel to control the minimum level of log notifications sent to the client, and with EmitLog to specify the severity of a message.
const ( LogDebug LogLevel = iota // debug: detailed debugging information LogInfo // info: general informational messages LogNotice // notice: normal but significant events LogWarning // warning: warning conditions LogError // error: error conditions LogCritical // critical: critical conditions LogAlert // alert: action must be taken immediately LogEmergency // emergency: system is unusable )
func ParseLogLevel ¶
ParseLogLevel converts a string to a LogLevel. Returns the level and true on success, or (LogDebug, false) for unknown strings.
type LogMessage ¶
type LogMessage struct {
Level string `json:"level"`
Logger string `json:"logger,omitempty"`
Data any `json:"data"`
}
LogMessage is the params payload for a notifications/message notification.
type ModelHint ¶
type ModelHint struct {
Name string `json:"name,omitempty"`
}
ModelHint provides hints about which model the server prefers for sampling.
type ModelPreferences ¶
type ModelPreferences struct {
Hints []ModelHint `json:"hints,omitempty"`
CostPriority *float64 `json:"costPriority,omitempty"`
SpeedPriority *float64 `json:"speedPriority,omitempty"`
IntelligencePriority *float64 `json:"intelligencePriority,omitempty"`
}
ModelPreferences describes the server's preferences for model selection when the client performs LLM sampling.
type NotificationHandler ¶
NotificationHandler receives server-to-client notifications (logging, progress, resource updates). Used by tests to verify notification delivery.
type NotifyFunc ¶
NotifyFunc sends a server-to-client JSON-RPC notification. method is the notification method (e.g., "notifications/message"). params will be JSON-marshaled as the notification's params field. This type is reusable for all server→client notifications (logging, progress, etc.).
type ProgressNotification ¶
type ProgressNotification struct {
// ProgressToken is the token from the request's _meta.progressToken field.
// It links this notification to the original request.
ProgressToken any `json:"progressToken"`
// Progress is the current progress value (e.g., bytes processed, items completed).
Progress float64 `json:"progress"`
// Total is the expected total value. Zero means indeterminate progress.
Total float64 `json:"total,omitempty"`
// Message is an optional human-readable status message.
Message string `json:"message,omitempty"`
}
ProgressNotification is the params payload for a notifications/progress notification. Servers send this during long-running operations to report progress to the client. The ProgressToken must match the token from the client's original request _meta.
type PromptArgument ¶
type PromptArgument struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
}
PromptArgument describes a single argument to a prompt.
type PromptDef ¶
type PromptDef struct {
// Name is the prompt identifier used in prompts/get.
Name string `json:"name"`
// Title is an optional display title.
Title string `json:"title,omitempty"`
// Description explains what this prompt does.
Description string `json:"description,omitempty"`
// Arguments defines the parameters this prompt accepts.
Arguments []PromptArgument `json:"arguments,omitempty"`
// Annotations holds optional metadata for this prompt.
Annotations map[string]any `json:"annotations,omitempty"`
}
PromptDef describes a prompt exposed via MCP.
type PromptHandler ¶
type PromptHandler func(ctx context.Context, req PromptRequest) (PromptResult, error)
PromptHandler generates prompt messages, optionally using arguments.
type PromptMessage ¶
type PromptMessage struct {
Role string `json:"role"`
Content Content `json:"content"` // reuses Content from tool.go
}
PromptMessage is a single message in a prompt result.
type PromptRequest ¶
PromptRequest is the validated input passed to a PromptHandler.
type PromptResult ¶
type PromptResult struct {
Description string `json:"description,omitempty"`
Messages []PromptMessage `json:"messages"`
}
PromptResult is the response from a prompt handler.
type Request ¶
type Request struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
Request is a JSON-RPC 2.0 request envelope.
func (*Request) IsNotification ¶
IsNotification returns true if this request has no ID (JSON-RPC notification).
type RequestFunc ¶
RequestFunc sends a server-to-client JSON-RPC request and blocks until the client sends a response. method is the JSON-RPC method (e.g., "sampling/createMessage"). params will be JSON-marshaled as the request's params field. Returns the raw JSON result on success, or an error on timeout, transport failure, or JSON-RPC error from the client.
type ResourceContent ¶
type ResourceContent struct {
URI string `json:"uri"`
MimeType string `json:"mimeType,omitempty"`
Text string `json:"text,omitempty"`
Blob string `json:"blob,omitempty"`
}
ResourceContent is an embedded resource reference in a tool result.
type ResourceDef ¶
type ResourceDef struct {
// URI uniquely identifies this resource.
URI string `json:"uri"`
// Name is a human-readable short name.
Name string `json:"name"`
// Title is an optional display title.
Title string `json:"title,omitempty"`
// Description explains what this resource provides.
Description string `json:"description,omitempty"`
// MimeType is the MIME type of the resource content.
MimeType string `json:"mimeType,omitempty"`
// Annotations holds optional metadata for this resource.
Annotations map[string]any `json:"annotations,omitempty"`
}
ResourceDef describes a resource exposed via MCP.
type ResourceHandler ¶
type ResourceHandler func(ctx context.Context, req ResourceRequest) (ResourceResult, error)
ResourceHandler reads a resource by URI.
type ResourceReadContent ¶
type ResourceReadContent struct {
URI string `json:"uri"`
MimeType string `json:"mimeType,omitempty"`
Text string `json:"text,omitempty"`
Blob string `json:"blob,omitempty"`
}
ResourceReadContent is a single content item returned by resources/read. Either Text or Blob is set, not both.
type ResourceRequest ¶
type ResourceRequest struct {
URI string
}
ResourceRequest is the validated input passed to a ResourceHandler.
type ResourceResult ¶
type ResourceResult struct {
Contents []ResourceReadContent `json:"contents"`
}
ResourceResult is the response from a resource handler.
type ResourceTemplate ¶
type ResourceTemplate struct {
// URITemplate is an RFC 6570 URI template (e.g., "file:///{path}").
URITemplate string `json:"uriTemplate"`
// Name is a human-readable short name.
Name string `json:"name"`
// Title is an optional display title.
Title string `json:"title,omitempty"`
// Description explains what this template provides.
Description string `json:"description,omitempty"`
// MimeType is the default MIME type for resources matching this template.
MimeType string `json:"mimeType,omitempty"`
// Annotations holds optional metadata for this template.
Annotations map[string]any `json:"annotations,omitempty"`
}
ResourceTemplate describes a parameterized resource URI template.
type ResourceUpdatedNotification ¶
type ResourceUpdatedNotification struct {
URI string `json:"uri"`
}
ResourceUpdatedNotification is the params payload for notifications/resources/updated. Sent by the server to subscribed clients when a resource's content has changed.
type Response ¶
type Response struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
}
Response is a JSON-RPC 2.0 response.
func NewErrorResponse ¶
func NewErrorResponse(id json.RawMessage, code int, message string) *Response
NewErrorResponse creates an error response for the given request ID.
func NewErrorResponseWithData ¶
NewErrorResponseWithData creates an error response with additional structured data. Used for protocol errors that carry machine-readable context (e.g., supported versions).
func NewResponse ¶
func NewResponse(id json.RawMessage, result any) *Response
NewResponse creates a success response for the given request ID.
type RootsCap ¶
type RootsCap struct {
ListChanged bool `json:"listChanged,omitempty"`
}
RootsCap describes the client's roots capability.
type SamplingMessage ¶
SamplingMessage is a single message in a sampling/createMessage request.
type ScopeAwareTokenSource ¶
type ScopeAwareTokenSource interface {
TokenSource
// TokenForScopes invalidates the cached token and triggers a new
// authorization flow with the given scopes merged into the existing set.
TokenForScopes(scopes []string) (string, error)
}
ScopeAwareTokenSource extends TokenSource with scope step-up capability. When the server returns 403 with required scopes in the WWW-Authenticate header, the client transport calls TokenForScopes to re-authenticate with broader permissions.
Implementations that support interactive re-auth (like OAuthTokenSource) should implement this interface. Static tokens and implementations that cannot acquire new scopes need not implement it — the transport will return a ClientAuthError instead of retrying.
type ServerInfo ¶
type ServerInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Instructions string `json:"instructions,omitempty"`
WebsiteURL string `json:"websiteUrl,omitempty"`
}
ServerInfo identifies an MCP server in the initialize response.
type ServerRequestHandler ¶
ServerRequestHandler handles server-to-client JSON-RPC requests (sampling, elicitation). The client registers this on the transport so the server can send requests during tool execution and receive responses.
type Stability ¶
type Stability string
Stability represents the maturity level of an extension.
const ( // Experimental indicates the extension is in development and may change. Experimental Stability = "experimental" // Stable indicates the extension is production-ready. Stable Stability = "stable" // Deprecated indicates the extension will be removed in a future version. Deprecated Stability = "deprecated" )
type TemplateHandler ¶
type TemplateHandler func(ctx context.Context, uri string, params map[string]string) (ResourceResult, error)
TemplateHandler reads a resource matched by a URI template. The uri parameter is the full resolved URI, params contains the extracted template variables.
type TokenSource ¶
type TokenSource interface {
// Token returns a valid access token, refreshing if necessary.
Token() (string, error)
}
TokenSource provides access tokens for the MCP client. Simple implementations return a static token; OAuth implementations handle the full flow including discovery, browser auth, and refresh.
type ToolDef ¶
type ToolDef struct {
// Name is the tool identifier used in tools/call.
Name string `json:"name"`
// Description is a human-readable summary of what the tool does.
Description string `json:"description"`
// InputSchema is the JSON Schema for the tool's arguments.
// Typically a map[string]any with "type": "object", "properties": {...}, "required": [...].
// Arbitrary JSON Schema fields (e.g. "$schema", "$defs", "$ref",
// "additionalProperties") are preserved as-is through registration,
// serialization, and client-side deserialization.
InputSchema any `json:"inputSchema"`
// OutputSchema is an optional JSON Schema for the tool's structuredContent output.
// When present, the tool SHOULD return StructuredContent matching this schema.
// Per MCP spec: enables clients to validate and process tool output programmatically.
OutputSchema any `json:"outputSchema,omitempty"`
// Annotations holds optional metadata for this tool.
// Convention: {"experimental": true} marks experimental tools.
Annotations map[string]any `json:"annotations,omitempty"`
}
ToolDef describes a tool exposed via MCP.
type ToolHandler ¶
type ToolHandler func(ctx context.Context, req ToolRequest) (ToolResult, error)
ToolHandler is the function signature for tool implementations.
type ToolRequest ¶
type ToolRequest struct {
// Name of the tool being called.
Name string
// Arguments is the raw JSON arguments from the tools/call params.
Arguments json.RawMessage
// RequestID is the JSON-RPC request ID.
RequestID json.RawMessage
// ProgressToken is the token from the request's _meta.progressToken field.
// Nil if the client did not request progress reporting. Pass this to
// EmitProgress to send notifications/progress notifications.
ProgressToken any
}
ToolRequest is the validated input passed to a ToolHandler.
func (*ToolRequest) Bind ¶
func (r *ToolRequest) Bind(v any) error
Bind unmarshals the tool arguments into the provided struct.
type ToolResult ¶
type ToolResult struct {
// Content is the list of content items to return.
Content []Content `json:"content"`
// IsError indicates the tool execution failed (but the JSON-RPC call itself succeeded).
IsError bool `json:"isError,omitempty"`
// StructuredContent holds optional structured data for the tool result.
// When the tool has an OutputSchema, this field carries typed data matching
// that schema. On error (IsError=true), it can carry structured error details.
// Per MCP spec: "If outputSchema is present, structuredContent SHOULD be included."
StructuredContent any `json:"structuredContent,omitempty"`
}
ToolResult is the response from a tool handler.
func ErrorResult ¶
func ErrorResult(text string) ToolResult
ErrorResult creates a ToolResult marked as an error with the given message.
func StructuredError ¶
func StructuredError(text string, data any) ToolResult
StructuredError creates a ToolResult marked as an error with both text and structured error data. Use this to return machine-readable error details alongside a human-readable error message.
func StructuredResult ¶
func StructuredResult(text string, data any) ToolResult
StructuredResult creates a ToolResult with both text content and structured data. Use this when the tool has an OutputSchema — structuredContent carries typed data matching the schema, while content provides a human-readable summary.
func TextResult ¶
func TextResult(text string) ToolResult
TextResult creates a ToolResult with a single text content item.
type Transport ¶
type Transport interface {
// Connect establishes the transport (e.g., SSE handshake, session creation).
Connect(ctx context.Context) error
// Call sends a JSON-RPC request and returns the response.
Call(ctx context.Context, req *Request) (*Response, error)
// Notify sends a JSON-RPC notification (no response expected).
Notify(ctx context.Context, req *Request) error
// Close shuts down the transport.
Close() error
// SessionID returns the transport's session identifier (empty if none).
SessionID() string
}
Transport is the minimal interface for client-server communication. Both HTTP transports and the in-process transport satisfy this interface. The client package consumes it; the server package provides implementations.