client

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 39 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

Overview

Code generated by ahp-codegen. DO NOT EDIT.

Package client delivers AHP boundaries and composes accepted protocol effects. It never executes an application operation or validates an application's schema.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnsolicitedFrame is reported to Options.TransportDiagnostic when a
	// persistent stdio backend writes a frame that matches no pending request.
	// The frame is discarded; it never fails or answers another request.
	ErrUnsolicitedFrame = errors.New("client: unsolicited stdio frame discarded")
	// ErrMalformedFrame is reported to Options.TransportDiagnostic when a stdio
	// backend writes a line that is not a JSON object. Repeated malformed output
	// terminates the backend process.
	ErrMalformedFrame = errors.New("client: malformed stdio frame discarded")
)
View Source
var ErrConfigurationLocalSecretReference = fmt.Errorf("%w: discovered upload names a local secret reference", ErrConfigurationSkipped)

ErrConfigurationLocalSecretReference wraps ErrConfigurationSkipped for discovered upload auth naming a local secret reference. It contains no reference name. A *ConfigurationSkipError with ConfigurationLocalSecret matches it.

View Source
var ErrConfigurationSkipped = errors.New("backend configuration unavailable or inapplicable")

ErrConfigurationSkipped reports that a backend without explicit subscriptions was skipped. It contains no endpoint, credentials, or backend response data. Every *ConfigurationSkipError matches it with errors.Is.

Functions

This section is empty.

Types

type AdmissionError

type AdmissionError struct {
	Kind string
	Err  error
}

AdmissionError describes a failure before a boundary was admitted. No backend call was made for a rejected boundary. Configuration failures use Kind config. Protocol delivery failures after admission live in Result.Diagnostics instead.

func (*AdmissionError) Error

func (e *AdmissionError) Error() string

func (*AdmissionError) Unwrap

func (e *AdmissionError) Unwrap() error

type Candidate added in v0.5.0

type Candidate struct {
	Messages    *ahp.MessagesCandidate
	Text        *ahp.TextCandidate
	Elicitation *ahp.ElicitResultCandidate
	Opaque      *ahp.InterceptRequestParamsStateCandidateValue
}

Candidate retains the complete candidate envelope. Exactly one field is populated according to the originating boundary. Opaque is caller-owned data; use a declared return codec or ToolBefore for its application contract.

type CapabilityAdmissionError

type CapabilityAdmissionError struct {
	Event  eventtype.Type
	Effect string
	Target string
	Reason string
}

CapabilityAdmissionError reports missing prepared inputs for protocol-only composition. Public boundary calls prepare verified bodies and snapshots first; invalid or missing host inputs fail admission before transport dispatch.

func (*CapabilityAdmissionError) Error

func (e *CapabilityAdmissionError) Error() string

type Codec added in v0.4.0

type Codec[T any] struct {
	Decode   func(json.RawMessage) (T, error)
	Encode   func(T) (json.RawMessage, error)
	Validate func(T) error
}

Codec declares a caller-owned value contract. Zero Encode and Decode functions use encoding/json with UseNumber. Validate is optional. Decoding rejects any round trip that drops or changes supplied data, including unknown fields. Custom types can preserve extensions in their own MarshalJSON/UnmarshalJSON. Callbacks must be deterministic and must not mutate their decoded values. Validation errors deliberately exclude payloads and caller error text.

func JSONCodec added in v0.4.0

func JSONCodec[T any](validate func(T) error) Codec[T]

func (Codec[T]) DecodeJSON added in v0.4.0

func (c Codec[T]) DecodeJSON(raw json.RawMessage) (T, error)

type ConfigurationSkipCode added in v0.13.1

type ConfigurationSkipCode string

ConfigurationSkipCode classifies why server-driven configuration skipped a backend. Its string values are the protocol's diagnostic codes.

const (
	// ConfigurationUnavailable: transport failure, timeout, non-success HTTP
	// status, a JSON-RPC error other than method-not-found, or an endpoint
	// authentication failure. It is re-attempted at a later event admission.
	ConfigurationUnavailable ConfigurationSkipCode = "configuration_unavailable"
	// ConfigurationInvalid: method-not-found, or an uncorrelated, malformed or
	// version-incompatible response (or a transport this client cannot open).
	ConfigurationInvalid ConfigurationSkipCode = "configuration_invalid"
	// ConfigurationNoApplicableSubscriptions: a valid advertisement with no
	// supported subscriptions.
	ConfigurationNoApplicableSubscriptions ConfigurationSkipCode = "no_applicable_subscriptions"
	// ConfigurationLocalSecret: a discovered subscription names a local secret
	// reference.
	ConfigurationLocalSecret ConfigurationSkipCode = "configuration_local_secret"
)

type ConfigurationSkipError added in v0.13.1

type ConfigurationSkipError struct {
	BackendID string
	Code      ConfigurationSkipCode
	AuthError auth.Code
	Recovery  auth.Recovery
}

ConfigurationSkipError is the host-visible diagnostic reported to Options.TransportDiagnostic when discovery skips a backend, at New or at a failed re-attempt. AuthError and Recovery are set only when an endpoint authentication error caused the skip; they are the safe auth code and its paired recovery. It never carries credentials, tokens, response bodies or event content. Cancellation is returned, never reported as a skip.

func (*ConfigurationSkipError) Error added in v0.13.1

func (e *ConfigurationSkipError) Error() string

func (*ConfigurationSkipError) Is added in v0.13.1

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

Is matches ErrConfigurationSkipped, and ErrConfigurationLocalSecretReference for ConfigurationLocalSecret.

func (ConfigurationSkipError) MarshalJSON added in v0.13.1

func (e ConfigurationSkipError) MarshalJSON() ([]byte, error)

MarshalJSON encodes {backendId, code, authError?, recovery?}.

func (*ConfigurationSkipError) Unwrap added in v0.13.1

func (e *ConfigurationSkipError) Unwrap() error

Unwrap returns the redacted *auth.Error that caused the skip, if any.

type ContentAuthorization

type ContentAuthorization struct {
	Operation      string // "read" for disclosure; "write" for new or changed inline text.
	BackendID      string
	SubscriptionID string
	Subscription   ahp.BackendSubscriptionsItem
	Item           ContentDescriptor
}

ContentAuthorization identifies the local receiving backend and subscription. Item is a copy of the descriptor, not an authorization claim from the payload.

type ContentDescriptor added in v0.5.0

type ContentDescriptor struct {
	ID          string
	Kind        string
	MediaType   string
	Category    ahp.Optional[string]
	Selection   string
	Size        ahp.Optional[json.Number]
	Sha256      ahp.Optional[string]
	Synthesized ahp.Optional[bool]
	// AdditionalProperties retains unknown members as opaque JSON, without
	// interpreting nested descriptors, payloads, or authorization claims.
	AdditionalProperties map[string]json.RawMessage
}

ContentDescriptor is a pre-disclosure projection, not a selected wire item. It has no text, body, or gap. Selection is a request, not permission.

func (ContentDescriptor) MarshalJSON added in v0.5.0

func (d ContentDescriptor) MarshalJSON() ([]byte, error)

MarshalJSON prevents extension members from overriding known fields or adding disclosure payloads, including when callers modify the extension bag.

type ContentOptions

type ContentOptions struct {
	Resolver         ContentResolver
	AuthorizeContent func(context.Context, ContentAuthorization) (bool, error)
	// ProjectOpaque explicitly projects duplicate bytes in native/input/output/params/extensions and
	// other host-defined opaque fields. Native is considered only when includeNative
	// is true. A nil callback withholds opaque fields. It must return a safe view;
	// the SDK cannot discover embedded secrets in arbitrary application JSON.
	ProjectOpaque func(ctx context.Context, scope ContentAuthorization, path string, value any) (any, error)
	// AllowLoopbackHTTP permits HTTP only to literal loopback IPs or localhost.
	// Production upload endpoints require HTTPS and normal certificate validation.
	AllowLoopbackHTTP bool
}

ContentOptions controls content disclosure independently from selection and event authentication. The zero value permits no body or opaque disclosure.

type ContentResolver

type ContentResolver func(context.Context, string) (io.ReadCloser, error)

ContentResolver opens host-owned content. A ref is an opaque handle, not a URL that the SDK fetches. Each call must return a fresh reader for the same bytes. The SDK owns and closes the returned reader. Opening must honor ctx; Close must unblock a pending Read, because cancellation can close it concurrently.

type DecodeError

type DecodeError struct{ Err error }

DecodeError means protocol acceptance succeeded but the effective input cannot be represented by the application's type. The returned Result retains accepted settlement for audit; Interrupted gates execution and Permission is not a grant.

func (*DecodeError) Error

func (e *DecodeError) Error() string

func (*DecodeError) Unwrap

func (e *DecodeError) Unwrap() error

type DeliveryError

type DeliveryError struct {
	BackendID    string
	Subscription int
	Stage        string
	Code         diagnostic.Code
	Err          error
	FailClosed   bool
	Auth         *auth.Error
}

DeliveryError is local audit information, not an explicit backend denial. Auth, when non-nil, is the redacted typed auth failure (code and validated required scopes), for example interaction_required: run login for BackendID.

func (DeliveryError) Error

func (e DeliveryError) Error() string

func (DeliveryError) Unwrap

func (e DeliveryError) Unwrap() error

type ElicitationRequest

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

ElicitationRequest is an immutable snapshot of the original MCP request and its AHP requester identity. Obtain it from a request result and supply it when processing the corresponding elicitation result. A zero value cannot authorize an answer. Metadata-only snapshots establish correlation, not form validity. The snapshot does not establish transport authentication or URL permission.

type FormAnswer added in v0.4.0

type FormAnswer[T any] struct {
	Result    ahp.McpElicitationElicitResult
	Answer    T
	Available bool
}

FormAnswer represents a validated generated MCP result. Answer is available only when Available is true (accept with form content). Decline and cancel have no answer. Form contracts do not accept URL-mode confirmations.

type FormContract added in v0.4.0

type FormContract[T any] struct {
	// contains filtered or unexported fields
}

FormContract derives MCP's restricted form schema from one flat struct T. Fields are required unless tagged omitempty. Pointers, interfaces, embedded fields, custom JSON codecs, nested objects and unconstrained arrays are rejected. An omitted optional field decodes to its Go zero value; null is never allowed. Contracts are immutable and safe for concurrent use.

func NewFormContract added in v0.4.0

func NewFormContract[T any](options ...FormContractOption) (*FormContract[T], error)

NewFormContract constructs a contract without creating a second wire schema. Supported Go fields are strings (including named strings), bools, integer and floating-point types, json.Number, and enum-constrained slices of strings.

func (*FormContract[T]) DecodeAnswers added in v0.4.0

func (c *FormContract[T]) DecodeAnswers(raw []byte) (T, error)

DecodeAnswers validates just the structured content against the same contract. Supplied zero-valued optional fields remain valid; the raw MCP result separately preserves their presence. Numeric values must survive decoding without rounding.

func (*FormContract[T]) DecodeResult added in v0.4.0

func (c *FormContract[T]) DecodeResult(raw []byte) (FormAnswer[T], error)

DecodeResult validates an entire MCP ElicitResult before decoding accepted content. It rejects undeclared keys (including case-insensitive Go aliases), null, missing required fields, invalid constraints and nonaccept content. json.Number values retain their exact wire spelling.

func (*FormContract[T]) Request added in v0.4.0

Request builds the generated MCP request from the same answer declaration.

func (*FormContract[T]) RequestedSchema added in v0.4.0

RequestedSchema returns an independent generated wire schema, suitable for McpElicitationElicitRequestFormParams.RequestedSchema. Mutating it does not change the contract's validation behavior.

type FormContractOption added in v0.4.0

type FormContractOption func(map[string]FormFieldOptions) error

FormContractOption configures a reflected form declaration.

func WithFormField added in v0.4.0

func WithFormField(name string, metadata FormFieldOptions) FormContractOption

WithFormField configures one JSON field. Duplicate options are rejected.

type FormFieldOptions added in v0.4.0

type FormFieldOptions struct {
	Title, Description   string
	Enum                 []string
	Format               ahp.McpElicitationStringSchemaFormat
	Minimum, Maximum     json.Number
	MinLength, MaxLength json.Number
	MinItems, MaxItems   json.Number
}

FormFieldOptions adds metadata to a field identified by its JSON name. Empty numeric bounds mean absent. Enum enables string single-select or []string multi-select; arrays without a nonempty enum are unsupported. Bounds are exact JSON numbers, not floating-point approximations.

type FormHookResult added in v0.4.0

type FormHookResult[T any] struct {
	*Result
	Candidate ahp.Optional[FormAnswer[T]]
	Answer    ahp.Optional[FormAnswer[T]]
}

FormHookResult keeps the complete protocol result (including opaque metadata) alongside a typed form answer. Candidate is present for intercepted requests; Answer is present for disclosed correlated result bodies. Decline and cancel wrappers are present but their FormAnswer.Available is false.

func ElicitForm added in v0.4.0

func ElicitForm[T any](ctx context.Context, hooks *Hooks, input event.UserElicitationRequestInput, form *FormContract[T], message string, options ...InterceptOption) (*FormHookResult[T], error)

ElicitForm derives requestedSchema and validates candidates from one T. The caller supplies requester/correlation metadata and a canonical inline body descriptor with its own identity; only that descriptor's request text is replaced. Unsupported form declarations fail at NewFormContract construction.

func ElicitFormResult added in v0.4.0

func ElicitFormResult[T any](ctx context.Context, hooks *Hooks, input event.UserElicitationResultInput, form *FormContract[T], snapshot *ElicitationRequest, options ...InterceptOption) (*FormHookResult[T], error)

ElicitFormResult validates disclosed result content and staged answer edits before publication. Snapshot binds the original request identity and schema. The supplied form must describe that original request; it cannot replace its schema. Without a disclosed result body no typed Answer is claimed.

type HeaderRequest added in v0.8.0

type HeaderRequest struct {
	BackendID   string
	Destination string
	Purpose     auth.Operation
	ValueRef    string
}

HeaderRequest scopes a harness-owned secret lookup to one backend event or upload destination. ValueRef is opaque and must not be included in diagnostics.

type HeaderResolver added in v0.8.0

type HeaderResolver func(ctx context.Context, request HeaderRequest) (string, error)

HeaderResolver resolves valueRef sources. Implementations must honor ctx and must not log returned values or references. Environment sources use os.LookupEnv.

type Hooks

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

Hooks is the registration-driven host for AHP boundary delivery. It composes protocol decisions, but never executes native operations.

Example (StdioServer)
package main

import (
	"context"
	"os"

	ahp "github.com/agenthooksprotocol/go-sdk"
	"github.com/agenthooksprotocol/go-sdk/server"
)

func main() {
	handler, err := server.NewHandler(server.Handlers{
		Intercept: server.InterceptHandlers{ToolBefore: func(context.Context, server.InterceptContext[ahp.ToolBeforeEvent, ahp.ToolBeforeCapabilities]) (server.ToolBeforeReply, error) {
			return server.ToolBeforeReply{}, nil
		}},
	}, server.Options{})
	if err != nil {
		panic(err)
	}
	// A standalone process owns these streams. ServeStdio closes them on exit;
	// use a cancellable application context for coordinated shutdown.
	if err := server.ServeStdio(context.Background(), os.Stdin, os.Stdout, handler); err != nil {
		panic(err)
	}
}

func New

func New(reg ahp.Registration, opts Options) (*Hooks, error)

New validates and snapshots configuration. Backends without explicit subscriptions are discovered within ConfigurationTimeout before New returns.

func (*Hooks) Close

func (c *Hooks) Close() error

Close cancels outstanding calls and observations and releases owned processes. Injected HTTP clients remain caller-owned. Close is safe to call repeatedly.

func (*Hooks) ConfigChangeAfter

func (c *Hooks) ConfigChangeAfter(ctx context.Context, input event.ConfigChangeAfterInput) (*Result, error)

func (*Hooks) ConfigChangeBefore

func (c *Hooks) ConfigChangeBefore(ctx context.Context, input event.ConfigChangeBeforeInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) ContextCompactAfter

func (c *Hooks) ContextCompactAfter(ctx context.Context, input event.ContextCompactAfterInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) ContextCompactBefore

func (c *Hooks) ContextCompactBefore(ctx context.Context, input event.ContextCompactBeforeInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) Dispatch

func (c *Hooks) Dispatch(ctx context.Context, name eventtype.Type, input any, options ...InterceptOption) (*Result, error)

Dispatch is the advanced canonical boundary entry point. Use generated event constants for name. Input uses canonical host fields (including nested call/tool envelopes), not flattened generated input fields. Source, type, and manifest remain SDK-owned and must be absent. An optional harness must match the configured identity. Prefer named methods and generated inputs for ordinary callers.

func (*Hooks) FileChanged

func (c *Hooks) FileChanged(ctx context.Context, input event.FileChangedInput) (*Result, error)

func (*Hooks) HookFailure

func (c *Hooks) HookFailure(ctx context.Context, input event.HookFailureInput) (*Result, error)

func (*Hooks) Intercepts added in v0.9.0

func (h *Hooks) Intercepts(eventType event.Type) bool

Intercepts reports whether any intercept subscription the host granted selects the event. Payload filters are not evaluated.

func (*Hooks) ModelError

func (c *Hooks) ModelError(ctx context.Context, input event.ModelErrorInput) (*Result, error)

func (*Hooks) ModelRequestBefore

func (c *Hooks) ModelRequestBefore(ctx context.Context, input event.ModelRequestBeforeInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) ModelResponseAfter

func (c *Hooks) ModelResponseAfter(ctx context.Context, input event.ModelResponseAfterInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) ModelSwitchAfter

func (c *Hooks) ModelSwitchAfter(ctx context.Context, input event.ModelSwitchAfterInput) (*Result, error)

func (*Hooks) ModelSwitchBefore

func (c *Hooks) ModelSwitchBefore(ctx context.Context, input event.ModelSwitchBeforeInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) SessionEnd

func (c *Hooks) SessionEnd(ctx context.Context, input event.SessionEndInput) (*Result, error)

func (*Hooks) SessionStart

func (c *Hooks) SessionStart(ctx context.Context, input event.SessionStartInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) Subscribes added in v0.5.0

func (h *Hooks) Subscribes(eventType event.Type) bool

Subscribes reports static subscription interest in a configured event. It includes intercept and observation deliveries, using the same selectors as dispatch. Payload filters are not evaluated: a matching subscription may return true even when a particular input would not pass its filters.

This synchronous lookup does not prepare input, authenticate, upload, or contact backends. It is neither permission nor a guarantee of delivery.

func (*Hooks) TaskChangeAfter

func (c *Hooks) TaskChangeAfter(ctx context.Context, input event.TaskChangeAfterInput) (*Result, error)

func (*Hooks) TaskChangeBefore

func (c *Hooks) TaskChangeBefore(ctx context.Context, input event.TaskChangeBeforeInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) ToolAfter

func (c *Hooks) ToolAfter(ctx context.Context, input event.ToolAfterInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) ToolBatchAfter

func (c *Hooks) ToolBatchAfter(ctx context.Context, input event.ToolBatchAfterInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) ToolBefore

func (c *Hooks) ToolBefore[T any](ctx context.Context, input event.ToolBeforeInput[T], opts ...InterceptOption) (*ToolBeforeResult[T], error)
Example
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http/httptest"

	ahp "github.com/agenthooksprotocol/go-sdk"
	"github.com/agenthooksprotocol/go-sdk/capability"
	"github.com/agenthooksprotocol/go-sdk/client"
	"github.com/agenthooksprotocol/go-sdk/effect"
	"github.com/agenthooksprotocol/go-sdk/event"
	"github.com/agenthooksprotocol/go-sdk/permission"
	"github.com/agenthooksprotocol/go-sdk/server"
	"github.com/agenthooksprotocol/go-sdk/state"
)

func main() {
	// The receiver is an ordinary http.Handler mounted on an owned server.
	handler, err := server.NewHandler(server.Handlers{
		Intercept: server.InterceptHandlers{ToolBefore: func(context.Context, server.InterceptContext[ahp.ToolBeforeEvent, ahp.ToolBeforeCapabilities]) (server.ToolBeforeReply, error) {
			replacement, err := effect.ModifyInputReplace(struct {
				Path string `json:"path"`
			}{Path: "safe.txt"})
			if err != nil {
				return server.ToolBeforeReply{}, err
			}
			typed, err := exampleToolBeforeEffect(replacement)
			if err != nil {
				return server.ToolBeforeReply{}, err
			}
			return server.ToolBeforeReply{Effects: []*ahp.ToolBeforeEffect{typed}}, nil
		}},
		Observe: server.ObserveHandlers{ToolBefore: func(context.Context, server.ObserveContext[ahp.ToolBeforeEvent]) error { return nil }},
	}, server.Options{})
	if err != nil {
		panic(err)
	}
	peer := httptest.NewServer(handler)
	defer peer.Close()

	// Registration is ordinary JSON, e.g. bytes from os.ReadFile. No SDK loader.
	data := []byte(fmt.Sprintf(`{"protocolVersion":"draft","hooks":[{
  "id":"com.example.guard","transport":{"type":"http","url":%q},
  "subscriptions":[
   {"events":["tool.before"],"mode":"intercept","timeoutMs":1000,"failurePolicy":"fail-closed","content":{"default":"metadata"}},
   {"events":["tool.before"],"mode":"observe","content":{"default":"metadata"}}
  ]}]}`, peer.URL))
	var registration ahp.Registration
	if err := json.Unmarshal(data, &registration); err != nil {
		panic(err)
	}

	narrowed := ahp.Capabilities{
		Effects: []ahp.CapabilitiesEffectsItem{{Known: ahp.Some(ahp.CapabilitiesEffectsItemKnown("modify"))}},
		Modify:  ahp.Some(ahp.CapabilitiesModify{Input: ahp.Some(ahp.CapabilitiesModifyInput{Replace: true, Merge: false})}),
	}
	hooks, err := client.New(registration, client.Options{
		Harness: ahp.Harness{Name: "test", Version: "1"},
		Source:  "urn:example:host",
		Events: capability.Host{
			ToolBefore: capability.ToolBefore{Deny: true, ModifyInput: capability.Replace(), Observe: true},
		},
		EventClient: peer.Client(),
		// Application input disclosure is an explicit host decision, not a grant
		// inferred from registration or the event capability map.
		Content: client.ContentOptions{ProjectOpaque: func(_ context.Context, _ client.ContentAuthorization, _ string, value any) (any, error) {
			return value, nil
		}},
	})
	if err != nil {
		panic(err)
	}
	defer hooks.Close()

	type Arguments struct {
		Path string `json:"path"`
	}
	ctx := context.Background()
	initial := state.Initial(permission.None)
	result, err := hooks.ToolBefore(ctx, event.ToolBeforeInput[Arguments]{
		CallID: "call-1", Path: "execute",
		Name: "read_file", Origin: ahp.ExecutionEventToolOriginNative,
		Input: Arguments{Path: "original.txt"},
	},
		client.WithInitialState(*initial),
		client.WithCapabilities(narrowed),
	)
	if err != nil {
		var decode *client.DecodeError
		if errors.As(err, &decode) && result != nil {
			// Protocol effects remain accepted. sdkJSON(result.Event.ToolBeforeEvent.Value.Tool.Input) is available;
			// do not execute result.Input when InputAvailable is false.
			return
		}
		panic(err)
	}
	if result.Interrupted || !result.InputAvailable || result.Permission == "deny" || len(result.Diagnostics) != 0 {
		return
	}
	// None is not approval; Ask requires host approval. Apply native permission
	// policy and application validation before actual execution. Printing is not execution.
	fmt.Println(result.Input.Path)
	// All observation delivery is already complete when ToolBefore returns.
	fmt.Println(len(result.Diagnostics))
}

// Decode the event-specific union without dropping caller-owned payloads or extras.
func exampleToolBeforeEffect(value *ahp.Effect) (*ahp.ToolBeforeEffect, error) {
	raw, err := json.Marshal(value)
	if err != nil {
		return nil, err
	}
	var typed ahp.ToolBeforeEffect
	if err := json.Unmarshal(raw, &typed); err != nil {
		return nil, err
	}
	return &typed, nil
}
Output:
safe.txt
0

func (*Hooks) ToolPermissionRequest

func (c *Hooks) ToolPermissionRequest(ctx context.Context, input event.ToolPermissionRequestInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) ToolPermissionResolved

func (c *Hooks) ToolPermissionResolved(ctx context.Context, input event.ToolPermissionResolvedInput) (*Result, error)

func (*Hooks) ToolProgress

func (c *Hooks) ToolProgress(ctx context.Context, input event.ToolProgressInput) (*Result, error)

func (*Hooks) TurnEnd

func (c *Hooks) TurnEnd(ctx context.Context, input event.TurnEndInput) (*Result, error)

func (*Hooks) TurnFinishBefore

func (c *Hooks) TurnFinishBefore(ctx context.Context, input event.TurnFinishBeforeInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) TurnProgress

func (c *Hooks) TurnProgress(ctx context.Context, input event.TurnProgressInput) (*Result, error)

func (*Hooks) TurnStart

func (c *Hooks) TurnStart(ctx context.Context, input event.TurnStartInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) UserAttention

func (c *Hooks) UserAttention(ctx context.Context, input event.UserAttentionInput) (*Result, error)

func (*Hooks) UserElicitationRequest

func (c *Hooks) UserElicitationRequest(ctx context.Context, input event.UserElicitationRequestInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) UserElicitationResult

func (c *Hooks) UserElicitationResult(ctx context.Context, input event.UserElicitationResultInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) UserMessageInbound

func (c *Hooks) UserMessageInbound(ctx context.Context, input event.UserMessageInboundInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) UserMessageOutbound

func (c *Hooks) UserMessageOutbound(ctx context.Context, input event.UserMessageOutboundInput, opts ...InterceptOption) (*Result, error)

func (*Hooks) WorkspaceChangeAfter

func (c *Hooks) WorkspaceChangeAfter(ctx context.Context, input event.WorkspaceChangeAfterInput) (*Result, error)

func (*Hooks) WorkspaceChangeBefore

func (c *Hooks) WorkspaceChangeBefore(ctx context.Context, input event.WorkspaceChangeBeforeInput, opts ...InterceptOption) (*Result, error)

type InterceptOption

type InterceptOption func(*interceptConfig)

InterceptOption configures one occurrence. Repeated setters use the last value.

func WithCapabilities

func WithCapabilities(caps ahp.Capabilities) InterceptOption

WithCapabilities narrows, but cannot expand, the configured manifest.

func WithCompactionInstructions

func WithCompactionInstructions(item ahp.ContentItem) InterceptOption

WithCompactionInstructions supplies a host-owned descriptor when optional instructions were absent. A metadata-only template starts without instructions; the first replacement creates bytes with that identity. A supplied body reference is resolved and verified. The SDK never invents content identity or metadata.

func WithContentSource

func WithContentSource(path string, source *content.Source) InterceptOption

WithContentSource binds an owned stream to an existing canonical content item. The item supplies identity and media metadata; it must not have a body reference. Prefer generated named input source fields when available. This path-based option is the advanced escape hatch, not a wire field or a content reference.

func WithElicitationRequest

func WithElicitationRequest(snapshot *ElicitationRequest) InterceptOption

WithElicitationRequest supplies an immutable original request snapshot for a correlated result occurrence. It does not create a registry or authorize UI.

func WithHostValueCodec added in v0.4.0

func WithHostValueCodec[T any](path string, codec Codec[T]) InterceptOption

WithHostValueCodec validates an explicitly selected caller-owned event value. path is a JSON Pointer, e.g. /params, /task/change, /task/prior, /native, or an opaque permission/discovery field. Missing optional values stay absent. Without this option these values are forwarded opaquely, not interpreted recursively.

func WithInitialState

func WithInitialState(state ahp.InterceptRequestParamsState) InterceptOption

WithInitialState supplies the already accepted native decision for this boundary. It neither grants authority nor asserts execution. Values are copied at dispatch.

func WithModificationTarget

func WithModificationTarget(target string, binding ModificationTarget) InterceptOption

WithModificationTarget selects the host's canonical representation of a native target. The SDK validates paths against the concrete event graph, not arbitrary application JSON. Compaction, elicitation and workspace use their fixed mapping.

func WithProvenanceCodec added in v0.4.0

func WithProvenanceCodec[T any](codec Codec[T]) InterceptOption

WithProvenanceCodec validates provenance only when a candidate supplies it. Replacement candidates do not inherit provenance from the previous candidate.

func WithReturnCodec added in v0.4.0

func WithReturnCodec[T any](codec Codec[T]) InterceptOption

WithReturnCodec declares the entire candidate/return value contract.

func WithTargetCodec added in v0.4.0

func WithTargetCodec[T any](target string, codec Codec[T]) InterceptOption

WithTargetCodec validates a whole effective target, after temporary shallow merge and before atomic publication. It never attempts to decode a patch as T. The target must match the boundary and be available in its prepared values.

type ManifestMetadata added in v0.5.0

type ManifestMetadata struct {
	Transports                ahp.Optional[[]ahp.StaticCapabilityManifestTransportsItem]
	Authentication            ahp.Optional[[]ahp.StaticCapabilityManifestAuthenticationItem]
	Gaps                      ahp.Optional[[]ahp.StaticCapabilityManifestGapsItem]
	ToolPaths                 ahp.Optional[[]string]
	ContentCategories         ahp.Optional[[]string]
	CorrelationIdentityFields ahp.Optional[[]string]
	Limits                    ahp.Optional[ahp.StaticCapabilityManifestLimits]
	ManagedPolicy             ahp.Optional[ahp.StaticCapabilityManifestManagedPolicy]
	AdditionalProperties      map[string]json.RawMessage
}

ManifestMetadata customizes non-event advertisement metadata. Events and capability grants come exclusively from Options.Events. Absent fields keep minimal defaults; explicit empty lists stay empty. Configuration is validated and detached at Hooks construction. Metadata is not execution permission.

type ModificationTarget

type ModificationTarget struct {
	Path      string
	Templates []ahp.ContentItem
}

ModificationTarget explicitly binds an ambiguous native target to a canonical event location. Path must be /items (a collection), /items/N (one body), /message/text or /message/payload (or an indexed child), or /params for a model request's opaque parameters. Collection effects carry an array of body values, even when empty or singleton; scalar effects carry one body value. Existing items retain identity. Templates supplies host-owned descriptors by output index for newly added items; no body/reference is invented for a missing template. This is an SDK mapping contract, not an extra AHP wire field.

type Options

type Options struct {
	// InitializationContext bounds configuration discovery during New. Nil uses Background.
	InitializationContext context.Context
	// ConfigurationTimeout bounds each discovery exchange; zero uses five seconds.
	ConfigurationTimeout time.Duration
	Source               string
	// Harness identifies the emitting runtime on every event.
	Harness ahp.Harness
	// Events explicitly advertises boundary modes and capabilities.
	// Metadata customizes only non-event advertisement fields.
	Events   capability.Host
	Metadata *ManifestMetadata
	// AuthProvider is harness-owned; Hooks never closes it.
	AuthProvider auth.Provider
	// HeaderResolver resolves registration valueRef sources for events and uploads.
	HeaderResolver  HeaderResolver
	EventClient     *http.Client
	UploadClient    *http.Client
	MaxContentBytes int64
	// MaxConcurrentUploads limits active transfers across invocations; zero uses 8.
	MaxConcurrentUploads   int
	MaxPendingObservations int
	ObservationTimeout     time.Duration
	Content                ContentOptions
	// InheritEnvironment starts stdio backends with the full host environment
	// instead of the minimal base (PATH, HOME, locale, temp directories and
	// similar). Registration env entries still apply on top. This SDK option is
	// not part of the protocol; it exists for hosts migrating backends that rely
	// on inherited variables. Prefer explicit registration env entries.
	InheritEnvironment bool
	// TransportDiagnostic, when non-nil, receives transport conditions that do
	// not fail a delivery, such as ErrUnsolicitedFrame for stdio output that
	// matched no pending request, and a *ConfigurationSkipError for every
	// backend that server-driven configuration skips. It may run on a
	// background goroutine, must be safe for concurrent use, and must not block.
	// Errors never carry payloads.
	TransportDiagnostic func(backendID string, err error)
	// ConfigurationRetryDelay is the first backoff before a backend skipped
	// with ConfigurationUnavailable is re-attempted at event admission; zero
	// uses 30 seconds. It doubles after each failed attempt, up to
	// ConfigurationRetryMaxDelay; zero uses one hour. A skip caused by an auth
	// error whose recovery is not retry is not re-attempted on backoff.
	ConfigurationRetryDelay    time.Duration
	ConfigurationRetryMaxDelay time.Duration
}

Options describes host-owned identity, supported protocol operations and I/O. The two HTTP clients are deliberately independent credential scopes.

type Result

type Result struct {

	// Snapshot retains the original MCP semantic contract, not body bytes.
	Snapshot *ElicitationRequest
	// Event is the authoritative SDK-owned settled event, including opaque extras.
	Event *ahp.Event

	// AcceptedResponses retains complete receiver envelopes in atomic acceptance
	// order, including envelope/result extras. The list is empty when no receiver
	// response is accepted; there is no separate aggregate/last-response snapshot.
	AcceptedResponses []ahp.ContextualResponse
	// Candidate distinguishes no candidate from an opaque candidate whose
	// value is JSON null. Schema-owned values are decoded using event context.
	Candidate ahp.Nullable[Candidate]

	// Flow is the settled canonical control flow.
	Flow ahp.Optional[ahp.InterceptRequestParamsStateFlow]
	// StateExtras preserves unknown state properties without granting authority.
	StateExtras map[string]json.RawMessage
	// Instructions and Injections retain the complete accumulated settlement,
	// including native initial state and omission versus an explicitly empty list.
	Instructions ahp.Optional[[]string]
	Injections   ahp.Optional[[]*ahp.InjectEffect]
	// Permission is the settled canonical permission, not proof of execution.
	// None and Ask are not grants; Interrupted always gates execution.
	Permission ahp.InterceptRequestParamsStatePermission
	// Diagnostics includes interception and completed observation delivery failures.
	Diagnostics []DeliveryError

	Interrupted bool
	// contains filtered or unexported fields
}

func (*Result) Close added in v0.2.0

func (r *Result) Close() error

Close releases effective owners, including unopened sources, and interrupts active reads. It is idempotent. Results must not be copied.

func (*Result) Content

func (r *Result) Content(path string) ([]byte, bool)

Content returns a defensive copy of already materialized effective content at a canonical item path. It never opens a lazy attachment. Use ReadContent to demand unread content. Successful results own their attachments until Close.

func (*Result) ReadContent added in v0.2.0

func (r *Result) ReadContent(ctx context.Context, path string) ([]byte, error)

ReadContent reads the effective attachment owner, returning a defensive copy. There is no result body store: selected upload and returned content share the same owner. The result remains usable after Hooks.Close.

type SettlementDecodeError added in v0.4.1

type SettlementDecodeError struct{ Err error }

SettlementDecodeError means canonical settlement could not be projected into schema-owned consumer models. Accepted responses remain available for audit, but the result is interrupted and cannot authorize execution.

func (*SettlementDecodeError) Error added in v0.4.1

func (e *SettlementDecodeError) Error() string

func (*SettlementDecodeError) Unwrap added in v0.4.1

func (e *SettlementDecodeError) Unwrap() error

type ToolBeforeResult

type ToolBeforeResult[T any] struct {
	*Result
	Input          T
	InputAvailable bool
}

type ToolContract added in v0.4.0

type ToolContract[A, R any] struct {
	Arguments Codec[A]
	Result    Codec[R]
}

ToolContract keeps the result contract independent of argument type A.

type ToolDecision added in v0.4.0

type ToolDecision[A, R, P any] struct {
	*Result
	Input          A
	InputAvailable bool
	// Absent is no candidate. Present with a nil Value is a candidate whose value
	// is literal JSON null, permitted only when the declared R codec accepts it.
	Candidate ahp.Optional[ahp.Candidate[R, P]]
}

func ToolBefore added in v0.4.0

func ToolBefore[A, R any](ctx context.Context, hooks *Hooks, input event.ToolBeforeInput[A], contract ToolContract[A, R], options ...InterceptOption) (*ToolDecision[A, R, json.RawMessage], error)

ToolBefore is the declared-contract companion to the Hooks convenience method. The runtime contract argument infers both A and R without generic methods.

func ToolBeforeWithProvenance added in v0.4.0

func ToolBeforeWithProvenance[A, R, P any](ctx context.Context, hooks *Hooks, input event.ToolBeforeInput[A], contract ToolContract[A, R], provenance Codec[P], options ...InterceptOption) (*ToolDecision[A, R, P], error)

Jump to

Keyboard shortcuts

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