mcp

package
v0.37.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: Apache-2.0 Imports: 75 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrCodeInvalidInput    = "INVALID_INPUT"
	ErrCodeNotFound        = "NOT_FOUND"
	ErrCodeValidationError = "VALIDATION_ERROR"
	ErrCodeLoadFailed      = "LOAD_FAILED"
	ErrCodeExecFailed      = "EXECUTION_FAILED"
	ErrCodeAuthRequired    = "AUTH_REQUIRED"
	ErrCodeConfigError     = "CONFIG_ERROR"
	ErrCodeVersionMismatch = "VERSION_MISMATCH"
)

Common error codes for MCP tools.

Variables

This section is empty.

Functions

func NewContext

func NewContext(opts ...ContextOption) context.Context

NewContext creates a context.Context pre-populated with all values that scafctl packages pull from context. This ensures MCP tool handlers do not need to figure out which context values each package expects.

Injected values:

  • logger (logr.Logger) - defaults to discard
  • config (*config.Config) - optional
  • auth registry (*auth.Registry) - defaults to empty
  • writer (*writer.Writer) - defaults to quiet/no-op
  • settings (*settings.Run) - defaults to quiet mode

Types

type Capability added in v0.14.0

type Capability struct {
	Kind        CapabilityKind   `json:"kind"        yaml:"kind"`
	Name        string           `json:"name"        yaml:"name"`
	Title       string           `json:"title"       yaml:"title"`
	Description string           `json:"description" yaml:"description"`
	Source      CapabilitySource `json:"source"      yaml:"source"`
	ReadOnly    bool             `json:"readOnly"    yaml:"readOnly"`
	Destructive bool             `json:"destructive" yaml:"destructive"`
}

Capability describes a single MCP tool or prompt.

type CapabilityKind added in v0.14.0

type CapabilityKind string

CapabilityKind distinguishes tools from prompts.

const (
	// CapabilityTool is an MCP tool (callable by agents).
	CapabilityTool CapabilityKind = "tool"
	// CapabilityPrompt is an MCP prompt (template for agent interactions).
	CapabilityPrompt CapabilityKind = "prompt"
)

type CapabilitySource added in v0.14.0

type CapabilitySource string

CapabilitySource identifies where a capability was registered.

const (
	// SourceCore marks capabilities registered by scafctl itself.
	SourceCore CapabilitySource = "core"
	// SourcePlugin marks capabilities registered by plugins or embedders.
	SourcePlugin CapabilitySource = "plugin"
	// SourceUpstream marks capabilities proxied from an upstream MCP server.
	SourceUpstream CapabilitySource = "upstream"
)

type ContextOption

type ContextOption func(*contextConfig)

ContextOption configures the MCP context setup.

func WithAuthRegistry

func WithAuthRegistry(reg *auth.Registry) ContextOption

WithAuthRegistry injects an auth handler registry into the MCP context. If not set, an empty registry is created.

func WithConfig

func WithConfig(cfg *config.Config) ContextOption

WithConfig injects application configuration into the MCP context.

func WithIOStreams

func WithIOStreams(ios *terminal.IOStreams) ContextOption

WithIOStreams injects custom IO streams into the MCP context. If not set, discard writers are used (MCP output goes through JSON-RPC).

func WithLogger

func WithLogger(lgr logr.Logger) ContextOption

WithLogger injects a logger into the MCP context. If not set, a discard logger is used.

func WithSettings

func WithSettings(s *settings.Run) ContextOption

WithSettings injects runtime settings into the MCP context. If not set, quiet/no-color defaults are used.

type ErrorOption

type ErrorOption func(*ToolError)

ErrorOption configures a ToolError.

func WithField

func WithField(field string) ErrorOption

WithField sets the field that caused the error.

func WithRelatedTools

func WithRelatedTools(tools ...string) ErrorOption

WithRelatedTools sets related tools that may help.

func WithSuggestion

func WithSuggestion(suggestion string) ErrorOption

WithSuggestion sets an actionable fix suggestion.

type Server

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

Server wraps the mcp-go MCPServer and holds shared dependencies that tool handlers need.

func NewServer

func NewServer(opts ...ServerOption) (*Server, error)

NewServer creates a new MCP server with all tools and resources registered.

func (*Server) AddPrompt added in v0.14.0

func (s *Server) AddPrompt(prompt mcp.Prompt, handler server.PromptHandlerFunc)

AddPrompt registers a prompt with the MCP server and tracks it for listing via ListCapabilities. Embedders should use this instead of MCPServer().AddPrompt() to ensure the prompt appears in listings.

func (*Server) Close added in v0.17.0

func (s *Server) Close()

Close releases resources owned by the server. Safe to call multiple times and concurrently with Serve*/Handler/Info.

func (*Server) Handler

func (s *Server) Handler(opts ...server.StreamableHTTPOption) http.Handler

Handler returns an http.Handler for the Streamable HTTP transport. Server context values are injected into every request context (see Serve). If the HTTP server was already created (by a prior call to Handler or ServeHTTP), the existing instance is returned and opts are ignored.

func (*Server) Info

func (s *Server) Info() ([]byte, error)

Info returns the server's tool and resource information as JSON. Used by `scafctl mcp serve --info`.

func (*Server) ListCapabilities added in v0.14.0

func (s *Server) ListCapabilities() []Capability

ListCapabilities returns all tools and tracked prompts registered on the server. Prompts must be registered via Server.AddPrompt (or the internal addCorePrompt) to appear; prompts added directly through MCPServer().AddPrompt() are not tracked. Core capabilities are tagged with SourceCore; embedder/plugin capabilities are tagged with SourcePlugin. The contextual tool filter is applied, so results match what MCP clients would discover at runtime.

func (*Server) MCPServer

func (s *Server) MCPServer() *server.MCPServer

MCPServer returns the underlying mcp-go MCPServer. This is useful for advanced operations like sending notifications.

Embedders can call MCPServer().AddTool() to register custom tools; these are automatically listed by ListCapabilities with SourcePlugin.

Note: prompts added via MCPServer().AddPrompt() will NOT appear in ListCapabilities because the mcp-go SDK does not expose a ListPrompts method. Use Server.AddPrompt instead to register prompts that should be discoverable.

func (*Server) NotifyResourcesChanged

func (s *Server) NotifyResourcesChanged(ctx context.Context) error

NotifyResourcesChanged sends a notification to all connected clients that the resource list has changed. Clients should re-list resources.

func (*Server) NotifyToolsChanged

func (s *Server) NotifyToolsChanged(ctx context.Context) error

NotifyToolsChanged sends a notification to all connected clients that the tool list has changed. Clients should re-list tools.

func (*Server) RequestElicitation

func (s *Server) RequestElicitation(ctx context.Context, req mcp.ElicitationRequest) (*mcp.ElicitationResult, error)

RequestElicitation asks the MCP client to prompt the user for input. This enables interactive parameter collection during tool execution.

func (*Server) RequestRoots

func (s *Server) RequestRoots(ctx context.Context) ([]mcp.Root, error)

RequestRoots asks the MCP client for its workspace root directories. This enables workspace-aware file discovery in tools.

func (*Server) RequestSampling

func (s *Server) RequestSampling(ctx context.Context, req mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error)

RequestSampling asks the MCP client's LLM to generate content. This enables server-side use of the client's AI capabilities.

func (*Server) SendLog

func (s *Server) SendLog(ctx context.Context, level mcp.LoggingLevel, loggerName, message string, data any) error

SendLog sends a structured log message to connected MCP clients. This enables real-time log streaming during tool execution.

func (*Server) Serve

func (s *Server) Serve(opts ...server.StdioOption) error

Serve starts the MCP server on stdio transport (blocking). Server context values (auth registry, config, settings, logger) are automatically injected into the transport's request context so that all tool handlers -- including those registered by embedders via MCPServer().AddTool() -- can access them.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(addr string, opts ...server.StreamableHTTPOption) error

ServeHTTP starts the MCP server on Streamable HTTP transport at the given address. Server context values are injected into every request context (see Serve).

func (*Server) ServeSSE

func (s *Server) ServeSSE(addr string, opts ...server.SSEOption) error

ServeSSE starts the MCP server on SSE transport at the given address. Server context values are injected into every request context (see Serve).

type ServerOption

type ServerOption func(*serverConfig)

ServerOption configures the MCP server.

func WithErrorLog

func WithErrorLog(lgr *log.Logger) ServerOption

WithErrorLog sets the error logger for the stdio transport.

func WithPaginationLimit

func WithPaginationLimit(limit int) ServerOption

WithPaginationLimit sets the maximum number of items per page for list operations (tools, resources, prompts).

func WithQueueSize

func WithQueueSize(size int) ServerOption

WithQueueSize sets the message queue size for the stdio transport.

func WithRootCommand added in v0.11.0

func WithRootCommand(cmd *cobra.Command) ServerOption

WithRootCommand sets the cobra root command for CLI introspection tools.

func WithServerAuthRegistry

func WithServerAuthRegistry(reg *auth.Registry) ServerOption

WithServerAuthRegistry sets the auth registry.

func WithServerConfig

func WithServerConfig(cfg *config.Config) ServerOption

WithServerConfig sets the application config.

func WithServerContext

func WithServerContext(ctx context.Context) ServerOption

WithServerContext sets the base context for the server.

func WithServerLogger

func WithServerLogger(lgr logr.Logger) ServerOption

WithServerLogger sets the logger for the MCP server.

func WithServerName added in v0.7.0

func WithServerName(name string) ServerOption

WithServerName sets the server name (defaults to "scafctl"). Used for MCP ServerInfo identity when scafctl is embedded in another CLI.

func WithServerPluginPool added in v0.15.0

func WithServerPluginPool(pool *plugin.Pool) ServerOption

WithServerPluginPool sets the plugin pool for auto-resolving official plugin providers on demand. When set, provider tool handlers (run_provider, get_provider_schema, get_provider_output_shape) will attempt to fetch and load official plugins that are not yet in the provider registry.

func WithServerRegistry

func WithServerRegistry(reg *provider.Registry) ServerOption

WithServerRegistry sets the provider registry.

func WithServerVersion

func WithServerVersion(version string) ServerOption

WithServerVersion sets the server version string.

func WithSupplementalInstructions added in v0.7.1

func WithSupplementalInstructions(instructions string) ServerOption

WithSupplementalInstructions appends additional instruction text to the server instructions returned to AI agents during initialization. Embedders use this to provide routing guidance for their custom tools.

The supplemental text is appended after the base server instructions, separated by a blank line. Binary-name substitution is automatically applied when the server name differs from the default.

Example:

srv, err := mcp.NewServer(
	mcp.WithServerName("mycli"),
	mcp.WithSupplementalInstructions(`
This server includes domain-specific migration tools.
Use migration tools ONLY when working with legacy solution files.
For new solutions, use only the core tools above.
`),
)

func WithUpstreamServer added in v0.17.0

func WithUpstreamServer(name string, cfg config.MCPServerConfig) ServerOption

WithUpstreamServer adds an upstream MCP server whose tools are auto-discovered and proxied through the local server. Auth tokens are injected automatically using the configured auth handler.

Multiple upstream servers can be added by calling this option multiple times.

func WithWorkerPoolSize

func WithWorkerPoolSize(size int) ServerOption

WithWorkerPoolSize sets the number of workers for the stdio transport.

type ToolError

type ToolError struct {
	// Code is a machine-readable error code (e.g., "INVALID_INPUT", "NOT_FOUND").
	Code string `json:"code"`
	// Message is a human-readable error description.
	Message string `json:"message"`
	// Field is the input field that caused the error (optional).
	Field string `json:"field,omitempty"`
	// Suggestion is an actionable hint for fixing the error (optional).
	Suggestion string `json:"suggestion,omitempty"`
	// Related lists tool names that may help resolve the issue (optional).
	Related []string `json:"related,omitempty"`
}

ToolError represents a structured error response from an MCP tool. It provides machine-readable error codes, actionable suggestions, and references to related tools that may help resolve the issue.

Directories

Path Synopsis
Package upstream provides MCP upstream server proxying with automatic auth token injection.
Package upstream provides MCP upstream server proxying with automatic auth token injection.

Jump to

Keyboard shortcuts

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