Documentation
¶
Overview ¶
Package agentcat is the shared integration surface of the AgentCat Go SDK.
Which package do I import? ¶
If you are instrumenting an MCP server, you want an ADAPTER, not this package:
go.agentcat.com/sdk/mcpgo/v2 // github.com/mark3labs/mcp-go servers go.agentcat.com/sdk/officialsdk/v2 // github.com/modelcontextprotocol/go-sdk servers
Each adapter exposes a single Track entry point plus its own Options, and re-exports every type an end user needs (UserIdentity, Event, ExporterConfig, CustomEventData), so a customer's server never imports this package directly.
What is in here ¶
This package holds everything the two adapters share and neither may duplicate: the pure schema-injection engine, the stateless session/agent handle primitives, the agent-facing copy (byte-identical across every AgentCat SDK), event construction, the server registry, and the publisher. The adapters live in their own Go modules, so they cannot reach this module's internal/ packages — everything they need is re-exported here, and nothing else is exported.
The API here is stable for the adapters that ship with this SDK. It is not a general-purpose API: it may change in a minor release if both adapters change with it.
How the pieces fit together ¶
On tools/list an adapter normalises its library's tools into []NormalizedTool, calls BuildInjectedTools, writes the mutated schemas back onto its own copies, and folds the returned Registries into the server's AgentCatInstance. On tools/call it resolves handles with ResolveSessionHandle, removes what the registries say it injected with StripToolArguments, dispatches, decorates a COPY of the response with BuildMintBackText and BuildHandleMirror (the wire only — the published event always carries the customer's raw request and undecorated response), and publishes one event built by NewToolCallEvent.
Index ¶
- Constants
- Variables
- func ApplySDKTags(evt *Event, ec *EventContext)
- func AttachEventMetadata(evt *Event, tags func() map[string]string, properties func() map[string]any)
- func BuildHandleMirror(in MirrorInput) map[string]any
- func BuildInjectedTools(cfg InjectConfig, tools []NormalizedTool) ([]NormalizedTool, *Registries)
- func BuildMintBackText(res SessionResolution) string
- func ClampAgentID(v string) string
- func ConvertToMap(v any) any
- func DeriveSessionID(customerID, projectID string) string
- func ExtractHandle(args map[string]any, name string) (string, bool)
- func GetDependencyVersion(modulePath string) string
- func InitDiagnostics(projectID string, disabled bool, integration, mcpSDKPath string)
- func InitPublisher(redactFn RedactFunc, redactEventFn RedactEventFunc, apiBaseURL string, ...) func(evt *Event)
- func IsValidSessionID(value string) bool
- func LogRecoveredPanic(where string, recovered any)
- func LogSetupComplete(projectID string, opts *Options)
- func LogSetupFailed(reason string)
- func LogWarn(format string, args ...any)
- func MintSessionID() string
- func NewEventID() string
- func Ptr[T any](v T) *T
- func PublishCustomEvent(serverOrSessionID any, projectID string, data *CustomEventData) error
- func RedactEvent(evt *Event, redactFn RedactFunc) error
- func RegisterServer[T any](server *T, instance *AgentCatInstance)
- func ReportSessionParamCollisions(instance *AgentCatInstance, reg *Registries)
- func ResetDiagnosticsForTest()
- func ResolveAPIBaseURL(optionURL string) string
- func ResolveContextDescription(custom string) string
- func SessionParamIsOurs(toolName string, reg *Registries) bool
- func SetDebug(debug bool)
- func ShouldMirror(toolName string, reg *Registries) bool
- func Shutdown(ctx context.Context) error
- func StripToolArguments(toolName string, args map[string]any, reg *Registries) map[string]any
- func UnregisterServer(server any)
- func ValidateTags(tags map[string]string) map[string]string
- type AgentCatInstance
- type CustomEventData
- type Event
- type EventContext
- type Exporter
- type ExporterConfig
- type IDPrefix
- type InjectConfig
- type MCPcatInstancedeprecated
- type MirrorInput
- type NormalizedTool
- type Options
- type RedactEventFunc
- type RedactFunc
- type Registries
- type SchemaObject
- type SessionResolution
- type SessionSource
- type UserIdentity
Constants ¶
const ( // SessionSourceSupplied: the agent echoed a session_id argument. SessionSourceSupplied = handles.SessionSourceSupplied // SessionSourceMinted: this SDK issued a fresh session for this call. SessionSourceMinted = handles.SessionSourceMinted // SessionSourceHook: derived from the customer's ResolveSessionID callback. SessionSourceHook = handles.SessionSourceHook // SessionSourceInvalid: the agent sent a session_id this server never // issued. The call publishes sessionless and the agent is told to re-send // the real one. SessionSourceInvalid = handles.SessionSourceInvalid // SessionSourceForeign: the customer's own tool declares session_id, so // AgentCat never injected one there. The call publishes sessionless and // nothing is said to the agent about a parameter that is not ours. SessionSourceForeign = handles.SessionSourceForeign )
const ( // ParamSessionID, ParamAgentID and ParamContext are the three parameter // names this SDK may inject into a tool's input schema. ParamSessionID = constants.ParamSessionID ParamAgentID = constants.ParamAgentID ParamContext = constants.ParamContext // MCPInstructionsKey is the structuredContent member carrying the handle // mirror, and the property declared on extended output schemas. MCPInstructionsKey = constants.MCPInstructionsKey // MetaClientInfoKey and MetaProtocolVersionKey are the reserved _meta keys // a 2026-07-28 client stamps on every request. MetaClientInfoKey = constants.MetaClientInfoKey MetaProtocolVersionKey = constants.MetaProtocolVersionKey // The SDK-owned event tags. These are set on every published event and // are exempt from the customer tag cap. TagSessionSource = constants.TagSessionSource TagAgentID = constants.TagAgentID TagAgentSource = constants.TagAgentSource TagProtocolVersion = constants.TagProtocolVersion TagMRTR = constants.TagMRTR // MRTR tag values: an intermediate round that asked the client for input, // and the continuation round that answered one. MRTRInputRequired = constants.MRTRInputRequired MRTRContinuation = constants.MRTRContinuation // The optional get_more_tools tool's name and agent-facing copy. GetMoreToolsName = constants.GetMoreToolsName GetMoreToolsDescription = constants.GetMoreToolsDescription GetMoreToolsContextDescription = constants.GetMoreToolsContextDescription GetMoreToolsResponseText = constants.GetMoreToolsResponseText )
Wire keys, injected parameter names, tags, and agent-facing copy shared with the adapters (which cannot import internal/ across module boundaries).
Every agent-facing string here is byte-identical to the TypeScript SDK and is defined exactly once, in internal/constants. Never retype one of these values as a literal — not in an adapter, not in a test.
const CustomEventType = "agentcat:custom"
CustomEventType is the wire event type for customer-published custom events.
const DefaultContextDescription = `` /* 532-byte string literal not displayed */
DefaultContextDescription is the default description for the "context" parameter that both adapters inject into tool input schemas, used when no CustomContextDescription is configured.
const SDKModulePath = core.SDKModulePath
SDKModulePath is this SDK's root module path, used to resolve its own version.
Variables ¶
var ( ErrServerNotTracked = errors.New("agentcat: server is not tracked; call Track first or provide a session ID string") ErrInvalidTarget = errors.New("agentcat: first parameter must be either an MCP server or a session ID string") )
Sentinel errors for PublishCustomEvent validation.
var ( ErrNilServer = errors.New("agentcat: server must not be nil") ErrEmptyProjectID = errors.New("agentcat: projectID must not be empty") )
Sentinel errors for Track validation.
Functions ¶
func ApplySDKTags ¶
func ApplySDKTags(evt *Event, ec *EventContext)
ApplySDKTags stamps the SDK-owned tags (session source, agent ID and its source, protocol version, MRTR) onto an event. Call it AFTER the customer's own tags: the SDK's win, and they are exempt from the customer tag cap.
func AttachEventMetadata ¶
func AttachEventMetadata(evt *Event, tags func() map[string]string, properties func() map[string]any)
AttachEventMetadata resolves customer-defined tags and properties via the given callbacks and attaches them to the event's wire fields. Integration API for adapter modules: each adapter constructs the closures from its typed Options callbacks. Either callback may be nil (skipped). A panic in a callback is swallowed so the event is still published without that metadata; tags are validated via ValidateTags and empty property maps are dropped.
func BuildHandleMirror ¶
func BuildHandleMirror(in MirrorInput) map[string]any
BuildHandleMirror assembles the _mcp_instructions value mirrored into a response's structuredContent. Returns nil when there is nothing the agent could echo back.
func BuildInjectedTools ¶
func BuildInjectedTools(cfg InjectConfig, tools []NormalizedTool) ([]NormalizedTool, *Registries)
BuildInjectedTools runs the pure injection pipeline: it returns the advertised tools and the registries describing exactly what it injected. Pure, deterministic, and idempotent — it never mutates its inputs and never fails a tool list; a tool it cannot safely touch passes through with an empty registry entry.
func BuildMintBackText ¶
func BuildMintBackText(res SessionResolution) string
BuildMintBackText renders the trailing [MCP INSTRUCTIONS] content block for one call, or "" when there is nothing to say. It is the single decision point for whether a call announces anything: minted announces the new handle, invalid corrects the agent without issuing a replacement, and hook, foreign and supplied say nothing. Adapters must not re-derive it.
func ClampAgentID ¶
ClampAgentID prepares a supplied agent_id for the SDK tag channel, which bypasses customer tag validation: newlines become spaces and the value is truncated to 200 bytes on a rune boundary.
func ConvertToMap ¶
ConvertToMap converts any value to map[string]any or []any via JSON round-trip.
func DeriveSessionID ¶
DeriveSessionID maps a customer correlation ID (plus the project ID) onto a stable ses_ session ID. Deterministic across processes, restarts, and every AgentCat SDK: the same input always yields the same session.
func ExtractHandle ¶
ExtractHandle returns args[name] when it is a string with non-blank content, VERBATIM (never trimmed or reformatted). It is shape-agnostic because it is shared with agent_id, which this SDK never validates; ResolveSessionHandle applies IsValidSessionID to the session handle.
func GetDependencyVersion ¶
GetDependencyVersion returns the version of the given module from build info, or "dev" if the module is not found.
func InitDiagnostics ¶
InitDiagnostics initializes internal SDK diagnostics and emits the setup-start beacon. Call it early in Track — before validation — so setup failures are captured. Idempotent across the process.
func InitPublisher ¶
func InitPublisher(redactFn RedactFunc, redactEventFn RedactEventFunc, apiBaseURL string, exporterConfigs map[string]ExporterConfig) func(evt *Event)
InitPublisher initializes the global event publisher and returns a publish function. The returned function can be called to publish events asynchronously. If apiBaseURL is empty, the default AgentCat API URL is used. When exporter configs are provided, every published event is also fanned out to the configured telemetry exporters, independently of the AgentCat API send.
func IsValidSessionID ¶
IsValidSessionID reports whether value is a session ID this SDK issued — the ses_ prefix plus a 27-character base62 KSUID. Anything else was invented by the agent or belongs to someone else, and is never adopted into Event.SessionId, which both redaction hooks are exempt from.
func LogRecoveredPanic ¶
LogRecoveredPanic logs a panic recovered inside SDK capture code (hooks, middleware, capture goroutines). Integration API for adapter modules: analytics failures must never crash the customer's server, so capture code recovers, calls this, and drops the event.
func LogSetupComplete ¶
LogSetupComplete emits the setup-complete beacon (metadata only).
func LogSetupFailed ¶
func LogSetupFailed(reason string)
LogSetupFailed logs a setup failure as ERROR so it surfaces in diagnostics.
func LogWarn ¶
LogWarn writes a warning to ~/agentcat.log. Integration API for the adapter modules, which cannot reach internal/logging across the module boundary. Use it for degraded-but-safe outcomes the customer may want to know about (a schema AgentCat could not read, a dropped event); anything that breaks capture outright belongs in LogRecoveredPanic or LogSetupFailed.
func MintSessionID ¶
func MintSessionID() string
MintSessionID returns a fresh random ses_-prefixed session ID.
func NewEventID ¶
func NewEventID() string
NewEventID generates a new unique event ID with the AgentCat prefix.
func Ptr ¶
func Ptr[T any](v T) *T
Ptr returns a pointer to the given value. Convenience helper for integration modules.
func PublishCustomEvent ¶
func PublishCustomEvent(serverOrSessionID any, projectID string, data *CustomEventData) error
PublishCustomEvent publishes a customer-defined event to AgentCat.
serverOrSessionID is either a tracked MCP server instance (any server previously passed to an adapter's Track function) or a session ID string. A string is used verbatim as the event's session ID — no derivation or validation is applied — so events correlate with whatever session or correlation ID the caller already holds. For a tracked server, the event publishes without a session unless one is provided via data.SessionID. A non-empty data.SessionID always takes precedence over a string target.
projectID is required. data is optional event payload.
func RedactEvent ¶
func RedactEvent(evt *Event, redactFn RedactFunc) error
RedactEvent applies the redaction function to sensitive fields in the event.
func RegisterServer ¶
func RegisterServer[T any](server *T, instance *AgentCatInstance)
RegisterServer stores the AgentCat instance for a given server in the global registry.
func ReportSessionParamCollisions ¶
func ReportSessionParamCollisions(instance *AgentCatInstance, reg *Registries)
ReportSessionParamCollisions logs, at most once per tool per tracked server, each customer-declared session_id parameter the engine refused to overwrite. Adapters call it after storing the registries a tools/list produced.
A session_id collision is an ERROR rather than a warning because it costs the customer correlation outright: every call to that tool publishes without a session and cannot be grouped with anything else. agent_id and context collisions stay warnings — they lose an attribute, not the thread.
Logging only. It reads the registries the pure engine produced and never affects them, so inject.Build stays deterministic.
func ResetDiagnosticsForTest ¶
func ResetDiagnosticsForTest()
ResetDiagnosticsForTest resets internal diagnostics + logging sink state. For tests.
func ResolveAPIBaseURL ¶
ResolveAPIBaseURL returns the API base URL to use, applying the priority: code option > AGENTCAT_API_URL env var > MCPCAT_API_URL env var (legacy fallback) > empty string (publisher uses default).
func ResolveContextDescription ¶
ResolveContextDescription returns the custom context-parameter description when non-empty, or DefaultContextDescription otherwise.
func SessionParamIsOurs ¶
func SessionParamIsOurs(toolName string, reg *Registries) bool
SessionParamIsOurs reports whether the session_id argument on a call to toolName is AgentCat's to read. A tool absent from the registries counts as ours, so a call arriving before any tools/list is still validated.
func ShouldMirror ¶
func ShouldMirror(toolName string, reg *Registries) bool
ShouldMirror reports whether this tool's declared output schema was extended to allow the mirror. Writing the mirror into a response whose schema does not declare it would fail the customer's own output validation.
func Shutdown ¶
Shutdown gracefully shuts down the global event publisher. This should be called when the application is shutting down to ensure all queued events are published before exit. The provided context controls the shutdown deadline; if no deadline is set, a default 5-second timeout is applied.
func StripToolArguments ¶
StripToolArguments returns a COPY of args with only the parameters the registries say this SDK injected for this tool removed. The customer's request object is never mutated, and the raw arguments still go on the published event. With no registries at all it falls back to removing the three injectable names heuristically.
func UnregisterServer ¶
func UnregisterServer(server any)
UnregisterServer removes a server from the global registry.
Types ¶
type AgentCatInstance ¶
type AgentCatInstance = core.AgentCatInstance
AgentCatInstance is the per-server tracked state the registry holds: project, options, injection registries, and the rebuild hook.
func GetInstance ¶
func GetInstance(server any) *AgentCatInstance
GetInstance retrieves the AgentCat instance for a given server from the global registry.
type CustomEventData ¶
type CustomEventData = core.CustomEventData
CustomEventData describes a customer-defined event.
type Event ¶
Event is a published event, as the RedactEvent hook sees it.
func NewToolCallEvent ¶
func NewToolCallEvent(ec *EventContext, duration *int32, isError bool, errorDetails error) *Event
NewToolCallEvent builds the single mcp:tools/call event for one call. duration is nil when nothing of this SDK's timed the call. Returns nil when the context is unusable.
type EventContext ¶
type EventContext = event.EventContext
EventContext is the per-request identity and handle state an adapter resolves before building an event.
type ExporterConfig ¶
type ExporterConfig = core.ExporterConfig
ExporterConfig configures one telemetry exporter.
type IDPrefix ¶
IDPrefix is the leading segment of an AgentCat-generated ID.
const ( PrefixSession IDPrefix = core.PrefixSession PrefixEvent IDPrefix = core.PrefixEvent // PrefixAgent is reserved across every AgentCat SDK. Nothing mints it — // agent IDs are self-chosen by the agent — but the prefix must never be // reused for anything else. PrefixAgent IDPrefix = core.PrefixAgent )
type InjectConfig ¶
InjectConfig selects what the engine injects. Build it with BuildInjectConfig; never assemble one by hand.
func BuildInjectConfig ¶
func BuildInjectConfig(opts *Options, hookMode bool) InjectConfig
BuildInjectConfig derives the pure pipeline config from tracked options. Deterministic: rebuild-on-demand depends on Build(cfg, tools) producing identical registries on every server instance. Adapters pass hookMode = (their Options.ResolveSessionID != nil).
type MCPcatInstance
deprecated
type MCPcatInstance = AgentCatInstance
MCPcatInstance is the former name of AgentCatInstance.
Deprecated: use AgentCatInstance.
type MirrorInput ¶
type MirrorInput = inject.MirrorInput
MirrorInput describes what the structured mirror may name for one call.
type NormalizedTool ¶
type NormalizedTool = inject.NormalizedTool
NormalizedTool is the engine's library-neutral view of one tool. An adapter builds these from its library's tools and writes the mutated schemas back onto its own copies afterwards.
type Options ¶
Options is the library-neutral tracked configuration. Each adapter maps its own public Options onto this once, at Track time.
func DefaultOptions ¶
func DefaultOptions() Options
DefaultOptions returns the library-neutral options with every feature at its default (all Disable* flags false).
type RedactEventFunc ¶
type RedactEventFunc = core.RedactEventFunc
RedactEventFunc is the event-level redaction hook; returning nil drops the event.
type RedactFunc ¶
type RedactFunc = core.RedactFunc
RedactFunc redacts sensitive text before an event is published.
type Registries ¶
type Registries = inject.Registries
Registries record exactly what the engine injected per tool. They drive argument stripping (StripToolArguments) and the mirror gate (ShouldMirror), so an adapter must keep them alive for every tool that has ever been listed — see AgentCatInstance.MergeRegistries.
type SchemaObject ¶
type SchemaObject = inject.SchemaObject
SchemaObject is a JSON object that preserves key order and the raw bytes of every value, so a customer's schema round-trips byte for byte through injection.
func NewSchemaObject ¶
func NewSchemaObject() *SchemaObject
NewSchemaObject returns an empty ordered JSON object.
func ParseSchemaObject ¶
func ParseSchemaObject(raw []byte) (*SchemaObject, error)
ParseSchemaObject parses raw as a JSON object, preserving key order. An error means the document is not a JSON object; the adapter must then treat the schema as opaque and advertise it untouched rather than replace it.
type SessionResolution ¶
type SessionResolution = handles.SessionResolution
SessionResolution is the outcome of one call's stateless session resolution.
func ResolveSessionHandle ¶
func ResolveSessionHandle(args map[string]any, hook func() (string, error), projectID string, sessionParamIsOurs bool) SessionResolution
ResolveSessionHandle resolves the session for one call, statelessly. hook is non-nil in hook mode (the adapter closes over the customer's ResolveSessionID), in which case the supplied arguments are ignored entirely. Never fails: a blank, errored, or panicking hook mints a session silently.
sessionParamIsOurs comes from SessionParamIsOurs and must be computed from registries the adapter has already loaded — resolve AFTER loading them. Passing true for a tool the customer owns would adopt their value.
type SessionSource ¶
type SessionSource = handles.SessionSource
SessionSource records how a call's session ID was obtained: echoed by the agent, minted by this SDK, or derived from the customer's hook.
type UserIdentity ¶
type UserIdentity = core.UserIdentity
UserIdentity names the actor behind a call, as an adapter's Identify callback returned it.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
constants
Package constants holds AgentCat's agent-facing copy and wire keys.
|
Package constants holds AgentCat's agent-facing copy and wire keys. |
|
diagnostics
Package diagnostics mirrors the SDK's internal operational logs to AgentCat's monitoring as OTLP/HTTP log records.
|
Package diagnostics mirrors the SDK's internal operational logs to AgentCat's monitoring as OTLP/HTTP log records. |
|
exporters
Package exporters implements telemetry exporters that forward AgentCat events to external observability systems (OTLP collectors, Datadog, Sentry, PostHog), mirroring the TypeScript SDK's exporter modules.
|
Package exporters implements telemetry exporters that forward AgentCat events to external observability systems (OTLP collectors, Datadog, Sentry, PostHog), mirroring the TypeScript SDK's exporter modules. |
|
handles
Package handles implements AgentCat's stateless session/agent handle primitives: minting, deterministic derivation, extraction, resolution, and mint-back text.
|
Package handles implements AgentCat's stateless session/agent handle primitives: minting, deterministic derivation, extraction, resolution, and mint-back text. |
|
inject
Package inject implements AgentCat's pure, deterministic schema-injection pipeline: (config, listed tools) in → (advertised tools, registries) out.
|
Package inject implements AgentCat's pure, deterministic schema-injection pipeline: (config, listed tools) in → (advertised tools, registries) out. |
|
logging
Package logging provides internal logging utilities for AgentCat.
|
Package logging provides internal logging utilities for AgentCat. |
|
registry
Package registry maps live MCP server objects to their AgentCatInstance.
|
Package registry maps live MCP server objects to their AgentCatInstance. |
|
sanitization
Package sanitization removes binary/non-text payloads from events before they are sent to the AgentCat API.
|
Package sanitization removes binary/non-text payloads from events before they are sent to the AgentCat API. |
|
truncation
Package truncation applies layered size limits to events before they are sent to the AgentCat API, mirroring the TypeScript SDK's truncation module:
|
Package truncation applies layered size limits to events before they are sent to the AgentCat API, mirroring the TypeScript SDK's truncation module: |
|
validation
Package validation validates customer-supplied event metadata (tags) against AgentCat's client-side constraints before events are published.
|
Package validation validates customer-supplied event metadata (tags) against AgentCat's client-side constraints before events are published. |
|
walk
Package walk provides a shared bounded deep-walk over JSON-shaped values (map[string]any / []any trees).
|
Package walk provides a shared bounded deep-walk over JSON-shaped values (map[string]any / []any trees). |