mcp

package
v0.47.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 29 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const DefaultRelayRefresh = 60 * time.Second

DefaultRelayRefresh is how often the relayed tool list is re-read when Hub announces no change: relays connect and drop without telling this process.

Variables

View Source
var AlwaysAvailableTools = []string{"orient", "guide", "session_info", "session_refresh", "namespace_list", "invitation_list"}

AlwaysAvailableTools stay listed and callable under every tool allowlist: they carry no KEG authority. orient and guide are how a session learns what it may do; session_info reports the identity and authority it already acts with; session_refresh retries a failed flight activation and cannot change a working one; namespace_list and invitation_list report the caller's own memberships and pending invitations.

View Source
var ErrOrientationDenied = fmt.Errorf("ORIENTATION_DENIED: the requested flight is not selectable from this connection's current authority or does not grant this operation. The operation was not performed: %w", keg.ErrOrientationDenied)

ErrOrientationDenied reports a fresh orientation that lacks the requested authority. Selecting a different accessible flight is explicit per call.

View Source
var ErrOrientationRootUnavailable = fmt.Errorf("ORIENTATION_ROOT_UNAVAILABLE: the connection-pinned root was deleted or is no longer accessible; start a new session to choose a different root. The operation was not performed: %w", keg.ErrOrientationRootUnavailable)

ErrOrientationRootUnavailable reports permanent loss of the connection-pinned root. A different root requires a newly launched session.

View Source
var ErrOrientationStale = fmt.Errorf("ORIENTATION_STALE: authority changed between per-call resolution and dispatch; retry the operation yourself after reviewing current authority. Mutations are never replayed automatically: %w", keg.ErrOrientationStale)

ErrOrientationStale is returned without performing the requested operation.

View Source
var ErrOrientationUnavailable = fmt.Errorf("ORIENTATION_UNAVAILABLE: current orientation authority could not be verified; retry after the Hub is available. The operation was not performed: %w", keg.ErrOrientationUnavailable)

ErrOrientationUnavailable reports a transient failure to recompute live authority. The caller may retry later, but the operation is never replayed.

Functions

func AggregateOrientationKegs added in v0.39.0

func AggregateOrientationKegs(flights []*tapper.Flight, authorized []tapper.OrientationKeg) []tapper.OrientationKeg

AggregateOrientationKegs projects each reachable flight over one identity load and merges duplicate KEGs by highest effective role.

func CanonicalOrientationIdentity added in v0.39.0

func CanonicalOrientationIdentity(identity AuthIdentity) (string, error)

CanonicalOrientationIdentity returns transport-neutral revision material for the authenticated identity on the pinned root's Hub. Hub routing aliases and credentials are deliberately absent so stdio and hosted MCP hash the same authority while unrelated Hub logins cannot stale a call.

func EffectiveOrientationRole added in v0.39.0

func EffectiveOrientationRole(row tapper.OrientationKeg) string

EffectiveOrientationRole intersects the identity's current ACL role with the selected flight's cover cap, so a cover never widens the identity role.

func FinalizeOrientation added in v0.39.0

func FinalizeOrientation(orientation *Orientation) error

FinalizeOrientation computes a deterministic revision when a provider has not supplied one.

func HasSessionOrientation added in v0.35.0

func HasSessionOrientation(ctx context.Context) bool

HasSessionOrientation reports whether the current call is governed by a session orientation gate. A governed recovery session has no flight but still returns true; ungated embedded surfaces return false.

func IsRelayedToolName added in v0.45.0

func IsRelayedToolName(name string) bool

IsRelayedToolName reports whether name has the shape Hub gives relayed tools: mcp__<owner>__<server>__<tool>. No hosted KEG tool has it.

func NewServer

func NewServer(tap *tapper.Tap, version string, defaults KegDefaults, opts ...ServerOptions) *sdkmcp.Server

NewServer builds an MCP server with all registered tools.

func SessionFlight added in v0.35.0

func SessionFlight(ctx context.Context) *tapper.Flight

SessionFlight returns the immutable flight snapshot captured for the current MCP tool-call boundary. Hosted discovery tools use it to apply the same cover as KEG operations without reaching into session storage.

func SessionFullAccess added in v0.39.0

func SessionFullAccess(ctx context.Context) bool

SessionFullAccess reports whether the current call runs under no-flight identity authority. Such a call has no flight snapshot but is not restricted: it reaches everything the identity reaches. Discovery tools must distinguish it from the other flightless state — failed-root recovery, which reaches nothing — because both report a nil SessionFlight.

func SessionOrientationKegs added in v0.39.0

func SessionOrientationKegs(ctx context.Context) []tapper.OrientationKeg

SessionOrientationKegs returns the exact selected-flight projection when flight was supplied, or the live no-flight identity / pinned-root graph projection when discovery omitted it. Aggregate rows are call-local and never cached in session state.

func StartRelayProxy added in v0.45.0

func StartRelayProxy(ctx context.Context, srv *sdkmcp.Server, opts RelayProxyOptions) (stop func())

StartRelayProxy keeps srv's relayed tools in step with Hub's /mcp/relay until ctx ends or the returned stop is called. It never blocks or fails the server: while Hub is unreachable the server simply has no relayed tools.

Types

type AgentProvider added in v0.44.0

type AgentProvider interface {
	// ListAgents returns a namespace's agents, or with an empty namespace the
	// agents of every namespace the caller belongs to.
	ListAgents(ctx context.Context, namespace string) ([]tapper.HubAgent, error)
	// GetAgent returns one agent, including its instructions.
	GetAgent(ctx context.Context, ref string) (*tapper.HubAgent, error)
	// CreateAgent creates an agent and returns it as stored.
	CreateAgent(context.Context, tapper.CreateAgentOptions) (*tapper.HubAgent, error)
	// EditAgent applies the set fields and returns the agent as stored.
	EditAgent(context.Context, tapper.EditAgentOptions) (*tapper.HubAgent, error)
	// DeleteAgent removes an agent.
	DeleteAgent(ctx context.Context, ref string) error
}

AgentProvider reads and manages Hub agents: a namespace-owned model, instructions, and tool allowlist. Implementations apply the caller's namespace role (members read, owners and admins write); agent refs are @namespace/name.

type AuthIdentity added in v0.37.0

type AuthIdentity struct {
	Hub              string   `json:"hub"`
	UserID           int64    `json:"user_id"`
	Username         string   `json:"username"`
	DisplayName      string   `json:"display_name,omitempty"`
	DefaultNamespace string   `json:"default_namespace"`
	Namespaces       []string `json:"namespaces"`
}

AuthIdentity is deliberately credential-free. Do not add token, email, scope, cookie, expiry, or session fields to this MCP wire shape.

type ExploreProvider added in v0.46.0

type ExploreProvider interface {
	// Explore returns a bounded page of public matches of one kind.
	Explore(ctx context.Context, kind tapper.ExploreKind, query string) (tapper.ExploreResult, error)
}

ExploreProvider searches the hub's public directory. It never sees the caller's private KEGs or flights: those are listed by keg_list and flight_list, never searched.

type FlightOrientationProvider added in v0.39.0

type FlightOrientationProvider interface {
	// Resolve reloads the pinned root's live graph and selects one flight for
	// the current call; an empty selection resolves to the root.
	Resolve(context.Context, string, string) (*Orientation, error)
}

FlightOrientationProvider refreshes one connection-pinned root and selects the root or an identity-accessible transitive descendant for one call.

type FlightProvider added in v0.37.0

type FlightProvider interface {
	// ListFlights returns the canonical refs of every flight this identity can see.
	ListFlights(context.Context) ([]string, error)
	// GetFlight resolves one flight by ref.
	GetFlight(context.Context, string) (*tapper.Flight, error)
	// CreateFlight persists a new flight and returns the stored manifest.
	CreateFlight(context.Context, tapper.CreateFlightOptions) (*tapper.Flight, error)
	// UpdateFlight applies a partial edit and returns the stored manifest. The
	// every subsequent authority-bearing call resolves the live graph again.
	UpdateFlight(context.Context, tapper.UpdateFlightOptions) (*tapper.Flight, error)
	// DeleteFlight removes a flight.
	DeleteFlight(context.Context, tapper.DeleteFlightOptions) error
}

FlightProvider supplies identity-authorized flight discovery and mutation. Session capability checks are enforced independently by the MCP gate, so implementations apply only their own transport's authorization.

type IdentityProvider added in v0.37.0

type IdentityProvider interface {
	// Identities returns the authenticated identities, without credentials.
	// Local MCP reports the selected Hub login; hosted MCP reports the one
	// authenticated account.
	Identities(context.Context) ([]AuthIdentity, error)
}

IdentityProvider reports who the session is authenticated as.

type InvitationLister added in v0.44.0

type InvitationLister interface {
	// ListInvitations returns the caller's pending, unexpired invitations.
	ListInvitations(context.Context) ([]tapper.HubInvitation, error)
}

InvitationLister is implemented by namespace providers that can list the caller's pending invitations. It is optional so a provider without it still satisfies NamespaceProvider; invitation_list registers only when present.

type KegDefaults

type KegDefaults struct {
	tapper.KegTargetOptions
	// contains filtered or unexported fields
}

KegDefaults holds server-wide keg targeting defaults.

type KegDeletionAuthorizer added in v0.47.0

type KegDeletionAuthorizer interface {
	// AuthorizesKegDeletion reports whether DeleteKeg authorizes the delete
	// itself, so keg_delete skips its cover pre-check.
	AuthorizesKegDeletion() bool
}

KegDeletionAuthorizer is a KegDeletionProvider that authorizes a delete with the session's full authority itself, as a Hub does: that authority may reach past the session flight's cover (a flight managing the namespace's KEGs), so keg_delete leaves the decision to it instead of pre-checking the cover.

type KegDeletionProvider added in v0.41.0

type KegDeletionProvider interface {
	// DeleteKeg removes the explicit canonical KEG and all its data, including snapshots.
	DeleteKeg(context.Context, string) error
}

KegDeletionProvider permanently removes catalog KEGs.

type KegDiscoveryProvider added in v0.37.0

type KegDiscoveryProvider interface {
	// ListKegs returns every identity-authorized canonical keg ref. MCP applies
	// the call-selected flight cover before releasing results, so
	// implementations do not filter by flight themselves.
	ListKegs(context.Context) ([]string, error)
	// CreateKeg provisions a keg and returns its canonical @namespace/keg ref.
	// The MCP gate has already checked that the session is active; whether it
	// may call keg_create at all is its agent's tools. Implementations apply
	// their own transport's identity authorization.
	CreateKeg(context.Context, tapper.CreateKegOptions) (string, error)
}

KegDiscoveryProvider reports the kegs an identity can reach and creates new ones. Creation lives here rather than on a keg-agnostic surface because both operations answer to the same authenticated catalog.

type NamespaceProvider added in v0.44.0

type NamespaceProvider interface {
	// ListNamespaces returns the namespaces the caller belongs to, with role.
	ListNamespaces(context.Context) ([]tapper.HubNamespace, error)
}

NamespaceProvider lists the caller's own namespaces. The hub-wide people directory is ExploreProvider's. Listing never grants authority.

type NodeSearchProvider added in v0.46.0

type NodeSearchProvider interface {
	// SearchNodes returns one ranked page for opts.Query.
	SearchNodes(ctx context.Context, opts tapper.SearchOptions) (*tapapi.SearchResponse, error)
}

NodeSearchProvider ranks nodes by relevance across the KEGs a call may read. opts.Keg names one KEG; otherwise the search covers opts.Kegs, narrowed to the call's flight cover (opts.FlightContext), or with neither, every KEG the caller may read. The node_search tool has already run opts.Validate.

type Orientation added in v0.37.0

type Orientation struct {
	Root             *tapper.Flight
	Flight           *tapper.Flight
	Path             []string
	AvailableFlights []string
	Identity         string
	Revision         string
	// RootHub binds the proof to this connection's validating Hub.
	RootHub        string
	AllowedTargets []string
	Payload        string
	Kegs           []tapper.OrientationKeg
	// AggregateKegs is the pinned root plus every accessible transitive
	// descendant, merged by highest effective role. It exists only on a live
	// per-call candidate and is never published into shared session state.
	AggregateKegs []tapper.OrientationKeg
	Warnings      []string
	// FullAccess marks an ungoverned no-flight candidate. It uses the identity's
	// real KEG roles, publishes the complete tool inventory, and emits no Hub
	// orientation header.
	FullAccess            bool
	ReconnectInstructions string
}

Orientation is one complete MCP authority candidate.

type OrientationProvider added in v0.37.0

type OrientationProvider interface {
	// Load selects the pinned root and renders it into a complete candidate.
	// It is the transport's reload boundary: whatever "which flight am I on"
	// depends on is re-read here and nowhere else.
	Load(context.Context) (*Orientation, error)
	// Render renders the exact supplied manifest. It must not consult a mutable
	// selection again, because its caller has already decided which flight is
	// authoritative and is only asking for the payload.
	Render(context.Context, *tapper.Flight) (*Orientation, error)
}

OrientationProvider owns transport-specific flight selection and rendering.

type PublicFlight added in v0.41.0

type PublicFlight struct {
	Name          string              `json:"name"`
	Hash          string              `json:"hash"`
	Title         string              `json:"title"`
	Description   string              `json:"description"`
	Source        string              `json:"source"`
	Visibility    string              `json:"visibility"`
	Cover         []PublicFlightCover `json:"cover"`
	Subflights    []string            `json:"subflights"`
	ManageKegs    bool                `json:"manage_kegs"`
	ManageFlights bool                `json:"manage_flights"`
	Instructions  string              `json:"instructions"`
}

PublicFlight is a deliberately explicit, permission-filtered manifest view. Do not serialize Flight itself: effective cover and internal identity fields are not manifest fields and do not describe the authority of an inspection.

type PublicFlightCover added in v0.41.0

type PublicFlightCover struct {
	Namespace string `json:"namespace"`
	Keg       string `json:"keg"`
	Role      string `json:"role"`
	Depth     int    `json:"depth"`
}

type RelayProxyOptions added in v0.45.0

type RelayProxyOptions struct {
	// Endpoint is Hub's /mcp/relay URL, with ?agent= when the session runs as
	// an agent.
	Endpoint string
	// Token returns the current Hub bearer token; it is read on every request
	// so a refreshed login is picked up.
	Token func() string
	// Refresh overrides DefaultRelayRefresh.
	Refresh time.Duration
	// HTTPClient overrides the client used to reach Hub.
	HTTPClient *http.Client
	Logger     *slog.Logger
	// Version is reported to Hub as the client version.
	Version string
}

RelayProxyOptions configures StartRelayProxy.

type ServerOptions added in v0.12.0

type ServerOptions struct {
	// Logger is the structured logger for invocation logging. When nil,
	// invocation logging is silently skipped.
	Logger *slog.Logger
	// Reporter receives privacy-minimized tool invocation telemetry. It is
	// independent of Logger and may be nil.
	Reporter tapper.InvocationReporter
	// Providers replace transport-specific registration branches. Nil providers
	// use local adapters over tap; hosted callers inject authenticated catalog
	// and account implementations.
	OrientationProvider OrientationProvider
	FlightProvider      FlightProvider
	KegProvider         KegDiscoveryProvider
	ExploreProvider     ExploreProvider
	IdentityProvider    IdentityProvider
	AgentProvider       AgentProvider
	NamespaceProvider   NamespaceProvider
	// NodeSearchProvider runs ranked node search. The local default asks the
	// selected Hub over REST; a Hub serving its own MCP endpoint injects one
	// backed by its search service.
	NodeSearchProvider NodeSearchProvider
	// SharedFilesystem reports that this server and the agent host driving it
	// see the same filesystem. That holds for stdio (`tap mcp`), where a path in
	// a tool argument names the same file on both sides, and never for a hosted
	// endpoint, where it would name the server's own disk. It selects the
	// attachment transfer tools: see registerFileTools. The zero value is the
	// safe one, so a caller that forgets it gets the hosted surface.
	SharedFilesystem bool
	// OrientationCacheTTL, when positive, lets a session reuse its resolved
	// orientation for that long instead of resolving it on every tool call.
	// It suits a client of a remote Hub, where each resolution costs several
	// requests and the Hub rechecks authority on every KEG request anyway.
	// orient, session_refresh, flight mutations, and any failed call always
	// discard the cached view.
	OrientationCacheTTL time.Duration
	// DiscoveryCache, when set, persists each session's Hub API discovery
	// successes (see apicontract.Session.Cache). `tap mcp` keeps them on
	// disk; hosted servers leave it nil.
	DiscoveryCache apicontract.DiscoveryCache
}

ServerOptions holds configuration for creating an MCP server.

type ToolAllowlist added in v0.44.0

type ToolAllowlist struct {
	// Resolve reloads the live policy for each tool request. Errors fail closed.
	Resolve func(context.Context) (*ToolAllowlist, error)
	// Names are the admitted tools; empty admits every tool unless Refused
	// is set.
	Names []string
	// Refused, when set, admits no tools beyond AlwaysAvailableTools and is
	// the reason a refused call reports.
	Refused string
	// Agent names whose tools these are, for refusal messages.
	Agent string
}

ToolAllowlist limits a server to an agent's tools. The zero value (and a nil *ToolAllowlist) admits every tool.

func (*ToolAllowlist) Allows added in v0.44.0

func (a *ToolAllowlist) Allows(name string) bool

Allows reports whether the allowlist admits the tool name.

func (*ToolAllowlist) Middleware added in v0.44.0

Middleware filters tools/list to the admitted tools and answers a tools/call outside them with a tool error, so the model sees why.

Directories

Path Synopsis
Package mcptest holds test helpers for MCP servers built on package mcp.
Package mcptest holds test helpers for MCP servers built on package mcp.

Jump to

Keyboard shortcuts

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