inventory

package
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MCPMethodInitialize             = "initialize"
	MCPMethodDiscover               = "server/discover"
	MCPMethodToolsList              = "tools/list"
	MCPMethodToolsCall              = "tools/call"
	MCPMethodResourcesList          = "resources/list"
	MCPMethodResourcesRead          = "resources/read"
	MCPMethodResourcesTemplatesList = "resources/templates/list"
	MCPMethodPromptsList            = "prompts/list"
	MCPMethodPromptsGet             = "prompts/get"
)

MCP method constants for use with ForMCPRequest.

View Source
const ProtocolVersionMultiRoundTrip = "2026-07-28"

ProtocolVersionMultiRoundTrip is the first MCP protocol version that supports multi-round-trip input requests.

Variables

View Source
var (
	// ErrUnknownTools is returned when tools specified via WithTools() are not recognized.
	ErrUnknownTools = errors.New("unknown tools specified in WithTools")
)
View Source
var HeaderParams = map[string]string{"owner": "owner", "repo": "repo"}

HeaderParams maps owner/repo input properties to the MCP-Param-* headers a header-aware proxy reads for repository routing. The enforcement test in pkg/github guards full coverage.

Functions

func AnnotateHeaderParams

func AnnotateHeaderParams(tool *mcp.Tool)

AnnotateHeaderParams returns a copy of tool whose owner/repo input properties carry an "x-mcp-header" annotation, which the SDK projects onto Mcp-Param-{name} request headers. It never mutates the input tool's schema or any map shared with the original tool definition: callers shallow-copy ServerTool.Tool, so the *jsonschema.Schema (and its per-property Extra maps) are shared, and per-request registration must not race on them. Only the schema, its Properties map, and the specific property schemas/Extra maps that gain an annotation are cloned.

func CachedInputSchemaFor

func CachedInputSchemaFor[T any](options *jsonschema.ForOptions, enums ...SchemaEnum) (*jsonschema.Schema, error)

CachedInputSchemaFor is like CachedSchemaFor and adds the standard owner/repo routing annotations before caching the immutable schema.

func CachedSchema

func CachedSchema(schema *jsonschema.Schema) (*jsonschema.Schema, error)

CachedSchema clones an explicit schema once per process and returns the immutable shared pointer. It is useful for schemas prepared by tool definitions that are reconstructed for request-scoped servers.

func CachedSchemaFor

func CachedSchemaFor[T any](options *jsonschema.ForOptions, enums ...SchemaEnum) (*jsonschema.Schema, error)

CachedSchemaFor infers a schema once per process for the Go type and immutable inference options. The returned schema is shared and must not be mutated. Enum overrides are applied while constructing the cached value.

func CloneSchema

func CloneSchema(schema *jsonschema.Schema) *jsonschema.Schema

CloneSchema deep-copies schema nodes, numeric bounds, and mutable metadata.

func CloneSchemaWithoutDefaults

func CloneSchemaWithoutDefaults(schema *jsonschema.Schema) *jsonschema.Schema

CloneSchemaWithoutDefaults returns a deep schema copy with default keywords removed. The MCP SDK applies input-schema defaults before decoding arguments, so use this for runtime validation schemas when omitted arguments must stay omitted. The original advertised schema is unchanged.

func EnumSchema

func EnumSchema(values ...string) *jsonschema.Schema

EnumSchema returns a string schema constrained to values.

func PreserveToolHandlerContent

func PreserveToolHandlerContent(ctx context.Context)

PreserveToolHandlerContent marks a typed call's handler content as intentionally non-JSON (for example CSV or resource blocks).

func ResolveFeature

func ResolveFeature(ctx context.Context, fallbackChecker FeatureFlagChecker, feature FeatureFlag) bool

ResolveFeature returns a feature value from request-owned resolution state. Context state and its checker are authoritative. fallbackChecker is used only when the context has no state; that uncached compatibility path lets handlers invoked directly outside a server continue to resolve features.

func WithEnum

func WithEnum(schema *jsonschema.Schema, path string, values ...string) (*jsonschema.Schema, error)

WithEnum clones schema and adds a string enum at the requested schema path. Array item schemas are addressed with the "items" path segment.

func WithFeatureState

func WithFeatureState(ctx context.Context, checker FeatureFlagChecker) context.Context

WithFeatureState installs request-owned lazy feature state. When state already exists, its checker is authoritative and checker is ignored.

Types

type Builder

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

Builder builds a Registry with the specified configuration. Use NewBuilder to create a builder, chain configuration methods, then call Build() to create the final inventory.

Example:

reg := NewBuilder().
    SetTools(tools).
    SetResources(resources).
    SetPrompts(prompts).
    WithDeprecatedAliases(aliases).
    WithReadOnly(true).
    WithToolsets([]string{"repos", "issues"}).
    WithFeatureChecker(checker).
    WithFilter(myFilter).
    Build()

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new Builder.

func (*Builder) Build

func (b *Builder) Build() (*Inventory, error)

Build creates the final Inventory with all configuration applied. This processes toolset filtering, tool name resolution, and sets up the inventory for use. The returned Inventory is ready for use with AvailableTools(), RegisterAll(), etc.

Build returns an error if any tools specified via WithTools() are not recognized (i.e., they don't exist in the tool set and are not deprecated aliases). This ensures invalid tool configurations fail fast at build time.

func (*Builder) SetPrompts

func (b *Builder) SetPrompts(prompts []ServerPrompt) *Builder

SetPrompts sets the prompts for the inventory. Returns self for chaining.

func (*Builder) SetResources

func (b *Builder) SetResources(resources []ServerResourceTemplate) *Builder

SetResources sets the resource templates for the inventory. Returns self for chaining.

func (*Builder) SetTools

func (b *Builder) SetTools(tools []ServerTool) *Builder

SetTools sets the tools for the inventory. Returns self for chaining.

func (*Builder) WithDeprecatedAliases

func (b *Builder) WithDeprecatedAliases(aliases map[string]string) *Builder

WithDeprecatedAliases adds deprecated tool name aliases that map to canonical names. Returns self for chaining.

func (*Builder) WithExcludeTools

func (b *Builder) WithExcludeTools(toolNames []string) *Builder

WithExcludeTools specifies tools that should be disabled regardless of other settings. These tools will be excluded even if their toolset is enabled or they are in the additional tools list. This takes precedence over all other tool enablement settings. Input is cleaned (trimmed, deduplicated) before applying. Returns self for chaining.

func (*Builder) WithFeatureChecker

func (b *Builder) WithFeatureChecker(checker FeatureFlagChecker) *Builder

WithFeatureChecker sets the feature flag checker function. Inventory items declare their feature dependencies and functional availability rules through FeatureRule. Checks are deduplicated into request-owned resolution state; errors are logged and treated as disabled.

When the checker is nil, no feature-flag filter is installed; tools, resources, and prompts pass through feature-flag gating unchanged. The per-request inventory in HTTP mode must always install a checker so that MCP registration (which can only serve a given tool name once) sees a deduplicated set of dual-name variants.

Returns self for chaining.

func (*Builder) WithFilter

func (b *Builder) WithFilter(filter ToolFilter) *Builder

WithFilter adds a filter function that will be applied to all tools. Multiple filters can be added and are evaluated in order. If any filter returns false or an error, the tool is excluded. Returns self for chaining.

func (*Builder) WithReadOnly

func (b *Builder) WithReadOnly(readOnly bool) *Builder

WithReadOnly sets whether only read-only tools should be available. When true, write tools are filtered out. Returns self for chaining.

func (*Builder) WithServerInstructions

func (b *Builder) WithServerInstructions() *Builder

func (*Builder) WithTools

func (b *Builder) WithTools(toolNames []string) *Builder

WithTools specifies additional tools that bypass toolset filtering. These tools are additive - they will be included even if their toolset is not enabled. Read-only filtering still applies to these tools. Input is cleaned (trimmed, deduplicated) during Build(). Deprecated tool aliases are automatically resolved to their canonical names during Build(). Returns self for chaining.

func (*Builder) WithToolsets

func (b *Builder) WithToolsets(toolsetIDs []string) *Builder

WithToolsets specifies which toolsets should be enabled. Special keywords:

  • "all": enables all toolsets
  • "default": expands to toolsets marked with Default: true in their metadata

Input strings are trimmed of whitespace and duplicates are removed. Pass nil to use default toolsets. Pass an empty slice to disable all toolsets. Returns self for chaining.

type ElicitationMode

type ElicitationMode string

ElicitationMode identifies a client-supported elicitation interaction mode.

const (
	// ElicitationModeForm collects structured user input through the client.
	ElicitationModeForm ElicitationMode = "form"
	// ElicitationModeURL directs the user to an external URL.
	ElicitationModeURL ElicitationMode = "url"
)

type FeatureFlag

type FeatureFlag string

FeatureFlag identifies a feature consistently across inventory consumers.

type FeatureFlagChecker

type FeatureFlagChecker func(ctx context.Context, flag string) (bool, error)

FeatureFlagChecker resolves one feature flag for the current request. Checkers must not call ResolveFeature; nested resolution fails the owning check closed.

type FeaturePredicate

type FeaturePredicate func(featureAsBool FeatureResolver) bool

FeaturePredicate determines whether an inventory item is available. Predicates must be pure: their result may depend only on calls to the supplied resolver.

type FeatureResolver

type FeatureResolver func(flag FeatureFlag) bool

FeatureResolver returns the resolved value of a feature flag. Implementations absorb resolution errors and fail closed.

type FeatureRule

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

FeatureRule declares the feature flags used by an availability predicate. The predicate resolves reached flags lazily with normal Go boolean semantics, while request state deduplicates repeated checks.

func NewFeatureRule

func NewFeatureRule(features []FeatureFlag, predicate FeaturePredicate) FeatureRule

NewFeatureRule creates an availability rule over the supplied feature flags.

func (FeatureRule) Enabled

func (r FeatureRule) Enabled(featureAsBool FeatureResolver) bool

Enabled evaluates the rule against resolved feature values.

func (FeatureRule) Features

func (r FeatureRule) Features() []FeatureFlag

Features returns the feature flags referenced by the rule.

func (FeatureRule) IsZero

func (r FeatureRule) IsZero() bool

IsZero reports whether no feature availability rule is configured.

type HandlerFunc

type HandlerFunc func(deps any) mcp.ToolHandler

HandlerFunc is a function that takes dependencies and returns an MCP tool handler. This allows tools to be defined statically while their handlers are generated on-demand with the appropriate dependencies. The deps parameter is typed as `any` to avoid circular dependencies - callers should define their own typed dependencies struct and type-assert as needed.

type InputNormalizer

type InputNormalizer func(json.RawMessage) (json.RawMessage, error)

InputNormalizer transforms raw tool arguments before the SDK validates and decodes them. Use it only for compatibility normalization; the registered input schema remains the contract clients see and the SDK validates.

type Inventory

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

Inventory holds a collection of tools, resources, and prompts with filtering applied. Create a Inventory using Builder:

reg := NewBuilder().
    SetTools(tools).
    WithReadOnly(true).
    WithToolsets([]string{"repos"}).
    Build()

The Inventory is configured at build time and provides:

  • Filtered access to tools/resources/prompts via Available* methods
  • Deterministic ordering for documentation generation
  • Lazy dependency injection during registration via RegisterAll()

func (*Inventory) AllTools

func (r *Inventory) AllTools() []ServerTool

AllTools returns all tools without any filtering, sorted deterministically.

func (*Inventory) AvailablePrompts

func (r *Inventory) AvailablePrompts(ctx context.Context) []ServerPrompt

AvailablePrompts returns prompts that pass all current filters, sorted deterministically by toolset ID, then prompt name. The context is used for feature flag evaluation.

func (*Inventory) AvailableResourceTemplates

func (r *Inventory) AvailableResourceTemplates(ctx context.Context) []ServerResourceTemplate

AvailableResourceTemplates returns resource templates that pass all current filters, sorted deterministically by toolset ID, then template name. The context is used for feature flag evaluation.

func (*Inventory) AvailableTools

func (r *Inventory) AvailableTools(ctx context.Context) []ServerTool

AvailableTools returns the tools that pass all current filters, sorted deterministically by toolset ID, then tool name. The context is used for feature flag evaluation.

func (*Inventory) AvailableToolsets

func (r *Inventory) AvailableToolsets(exclude ...ToolsetID) []ToolsetMetadata

AvailableToolsets returns the unique toolsets that have tools, in sorted order. This is the ordered intersection of toolsets with reality - only toolsets that actually contain tools are returned, sorted by toolset ID. Optional exclude parameter filters out specific toolset IDs from the result.

func (*Inventory) DefaultToolsetIDs

func (r *Inventory) DefaultToolsetIDs() []ToolsetID

DefaultToolsetIDs returns the IDs of toolsets marked as Default in their metadata. The IDs are returned in sorted order for deterministic output.

func (*Inventory) EnabledToolsets

func (r *Inventory) EnabledToolsets() []ToolsetMetadata

EnabledToolsets returns the unique toolsets that are enabled based on current filters. This is similar to AvailableToolsets but respects the enabledToolsets filter. Returns toolsets in sorted order by toolset ID.

func (*Inventory) FilteredTools

func (r *Inventory) FilteredTools(ctx context.Context) ([]ServerTool, error)

FilteredTools returns tools filtered by the Enabled function and builder filters. This provides an explicit API for accessing filtered tools, currently implemented as an alias for AvailableTools.

The error return is currently always nil but is included for future extensibility. Library consumers (e.g., remote server implementations) may need to surface recoverable filter errors rather than silently logging them. Having the error return in the API now avoids breaking changes later.

The context is used for Enabled function evaluation and builder filter checks.

func (*Inventory) FindToolByName

func (r *Inventory) FindToolByName(toolName string) (*ServerTool, ToolsetID, error)

FindToolByName searches all tools for one matching the given name. Returns the tool, its toolset ID, and an error if not found. This searches ALL tools regardless of filters.

func (*Inventory) ForMCPRequest

func (r *Inventory) ForMCPRequest(method string, itemName string) *Inventory

ForMCPRequest returns a Registry optimized for a specific MCP request. This is designed for servers that create a new instance per request (like the remote server), allowing them to only register the items needed for that specific request rather than all ~90 tools.

Parameters:

  • method: The MCP method being called (use MCP* constants)
  • itemName: Name of specific item for call/get methods (tool name, resource URI, or prompt name)

Returns a new Registry containing only the items relevant to the request:

  • MCPMethodInitialize / MCPMethodDiscover: Empty items (capabilities from ServerOptions; instructions preserved)
  • MCPMethodToolsList: All available tools (no resources/prompts)
  • MCPMethodToolsCall: Only the named tool
  • MCPMethodResourcesList, MCPMethodResourcesTemplatesList: All available resources (no tools/prompts)
  • MCPMethodResourcesRead: All resources (SDK handles URI template matching)
  • MCPMethodPromptsList: All available prompts (no tools/resources)
  • MCPMethodPromptsGet: Only the named prompt
  • Unknown methods: Empty (no items registered)

All existing filters (read-only, toolsets, etc.) still apply to the returned items.

func (*Inventory) HasToolset

func (r *Inventory) HasToolset(toolsetID ToolsetID) bool

HasToolset checks if any tool/resource/prompt belongs to the given toolset.

func (*Inventory) Instructions

func (r *Inventory) Instructions() string

func (*Inventory) RegisterAll

func (r *Inventory) RegisterAll(ctx context.Context, s *mcp.Server, deps any, middleware ...ToolHandlerMiddleware)

RegisterAll registers all available tools, resources, and prompts with the server. The context is used for feature flag evaluation.

func (*Inventory) RegisterPrompts

func (r *Inventory) RegisterPrompts(ctx context.Context, s *mcp.Server)

RegisterPrompts registers all available prompts with the server. The context is used for feature flag evaluation. Icons are automatically applied from the toolset metadata if not already set.

func (*Inventory) RegisterResourceTemplates

func (r *Inventory) RegisterResourceTemplates(ctx context.Context, s *mcp.Server, deps any)

RegisterResourceTemplates registers all available resource templates with the server. The context is used for feature flag evaluation. Icons are automatically applied from the toolset metadata if not already set.

func (*Inventory) RegisterTools

func (r *Inventory) RegisterTools(ctx context.Context, s *mcp.Server, deps any, middleware ...ToolHandlerMiddleware)

RegisterTools registers all available tools with the server using the provided dependencies. The context is used for feature flag evaluation and client capability checks.

MCP Apps UI metadata (`_meta.ui`) is stripped from the registered tools when the client did not advertise the io.modelcontextprotocol/ui extension. The strip happens here (rather than at Build() time) so the per-request context, which carries the client capability, is in scope.

Schema definitions must remain immutable and be reused across registrations. Their encodings are retained process-wide, keyed by source schema identity.

func (*Inventory) RegisterToolsForProtocolEra

func (r *Inventory) RegisterToolsForProtocolEra(ctx context.Context, s *mcp.Server, deps any, era ProtocolEra, middleware ...ToolHandlerMiddleware)

RegisterToolsForProtocolEra registers a preselected protocol-compatible variant. Remote stateless servers should use this to select schemas before registering their request-scoped server.

func (*Inventory) RequiredFeatures

func (r *Inventory) RequiredFeatures() []FeatureFlag

RequiredFeatures returns the deduplicated feature flags used to expose the inventory's current tools, resources, and prompts.

func (*Inventory) ResolveToolAliases

func (r *Inventory) ResolveToolAliases(toolNames []string) (resolved []string, aliasesUsed map[string]string)

ResolveToolAliases resolves deprecated tool aliases to their canonical names. It logs a warning to stderr for each deprecated alias that is resolved. Returns:

  • resolved: tool names with aliases replaced by canonical names
  • aliasesUsed: map of oldName → newName for each alias that was resolved

func (*Inventory) ToolsForRegistration

func (r *Inventory) ToolsForRegistration(ctx context.Context) []ServerTool

ToolsForRegistration returns AvailableTools(ctx) post-processed exactly as RegisterTools would expose them: with MCP Apps UI metadata stripped when the client cannot consume it. Useful for documentation generators and diagnostics that need the same view of the tool surface the server would register.

MCP Apps UI metadata is stripped only when the client explicitly did not advertise the io.modelcontextprotocol/ui extension capability (per the 2026-01-26 MCP Apps spec, servers SHOULD check client capabilities before exposing UI-enabled tools). In that case app-only tools (whose _meta.ui.visibility excludes "model") are omitted entirely. When the capability is unknown (e.g. stdio paths that do not populate the context flag) the metadata is kept.

func (*Inventory) ToolsetDescriptions

func (r *Inventory) ToolsetDescriptions() map[ToolsetID]string

ToolsetDescriptions returns a map of toolset ID to description for all toolsets.

func (*Inventory) ToolsetIDs

func (r *Inventory) ToolsetIDs() []ToolsetID

ToolsetIDs returns a sorted list of unique toolset IDs from all tools in this group.

func (*Inventory) UnrecognizedToolsets

func (r *Inventory) UnrecognizedToolsets() []string

UnrecognizedToolsets returns toolset IDs that were passed to WithToolsets but don't match any registered toolsets. This is useful for warning users about typos.

func (*Inventory) WithFeatureState

func (r *Inventory) WithFeatureState(ctx context.Context) context.Context

WithFeatureState installs request-owned feature state without resolving any flags up front. Handler-only checks are resolved lazily and cached.

type ProtocolEra

type ProtocolEra uint8

ProtocolEra selects the wire-compatible registration variant.

const (
	// ProtocolEraDynamic selects a variant at request time.
	ProtocolEraDynamic ProtocolEra = iota
	// ProtocolEraLegacy registers without an output schema or generated output.
	ProtocolEraLegacy
	// ProtocolEraModern registers the 2026-07-28 output-schema variant.
	ProtocolEraModern
)

func ProtocolEraForVersion

func ProtocolEraForVersion(version string) ProtocolEra

ProtocolEraForVersion selects modern behavior for SDK-supported protocol versions from 2026-07-28 onward. Unknown versions remain legacy.

type ResourceHandlerFunc

type ResourceHandlerFunc func(deps any) mcp.ResourceHandler

ResourceHandlerFunc is a function that takes dependencies and returns an MCP resource handler. This allows resources to be defined statically while their handlers are generated on-demand with the appropriate dependencies.

type SchemaEnum

type SchemaEnum struct {
	Path   string
	Values []string
}

SchemaEnum adds an enum to a property of an inferred schema. Path is a dot-separated JSON Schema path; use "items" to descend into array items.

type ScopeAccess

type ScopeAccess struct {
	// Scopes is the exhaustive upper bound of every scope this tool may request.
	// It is used for documentation, the list-scopes command, and bypassing
	// call-specific challenge evaluation when a token already grants them all.
	Scopes []string

	// Visible is used when filtering tools for a fixed-scope token.
	// Nil means the tool remains visible.
	Visible ScopeVisibility

	// Challenge evaluates one call before its handler runs.
	// Nil means the call does not use OAuth scope challenges.
	Challenge ScopeChallenge

	// Dynamic reports whether Challenge depends on tool arguments. Dynamic
	// policies must declare their exhaustive upper bound in Scopes.
	Dynamic bool

	// ArgumentNormalizer canonicalizes raw arguments before evaluating a
	// dynamic scope challenge. Inventory populates this from the tool's
	// InputNormalizer when building the HTTP scope map.
	ArgumentNormalizer InputNormalizer
}

ScopeAccess contains scope metadata and the two checks used by the server.

type ScopeChallenge

type ScopeChallenge func(arguments map[string]any, activeScopes []string) []string

ScopeChallenge returns the exact scopes to include in an OAuth challenge. An empty result means the call can continue.

type ScopeVisibility

type ScopeVisibility func(activeScopes []string) bool

ScopeVisibility reports whether a token can use any form of a tool.

type ServerPrompt

type ServerPrompt struct {
	Prompt  mcp.Prompt
	Handler mcp.PromptHandler
	// Toolset identifies which toolset this prompt belongs to
	Toolset ToolsetMetadata
	// FeatureRule controls whether this prompt is available.
	FeatureRule FeatureRule
}

ServerPrompt pairs a prompt with its toolset metadata.

func NewServerPrompt

func NewServerPrompt(toolset ToolsetMetadata, prompt mcp.Prompt, handler mcp.PromptHandler) ServerPrompt

NewServerPrompt creates a new ServerPrompt with toolset metadata.

type ServerResourceTemplate

type ServerResourceTemplate struct {
	Template mcp.ResourceTemplate
	// HandlerFunc generates the handler when given dependencies.
	// This allows resources to be passed around without handlers being set up,
	// and handlers are only created when needed.
	HandlerFunc ResourceHandlerFunc
	// Toolset identifies which toolset this resource belongs to
	Toolset ToolsetMetadata
	// FeatureRule controls whether this resource is available.
	FeatureRule FeatureRule
}

ServerResourceTemplate pairs a resource template with its toolset metadata.

func NewServerResourceTemplate

func NewServerResourceTemplate(toolset ToolsetMetadata, resourceTemplate mcp.ResourceTemplate, handlerFn ResourceHandlerFunc) ServerResourceTemplate

NewServerResourceTemplate creates a new ServerResourceTemplate with toolset metadata.

func (*ServerResourceTemplate) Handler

func (sr *ServerResourceTemplate) Handler(deps any) mcp.ResourceHandler

Handler returns a resource handler by calling HandlerFunc with the given dependencies. Panics if HandlerFunc is nil - all resources should have handlers.

func (*ServerResourceTemplate) HasHandler

func (sr *ServerResourceTemplate) HasHandler() bool

HasHandler returns true if this resource has a handler function.

type ServerTool

type ServerTool struct {
	// Tool is the MCP tool definition containing name, description, schema, etc.
	Tool mcp.Tool

	// Toolset contains metadata about which toolset this tool belongs to.
	Toolset ToolsetMetadata

	// HandlerFunc generates the handler when given dependencies.
	// This allows tools to be passed around without handlers being set up,
	// and handlers are only created when needed.
	HandlerFunc HandlerFunc

	// FeatureRule declares and evaluates the feature flags that control whether
	// this tool is available. Its zero value leaves the tool available.
	FeatureRule FeatureRule

	// Enabled is an optional function called at build/filter time to determine
	// if this tool should be available. If nil, the tool is considered enabled
	// (subject to feature flag checks).
	// The context carries request-scoped information for the consumer to use.
	// Returns (enabled, error). On error, the tool should be treated as disabled.
	Enabled func(ctx context.Context) (bool, error)

	// MinimumProtocolVersion is the oldest MCP protocol version that may list or
	// call this tool. Empty means the tool is available on every version.
	MinimumProtocolVersion string

	// RequiredElicitationMode is the elicitation mode the client must support to
	// list or call this tool. Empty means the tool does not require elicitation.
	RequiredElicitationMode ElicitationMode

	// ScopeAccess controls fixed-token visibility and per-call OAuth challenges.
	ScopeAccess ScopeAccess
	// contains filtered or unexported fields
}

ServerTool represents an MCP tool with metadata and a handler generator function. The tool definition is static, while the handler is generated on-demand when the tool is registered with a server. Tools are now self-describing with their toolset membership and read-only status derived from the Tool.Annotations.ReadOnlyHint field.

func NewServerTool

func NewServerTool(tool mcp.Tool, toolset ToolsetMetadata, handler mcp.ToolHandler) ServerTool

NewServerTool creates a ServerTool with a raw handler that receives deps via context. This is the preferred constructor for tools that use mcp.ToolHandler directly because it doesn't create closures at registration time, which is critical for performance in servers that create a new instance per request.

The handler function is stored directly without wrapping in a deps closure. Dependencies should be injected into context before calling tool handlers.

func NewServerToolWithContextHandler

func NewServerToolWithContextHandler[In any, Out any](tool mcp.Tool, toolset ToolsetMetadata, handler mcp.ToolHandlerFor[In, Out], inputNormalizers ...InputNormalizer) ServerTool

NewServerToolWithContextHandler creates a ServerTool with a handler that receives deps via context. This is the preferred approach for tools because it doesn't create closures at registration time, which is critical for performance in servers that create a new instance per request.

When Out is concrete, registration uses mcp.AddTool so the SDK infers missing schemas and validates typed input and output. Out=any retains the raw handler registration path. Optional InputNormalizer callbacks can canonicalize raw JSON before SDK validation without weakening the advertised schema. Direct Handler calls apply the same normalization before decoding.

The handler function is stored directly without wrapping in a deps closure. Dependencies should be injected into context before calling tool handlers.

func NewServerToolWithContextHandlerAndSchemaOptions

func NewServerToolWithContextHandlerAndSchemaOptions[In any, Out any](
	tool mcp.Tool,
	toolset ToolsetMetadata,
	handler mcp.ToolHandlerFor[In, Out],
	schemaOptions TypedSchemaOptions,
	inputNormalizers ...InputNormalizer,
) ServerTool

NewServerToolWithContextHandlerAndSchemaOptions is like NewServerToolWithContextHandler, with additional schema inference options. Inferred input and output schemas are cached per ServerTool.

func (*ServerTool) AddHandlerMiddleware

func (st *ServerTool) AddHandlerMiddleware(provider ToolHandlerMiddlewareProvider)

AddHandlerMiddleware adds dependency-aware middleware used on both typed and raw registration paths.

func (*ServerTool) GetInputNormalizer

func (st *ServerTool) GetInputNormalizer() InputNormalizer

GetInputNormalizer returns the compatibility normalizer configured for this tool, if any.

func (*ServerTool) Handler

func (st *ServerTool) Handler(deps any) mcp.ToolHandler

Handler returns a tool handler by calling HandlerFunc with the given dependencies. Panics if HandlerFunc is nil - all tools should have handlers.

func (*ServerTool) HasHandler

func (st *ServerTool) HasHandler() bool

HasHandler returns true if this tool has a handler function.

func (*ServerTool) IsReadOnly

func (st *ServerTool) IsReadOnly() bool

IsReadOnly returns true if this tool is marked as read-only via annotations.

func (*ServerTool) RegisterFunc

func (st *ServerTool) RegisterFunc(s *mcp.Server, deps any, middleware ...ToolHandlerMiddleware)

RegisterFunc registers the tool with the server using the provided dependencies. Icons are automatically applied from the toolset metadata if not already set. A shallow copy of the tool is made to avoid mutating the original ServerTool. Panics if the tool has no handler - all tools should have handlers.

func (*ServerTool) RegisterFuncForProtocolEra

func (st *ServerTool) RegisterFuncForProtocolEra(s *mcp.Server, deps any, era ProtocolEra, middleware ...ToolHandlerMiddleware)

RegisterFuncForProtocolEra registers a preselected legacy or modern tool variant. Use this when the protocol era is known before server construction.

type ToolCallPreflight

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

ToolCallPreflight inspects raw call arguments before SDK schema validation. Return nil, nil to continue; a result or error short-circuits the call. Returning a non-nil context passes request-scoped preparation to the handler.

type ToolDoesNotExistError

type ToolDoesNotExistError struct {
	Name string
}

ToolDoesNotExistError is returned when a tool is not found.

func NewToolDoesNotExistError

func NewToolDoesNotExistError(name string) *ToolDoesNotExistError

NewToolDoesNotExistError creates a new ToolDoesNotExistError.

func (*ToolDoesNotExistError) Error

func (e *ToolDoesNotExistError) Error() string

type ToolFilter

type ToolFilter func(ctx context.Context, tool *ServerTool) (bool, error)

ToolFilter is a function that determines if a tool should be included. Returns true if the tool should be included, false to exclude it.

func CreateExcludeToolsFilter

func CreateExcludeToolsFilter(excluded []string) ToolFilter

CreateExcludeToolsFilter creates a ToolFilter that excludes tools by name. Any tool whose name appears in the excluded list will be filtered out. The input slice should already be cleaned (trimmed, deduplicated).

type ToolHandlerMiddleware

type ToolHandlerMiddleware func(next mcp.ToolHandler) mcp.ToolHandler

ToolHandlerMiddleware wraps an MCP tool handler. Middleware is applied from right to left, so the first middleware passed to RegisterFunc executes first.

type ToolHandlerMiddlewareProvider

type ToolHandlerMiddlewareProvider func(deps any) ToolHandlerMiddleware

ToolHandlerMiddlewareProvider creates tool-specific middleware using the dependencies supplied when the tool is registered.

type ToolInputError

type ToolInputError struct {
	Message string
}

ToolInputError represents an argument validation error whose message should be shown to the tool caller without additional wrapper text.

func (*ToolInputError) Error

func (err *ToolInputError) Error() string

Error implements error.

type ToolsetDoesNotExistError

type ToolsetDoesNotExistError struct {
	Name string
}

ToolsetDoesNotExistError is returned when a toolset is not found.

func NewToolsetDoesNotExistError

func NewToolsetDoesNotExistError(name string) *ToolsetDoesNotExistError

NewToolsetDoesNotExistError creates a new ToolsetDoesNotExistError.

func (*ToolsetDoesNotExistError) Error

func (e *ToolsetDoesNotExistError) Error() string

func (*ToolsetDoesNotExistError) Is

func (e *ToolsetDoesNotExistError) Is(target error) bool

type ToolsetID

type ToolsetID string

ToolsetID is a unique identifier for a toolset. Using a distinct type provides compile-time type safety.

type ToolsetMetadata

type ToolsetMetadata struct {
	// ID is the unique identifier for the toolset (e.g., "repos", "issues")
	ID ToolsetID
	// Description provides a human-readable description of the toolset
	Description string
	// Default indicates this toolset should be enabled by default
	Default bool
	// Icon is the name of the Octicon to use for tools in this toolset.
	// Use the base name without size suffix, e.g., "repo" not "repo-16".
	// See https://primer.style/foundations/icons for available icons.
	Icon string
	// InstructionsFunc optionally returns instructions for this toolset.
	// It receives the inventory so it can check what other toolsets are enabled.
	InstructionsFunc func(inv *Inventory) string
}

ToolsetMetadata contains metadata about the toolset a tool belongs to.

func (ToolsetMetadata) Icons

func (tm ToolsetMetadata) Icons() []mcp.Icon

Icons returns MCP Icon objects for this toolset, or nil if no icon is set. Icons are provided in both 16x16 and 24x24 sizes.

type TypedSchemaOptions

type TypedSchemaOptions struct {
	Input                  *jsonschema.ForOptions
	Output                 *jsonschema.ForOptions
	ValidationInputSchema  *jsonschema.Schema
	InputEnums             []SchemaEnum
	OutputEnums            []SchemaEnum
	Preflight              ToolCallPreflight
	PreserveHandlerContent bool
}

TypedSchemaOptions customizes schemas inferred for a typed tool.

Input and Output are passed to jsonschema.For when the corresponding schema is not provided on the tool. ValidationInputSchema, when set, is used by the SDK to validate calls while the tool's declared InputSchema remains visible to clients. InputEnums and OutputEnums are applied to inferred schemas at registration time.

Jump to

Keyboard shortcuts

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