mcpserver

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MPL-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// PageSizeDefault, PageSizeMin, and PageSizeMax bound one page's item count.
	PageSizeDefault = 25
	PageSizeMin     = 1
	PageSizeMax     = 100
	// CursorMaxBytes bounds an accepted cursor's encoded size.
	CursorMaxBytes = 2 << 10
	// CursorTTL is the one chain expiry; continuation never renews it.
	CursorTTL = 15 * time.Minute
	// Chain bounds: one cursor chain returns at most MaxChainPages pages,
	// MaxChainItems items, and MaxChainBytes encoded structured content.
	MaxChainPages = 10
	MaxChainItems = 1000
	MaxChainBytes = 1 << 20
)

Phase-1 pagination and traversal bounds (mcp-server ADR, Pagination and output bounds).

View Source
const (
	Path                       = "/mcp"
	ProtocolVersion            = "2026-07-28"
	MaxRequestBytes            = 256 << 10
	MaxStaticResponseBytes     = 64 << 10
	MaxBearerBytes             = 4096
	ToolExecutionTimeout       = 30 * time.Second
	DefaultInstanceConcurrency = 64
)
View Source
const (
	// MaxStructuredContentBytes is the phase-1 encoded tool-result bound.
	MaxStructuredContentBytes = 256 << 10
	// MaxCompatibilityTextBytes is the phase-1 compatibility-summary bound.
	MaxCompatibilityTextBytes = 4 << 10
	// SafeOperationError is the only fallback text emitted for an unexpected
	// service error. Domain-specific safe errors can join this closed policy in
	// the tool ticket; raw errors never cross the transport.
	SafeOperationError = "Hikyo operation refused"
)
View Source
const (
	ToolListDefinitions      = "hikyo_list_definitions"
	ToolListEnvironments     = "hikyo_list_environments"
	ToolInspectConfiguration = "hikyo_inspect_configuration"
	ToolListPendingChanges   = "hikyo_list_pending_changes"
	ToolListRevisions        = "hikyo_list_revisions"
)

Tool names are stable MCP surface once released.

View Source
const (
	ToolStageChange    = "hikyo_stage_change"
	ToolValidateChange = "hikyo_validate_change"
)

Write tool names are stable MCP surface once released.

View Source
const CodexPath = "/mcp/codex"

CodexPath is an explicit stateless compatibility boundary. The modern /mcp endpoint retains its independently validated 2026-07-28 wire contract.

View Source
const CodexProtocolVersion = "2025-06-18"

Variables

View Source
var (
	// ErrInvalidCursor is the single safe response to a missing, tampered,
	// expired, or scope-mismatched cursor. It never distinguishes which.
	ErrInvalidCursor = errors.New("invalid_cursor")
	// ErrTraversalLimitReached is returned when a chain bound is reached; no
	// continuation cursor accompanies it.
	ErrTraversalLimitReached = errors.New("traversal_limit_reached")
	// ErrResultItemTooLarge is returned when the next single valid item cannot
	// fit within the structured-content bound.
	ErrResultItemTooLarge = errors.New("result_item_too_large")
	// ErrInvalidArgument is the safe response to an out-of-range argument.
	ErrInvalidArgument = errors.New("invalid_argument")
)

Named, tenant-safe tool errors. They describe the cursor, a bound, or an argument, never a tenant fact, so the transport surfaces their exact token while every other failure collapses to SafeOperationError.

View Source
var ErrRateLimited = errors.New("mcpserver: rate limited")

ErrRateLimited lets an authenticated service callback request the transport's uniform HTTP 429 response without exposing internal error details.

Functions

func AllToolNames

func AllToolNames() []string

AllToolNames is the read catalog followed by the write catalog: the closed telemetry label set.

func New

func New(options Options) (http.Handler, error)

New constructs the feature-gated endpoint handler around the pinned SDK.

func Paginate

func Paginate[Row, Elem any](ctx context.Context, spec PageSpec[Row, Elem]) ([]Elem, string, error)

Paginate resolves one page under the phase-1 cursor, chain, and output-byte bounds. It authenticates the presented cursor against the scope, refuses when a chain bound is reached, fetches one row past the page to detect a continuation, and includes only the elements that fit the structured-content bound. It returns the page's elements and, when a continuation exists, an authenticated next cursor; the caller wraps them in the tool's output.

func ProductionToolNames

func ProductionToolNames() []string

ProductionToolNames returns the closed phase-1 catalog for telemetry and interoperability checks without exposing mutable registry state.

func Register

func Register[In, Out any](registry *Registry, spec ToolSpec, handler func(context.Context, Bearer, In) (Out, error)) error

Register adds one typed service-operation mapping to the closed registry.

func RegisterConformanceDiagnostics

func RegisterConformanceDiagnostics(registry *Registry) error

RegisterConformanceDiagnostics adds only the three upstream SEP-2575 probe tools. It is for scripts/ci/mcp-conformance-server and must never be called by production wiring. Keeping the fixture on New still exercises Hikyo's actual host, origin, metadata, header, statelessness, and status adapters.

func RegisterProductionTools

func RegisterProductionTools(registry *Registry, services ProductionServices) error

RegisterProductionTools registers the five phase-1 read tools onto a fresh registry. It returns the first registration error, so a boot that cannot pin the closed surface refuses to serve.

func RegisterWriteTools

func RegisterWriteTools(registry *Registry, services WriteServices) error

RegisterWriteTools installs the write surface onto a registry that already holds the read tools. It returns the first registration error, so a boot that cannot pin the closed surface refuses to serve.

func WriteToolNames

func WriteToolNames() []string

WriteToolNames returns the closed write-surface catalog. Their metric labels are pinned whether or not the operator installs the tools, so the label set never depends on a flag.

Types

type AdmissionService

type AdmissionService interface {
	Acquire(context.Context, service.Actor, authz.Operation, domain.Scope) (func() error, error)
}

AdmissionService is service.MCPAdmission. It authorizes before claiming shared rate/concurrency capacity; the page service authorizes again.

type AuditDisposition

type AuditDisposition string
const (
	// AuditDispositionNone is the phase-1 read disposition: the mapped
	// operation is a tenant-class audited-none pure read.
	AuditDispositionNone AuditDisposition = "audited:none"
	// AuditDispositionEvents is the write-surface disposition (mcp-write ADR
	// § 3): the mapped operation emits audit events on every call, so the trail
	// is the operation's own and the transport adds only origin=mcp.
	AuditDispositionEvents AuditDisposition = "audited:events"
)

type Bearer

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

Bearer wraps the raw presented service-account artifact. Formatting is always redacted; only this adapter package can unwrap it for a service call.

func (Bearer) GoString

func (Bearer) GoString() string

func (Bearer) String

func (Bearer) String() string

type ConfigurationService

type ConfigurationService interface {
	ListPage(ctx context.Context, actor service.Actor, scope domain.Scope, afterName string, limit int) ([]service.ValueCell, error)
}

ConfigurationService is service.Values.

type CursorScope

type CursorScope struct {
	Tool     string
	Org      string
	Project  string
	Env      string
	PageSize int
}

CursorScope is the tool and immutable id chain a cursor is bound to. A continuation whose scope does not match the presented request is rejected as one safe invalid-cursor error.

type CursorSealer

type CursorSealer interface {
	Seal(context.Context, []byte) (string, error)
	Open(context.Context, string) ([]byte, error)
}

CursorSealer encrypts and authenticates opaque cursor payloads. It is injected because the crypto chokepoint confines the AEAD to internal/crypto; the transport holds only this narrow verb. Open returns a non-nil error for any tampered, truncated, or forged token, without distinguishing which.

type DefinitionsService

type DefinitionsService interface {
	ListPage(ctx context.Context, actor service.Actor, scope domain.Scope, afterName string, limit int) ([]service.Key, int64, error)
}

DefinitionsService is service.Keys.

type EnvironmentsService

type EnvironmentsService interface {
	ListPage(ctx context.Context, actor service.Actor, scope domain.Scope, afterDisplayOrder int64, afterName string, limit int) ([]service.Environment, error)
}

EnvironmentsService is service.Environments.

type Options

type Options struct {
	Registry       *Registry
	ExternalOrigin string
	AllowedOrigins []string
	TrustedProxies []*net.IPNet
	Admission      discoveryAdmission
	Version        string
	MaxConcurrent  int
	// CursorSealer encrypts and authenticates pagination cursors. Its live key
	// comes from shared authoritative configuration, so cursors are portable
	// across replicas and token-key rotation cannot leave a stale cached key.
	// It is required whenever the registry advertises a paginated tool. New
	// refuses a non-empty registry without it. The crypto chokepoint confines
	// the AEAD primitive to internal/crypto.
	CursorSealer CursorSealer
	// OnReleaseFailure is told when an admission slot could not be released
	// after the call itself succeeded (the call keeps its committed outcome).
	// It receives the authorization operation and the coordinator's error,
	// never a bearer or request material. The package owns no telemetry sink
	// (MCP secret boundary, internal/boundary); the app routes this to its
	// logger. Nil drops the notice, and the lease still expires on its TTL.
	OnReleaseFailure func(operation string, err error)
}

Options fixes the transport policy at process boot.

type PageSpec

type PageSpec[Row, Elem any] struct {
	Scope    CursorScope
	Cursor   string
	PageSize int
	// Fetch returns up to limit rows strictly past the keyset position after
	// ("" for the first page), in the tool's stable order.
	Fetch func(ctx context.Context, after string, limit int) ([]Row, error)
	// Map projects one service row into its whitelisted output element.
	Map func(Row) (Elem, error)
	// Key returns one row's stable keyset position (the cursor advances on it).
	Key func(Row) string
	// StructuredSize returns the exact encoded structuredContent byte count for
	// these elements and cursor, including addressed ids and other tool fields.
	StructuredSize func([]Elem, string) (int, error)
}

PageSpec is one bounded page request the transport resolves on a tool's behalf. Row is the service result element; Elem is the whitelisted output element the tool emits. The tool supplies the fetch, the row-to-element mapping, and the stable keyset accessor; the transport owns cursor authentication, chain bounds, and the output byte fit.

type PendingService

type PendingService interface {
	PendingDraftsPage(ctx context.Context, actor service.Actor, scope domain.Scope, afterKeyID string, limit int) ([]service.PendingDraft, error)
}

PendingService is service.Revisions.

type ProductionServices

type ProductionServices struct {
	Admission     AdmissionService
	Definitions   DefinitionsService
	Environments  EnvironmentsService
	Configuration ConfigurationService
	Pending       PendingService
	Revisions     RevisionsService
}

ProductionServices are the five read services the phase-1 tools map onto. The wiring layer supplies the concrete service structs.

type Registry

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

Registry is a closed tool set. New freezes it before serving.

func NewRegistry

func NewRegistry() *Registry

func (*Registry) Rows

func (r *Registry) Rows() []RegistryRow

Rows returns the deterministic policy projection.

type RegistryRow

type RegistryRow struct {
	Name                   string
	InputSchema            json.RawMessage
	OutputSchema           json.RawMessage
	ServiceOperation       string
	AuthorizationOperation string
	Formula                []string
	Artifacts              []string
	Class                  ToolClass
	AuditDisposition       AuditDisposition
	// ReadOnly is derived from the authorization registry's policy for the
	// mapped operation, never hand-set, and drives the tool annotations.
	ReadOnly     bool
	ResultBytes  int
	SecretPolicy SecretPolicy
}

RegistryRow is the immutable, reviewable projection used by closure tests.

type RevisionsService

type RevisionsService interface {
	HistoryPage(ctx context.Context, actor service.Actor, scope domain.Scope, beforeRevision int64, limit int) ([]service.RevisionView, error)
}

RevisionsService is service.Revisions.

type SecretPolicy

type SecretPolicy string
const SecretPolicyNoSecretMaterial SecretPolicy = "no-secret-material"

type StagingService

type StagingService interface {
	Set(ctx context.Context, actor service.Actor, scope domain.Scope, keyName, value string, acks []string) (service.StagedChange, error)
	Unset(ctx context.Context, actor service.Actor, scope domain.Scope, keyName string) (service.StagedChange, error)
}

StagingService is service.Values' stage ingress.

type ToolClass

type ToolClass string

ToolClass is the declared class the registration gate keys off (mcp-write ADR § 4). A read tool must map to an audited-none read-only operation. A write-surface tool must map to an events-emitting operation; it is never audited:none. The empty class is read: the strictest gate is the default, so a spec that forgets to declare itself cannot register a mutation.

const (
	ToolClassRead         ToolClass = "read"
	ToolClassWriteSurface ToolClass = "write-surface"
)

type ToolSpec

type ToolSpec struct {
	Name             string
	Title            string
	Description      string
	ServiceOperation string
	Contract         operation.Contract
	Class            ToolClass
	AuditDisposition AuditDisposition
	SecretPolicy     SecretPolicy
}

ToolSpec is the security and wire policy for one explicitly registered operation. Input and output schemas are inferred once from the generic Register types and pinned into the immutable registry row.

type ValidationService

type ValidationService interface {
	ValidateSet(ctx context.Context, actor service.Actor, scope domain.Scope, keyName, value string) (service.ValidatedChange, error)
	ValidateUnset(ctx context.Context, actor service.Actor, scope domain.Scope, keyName string) (service.ValidatedChange, error)
}

ValidationService is service.Values' validate operation.

type WriteServices

type WriteServices struct {
	Admission  AdmissionService
	Staging    StagingService
	Validation ValidationService
}

WriteServices are the services the write tools map onto.

Jump to

Keyboard shortcuts

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