Documentation
¶
Overview ¶
Package middleware provides various interceptors for the MCP server.
Package middleware provides HTTP middleware for the application.
Package middleware provides various interceptors for the MCP server.
Index ¶
- Constants
- func AuthMiddleware(authManager *auth.Manager) mcp.Middleware
- func CORSMiddleware() mcp.Middleware
- func CalculateToolResultTokens(t tokenizer.Tokenizer, result any) int
- func DLPMiddleware(config *configv1.DLPConfig, log *slog.Logger) mcp.Middleware
- func DebugMiddleware() mcp.Middleware
- func GetHTTPMiddlewares(configs []*configv1.Middleware) []func(http.Handler) http.Handler
- func GetMCPMiddlewares(configs []*configv1.Middleware) []func(mcp.MethodHandler) mcp.MethodHandler
- func GetParentID(ctx context.Context) string
- func GetSpanID(ctx context.Context) string
- func GetTraceID(ctx context.Context) string
- func GzipCompressionMiddleware(next http.Handler) http.Handler
- func HTTPSecurityHeadersMiddleware(next http.Handler) http.Handler
- func JSONRPCComplianceMiddleware(next http.Handler) http.Handler
- func LoggingMiddleware(log *slog.Logger) mcp.Middleware
- func NewGuardrailsMiddleware(config GuardrailsConfig) gin.HandlerFunc
- func PrometheusMetricsMiddleware(t tokenizer.Tokenizer) mcp.Middleware
- func RecoveryMiddleware(next http.Handler) http.Handler
- func Register(name string, factory Factory)
- func RegisterMCP(name string, factory MCPFactory)
- func SSOMiddleware(config *configv1.SSOConfig) func(http.Handler) http.Handler
- func SetRedisClientCreatorForTests(creator func(opts *redis.Options) *redis.Client)
- func WithTraceContext(ctx context.Context, traceID, spanID, parentID string) context.Context
- type A2ABridgeMiddleware
- type AIABroker
- type AIABrokerConfig
- type AuditMiddleware
- func (m *AuditMiddleware) Broadcast(entry audit.Entry)
- func (m *AuditMiddleware) ClearHistory()
- func (m *AuditMiddleware) Close() error
- func (m *AuditMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
- func (m *AuditMiddleware) GetHistory() []any
- func (m *AuditMiddleware) Read(ctx context.Context, filter audit.Filter) ([]audit.Entry, error)
- func (m *AuditMiddleware) SetStore(store audit.Store)
- func (m *AuditMiddleware) SubscribeWithHistory() (chan any, []any)
- func (m *AuditMiddleware) Unsubscribe(ch chan any)
- func (m *AuditMiddleware) UpdateConfig(auditConfig *configv1.AuditConfig) error
- func (m *AuditMiddleware) Write(ctx context.Context, entry audit.Entry) error
- type BlackboardStore
- type CFIAConfig
- type CFIAMiddleware
- type CSRFMiddleware
- type CachingMiddleware
- type CallPolicyMiddleware
- type ContextOptimizer
- type DMRHub
- type DMRHubConfig
- type DebugEntry
- type Debugger
- type DiscoverySandboxConfig
- type DiscoverySandboxMiddleware
- type ESBMiddleware
- type EmbeddingProvider
- type ErrorMappingMiddleware
- type Factory
- type GlobalRateLimitMiddleware
- type GuardrailsConfig
- type HITLApprovalRequest
- type HITLApprovalResponse
- type HITLConfig
- type HITLMiddleware
- type HTTPCORSMiddleware
- type HTTPEmbeddingProvider
- type HTTPRateLimitMiddleware
- type HTTPRateLimitOption
- type IPAllowlistMiddleware
- type JSONRPCError
- type JSONRPCResponse
- type LazyMCPConfig
- type LazyMCPMiddleware
- type Limiter
- type LocalLimiter
- type LocalStrategy
- type MCPFactory
- type MetadataSanitizationGateway
- type OllamaEmbeddingProvider
- type OpenAIEmbeddingProvider
- type Option
- type PostgresVectorStore
- func (s *PostgresVectorStore) Add(ctx context.Context, key string, vector []float32, result any, ...) error
- func (s *PostgresVectorStore) Close() error
- func (s *PostgresVectorStore) Prune(ctx context.Context, key string)
- func (s *PostgresVectorStore) Search(ctx context.Context, key string, query []float32) (any, float32, bool)
- type ProjectConfigGuardConfig
- type ProjectConfigGuardMiddleware
- type ProviderFactory
- type RBACMiddleware
- type RateLimitMiddleware
- type RateLimitStrategy
- type RecursiveContextKeyType
- type RecursiveContextManager
- func (m *RecursiveContextManager) APIHandler() http.HandlerFunc
- func (m *RecursiveContextManager) CreateSession(data map[string]interface{}, ttl time.Duration) *SessionState
- func (m *RecursiveContextManager) GetSession(id string) (*SessionState, bool)
- func (m *RecursiveContextManager) HandleContext(next http.Handler) http.Handler
- type Redactor
- type RedisLimiter
- func NewRedisLimiter(serviceID string, config *configv1.RateLimitConfig) (*RedisLimiter, error)
- func NewRedisLimiterWithClient(client *redis.Client, serviceID, limitScopeKey, partitionKey string, ...) *RedisLimiter
- func NewRedisLimiterWithPartition(serviceID, limitScopeKey, partitionKey string, ...) (*RedisLimiter, error)
- type RedisStrategy
- type Registry
- type ResilienceMiddleware
- type SQLiteVectorStore
- func (s *SQLiteVectorStore) Add(ctx context.Context, key string, vector []float32, result any, ...) error
- func (s *SQLiteVectorStore) Close() error
- func (s *SQLiteVectorStore) Prune(ctx context.Context, key string)
- func (s *SQLiteVectorStore) Search(ctx context.Context, key string, query []float32) (any, float32, bool)
- type ScopesConfig
- type ScopesMiddleware
- type SemanticCache
- type SessionState
- type SimpleVectorStore
- type SmartRecoveryMiddleware
- type StandardMiddlewares
- type ToolMetricsMiddleware
- type VectorEntry
- type VectorStore
Constants ¶
const HTTPRequestContextKey contextKey = "http.request"
HTTPRequestContextKey is the context key for the HTTP request.
Summary: Context key used to store the original HTTP request.
const RedisRateLimitScript = `` /* 1550-byte string literal not displayed */
RedisRateLimitScript is the Lua script executed atomically in Redis to perform token bucket updates. It handles token refill based on time elapsed, checks against burst capacity, and manages the expiration of unused keys to prevent memory leaks in Redis.
Summary: Represents a RedisRateLimitScript.
Variables ¶
This section is empty.
Functions ¶
func AuthMiddleware ¶
func AuthMiddleware(authManager *auth.Manager) mcp.Middleware
AuthMiddleware creates an MCP middleware for handling authentication.
It is intended to inspect incoming requests and use the provided `AuthManager` to verify credentials before passing the request to the next handler.
Parameters:
- authManager (*auth.Manager): The authentication manager.
Returns:
- mcp.Middleware: The authentication middleware function.
Side Effects:
- Modifies the context to include authenticated user info.
Summary: Executes AuthMiddleware operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func CORSMiddleware ¶
func CORSMiddleware() mcp.Middleware
CORSMiddleware creates an MCP middleware for handling Cross-Origin Resource Sharing (CORS). It is intended to add the necessary CORS headers to outgoing responses, allowing web browsers to securely make cross-origin requests to the MCP server.
NOTE: This middleware is currently a placeholder for MCP-level (JSON-RPC) interception and does not handle HTTP CORS headers. HTTP CORS is handled by the dedicated HTTP middleware in cors_http.go.
Summary: Creates a placeholder MCP CORS middleware.
Returns:
- (mcp.Middleware): The middleware function.
func CalculateToolResultTokens ¶
CalculateToolResultTokens calculates the number of tokens in a tool result.
Parameters:
- t: tokenizer.Tokenizer. The tokenizer to use for counting.
- result: any. The result object to analyze (can be *mcp.CallToolResult, string, []byte, or others).
Returns:
- int: The estimated token count.
Summary: Executes CalculateToolResultTokens operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func DLPMiddleware ¶
DLPMiddleware creates a middleware that redacts PII from request arguments and result content.
Summary: Middleware for Data Loss Prevention (PII redaction).
Parameters:
- config (*configv1.DLPConfig): The DLP configuration settings.
- log (*slog.Logger): The logger for reporting errors.
Returns:
- mcp.Middleware: The configured middleware function.
func DebugMiddleware ¶
func DebugMiddleware() mcp.Middleware
DebugMiddleware returns a middleware function that logs the full request and response of each MCP method call. This is useful for debugging and understanding the flow of data through the server.
Parameters:
- None
Returns:
- mcp.Middleware: The resulting mcp.Middleware.
Errors:
- None
Side Effects:
- None
Summary: Executes DebugMiddleware operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func GetHTTPMiddlewares ¶
GetHTTPMiddlewares returns a sorted list of HTTP middlewares based on configuration.
Parameters:
- configs ([]*configv1.Middleware): The configs.
Returns:
- ([]func(http.Handler) http.Handler): The result.
Summary: Retrieves GetHTTPMiddlewares operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func GetMCPMiddlewares ¶
func GetMCPMiddlewares(configs []*configv1.Middleware) []func(mcp.MethodHandler) mcp.MethodHandler
GetMCPMiddlewares returns a sorted list of MCP middlewares based on configuration.
Parameters:
- configs ([]*configv1.Middleware): The configs.
Returns:
- ([]func(mcp.MethodHandler) mcp.MethodHandler): The result.
Summary: Retrieves GetMCPMiddlewares operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func GetParentID ¶
GetParentID returns the parent span ID from the context.
Summary: Retrieves the parent span ID from the context.
Parameters:
- ctx: context.Context. The context to check.
Returns:
- string: The parent ID if present, otherwise an empty string.
func GetSpanID ¶
GetSpanID returns the span ID from the context.
Summary: Retrieves the span ID from the context.
Parameters:
- ctx: context.Context. The context to check.
Returns:
- string: The span ID if present, otherwise an empty string.
func GetTraceID ¶
GetTraceID returns the trace ID from the context.
Summary: Retrieves the trace ID from the context.
Parameters:
- ctx: context.Context. The context to check.
Returns:
- string: The trace ID if present, otherwise an empty string.
func GzipCompressionMiddleware ¶
GzipCompressionMiddleware returns a middleware that compresses HTTP responses using Gzip.
Summary: Middleware that compresses HTTP responses using Gzip if supported by the client.
Parameters:
- next: http.Handler. The next handler in the chain.
Returns:
- http.Handler: The wrapped handler that performs compression.
Side Effects:
- Intercepts the response writer to buffer and compress content.
- Modifies the Content-Encoding header.
func HTTPSecurityHeadersMiddleware ¶
HTTPSecurityHeadersMiddleware adds security headers to HTTP responses.
Summary: Middleware that adds standard security headers to all HTTP responses.
Parameters:
- next: http.Handler. The next handler in the chain.
Returns:
- http.Handler: The wrapped handler that sets security headers.
func JSONRPCComplianceMiddleware ¶
JSONRPCComplianceMiddleware ensures that errors are returned as valid JSON-RPC responses.
Summary: Wraps non-JSON error responses in a JSON-RPC error format.
Parameters:
- next: http.Handler. The next handler in the chain.
Returns:
- http.Handler: The wrapped handler that enforces JSON-RPC compliance for errors.
Side Effects:
- Intercepts and rewrites HTTP response bodies for error status codes.
func LoggingMiddleware ¶
func LoggingMiddleware(log *slog.Logger) mcp.Middleware
LoggingMiddleware creates an MCP middleware that logs information about each incoming request. It records the start and completion of each request, including the duration of the handling.
This is useful for debugging and monitoring the flow of requests through the server.
Parameters:
- log (*slog.Logger): The logger to be used. If `nil`, the default global logger will be used.
Returns:
- mcp.Middleware: The logging middleware function.
Side Effects:
- Logs request start and end.
- Updates metrics.
Summary: Executes LoggingMiddleware operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func NewGuardrailsMiddleware ¶
func NewGuardrailsMiddleware(config GuardrailsConfig) gin.HandlerFunc
NewGuardrailsMiddleware creates a new Guardrails middleware.
Summary: Initializes the guardrails middleware for blocking malicious prompts.
Parameters:
- config: GuardrailsConfig. The configuration for blocking patterns.
Returns:
- gin.HandlerFunc: The Gin middleware handler.
func PrometheusMetricsMiddleware ¶
func PrometheusMetricsMiddleware(t tokenizer.Tokenizer) mcp.Middleware
PrometheusMetricsMiddleware provides protocol-level metrics for all MCP requests. It intercepts requests to track duration, success/failure counts, payload sizes, and token counts.
Parameters:
- t (tokenizer.Tokenizer): The t parameter.
Returns:
- mcp.Middleware: The resulting mcp.Middleware.
Errors:
- None
Side Effects:
- None
Summary: Executes PrometheusMetricsMiddleware operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func RecoveryMiddleware ¶
RecoveryMiddleware recovers from panics in the handler chain, logs the panic, and returns a generic 500 Internal Server Error response.
Summary: Middleware to recover from panics.
Parameters:
- next (http.Handler): The next handler in the chain.
Returns:
- http.Handler: A handler that wraps the next handler with recovery logic.
Side Effects:
- Logs panic details if a panic occurs.
- Writes a 500 Internal Server Error response to the client on panic.
func Register ¶
Register registers a HTTP middleware factory.
Parameters:
- name (string): The name of the resource.
- factory (Factory): The factory.
Summary: Executes Register operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func RegisterMCP ¶
func RegisterMCP(name string, factory MCPFactory)
RegisterMCP registers an MCP middleware factory.
Parameters:
- name (string): The name of the resource.
- factory (MCPFactory): The factory.
Summary: Executes RegisterMCP operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func SSOMiddleware ¶
SSOMiddleware creates a new SSO middleware.
Summary: Middleware that enforces SSO authentication via trusted proxy headers or IDP bearer tokens.
Parameters:
- config: *configv1.SSOConfig. The configuration settings for SSO.
Returns:
- func(http.Handler) http.Handler: The HTTP middleware handler.
Side Effects:
- Inspects headers for authentication information.
- Calls IDP /userinfo endpoint to validate bearer tokens.
- Aborts the request with 401 Unauthorized if authentication is missing or invalid.
- Sets "X-User-ID" header on the request on successful authentication for downstream handlers.
func SetRedisClientCreatorForTests ¶
SetRedisClientCreatorForTests allows injecting a mock Redis client creator for testing purposes.
Summary: Replaces the default Redis client creator with a mock for unit testing.
Parameters:
- creator: func(*redis.Options) *redis.Client. The factory function to create Redis clients.
Side Effects:
- Modifies the global redisClientCreator variable.
func WithTraceContext ¶
WithTraceContext returns a new context with trace information.
Summary: Injects trace, span, and parent IDs into the context.
Parameters:
- ctx: context.Context. The parent context.
- traceID: string. The unique identifier for the trace.
- spanID: string. The unique identifier for the current span.
- parentID: string. The unique identifier for the parent span (optional).
Returns:
- context.Context: The new context with trace information attached.
Types ¶
type A2ABridgeMiddleware ¶
type A2ABridgeMiddleware struct {
// contains filtered or unexported fields
}
A2ABridgeMiddleware represents the Agent-to-Agent (A2A) Bridge middleware. It intercepts tool calls prefixed with "call_agent_" and bridges them to the A2A protocol.
Summary: Represents a A2ABridgeMiddleware.
func NewA2ABridgeMiddleware ¶
func NewA2ABridgeMiddleware(contextManager *RecursiveContextManager) *A2ABridgeMiddleware
NewA2ABridgeMiddleware creates a new A2ABridgeMiddleware.
Parameters:
- contextManager (*RecursiveContextManager): The manager for A2A session tokens.
Returns:
- *A2ABridgeMiddleware: The newly created middleware.
Errors:
- None.
Side Effects:
- Allocates memory for the middleware struct.
Summary: Initializes NewA2ABridgeMiddleware operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*A2ABridgeMiddleware) Execute ¶
func (m *A2ABridgeMiddleware) Execute(ctx context.Context, method string, req mcp.Request, next mcp.MethodHandler) (mcp.Result, error)
Execute processes the MCP request and intercepts A2A agent calls.
Parameters:
- ctx (context.Context): The context for the request.
- method (string): The MCP method being called.
- req (mcp.Request): The incoming MCP request.
- next (mcp.MethodHandler): The next handler in the middleware chain.
Returns:
- mcp.Result: The result of the request, either intercepted or from the next handler.
- error: Any error that occurred during processing.
Errors:
- Returns errors from the next handler if the request is not intercepted.
Side Effects:
- May create a new session in the RecursiveContextManager if intercepted.
Summary: Executes Execute operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
type AIABroker ¶
type AIABroker struct {
// contains filtered or unexported fields
}
AIABroker implements the Active Intent Alignment Broker middleware. It verifies that specialist agent reasoning traces remain semantically aligned with the mission-root intent.
Summary: Represents the AIA Broker middleware.
func NewAIABroker ¶
func NewAIABroker(config AIABrokerConfig) *AIABroker
NewAIABroker creates a new AIABroker middleware instance.
Summary: Creates a new Active Intent Alignment Broker instance.
Parameters:
- config (AIABrokerConfig): The configuration settings.
Returns:
- *AIABroker: The resulting AIA Broker instance.
Errors:
- None.
Side Effects:
- None.
func (*AIABroker) Execute ¶
func (b *AIABroker) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute enforces intent alignment before proceeding to the next handler.
Summary: Executes the intent alignment check before proceeding.
Parameters:
- ctx (context.Context): The execution context.
- req (*tool.ExecutionRequest): The tool execution request.
- next (tool.ExecutionFunc): The next handler in the chain.
Returns:
- any: The execution result if allowed.
- error: An error if the policy blocks execution or policy evaluation fails.
Errors:
- Returns error if intent drift is detected or required headers are missing.
Side Effects:
- Logs validation failures.
type AIABrokerConfig ¶
type AIABrokerConfig struct {
// Enabled determines if the AIA Broker is active.
Enabled bool `json:"enabled"`
// RequiredFor tools that mandate a mission-root intent heartbeat.
// If empty and Enabled is true, it applies to all tools.
RequiredFor []string `json:"required_for"`
}
AIABrokerConfig defines the configuration for the Active Intent Alignment Broker.
Summary: Configuration for Active Intent Alignment Broker.
type AuditMiddleware ¶
type AuditMiddleware struct {
// contains filtered or unexported fields
}
AuditMiddleware provides audit logging for tool executions.
Summary: Middleware for auditing tool execution.
func NewAuditMiddleware ¶
func NewAuditMiddleware(auditConfig *configv1.AuditConfig) (*AuditMiddleware, error)
NewAuditMiddleware creates a new AuditMiddleware.
Summary: Initializes the audit middleware with the provided configuration.
Parameters:
- auditConfig (*configv1.AuditConfig): The configuration for audit logging.
Returns:
- *AuditMiddleware: The initialized middleware instance.
- error: An error if the middleware cannot be initialized.
Errors:
- Returns error if audit store initialization fails.
Side Effects:
- Initializes internal stores and redactor.
func (*AuditMiddleware) Broadcast ¶
func (m *AuditMiddleware) Broadcast(entry audit.Entry)
Broadcast manually broadcasts an audit entry, used primarily for test seeding.
Summary: Broadcasts an audit entry.
Parameters:
- entry (audit.Entry): The audit entry to broadcast.
func (*AuditMiddleware) ClearHistory ¶
func (m *AuditMiddleware) ClearHistory()
ClearHistory clears the audit history from the broadcaster.
Summary: Clears the audit history.
Side Effects:
- Clears the history in the broadcaster.
func (*AuditMiddleware) Close ¶
func (m *AuditMiddleware) Close() error
Close closes the underlying store.
Summary: Closes the audit store.
Returns:
- error: An error if the operation fails.
Side Effects:
- Closes the audit store connection.
func (*AuditMiddleware) Execute ¶
func (m *AuditMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute intercepts tool execution to log audit events.
Summary: Intercepts and logs tool execution requests and results.
Parameters:
- ctx (context.Context): The context for the request.
- req (*tool.ExecutionRequest): The tool execution request.
- next (tool.ExecutionFunc): The next handler in the chain.
Returns:
- any: The result of the tool execution.
- error: An error if the tool execution fails.
Side Effects:
- Writes an audit log entry to the configured store.
func (*AuditMiddleware) GetHistory ¶
func (m *AuditMiddleware) GetHistory() []any
GetHistory returns the current broadcast history.
Summary: Retrieves the audit history from the broadcaster.
Returns:
- []any: A slice of audit entries.
Side Effects:
- None.
func (*AuditMiddleware) Read ¶
Read reads audit entries from the underlying store.
Summary: Reads historical audit logs from storage.
Parameters:
- ctx (context.Context): The context for the request.
- filter (audit.Filter): The filter criteria for querying logs.
Returns:
- []audit.Entry: A slice of audit entries matching the filter.
- error: An error if reading fails.
Errors:
- Returns error if store is not initialized.
Side Effects:
- Reads from the audit store.
func (*AuditMiddleware) SetStore ¶
func (m *AuditMiddleware) SetStore(store audit.Store)
SetStore sets the audit store. This is primarily used for testing.
Summary: Sets the audit store implementation.
Parameters:
- store (audit.Store): The audit store to use.
Side Effects:
- Replaces the current audit store.
func (*AuditMiddleware) SubscribeWithHistory ¶
func (m *AuditMiddleware) SubscribeWithHistory() (chan any, []any)
SubscribeWithHistory returns a channel that will receive broadcast messages, and the current history of messages.
Summary: Subscribes to audit events with history.
Parameters:
- None.
Returns:
- chan any: A channel receiving new audit entries.
- []any: A slice of historical audit entries.
Side Effects:
- Adds a new subscriber to the broadcaster.
func (*AuditMiddleware) Unsubscribe ¶
func (m *AuditMiddleware) Unsubscribe(ch chan any)
Unsubscribe removes a subscriber channel.
Summary: Unsubscribes from audit events.
Parameters:
- ch (chan any): The channel to unsubscribe.
Side Effects:
- Removes the subscriber from the broadcaster.
func (*AuditMiddleware) UpdateConfig ¶
func (m *AuditMiddleware) UpdateConfig(auditConfig *configv1.AuditConfig) error
UpdateConfig updates the audit configuration safely.
Summary: Updates the middleware configuration and re-initializes the store if needed.
Parameters:
- auditConfig (*configv1.AuditConfig): The new configuration.
Returns:
- error: An error if the store re-initialization fails.
Errors:
- Returns error if store re-initialization fails.
Side Effects:
- May close existing store and open a new one.
- Updates redactor configuration.
func (*AuditMiddleware) Write ¶
Write writes an audit entry directly to the store.
Parameters:
- ctx: context.Context for the operation.
- entry: The audit.Entry to write.
Returns:
- error: An error if the write fails, or nil on success.
Errors:
- Returns an error if the audit store is not initialized.
Summary: Updates Write operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
type BlackboardStore ¶
type BlackboardStore struct {
// contains filtered or unexported fields
}
BlackboardStore represents a shared key-value store with agent-aware row-level security.
Summary: Represents a shared key-value store with agent-aware row-level security.
func NewBlackboardStore ¶
func NewBlackboardStore(path string) (*BlackboardStore, error)
NewBlackboardStore creates a new SQLite Blackboard store.
Summary: Creates a new SQLite-backed Blackboard store.
Parameters:
- path (string): The file path to the SQLite database.
Returns:
- *BlackboardStore: A new instance of the BlackboardStore.
- error: An error if the database connection or schema creation fails.
Errors:
- Returns an error if the path is empty.
- Returns an error if opening the sqlite database fails.
- Returns an error if creating the blackboard table fails.
Side Effects:
- Connects to the specified SQLite database.
- Executes schema creation queries (CREATE TABLE, CREATE INDEX).
func (*BlackboardStore) Close ¶
func (s *BlackboardStore) Close() error
Close closes the database connection.
Summary: Closes the underlying database connection.
Parameters:
- None.
Returns:
- error: An error if closing the connection fails.
Errors:
- Returns an error if the database connection cannot be closed properly.
Side Effects:
- Closes the active database connection, preventing further queries.
func (*BlackboardStore) Get ¶
Get retrieves a value from the blackboard for a specific agent.
Summary: Retrieves a value from the blackboard for a specific agent.
Parameters:
- ctx (context.Context): The context for the request.
- agentID (string): The identifier of the agent.
- key (string): The key to lookup.
Returns:
- string: The retrieved value.
- error: An error if the value cannot be retrieved.
Errors:
- Returns "key not found" if the key does not exist for the specified agent.
- Returns an error if the database query fails.
Side Effects:
- Executes a SELECT query on the database.
func (*BlackboardStore) Set ¶
func (s *BlackboardStore) Set(ctx context.Context, agentID, key, value string) error
Set stores a value in the blackboard for a specific agent.
Summary: Stores a value in the blackboard for a specific agent.
Parameters:
- ctx (context.Context): The context for the request.
- agentID (string): The identifier of the agent.
- key (string): The key to store the value under.
- value (string): The value to store.
Returns:
- error: An error if the storage operation fails.
Errors:
- Returns an error if the database execution fails.
Side Effects:
- Executes an INSERT OR REPLACE (UPSERT) query on the database.
type CFIAConfig ¶
type CFIAConfig struct {
// Enabled determines if the CFIA middleware is active.
Enabled bool `json:"enabled"`
// TargetTools lists the tools that should be inspected for file reads (e.g., fs:read, read_file).
TargetTools []string `json:"target_tools"`
// AttestedHashes maps file paths to their expected, hardware-attested SHA-256 hashes.
AttestedHashes map[string]string `json:"attested_hashes"`
// ArgumentName specifies the argument name that contains the file path in the tool request.
ArgumentName string `json:"argument_name"`
}
CFIAConfig defines the configuration for Context-File Integrity Attestation.
Summary: Configuration for Context-File Integrity Attestation (CFIA) Middleware.
type CFIAMiddleware ¶
type CFIAMiddleware struct {
// contains filtered or unexported fields
}
CFIAMiddleware implements Context-File Integrity Attestation. It intercepts requests to read local files, calculates their hashes, and ensures they match known-good, hardware-attested manifests to prevent Deceptive Context Injection.
Summary: Represents the CFIA Middleware.
func NewCFIAMiddleware ¶
func NewCFIAMiddleware(config CFIAConfig) *CFIAMiddleware
NewCFIAMiddleware creates a new CFIAMiddleware instance.
Summary: Creates a new Context-File Integrity Attestation middleware instance.
Parameters:
- config (CFIAConfig): The configuration settings.
Returns:
- *CFIAMiddleware: The resulting CFIA middleware instance.
Errors:
- None.
Side Effects:
- None.
func (*CFIAMiddleware) Execute ¶
func (m *CFIAMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute enforces context-file integrity before proceeding to the next handler.
Summary: Executes the Context-File Integrity Attestation check on the request.
Parameters:
- ctx (context.Context): The execution context.
- req (*tool.ExecutionRequest): The tool execution request.
- next (tool.ExecutionFunc): The next handler in the chain.
Returns:
- any: The execution result if the file hash matches or isn't required.
- error: An error if integrity verification fails (hash mismatch or missing).
Errors:
- Returns an error if the requested file's hash does not match the attested hash.
- Returns an error if the file cannot be read for hashing.
Side Effects:
- Reads the target file from the filesystem.
- Logs validation outcomes (success or failure).
type CSRFMiddleware ¶
type CSRFMiddleware struct {
// contains filtered or unexported fields
}
CSRFMiddleware protects against Cross-Site Request Forgery attacks.
Summary: Middleware that blocks unauthorized cross-origin requests.
func NewCSRFMiddleware ¶
func NewCSRFMiddleware(allowedOrigins []string) *CSRFMiddleware
NewCSRFMiddleware creates a new CSRFMiddleware.
Summary: Initializes a new CSRFMiddleware with a list of allowed origins.
Parameters:
- allowedOrigins: []string. A list of origin strings (e.g., "https://example.com") allowed to make requests.
Returns:
- *CSRFMiddleware: The initialized middleware.
Side Effects:
- Populates the internal allowed origins map.
func (*CSRFMiddleware) Handler ¶
func (m *CSRFMiddleware) Handler(next http.Handler) http.Handler
Handler returns the HTTP handler.
Summary: Returns an HTTP handler that enforces CSRF protection checks.
Parameters:
- next: http.Handler. The next handler in the chain.
Returns:
- http.Handler: The wrapped handler.
Side Effects:
- Inspects Method, Headers, Origin, and Referer of incoming requests.
- Blocks requests with 403 Forbidden if validation fails.
- Logs warnings for blocked requests.
func (*CSRFMiddleware) Update ¶
func (m *CSRFMiddleware) Update(origins []string)
Update updates the allowed origins.
Summary: Updates the list of allowed origins at runtime.
Parameters:
- origins: []string. The new list of allowed origins.
Side Effects:
- Replaces the existing allowed origins map in a thread-safe manner.
type CachingMiddleware ¶
type CachingMiddleware struct {
// contains filtered or unexported fields
}
CachingMiddleware handles caching of tool execution results.
Summary: Represents a CachingMiddleware.
func NewCachingMiddleware ¶
func NewCachingMiddleware(toolManager tool.ManagerInterface) *CachingMiddleware
NewCachingMiddleware creates a new CachingMiddleware. toolManager is the toolManager. Returns the result.
Parameters:
- toolManager (tool.ManagerInterface): The toolManager parameter.
Returns:
- *CachingMiddleware: The resulting *CachingMiddleware.
Errors:
- None
Side Effects:
- None
Summary: Initializes NewCachingMiddleware operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*CachingMiddleware) Clear ¶
func (m *CachingMiddleware) Clear(ctx context.Context) error
Clear clears the cache. ctx is the context for the request. Returns an error if the operation fails.
Parameters:
- ctx (context.Context): The context for the request.
Returns:
- error: An error if the operation fails.
Errors:
- Returns an error if the operation fails or is invalid.
Side Effects:
- None
Summary: Executes Clear operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*CachingMiddleware) Execute ¶
func (m *CachingMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute executes the caching middleware. ctx is the context for the request. req is the request object. next is the next. Returns the result. Returns an error if the operation fails.
Parameters:
- ctx (context.Context): The context for the request.
- req (*tool.ExecutionRequest): The request object.
- next (tool.ExecutionFunc): The next parameter.
Returns:
- any: The resulting any.
- error: An error if the operation fails.
Errors:
- Returns an error if the operation fails or is invalid.
Side Effects:
- None
Summary: Executes Execute operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*CachingMiddleware) SetProviderFactory ¶
func (m *CachingMiddleware) SetProviderFactory(factory ProviderFactory)
SetProviderFactory allows overriding the default provider factory for testing. factory is the factory.
Parameters:
- factory (ProviderFactory): The factory parameter.
Returns:
- None
Errors:
- None
Side Effects:
- None
Summary: Updates SetProviderFactory operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
type CallPolicyMiddleware ¶
type CallPolicyMiddleware struct {
// contains filtered or unexported fields
}
CallPolicyMiddleware is a middleware that enforces call policies (allow/deny) based on tool name and arguments.
Summary: Middleware that evaluates and enforces security policies for tool executions.
func NewCallPolicyMiddleware ¶
func NewCallPolicyMiddleware(toolManager tool.ManagerInterface) *CallPolicyMiddleware
NewCallPolicyMiddleware creates a new CallPolicyMiddleware.
Summary: Initializes a new CallPolicyMiddleware.
Parameters:
- toolManager: tool.ManagerInterface. The tool manager to access tool and service information.
Returns:
- *CallPolicyMiddleware: The initialized middleware.
func (*CallPolicyMiddleware) Execute ¶
func (m *CallPolicyMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute enforces call policies before proceeding to the next handler.
Summary: Checks if the tool execution is allowed by the service's policies.
Parameters:
- ctx: context.Context. The execution context.
- req: *tool.ExecutionRequest. The tool execution request.
- next: tool.ExecutionFunc. The next handler in the chain.
Returns:
- any: The execution result if allowed.
- error: An error if the policy blocks execution or policy evaluation fails.
Errors:
- Returns error if service info is not found (fail closed).
- Returns error if policy evaluation fails.
- Returns "execution denied by policy" if the policy denies the request.
Side Effects:
- Logs errors if service info is missing or policy evaluation fails.
- Increments a metric counter when a call is blocked.
type ContextOptimizer ¶
type ContextOptimizer struct {
MaxChars int
}
ContextOptimizer optimises the context size of responses.
Summary: Middleware that truncates excessively long string values in JSON responses to fit within a context window.
func NewContextOptimizer ¶
func NewContextOptimizer(maxChars int) *ContextOptimizer
NewContextOptimizer creates a new ContextOptimizer.
Summary: Initializes a new ContextOptimizer with a maximum character limit.
Parameters:
- maxChars: int. The maximum allowed number of characters for string values in the JSON response.
Returns:
- *ContextOptimizer: The initialized optimizer.
func (*ContextOptimizer) Handler ¶
func (co *ContextOptimizer) Handler(next http.Handler) http.Handler
Handler returns the middleware handler.
Summary: Returns an HTTP handler that intercepts and potentially truncates response bodies.
Parameters:
- next: http.Handler. The next handler in the chain.
Returns:
- http.Handler: The wrapped handler.
Side Effects:
- Buffers the entire response body.
- Modifies the response body if it contains JSON strings exceeding MaxChars.
- Updates the Content-Length header.
type DMRHub ¶
type DMRHub struct {
// contains filtered or unexported fields
}
DMRHub implements the Dynamic Mesh Resilience Hub middleware. It verifies Zero-Knowledge State Attestation (ZKSA) migrations between physical nodes upon subagent failure.
Summary: Represents the DMR Hub middleware.
func NewDMRHub ¶
func NewDMRHub(config DMRHubConfig) *DMRHub
NewDMRHub creates a new DMRHub middleware instance.
Summary: Creates a new Dynamic Mesh Resilience Hub instance.
Parameters:
- config (DMRHubConfig): The configuration settings.
Returns:
- *DMRHub: The resulting DMR Hub instance.
func (*DMRHub) Execute ¶
func (h *DMRHub) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute enforces state migration proofs before proceeding to the next handler.
Summary: Executes the node status and ZKSA proof checks.
Parameters:
- ctx (context.Context): The execution context.
- req (*tool.ExecutionRequest): The tool execution request.
- next (tool.ExecutionFunc): The next handler in the chain.
Returns:
- any: The execution result if allowed.
- error: An error if the migration proof is invalid or missing during failure.
type DMRHubConfig ¶
type DMRHubConfig struct {
// Enabled determines if the DMR Hub is active.
Enabled bool `json:"enabled"`
// StatefulTools is a list of tools that require state migration verification.
// If empty and Enabled is true, it applies to all tools.
StatefulTools []string `json:"stateful_tools"`
}
DMRHubConfig defines the configuration for the Dynamic Mesh Resilience Hub.
Summary: Configuration for Dynamic Mesh Resilience Hub.
type DebugEntry ¶
type DebugEntry struct {
ID string `json:"id"`
TraceID string `json:"trace_id"`
SpanID string `json:"span_id"`
ParentID string `json:"parent_id,omitempty"`
Timestamp time.Time `json:"timestamp"`
Method string `json:"method"`
Path string `json:"path"`
Status int `json:"status"`
Duration time.Duration `json:"duration"`
RequestHeaders http.Header `json:"request_headers"`
ResponseHeaders http.Header `json:"response_headers"`
RequestBody string `json:"request_body,omitempty"`
ResponseBody string `json:"response_body,omitempty"`
}
DebugEntry represents a captured HTTP request/response.
Summary: Data structure holding details of a captured HTTP transaction.
type Debugger ¶
type Debugger struct {
// contains filtered or unexported fields
}
Debugger monitors and records traffic for inspection.
Summary: Middleware that captures recent HTTP traffic for debugging purposes.
func NewDebugger ¶
NewDebugger creates a new Debugger middleware.
Summary: Initializes the debugger with a fixed-size ring buffer.
Parameters:
- size: int. The number of recent requests to keep in memory.
Returns:
- *Debugger: The initialized debugger.
Side Effects:
- Starts a background goroutine to process debug entries.
func (*Debugger) APIHandler ¶
func (d *Debugger) APIHandler() http.HandlerFunc
APIHandler returns a http.HandlerFunc to view entries.
Summary: Returns an HTTP handler that exposes the debug entries as JSON.
Returns:
- http.HandlerFunc: The API handler function.
Side Effects:
- Encodes the entries to JSON and writes to the response.
func (*Debugger) Close ¶
func (d *Debugger) Close()
Close stops the background processor. Summary: Shuts down the debugger and releases resources. Side Effects: - Closes the ingress channel. - Waits for the background processor to finish.
Parameters:
- None
Returns:
- None
Errors:
- None
Side Effects:
- None
Summary: Executes Close operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*Debugger) Entries ¶
func (d *Debugger) Entries() []DebugEntry
Entries returns the last captured entries.
Summary: Retrieves the list of captured debug entries from the ring buffer.
Returns:
- []DebugEntry: A slice of the most recent captured requests and responses.
Side Effects:
- Acquires a read lock on the ring buffer.
func (*Debugger) Handler ¶
Handler returns the http handler.
Summary: Returns an HTTP handler that captures traffic.
Parameters:
- next: http.Handler. The next handler in the chain.
Returns:
- http.Handler: The wrapped handler.
Side Effects:
- Intercepts HTTP requests and responses.
- Generates trace and span IDs if missing.
- Captures request and response bodies (truncated).
- Sends debug entries to the ingress channel.
type DiscoverySandboxConfig ¶
type DiscoverySandboxConfig struct {
// Enabled determines if the DiscoverySandbox middleware is active.
Enabled bool `json:"enabled"`
// IsolatedEnvironment specifies the type of sandbox (e.g., "gVisor", "ephemeral-container", "strict-seccomp").
IsolatedEnvironment string `json:"isolated_environment"`
// MaxExecutionTimeMs specifies the maximum allowed time in milliseconds for discovery.
MaxExecutionTimeMs int `json:"max_execution_time_ms"`
// AllowedPaths lists the file paths the discovery process is allowed to read.
AllowedPaths []string `json:"allowed_paths"`
}
DiscoverySandboxConfig defines the configuration for Discovery-Phase Sandbox Isolation.
Summary: Represents the configuration for the Discovery-Phase Sandbox middleware.
type DiscoverySandboxMiddleware ¶
type DiscoverySandboxMiddleware struct {
// contains filtered or unexported fields
}
DiscoverySandboxMiddleware wraps discovery commands in a secure, ephemeral execution environment to prevent startup-time RCE and Ghost-Execution exploits during capability discovery.
Summary: Represents the middleware for Discovery-Phase Sandbox Isolation.
func NewDiscoverySandboxMiddleware ¶
func NewDiscoverySandboxMiddleware(config DiscoverySandboxConfig) *DiscoverySandboxMiddleware
NewDiscoverySandboxMiddleware creates a new DiscoverySandboxMiddleware instance.
Summary: Creates a new Discovery-Phase Sandbox Isolation middleware instance.
Parameters:
- config (DiscoverySandboxConfig): The configuration settings.
Returns:
- *DiscoverySandboxMiddleware: The resulting middleware instance.
Errors:
- None.
Side Effects:
- None.
func (*DiscoverySandboxMiddleware) PostExecute ¶
func (m *DiscoverySandboxMiddleware) PostExecute(ctx context.Context, req *mcp.CallToolRequest, result *mcp.CallToolResult, err error) (*mcp.CallToolResult, error)
PostExecute is called after the tool completes, successfully or not.
Summary: PostExecute performs cleanup of the ephemeral sandbox environment.
Parameters:
- ctx (context.Context): The execution context.
- req (*mcp.CallToolRequest): The tool execution request.
- result (*mcp.CallToolResult): The result of the tool execution.
- err (error): The error returned by the tool, if any.
Returns:
- *mcp.CallToolResult: The original result.
- error: The original error.
Errors:
- None.
Side Effects:
- Logs the teardown of the ephemeral sandbox.
func (*DiscoverySandboxMiddleware) PreExecute ¶
func (m *DiscoverySandboxMiddleware) PreExecute(ctx context.Context, req *mcp.CallToolRequest, t *tool.Tool) error
PreExecute is called before a tool is executed. For discovery commands, it validates constraints and simulates launching an isolated sandbox environment.
Summary: Intercepts tool execution to enforce discovery-phase sandbox constraints.
Parameters:
- ctx (context.Context): The execution context.
- req (*mcp.CallToolRequest): The tool execution request.
- t (*tool.Tool): The tool being executed.
Returns:
- error: An error if sandbox constraints are violated.
Errors:
- Returns an error if the tool name indicates a discovery command and sandbox simulation fails.
Side Effects:
- Logs a security audit event upon sandbox constraint enforcement.
type ESBMiddleware ¶
type ESBMiddleware struct {
// contains filtered or unexported fields
}
ESBMiddleware (Entangled State Broker) provides side-channel-immune speculative guarding and enforces that requests are cryptographically bound to a mission-root intent.
Summary: Implements the Entangled State Broker.
func NewESBMiddleware ¶
func NewESBMiddleware(config *configv1.Middleware) *ESBMiddleware
NewESBMiddleware creates a new instance of the ESBMiddleware.
Parameters:
- config (*configv1.Middleware): The configuration for the middleware.
Returns:
- (*ESBMiddleware): The newly created middleware.
Summary: Creates a new ESBMiddleware.
func (*ESBMiddleware) Execute ¶
func (m *ESBMiddleware) Execute(ctx context.Context, method string, req mcp.Request, next mcp.MethodHandler) (mcp.Result, error)
Execute applies the ESB logic to the incoming MCP request. It verifies the presence of required headers and injects Temporal Shard Jitter (TSJ).
Parameters:
- ctx (context.Context): The context of the request.
- method (string): The MCP method being called.
- req (mcp.Request): The incoming request.
- next (mcp.MethodHandler): The next handler in the chain.
Returns:
- (mcp.Result): The result of the request execution.
- (error): An error if the request fails validation or execution.
Summary: Executes the ESB middleware logic.
type EmbeddingProvider ¶
type EmbeddingProvider interface {
// Embed generates an embedding vector for the given text.
//
// Parameters:
// - ctx: context.Context. The request context.
// - text: string. The text to embed.
//
// Returns:
// - []float32: The resulting embedding vector.
// - error: An error if generation fails.
Embed(ctx context.Context, text string) ([]float32, error)
}
EmbeddingProvider defines the interface for fetching text embeddings.
Summary: Interface for services that can generate vector embeddings from text.
type ErrorMappingMiddleware ¶
type ErrorMappingMiddleware struct{}
ErrorMappingMiddleware normalizes diverse upstream errors into standard MCP errors.
Summary: Normalizes arbitrary tool execution errors.
func NewErrorMappingMiddleware ¶
func NewErrorMappingMiddleware() *ErrorMappingMiddleware
NewErrorMappingMiddleware creates a new error mapping middleware.
Summary: Initializes the middleware responsible for translating internal errors into safe external responses.
Parameters:
- None.
Returns:
- mcp.Middleware: The initialized error mapping middleware.
Throws/Errors:
- None.
func (*ErrorMappingMiddleware) Execute ¶
func (m *ErrorMappingMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute performs the middleware logic, wrapping the next handler.
Summary: Executes middleware logic.
Parameters:
- ctx (context.Context): The context for the execution.
- req (*tool.ExecutionRequest): The execution request.
- next (tool.ExecutionFunc): The next handler in the chain.
Returns:
- any: The result of the execution.
- error: An error if execution fails.
type Factory ¶
Factory is a function that creates a HTTP middleware from configuration.
Summary: Represents a Factory.
type GlobalRateLimitMiddleware ¶
type GlobalRateLimitMiddleware struct {
// contains filtered or unexported fields
}
GlobalRateLimitMiddleware provides rate limiting functionality for all MCP requests.
Summary: Middleware that enforces global rate limits on MCP requests across the entire server.
func NewGlobalRateLimitMiddleware ¶
func NewGlobalRateLimitMiddleware(config *configv1.RateLimitConfig) *GlobalRateLimitMiddleware
NewGlobalRateLimitMiddleware creates a new GlobalRateLimitMiddleware.
Summary: Initializes the global rate limit middleware with the provided configuration.
Parameters:
- config: *configv1.RateLimitConfig. The rate limit configuration settings.
Returns:
- *GlobalRateLimitMiddleware: The initialized middleware instance.
Side Effects:
- Initializes internal caches for limiters.
func (*GlobalRateLimitMiddleware) Execute ¶
func (m *GlobalRateLimitMiddleware) Execute(ctx context.Context, method string, req mcp.Request, next mcp.MethodHandler) (mcp.Result, error)
Execute executes the rate limiting middleware.
Summary: Intercepts requests and enforces the configured rate limits.
Parameters:
- ctx: context.Context. The request context.
- method: string. The MCP method being called.
- req: mcp.Request. The request payload.
- next: mcp.MethodHandler. The next handler in the chain.
Returns:
- mcp.Result: The result of the next handler if allowed.
- error: An error if the rate limit is exceeded or the next handler fails.
Errors:
- Returns "global rate limit exceeded" if the request is blocked.
Side Effects:
- Records metrics for allowed and blocked requests.
- May update the state of the rate limiter (e.g., consume tokens).
func (*GlobalRateLimitMiddleware) UpdateConfig ¶
func (m *GlobalRateLimitMiddleware) UpdateConfig(config *configv1.RateLimitConfig)
UpdateConfig updates the rate limit configuration safely.
Summary: Updates the rate limit configuration at runtime.
Parameters:
- config: *configv1.RateLimitConfig. The new configuration settings.
Side Effects:
- Acquires a lock to safely update the configuration.
- Effectively changes rate limiting behavior for subsequent requests.
type GuardrailsConfig ¶
type GuardrailsConfig struct {
BlockedPhrases []string
}
GuardrailsConfig defines patterns to block.
Summary: Configuration for the guardrails middleware.
type HITLApprovalRequest ¶
type HITLApprovalRequest struct {
ExecutionID string `json:"execution_id"`
ToolName string `json:"tool_name"`
RequireMFA bool `json:"require_mfa"`
}
HITLApprovalRequest represents a request for human approval published to the bus.
Summary: Represents a request for human approval published to the message bus.
type HITLApprovalResponse ¶
type HITLApprovalResponse struct {
ExecutionID string `json:"execution_id"`
Approved bool `json:"approved"`
}
HITLApprovalResponse represents the response from the human operator.
Summary: Represents the response from a human operator regarding a tool execution approval request.
type HITLConfig ¶
type HITLConfig struct {
Enabled bool `json:"enabled"`
SensitiveTools []string `json:"sensitive_tools"`
RequireMFA bool `json:"require_mfa"`
TimeoutSeconds int `json:"timeout_seconds"`
}
HITLConfig defines the configuration for Human-In-The-Loop approval flows.
Summary: Represents the configuration for Human-In-The-Loop (HITL) approval flows.
type HITLMiddleware ¶
type HITLMiddleware struct {
// contains filtered or unexported fields
}
HITLMiddleware enforces Human-In-The-Loop approvals for sensitive actions.
Summary: Represents middleware that enforces Human-In-The-Loop (HITL) approvals for sensitive actions.
func NewHITLMiddleware ¶
func NewHITLMiddleware(config HITLConfig, busProvider *bus.Provider) *HITLMiddleware
NewHITLMiddleware creates a new HITLMiddleware.
Summary: Creates a new instance of HITLMiddleware.
Parameters:
- config (HITLConfig): The configuration settings for HITL approvals.
- busProvider (*bus.Provider): The message bus provider used to publish and subscribe to approval events.
Returns:
- *HITLMiddleware: A new instance of the middleware.
Errors:
- None.
Side Effects:
- None.
func (*HITLMiddleware) Execute ¶
func (m *HITLMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute checks if the tool requires HITL approval before proceeding.
Summary: Validates whether a requested tool execution requires human approval and manages the approval flow.
Parameters:
- ctx (context.Context): The context for the request.
- req (*tool.ExecutionRequest): The execution request detailing the tool to be called.
- next (tool.ExecutionFunc): The next execution function in the middleware chain.
Returns:
- any: The result of the tool execution if permitted.
- error: An error if approval is denied, times out, or fails.
Errors:
- Returns an error if the request to get the hitl request bus fails.
- Returns an error if the request to get the hitl response bus fails.
- Returns an error if publishing the approval request fails.
- Returns an error if the execution times out or context is cancelled.
- Returns an error if the human operator denies the request.
Side Effects:
- Publishes approval requests to the message bus.
- Subscribes to response topics on the message bus.
- Blocks execution pending a response from the message bus or a timeout.
type HTTPCORSMiddleware ¶
type HTTPCORSMiddleware struct {
// contains filtered or unexported fields
}
HTTPCORSMiddleware handles CORS for HTTP endpoints. It is thread-safe and supports dynamic updates.
Summary: Represents a HTTPCORSMiddleware.
func NewHTTPCORSMiddleware ¶
func NewHTTPCORSMiddleware(allowedOrigins []string) *HTTPCORSMiddleware
NewHTTPCORSMiddleware creates a new HTTPCORSMiddleware.
Summary: Initializes HTTP CORS middleware.
If allowedOrigins is empty, it defaults to allowing nothing (or behaving like standard Same-Origin). To allow all, pass []string{"*"}.
Parameters:
- allowedOrigins ([]string): The allowed origins.
Returns:
- (*HTTPCORSMiddleware): The initialized middleware.
func (*HTTPCORSMiddleware) Handler ¶
func (m *HTTPCORSMiddleware) Handler(next http.Handler) http.Handler
Handler wraps an http.Handler with CORS logic.
Summary: Middleware to handle CORS headers.
Parameters:
- next (http.Handler): The next handler in the chain.
Returns:
- (http.Handler): The wrapped handler.
func (*HTTPCORSMiddleware) Update ¶
func (m *HTTPCORSMiddleware) Update(allowedOrigins []string)
Update updates the allowed origins.
Summary: Updates the allowed origins dynamically.
Parameters:
- allowedOrigins ([]string): The new list of allowed origins.
type HTTPEmbeddingProvider ¶
type HTTPEmbeddingProvider struct {
// contains filtered or unexported fields
}
HTTPEmbeddingProvider implements a generic HTTP EmbeddingProvider.
Summary: A generic provider that fetches embeddings from an arbitrary HTTP endpoint.
func NewHTTPEmbeddingProvider ¶
func NewHTTPEmbeddingProvider(url string, headers map[string]string, bodyTemplateStr, responseJSONPath string) (*HTTPEmbeddingProvider, error)
NewHTTPEmbeddingProvider creates a new HTTPEmbeddingProvider.
Summary: Initializes a new HTTPEmbeddingProvider with custom request formatting.
Parameters:
- url: string. The API endpoint URL.
- headers: map[string]string. Custom HTTP headers to include in the request.
- bodyTemplateStr: string. A Go template string for the request body (input text is available as {{.input}}).
- responseJSONPath: string. The JSONPath expression to extract the embedding from the response.
Returns:
- *HTTPEmbeddingProvider: The initialized provider.
- error: An error if the URL is empty or the body template is invalid.
Errors:
- Returns "url is required" if the URL is empty.
- Returns error if template parsing fails.
Side Effects:
- Compiles the body template.
func (*HTTPEmbeddingProvider) Embed ¶
Embed generates an embedding for the given text.
Summary: Generates an embedding by sending a templated HTTP request and extracting the result via JSONPath.
Parameters:
- ctx: context.Context. The request context.
- text: string. The input text to embed.
Returns:
- []float32: The extracted embedding vector.
- error: An error if the request fails or response parsing fails.
Errors:
- Returns error if template execution fails.
- Returns error if HTTP request creation or execution fails.
- Returns error if the API returns a non-success status code.
- Returns error if JSON unmarshaling or JSONPath extraction fails.
- Returns error if the extracted result is not a number array or is empty.
Side Effects:
- Makes an HTTP POST request to the configured URL.
type HTTPRateLimitMiddleware ¶
type HTTPRateLimitMiddleware struct {
// contains filtered or unexported fields
}
HTTPRateLimitMiddleware provides global rate limiting for HTTP endpoints.
Summary: Middleware for rate limiting HTTP requests based on IP address.
func NewHTTPRateLimitMiddleware ¶
func NewHTTPRateLimitMiddleware(rps float64, burst int, opts ...HTTPRateLimitOption) *HTTPRateLimitMiddleware
NewHTTPRateLimitMiddleware creates a new HTTPRateLimitMiddleware.
Summary: Initializes a new HTTP rate limit middleware.
Parameters:
- rps: float64. Requests per second allowed per IP.
- burst: int. Maximum burst size allowed per IP.
- opts: ...HTTPRateLimitOption. Optional configuration options.
Returns:
- *HTTPRateLimitMiddleware: The initialized middleware instance.
func (*HTTPRateLimitMiddleware) Handler ¶
func (m *HTTPRateLimitMiddleware) Handler(next http.Handler) http.Handler
Handler wraps an http.Handler with rate limiting.
Summary: Returns a handler that enforces rate limiting.
Parameters:
- next: http.Handler. The next handler in the chain.
Returns:
- http.Handler: The wrapped handler.
type HTTPRateLimitOption ¶
type HTTPRateLimitOption func(*HTTPRateLimitMiddleware)
HTTPRateLimitOption defines a functional option for HTTPRateLimitMiddleware.
Summary: Functional option type for configuring the middleware.
func WithTrustProxy ¶
func WithTrustProxy(trust bool) HTTPRateLimitOption
WithTrustProxy enables trusting the X-Forwarded-For header.
Summary: Configures the middleware to trust the X-Forwarded-For header.
Parameters:
- trust: bool. Whether to trust the proxy headers.
Returns:
- HTTPRateLimitOption: The configuration option.
type IPAllowlistMiddleware ¶
type IPAllowlistMiddleware struct {
// contains filtered or unexported fields
}
IPAllowlistMiddleware restricts access to allowed IP addresses.
Summary: Middleware that filters requests based on a list of allowed IP addresses or CIDRs.
func NewIPAllowlistMiddleware ¶
func NewIPAllowlistMiddleware(allowedCIDRs []string) (*IPAllowlistMiddleware, error)
NewIPAllowlistMiddleware creates a new IPAllowlistMiddleware.
Summary: Initializes the middleware with the initial list of allowed CIDRs.
Parameters:
- allowedCIDRs: []string. A list of IP addresses or CIDR blocks to allow.
Returns:
- *IPAllowlistMiddleware: The initialized middleware instance.
- error: An error if any of the provided CIDRs are invalid.
func (*IPAllowlistMiddleware) Allow ¶
func (m *IPAllowlistMiddleware) Allow(remoteAddr string) bool
Allow checks if the given remote address is allowed.
Summary: Checks if a remote address is in the allowed list.
Parameters:
- remoteAddr: string. The remote address (IP or IP:Port).
Returns:
- bool: True if allowed, false otherwise.
func (*IPAllowlistMiddleware) Handler ¶
func (m *IPAllowlistMiddleware) Handler(next http.Handler) http.Handler
Handler returns an HTTP handler that enforces the allowlist.
Summary: Returns an HTTP handler that blocks unauthorized IPs.
Parameters:
- next: http.Handler. The next handler in the chain.
Returns:
- http.Handler: The wrapped handler.
func (*IPAllowlistMiddleware) Update ¶
func (m *IPAllowlistMiddleware) Update(allowedCIDRs []string) error
Update updates the allowlist with new CIDRs/IPs.
Summary: Dynamically updates the list of allowed IPs.
Parameters:
- allowedCIDRs: []string. The new list of allowed IP addresses or CIDR blocks.
Returns:
- error: An error if any of the provided CIDRs are invalid.
type JSONRPCError ¶
type JSONRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
JSONRPCError represents a JSON-RPC 2.0 error object.
Summary: Represents a JSONRPCError.
type JSONRPCResponse ¶
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id"`
Error *JSONRPCError `json:"error,omitempty"`
}
JSONRPCResponse represents a JSON-RPC 2.0 response object.
Summary: Represents a JSONRPCResponse.
type LazyMCPConfig ¶
type LazyMCPConfig struct {
Enabled bool `json:"enabled"`
Threshold float64 `json:"threshold"`
CacheTTL int `json:"cache_ttl"`
}
LazyMCPConfig defines the configuration for On-Demand Discovery filtering.
Summary: Represents the configuration for the LazyMCP middleware.
type LazyMCPMiddleware ¶
type LazyMCPMiddleware struct {
// contains filtered or unexported fields
}
LazyMCPMiddleware filters tools based on a simplistic similarity logic to prevent context pollution.
Summary: Represents the middleware for filtering tools based on intent.
func NewLazyMCPMiddleware ¶
func NewLazyMCPMiddleware(config LazyMCPConfig) *LazyMCPMiddleware
NewLazyMCPMiddleware creates a new LazyMCPMiddleware.
Summary: Creates a new instance of LazyMCPMiddleware.
Parameters:
- config (LazyMCPConfig): The configuration settings for the middleware.
Returns:
- *LazyMCPMiddleware: A new instance of the middleware.
Errors:
- None.
Side Effects:
- None.
func (*LazyMCPMiddleware) FilterTools ¶
func (m *LazyMCPMiddleware) FilterTools(res *mcp.ListToolsResult, intent string) *mcp.ListToolsResult
FilterTools takes an original tool list result and an intent string (from the context or header), and returns a new list of tools that are "similar" to the intent.
Summary: Filters a list of tools based on their similarity to the provided intent.
Parameters:
- res (*mcp.ListToolsResult): The original list of tools to filter.
- intent (string): The user's intent to match against tool names and descriptions.
Returns:
- *mcp.ListToolsResult: A new list of tools that match the given intent.
Errors:
- None.
Side Effects:
- None.
type Limiter ¶
type Limiter interface {
// Allow checks if the request is allowed.
//
// ctx is the context for the request.
//
// Returns true if successful.
// Returns an error if the operation fails.
Allow(ctx context.Context) (bool, error)
// AllowN checks if the request is allowed with a specific cost.
//
// ctx is the context for the request.
// n is the n.
//
// Returns true if successful.
// Returns an error if the operation fails.
AllowN(ctx context.Context, n int) (bool, error)
// Update updates the limiter configuration.
//
// rps is the rps.
// burst is the burst.
Update(rps float64, burst int)
}
Limiter interface defines the methods required for a rate limiter.
Summary: Represents a Limiter.
type LocalLimiter ¶
LocalLimiter is an in-memory implementation of Limiter.
Summary: Rate limiter implementation using golang.org/x/time/rate.
func (*LocalLimiter) Allow ¶
func (l *LocalLimiter) Allow(_ context.Context) (bool, error)
Allow checks if the request is allowed (cost 1).
Summary: Checks if a single event is allowed by the rate limiter.
Parameters:
- _: context.Context. Unused.
Returns:
- bool: True if allowed, false otherwise.
- error: Always nil.
Side Effects:
- Consumes 1 token from the bucket if allowed.
func (*LocalLimiter) AllowN ¶
AllowN checks if the request is allowed with a specific cost.
Summary: Checks if N events are allowed by the rate limiter.
Parameters:
- _: context.Context. Unused.
- n: int. The cost of the event.
Returns:
- bool: True if allowed, false otherwise.
- error: Always nil.
Side Effects:
- Consumes n tokens from the bucket if allowed.
func (*LocalLimiter) Update ¶
func (l *LocalLimiter) Update(rps float64, burst int)
Update updates the limiter configuration.
Summary: Dynamically updates the rate limit and burst size.
Parameters:
- rps: float64. The new requests per second limit.
- burst: int. The new burst size.
Side Effects:
- Modifies the underlying rate.Limiter state.
type LocalStrategy ¶
type LocalStrategy struct{}
LocalStrategy implements RateLimitStrategy for local in-memory rate limiting.
Summary: Strategy for creating local rate limiters.
func NewLocalStrategy ¶
func NewLocalStrategy() *LocalStrategy
NewLocalStrategy creates a new LocalStrategy.
Summary: Initializes a new LocalStrategy.
Returns:
- *LocalStrategy: The initialized strategy.
func (*LocalStrategy) Create ¶
func (s *LocalStrategy) Create(_ context.Context, _, _, _ string, config *configv1.RateLimitConfig) (Limiter, error)
Create creates a new LocalLimiter.
Summary: Creates a new in-memory rate limiter based on the provided configuration.
Parameters:
- _: context.Context. Unused.
- _: string. Unused (serviceID).
- _: string. Unused (limitScopeKey).
- _: string. Unused (partitionKey).
- config: *configv1.RateLimitConfig. The rate limit configuration.
Returns:
- Limiter: The created LocalLimiter.
- error: Always nil.
Side Effects:
- Sets a minimum burst of 1 if configured lower.
type MCPFactory ¶
type MCPFactory func(config *configv1.Middleware) func(mcp.MethodHandler) mcp.MethodHandler
MCPFactory is a function that creates an MCP middleware from configuration.
Summary: Represents a MCPFactory.
type MetadataSanitizationGateway ¶
type MetadataSanitizationGateway struct {
// contains filtered or unexported fields
}
MetadataSanitizationGateway implements the MSG specification for scrubbing malicious instructions from agent-ingested external metadata. MetadataSanitizationGateway scrubs sensitive metadata from tool requests and responses.
Summary: Protects sensitive system metadata from leaking to downstream components.
Parameters:
- None.
Returns:
- None.
Throws/Errors:
- None.
func NewMetadataSanitizationGateway ¶
func NewMetadataSanitizationGateway(cfg *configv1.MetadataSanitizationConfig) *MetadataSanitizationGateway
NewMetadataSanitizationGateway initializes a new gateway instance.
Summary: Creates a new MetadataSanitizationGateway ready for use.
Parameters:
- cfg (*configv1.MetadataSanitizationConfig): The configuration.
Returns:
- *MetadataSanitizationGateway: The initialized gateway.
Throws/Errors:
- None.
func (*MetadataSanitizationGateway) Middleware ¶
func (m *MetadataSanitizationGateway) Middleware() func(mcp.MethodHandler) mcp.MethodHandler
Middleware returns an MCP handler that wraps the next handler in the chain.
Summary: Applies the sanitization rules to the incoming request and outgoing response.
Parameters:
- None.
Returns:
- mcp.Middleware: The middleware constructor.
Throws/Errors:
- None.
type OllamaEmbeddingProvider ¶
type OllamaEmbeddingProvider struct {
// contains filtered or unexported fields
}
OllamaEmbeddingProvider implements EmbeddingProvider for Ollama.
Summary: Provides an interface to generate text embeddings using the Ollama API.
func NewOllamaEmbeddingProvider ¶
func NewOllamaEmbeddingProvider(baseURL, model string) *OllamaEmbeddingProvider
NewOllamaEmbeddingProvider creates a new OllamaEmbeddingProvider.
Summary: Initializes a new provider for Ollama embeddings.
Parameters:
- baseURL: string. The base URL of the Ollama API (defaults to "http://localhost:11434" if empty).
- model: string. The name of the embedding model to use (defaults to "nomic-embed-text" if empty).
Returns:
- *OllamaEmbeddingProvider: The initialized embedding provider.
Side Effects:
- Sets default values for baseURL and model if not provided.
func (*OllamaEmbeddingProvider) Embed ¶
Embed generates an embedding for the given text using Ollama.
Summary: Calls the Ollama API to generate a vector embedding for the input text.
Parameters:
- ctx: context.Context. The context for the HTTP request.
- text: string. The input text to be embedded.
Returns:
- []float32: The generated embedding vector.
- error: An error if the API call fails or the response is invalid.
Errors:
- Returns error if request marshaling or creation fails.
- Returns error if the HTTP request fails.
- Returns error if the API returns a non-200 status code.
- Returns error if response decoding fails or no embedding data is returned.
Side Effects:
- Makes an HTTP POST request to the configured Ollama API endpoint.
type OpenAIEmbeddingProvider ¶
type OpenAIEmbeddingProvider struct {
// contains filtered or unexported fields
}
OpenAIEmbeddingProvider implements EmbeddingProvider for OpenAI.
Summary: Provides vector embeddings using the OpenAI API.
func NewOpenAIEmbeddingProvider ¶
func NewOpenAIEmbeddingProvider(apiKey, model string) *OpenAIEmbeddingProvider
NewOpenAIEmbeddingProvider creates a new OpenAIEmbeddingProvider.
Summary: Initializes a new OpenAIEmbeddingProvider with the given API key and model.
Parameters:
- apiKey: string. The OpenAI API key.
- model: string. The model ID (defaults to "text-embedding-3-small" if empty).
Returns:
- *OpenAIEmbeddingProvider: The initialized provider.
Side Effects:
- Sets a default model and base URL.
- Initializes an HTTP client with a timeout.
func (*OpenAIEmbeddingProvider) Embed ¶
Embed generates an embedding vector for the given text using the OpenAI API.
Summary: Calls the OpenAI API to generate an embedding for the input text.
Parameters:
- ctx: context.Context. The request context.
- text: string. The text to embed.
Returns:
- []float32: The generated embedding vector.
- error: An error if the API call fails.
Errors:
- Returns error if request marshaling or creation fails.
- Returns error if the HTTP request fails.
- Returns error if the API returns a non-200 status code or an error object.
- Returns error if no embedding data is found in the response.
Side Effects:
- Makes an external HTTP POST request to the OpenAI API.
type Option ¶
type Option func(*RateLimitMiddleware)
Option defines a functional option for RateLimitMiddleware.
Summary: Functional option for RateLimitMiddleware.
func WithTokenizer ¶
WithTokenizer sets a custom tokenizer for the middleware.
Summary: Configures a custom tokenizer.
Parameters:
- t (tokenizer.Tokenizer): The tokenizer to use.
Returns:
- (Option): The configured option.
type PostgresVectorStore ¶
type PostgresVectorStore struct {
// contains filtered or unexported fields
}
PostgresVectorStore implements VectorStore using PostgreSQL and pgvector.
Summary: Provides vector storage capabilities using a PostgreSQL database with the pgvector extension.
func NewPostgresVectorStore ¶
func NewPostgresVectorStore(dsn string) (*PostgresVectorStore, error)
NewPostgresVectorStore creates a new PostgresVectorStore.
Summary: Initializes a new PostgresVectorStore with a connection string.
Parameters:
- dsn: string. The Data Source Name for connecting to the PostgreSQL database.
Returns:
- *PostgresVectorStore: The initialized vector store.
- error: An error if the DSN is empty or the connection fails.
Errors:
- Returns "postgres dsn is required" if the dsn is empty.
- Returns connection errors if sql.Open or NewPostgresVectorStoreWithDB fails.
Side Effects:
- Opens a connection to the PostgreSQL database.
- May create the 'vector' extension and 'semantic_cache_entries' table if they do not exist.
func NewPostgresVectorStoreWithDB ¶
func NewPostgresVectorStoreWithDB(db *sql.DB) (*PostgresVectorStore, error)
NewPostgresVectorStoreWithDB creates a new PostgresVectorStore using an existing database connection.
Summary: Initializes a new PostgresVectorStore with an existing sql.DB connection.
Parameters:
- db: *sql.DB. The existing database connection.
Returns:
- *PostgresVectorStore: The initialized vector store.
- error: An error if the database is unreachable or schema initialization fails.
Errors:
- Returns error if pinging the database fails.
- Returns error if creating the vector extension or table fails.
Side Effects:
- Verifies the database connection.
- Creates the 'vector' extension if it doesn't exist.
- Creates the 'semantic_cache_entries' table and indexes if they don't exist.
func (*PostgresVectorStore) Add ¶
func (s *PostgresVectorStore) Add(ctx context.Context, key string, vector []float32, result any, ttl time.Duration) error
Add adds a new entry to the vector store.
Summary: Inserts a new semantic cache entry into the database.
Parameters:
- ctx: context.Context. The context for the database operation.
- key: string. The unique key for the cache entry.
- vector: []float32. The embedding vector associated with the entry.
- result: any. The result data to be cached (marshaled to JSON).
- ttl: time.Duration. The time-to-live for the cache entry.
Returns:
- error: An error if marshaling fails or the database insert fails.
Errors:
- Returns error if JSON marshaling of vector or result fails.
- Returns error if the database execution fails.
Side Effects:
- Writes a new row to the 'semantic_cache_entries' table.
func (*PostgresVectorStore) Close ¶
func (s *PostgresVectorStore) Close() error
Close closes the database connection.
Summary: Closes the underlying PostgreSQL database connection.
Returns:
- error: An error if closing the connection fails.
Side Effects:
- Closes the DB connection.
func (*PostgresVectorStore) Prune ¶
func (s *PostgresVectorStore) Prune(ctx context.Context, key string)
Prune removes expired entries.
Summary: Deletes expired cache entries from the database.
Parameters:
- ctx: context.Context. The context for the database operation.
- key: string. Optional key to restrict pruning to a specific cache key. If empty, prunes all expired entries.
Side Effects:
- Deletes rows from the 'semantic_cache_entries' table.
func (*PostgresVectorStore) Search ¶
func (s *PostgresVectorStore) Search(ctx context.Context, key string, query []float32) (any, float32, bool)
Search searches for the most similar entry in the vector store.
Summary: Finds the nearest neighbor for the given query vector.
Parameters:
- ctx: context.Context. The context for the database query.
- key: string. The key to filter results by.
- query: []float32. The query embedding vector.
Returns:
- any: The cached result (unmarshaled from JSON).
- float32: The similarity score (1.0 - cosine distance).
- bool: True if a matching entry was found, false otherwise.
Errors:
- Returns false if no matching row is found or if JSON unmarshaling fails.
Side Effects:
- Executes a SELECT query on the database.
type ProjectConfigGuardConfig ¶
type ProjectConfigGuardConfig struct {
// Enabled determines if the guard is active.
Enabled bool `json:"enabled"`
// TargetTools lists the tools that should be inspected for file reads.
TargetTools []string `json:"target_tools"`
// TargetFiles lists the project-local config filenames to intercept (e.g., ".claude/settings.json").
TargetFiles []string `json:"target_files"`
// ArgumentName specifies the argument name that contains the file path in the tool request.
ArgumentName string `json:"argument_name"`
// ApprovedHooks maps hook hashes or names to a boolean indicating MFA/HLCA approval.
ApprovedHooks map[string]bool `json:"approved_hooks"`
// ApprovedServers indicates if enableAllProjectMcpServers is attested.
ApprovedServers bool `json:"approved_servers"`
// SafeBaseURL is the proxy address to rewrite base_url to.
SafeBaseURL string `json:"safe_base_url"`
// RequireHLCA enforces Hardware-Locked Configuration Anchors validation.
RequireHLCA bool `json:"require_hlca"`
// AttestedHLCAMap maps file paths to their expected TPM-bound user session signatures.
AttestedHLCAMap map[string]string `json:"attested_hlca_map"`
}
ProjectConfigGuardConfig defines the configuration for the Project Configuration Security Guard.
Summary: Configuration for the Project Configuration Security Guard middleware.
type ProjectConfigGuardMiddleware ¶
type ProjectConfigGuardMiddleware struct {
// contains filtered or unexported fields
}
ProjectConfigGuardMiddleware implements the Project Configuration Security Guard.
Summary: Represents the Project Config Guard Middleware.
func NewProjectConfigGuardMiddleware ¶
func NewProjectConfigGuardMiddleware(config ProjectConfigGuardConfig) *ProjectConfigGuardMiddleware
NewProjectConfigGuardMiddleware creates a new ProjectConfigGuardMiddleware instance.
Summary: Creates a new Project Configuration Security Guard middleware instance.
Parameters:
- config (ProjectConfigGuardConfig): The configuration settings.
Returns:
- *ProjectConfigGuardMiddleware: The resulting middleware instance.
Errors:
- None.
Side Effects:
- None.
func (*ProjectConfigGuardMiddleware) Execute ¶
func (m *ProjectConfigGuardMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute enforces project config security before proceeding.
Summary: Executes the Project Config Guard check on the request.
Parameters:
- ctx (context.Context): The execution context.
- req (*tool.ExecutionRequest): The tool execution request.
- next (tool.ExecutionFunc): The next handler in the chain.
Returns:
- any: The execution result if validation passes.
- error: An error if validation fails.
Errors:
- Returns an error if an un-attested hook is found.
- Returns an error if enableAllProjectMcpServers is used without attestation.
- Returns an error if HLCA validation fails.
Side Effects:
- May intercept and read target files.
- Rewrites base URLs if configured.
type ProviderFactory ¶
type ProviderFactory func(config *configv1.SemanticCacheConfig, apiKey string) (EmbeddingProvider, error)
ProviderFactory is a function that creates an EmbeddingProvider.
Summary: Represents a ProviderFactory.
type RBACMiddleware ¶
type RBACMiddleware struct {
// contains filtered or unexported fields
}
RBACMiddleware provides middleware for Role-Based Access Control.
Summary: Middleware for enforcing role-based access control policies.
func NewRBACMiddleware ¶
func NewRBACMiddleware() *RBACMiddleware
NewRBACMiddleware creates a new RBACMiddleware.
Summary: Initializes the RBAC middleware.
Returns:
- *RBACMiddleware: The initialized middleware.
func (*RBACMiddleware) EnforcePolicy ¶
func (m *RBACMiddleware) EnforcePolicy(_ func(user *configv1.User) bool) func(http.Handler) http.Handler
EnforcePolicy allows passing a custom policy function.
Summary: Enforces a custom policy based on the user object.
Parameters:
- policy: func(user *configv1.User) bool. The policy function to evaluate.
Returns:
- func(http.Handler) http.Handler: The middleware function.
func (*RBACMiddleware) RequireAnyRole ¶
RequireAnyRole returns an HTTP middleware that requires the user to have at least one of the specified roles.
Summary: Enforces that the authenticated user possesses at least one of the specified roles.
Parameters:
- roles: ...string. The list of allowed roles.
Returns:
- func(http.Handler) http.Handler: The middleware function.
func (*RBACMiddleware) RequireRole ¶
RequireRole returns an HTTP middleware that requires the user to have the specified role.
Summary: Enforces that the authenticated user possesses a specific role.
Parameters:
- role: string. The required role.
Returns:
- func(http.Handler) http.Handler: The middleware function.
type RateLimitMiddleware ¶
type RateLimitMiddleware struct {
// contains filtered or unexported fields
}
RateLimitMiddleware is a tool execution middleware that provides rate limiting functionality for upstream services.
Summary: Middleware for rate limiting tool execution.
func NewRateLimitMiddleware ¶
func NewRateLimitMiddleware(toolManager tool.ManagerInterface, opts ...Option) *RateLimitMiddleware
NewRateLimitMiddleware creates a new RateLimitMiddleware.
Summary: Initializes the rate limit middleware.
Parameters:
- toolManager (tool.ManagerInterface): The tool manager.
- opts (...Option): Optional configuration settings.
Returns:
- (*RateLimitMiddleware): The initialized middleware.
func (*RateLimitMiddleware) Execute ¶
func (m *RateLimitMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute executes the rate limiting middleware.
Summary: Executes rate limiting logic before passing to the next handler.
Parameters:
- ctx (context.Context): The context for the request.
- req (*tool.ExecutionRequest): The execution request.
- next (tool.ExecutionFunc): The next handler.
Returns:
- (any): The result of the execution.
- (error): An error if the limit is exceeded or the operation fails.
Side Effects:
- Checks against rate limits in memory or Redis.
- Increments counters.
type RateLimitStrategy ¶
type RateLimitStrategy interface {
// Create creates a new Limiter instance.
//
// ctx is the context for the request.
// serviceID is the serviceID.
// limitScopeKey is the limitScopeKey.
// partitionKey is the partitionKey.
// config holds the configuration settings.
//
// Returns the result.
// Returns an error if the operation fails.
Create(ctx context.Context, serviceID, limitScopeKey, partitionKey string, config *configv1.RateLimitConfig) (Limiter, error)
}
RateLimitStrategy defines the interface for creating rate limiters.
Summary: Represents a RateLimitStrategy.
type RecursiveContextKeyType ¶
type RecursiveContextKeyType string
RecursiveContextKeyType is a custom type for context keys to avoid collisions.
Summary: Represents a RecursiveContextKeyType.
const ( // RecursiveContextDataKey is the key used to store the recursive context data in the request context. // Summary: Defines RecursiveContextDataKe. RecursiveContextDataKey RecursiveContextKeyType = "recursive_context_data" )
type RecursiveContextManager ¶
type RecursiveContextManager struct {
// contains filtered or unexported fields
}
RecursiveContextManager manages the shared context sessions (Blackboard).
Summary: Represents a RecursiveContextManager.
func NewRecursiveContextManager ¶
func NewRecursiveContextManager() *RecursiveContextManager
NewRecursiveContextManager initializes and returns a new RecursiveContextManager.
Parameters:
- None.
Returns:
- *RecursiveContextManager: A pointer to the newly created manager instance.
Errors:
- None.
Side Effects:
- Allocates memory for the manager and its internal session map.
Summary: Initializes NewRecursiveContextManager operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*RecursiveContextManager) APIHandler ¶
func (m *RecursiveContextManager) APIHandler() http.HandlerFunc
APIHandler constructs an HTTP handler function for managing Recursive Context Protocol endpoints.
Parameters:
- None.
Returns:
- http.HandlerFunc: A handler function that processes POST (create session) and GET (retrieve session) requests.
Errors:
- None.
Side Effects:
- Modifies the HTTP response writer based on the request logic, including sending JSON responses and error codes.
- When processing a POST request, creates a new session in the manager.
Summary: Executes APIHandler operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*RecursiveContextManager) CreateSession ¶
func (m *RecursiveContextManager) CreateSession(data map[string]interface{}, ttl time.Duration) *SessionState
CreateSession generates a new recursive context session with the provided data and expiration time.
Parameters:
- data (map[string]interface{}): The initial state data to be stored in the session.
- ttl (time.Duration): The time-to-live duration for the session before it expires.
Returns:
- *SessionState: A pointer to the newly created session state.
Errors:
- None.
Side Effects:
- Modifies the internal sessions map by adding a new session.
- Performs a cleanup of expired sessions during insertion, removing them from the map.
Summary: Initializes CreateSession operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*RecursiveContextManager) GetSession ¶
func (m *RecursiveContextManager) GetSession(id string) (*SessionState, bool)
GetSession retrieves an active context session by its unique identifier.
Parameters:
- id (string): The unique UUID string of the session to retrieve.
Returns:
- *SessionState: A pointer to the requested session state, or nil if not found or expired.
- bool: True if the session was successfully found and is active, false otherwise.
Errors:
- None.
Side Effects:
- None.
Summary: Retrieves GetSession operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*RecursiveContextManager) HandleContext ¶
func (m *RecursiveContextManager) HandleContext(next http.Handler) http.Handler
HandleContext intercepts HTTP requests to inject recursive context state based on the X-MCP-Parent-Context-ID header.
Parameters:
- next (http.Handler): The next HTTP handler in the middleware chain.
Returns:
- http.Handler: A new HTTP handler that wraps the provided handler with context injection logic.
Errors:
- None.
Side Effects:
- Reads from the incoming HTTP request headers.
- Modifies the request context by injecting session data if a valid context ID is found.
- Logs debug or warning messages depending on the presence and validity of the context session.
Summary: Executes HandleContext operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
type Redactor ¶
type Redactor struct {
// contains filtered or unexported fields
}
Redactor handles redaction of sensitive data based on configuration.
Summary: Component responsible for identifying and masking sensitive information (PII) in data.
func NewRedactor ¶
NewRedactor creates a new Redactor from the given DLP config.
Summary: Initializes a new Redactor based on Data Loss Prevention (DLP) configuration.
Parameters:
- config: *configv1.DLPConfig. The DLP configuration containing enabled status and custom patterns.
- log: *slog.Logger. Logger for warning about invalid patterns.
Returns:
- *Redactor: The initialized redactor, or nil if DLP is disabled or config is nil.
Side Effects:
- Compiles regular expressions for custom patterns.
- Logs warnings for invalid regex patterns.
func (*Redactor) RedactJSON ¶
RedactJSON redacts sensitive information from a JSON byte slice.
Summary: Scans and redacts PII from a JSON-encoded byte slice.
Parameters:
- data: []byte. The JSON data to redact.
Returns:
- []byte: The redacted JSON data (or original if no redaction needed).
- error: An error if JSON parsing fails (though often swallowed/ignored for safety).
Side Effects:
- Walks the JSON structure.
- Unmarshals and remarshals strings if modification is needed.
func (*Redactor) RedactString ¶
RedactString redacts sensitive information from a string.
Summary: Applies redaction rules to a plain string.
Parameters:
- s: string. The input string.
Returns:
- string: The redacted string.
Side Effects:
- Performs regex replacements for emails, credit cards, SSNs, and custom patterns.
func (*Redactor) RedactStruct ¶
RedactStruct redacts sensitive information from a map.
Summary: Recursively redacts sensitive information from a map (struct representation).
Parameters:
- v: map[string]interface{}. The map to redact.
Side Effects:
- Modifies the map in place.
func (*Redactor) RedactValue ¶
func (r *Redactor) RedactValue(val interface{}) interface{}
RedactValue redacts sensitive information from a value.
Summary: Recursively redacts sensitive information from an arbitrary value (string, map, slice).
Parameters:
- val: interface{}. The value to redact.
Returns:
- interface{}: The redacted value.
Side Effects:
- Recursively processes maps and slices.
type RedisLimiter ¶
type RedisLimiter struct {
// contains filtered or unexported fields
}
RedisLimiter implements a distributed rate limiter backed by Redis. It uses a token bucket algorithm to enforce rate limits across multiple service instances, ensuring that the configured Requests Per Second (RPS) and burst limits are respected regardless of how many server replicas are running.
Summary: Distributed token bucket rate limiter using Redis.
func NewRedisLimiter ¶
func NewRedisLimiter(serviceID string, config *configv1.RateLimitConfig) (*RedisLimiter, error)
NewRedisLimiter creates a new RedisLimiter for the specified service using the provided configuration. It initializes a connection to Redis and sets up the rate limiting parameters.
Summary: Initializes a new Redis-backed rate limiter.
Parameters:
- serviceID: string. The unique identifier of the service to be rate-limited.
- config: *configv1.RateLimitConfig. The configuration containing Redis connection details, RPS, and burst settings.
Returns:
- *RedisLimiter: The initialized RedisLimiter, or nil if an error occurs.
- error: An error if the configuration is invalid or the Redis connection fails.
Side Effects:
- Creates a new Redis connection.
func NewRedisLimiterWithClient ¶
func NewRedisLimiterWithClient(client *redis.Client, serviceID, limitScopeKey, partitionKey string, config *configv1.RateLimitConfig) *RedisLimiter
NewRedisLimiterWithClient creates a new RedisLimiter using an existing Redis client. This avoids creating a new connection pool if one is already available.
Summary: Initializes a RedisLimiter reusing an existing Redis client.
Parameters:
- client: *redis.Client. The existing Redis client instance.
- serviceID: string. The unique identifier of the service.
- limitScopeKey: string. An optional key to scope the limit.
- partitionKey: string. An optional key to further partition the limit.
- config: *configv1.RateLimitConfig. The rate limit configuration.
Returns:
- *RedisLimiter: The initialized limiter.
func NewRedisLimiterWithPartition ¶
func NewRedisLimiterWithPartition(serviceID, limitScopeKey, partitionKey string, config *configv1.RateLimitConfig) (*RedisLimiter, error)
NewRedisLimiterWithPartition creates a new RedisLimiter with support for partitioned rate limiting. This is useful for more granular control, such as per-user or per-IP limits within a service.
Summary: Initializes a Redis-backed rate limiter with partitioning support.
Parameters:
- serviceID: string. The unique identifier of the service.
- limitScopeKey: string. An optional key to scope the limit (e.g., "user_id").
- partitionKey: string. An optional key to further partition the limit (e.g., "12345").
- config: *configv1.RateLimitConfig. The rate limit configuration.
Returns:
- *RedisLimiter: The initialized limiter.
- error: An error if Redis config is missing.
Errors:
- Returns "redis config is missing" if config is incomplete.
Side Effects:
- Creates a new Redis connection.
func (*RedisLimiter) Allow ¶
func (l *RedisLimiter) Allow(ctx context.Context) (bool, error)
Allow checks if a single request is allowed under the current rate limit policy. It decrements the token bucket by 1.
Summary: Checks if a single request is allowed.
Parameters:
- ctx: context.Context. The context for the request.
Returns:
- bool: true if the request is allowed.
- error: An error if the Redis operation fails.
Side Effects:
- Executes a Lua script on Redis to atomically consume tokens.
func (*RedisLimiter) AllowN ¶
AllowN checks if a request with a specific cost is allowed. It attempts to consume 'n' tokens from the bucket.
Summary: Checks if a request with cost N is allowed.
Parameters:
- ctx: context.Context. The context for the request.
- n: int. The cost of the request.
Returns:
- bool: true if the request is allowed.
- error: An error if the Redis operation fails.
Side Effects:
- Executes a Lua script on Redis to atomically consume tokens.
func (*RedisLimiter) Close ¶
func (l *RedisLimiter) Close() error
Close terminates the Redis client connection and releases resources.
Summary: Closes the Redis client connection.
Returns:
- error: An error if closing the client fails.
Side Effects:
- Closes the TCP connection to Redis.
func (*RedisLimiter) GetConfigHash ¶
func (l *RedisLimiter) GetConfigHash() string
GetConfigHash returns a hash string representing the underlying Redis configuration. This is used to detect configuration changes that might require a client reconnection.
Summary: Retrieves the hash of the current Redis configuration.
Returns:
- string: The configuration hash string.
func (*RedisLimiter) Update ¶
func (l *RedisLimiter) Update(rps float64, burst int)
Update dynamically updates the rate limit configuration for the running limiter.
Summary: Updates the rate limit settings (RPS and burst).
Parameters:
- rps: float64. The new requests per second limit.
- burst: int. The new burst capacity.
Side Effects:
- Modifies the internal state of the limiter.
type RedisStrategy ¶
type RedisStrategy struct {
// contains filtered or unexported fields
}
RedisStrategy implements RateLimitStrategy for Redis-based rate limiting.
Summary: Strategy for creating Redis-backed distributed rate limiters.
func NewRedisStrategy ¶
func NewRedisStrategy() *RedisStrategy
NewRedisStrategy creates a new RedisStrategy.
Summary: Initializes a new RedisStrategy.
Returns:
- *RedisStrategy: The initialized strategy.
func (*RedisStrategy) Create ¶
func (s *RedisStrategy) Create(_ context.Context, serviceID, limitScopeKey, partitionKey string, config *configv1.RateLimitConfig) (Limiter, error)
Create creates a new RedisLimiter.
Summary: Creates a new Redis-backed rate limiter.
Parameters:
- _: context.Context. Unused.
- serviceID: string. The service identifier.
- limitScopeKey: string. The scope key for the limit.
- partitionKey: string. The partition key for the limit.
- config: *configv1.RateLimitConfig. The rate limit configuration.
Returns:
- Limiter: The created RedisLimiter.
- error: An error if the Redis configuration is missing.
Errors:
- Returns "redis config is missing" if the config does not contain Redis settings.
Side Effects:
- Establishes or reuses a Redis connection.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages available middlewares.
Summary: Represents a Registry.
type ResilienceMiddleware ¶
type ResilienceMiddleware struct {
// contains filtered or unexported fields
}
ResilienceMiddleware provides circuit breaker and retry functionality for tool executions.
Summary: Middleware that wraps tool executions with circuit breakers, retries, and timeouts.
func NewResilienceMiddleware ¶
func NewResilienceMiddleware(toolManager tool.ManagerInterface) *ResilienceMiddleware
NewResilienceMiddleware creates a new ResilienceMiddleware.
Summary: Initializes the ResilienceMiddleware with a tool manager.
Parameters:
- toolManager: tool.ManagerInterface. The manager for retrieving tool and service information.
Returns:
- *ResilienceMiddleware: The initialized middleware.
func (*ResilienceMiddleware) Execute ¶
func (m *ResilienceMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute executes the resilience middleware.
Summary: Executes the tool call within a resilience wrapper (circuit breaker, retry).
Parameters:
- ctx: context.Context. The execution context.
- req: *tool.ExecutionRequest. The tool execution request.
- next: tool.ExecutionFunc. The next handler in the chain.
Returns:
- any: The execution result.
- error: An error if the execution or resilience policy fails.
Side Effects:
- Checks circuit breaker state.
- May retry the execution on failure.
- Records success/failure to update circuit breaker stats.
type SQLiteVectorStore ¶
type SQLiteVectorStore struct {
// contains filtered or unexported fields
}
SQLiteVectorStore implements VectorStore using SQLite for persistence and an in-memory cache for fast search.
Summary: A hybrid vector store that uses SQLite for persistence and an in-memory structure for search.
func NewSQLiteVectorStore ¶
func NewSQLiteVectorStore(path string) (*SQLiteVectorStore, error)
NewSQLiteVectorStore creates a new SQLiteVectorStore.
Summary: Initializes a new SQLiteVectorStore from the specified file path.
Parameters:
- path: string. The file path to the SQLite database.
Returns:
- *SQLiteVectorStore: The initialized vector store.
- error: An error if the path is empty, database cannot be opened, or schema creation fails.
Errors:
- Returns "sqlite path is required" if the path is empty.
- Returns error if database connection or schema initialization fails.
Side Effects:
- Opens (and creates if missing) the SQLite database file.
- Creates the 'semantic_cache_entries' table.
- Sets SQLite PRAGMAs for performance optimization.
- Loads existing unexpired entries into memory.
func (*SQLiteVectorStore) Add ¶
func (s *SQLiteVectorStore) Add(ctx context.Context, key string, vector []float32, result any, ttl time.Duration) error
Add adds a new entry to both memory and DB.
Summary: Inserts a cache entry into the in-memory store and the persistent SQLite database.
Parameters:
- ctx: context.Context. The request context.
- key: string. The cache key.
- vector: []float32. The embedding vector.
- result: any. The result to cache.
- ttl: time.Duration. The time-to-live for the entry.
Returns:
- error: An error if writing to memory or DB fails.
Errors:
- Returns error if memory store addition fails.
- Returns error if JSON marshaling fails.
- Returns error if database insert fails.
Side Effects:
- Updates in-memory cache state.
- Writes row to SQLite database.
- May trigger async probabilistic pruning of expired DB entries.
func (*SQLiteVectorStore) Close ¶
func (s *SQLiteVectorStore) Close() error
Close closes the database connection.
Summary: Closes the SQLite database connection.
Returns:
- error: An error if closing fails.
func (*SQLiteVectorStore) Prune ¶
func (s *SQLiteVectorStore) Prune(ctx context.Context, key string)
Prune removes expired entries from both memory and DB.
Summary: Manually triggers removal of expired entries from memory and disk.
Parameters:
- ctx: context.Context. The request context.
- key: string. Optional key to restrict pruning scope.
Side Effects:
- Removes items from memory.
- Deletes rows from SQLite database.
func (*SQLiteVectorStore) Search ¶
func (s *SQLiteVectorStore) Search(ctx context.Context, key string, query []float32) (any, float32, bool)
Search searches in memory.
Summary: Searches the in-memory store for the nearest neighbor.
Parameters:
- ctx: context.Context. The request context.
- key: string. The key to filter results.
- query: []float32. The query embedding vector.
Returns:
- any: The best matching result data.
- float32: The similarity score (0-1).
- bool: True if a match was found.
type ScopesConfig ¶
type ScopesConfig struct {
// Roles maps a role name to a list of allowed capability prefixes.
Roles map[string][]string `json:"roles"`
}
ScopesConfig defines the configuration for capability-based scoping.
Summary: Represents the configuration for capability-based tool scoping.
type ScopesMiddleware ¶
type ScopesMiddleware struct {
// contains filtered or unexported fields
}
ScopesMiddleware enforces granular capability-based tokens for tool execution.
Summary: Represents middleware that enforces tool execution scopes based on agent roles.
func NewScopesMiddleware ¶
func NewScopesMiddleware(config ScopesConfig) *ScopesMiddleware
NewScopesMiddleware creates a new ScopesMiddleware.
Summary: Creates a new instance of ScopesMiddleware.
Parameters:
- config (ScopesConfig): The configuration settings specifying allowed scopes per role.
Returns:
- *ScopesMiddleware: A new instance of the middleware.
Errors:
- None.
Side Effects:
- None.
func (*ScopesMiddleware) Execute ¶
func (m *ScopesMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute checks if the tool name matches any capability token prefix granted to the agent's role.
Summary: Validates that the requested tool is allowed for the agent's role before execution.
Parameters:
- ctx (context.Context): The context for the request, optionally containing the agent's role.
- req (*tool.ExecutionRequest): The execution request detailing the tool to be called.
- next (tool.ExecutionFunc): The next execution function in the middleware chain.
Returns:
- any: The result of the tool execution if permitted.
- error: An error if access is denied or execution fails.
Errors:
- Returns an error if no scope configuration exists for the agent's role.
- Returns an error if the requested tool is outside the granted scopes.
Side Effects:
- Executes the next function in the chain if access is granted.
type SemanticCache ¶
type SemanticCache struct {
// contains filtered or unexported fields
}
SemanticCache implements a semantic cache using embeddings and cosine similarity.
Summary: A cache implementation that uses semantic similarity rather than exact key matching.
func NewSemanticCache ¶
func NewSemanticCache(provider EmbeddingProvider, store VectorStore, threshold float32) *SemanticCache
NewSemanticCache creates a new SemanticCache.
Summary: Initializes a new SemanticCache.
Parameters:
- provider: EmbeddingProvider. The service to generate embeddings.
- store: VectorStore. The storage backend for vectors.
- threshold: float32. The minimum similarity score (0-1) to consider a hit.
Returns:
- *SemanticCache: The initialized semantic cache.
Side Effects:
- Sets a default threshold of 0.9 if the provided threshold is <= 0.
- Creates a memory-based vector store if store is nil.
func (*SemanticCache) Get ¶
func (c *SemanticCache) Get(ctx context.Context, key string, input string) (any, []float32, bool, error)
Get attempts to find a semantically similar cached result.
Summary: Retrieves a cached result if a semantically similar entry exists.
Parameters:
- ctx: context.Context. The request context.
- key: string. The semantic key or scope.
- input: string. The query text to match against.
Returns:
- any: The cached result if found.
- []float32: The embedding generated for the input text (useful for subsequent Set).
- bool: True if a cache hit occurred.
- error: An error if embedding generation fails.
Errors:
- Returns error if the embedding provider fails.
Side Effects:
- calls the EmbeddingProvider to generate an embedding.
- calls the VectorStore to search for matches.
func (*SemanticCache) Set ¶
func (c *SemanticCache) Set(ctx context.Context, key string, embedding []float32, result any, ttl time.Duration) error
Set adds a result to the cache using the provided embedding.
Summary: Caches a result associated with a specific embedding.
Parameters:
- ctx: context.Context. The request context.
- key: string. The semantic key or scope.
- embedding: []float32. The embedding vector (usually returned from Get).
- result: any. The result data to cache.
- ttl: time.Duration. The expiration time for the cache entry.
Returns:
- error: An error if the storage operation fails.
Side Effects:
- Writes to the underlying VectorStore.
type SessionState ¶
type SessionState struct {
ID string `json:"id"`
Data map[string]interface{} `json:"data"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
SessionState represents the shared state for a recursive context session.
Summary: Represents a SessionState.
type SimpleVectorStore ¶
type SimpleVectorStore struct {
// contains filtered or unexported fields
}
SimpleVectorStore is a naive in-memory vector store.
Summary: Represents a SimpleVectorStore.
func NewSimpleVectorStore ¶
func NewSimpleVectorStore() *SimpleVectorStore
NewSimpleVectorStore creates a new SimpleVectorStore. It initializes the store with a default configuration.
Returns:
- *SimpleVectorStore: A pointer to the newly created SimpleVectorStore.
Summary: Initializes NewSimpleVectorStore operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*SimpleVectorStore) Add ¶
func (s *SimpleVectorStore) Add(_ context.Context, key string, vector []float32, result any, ttl time.Duration) error
Add adds a new entry to the vector store. It evicts the oldest entry if the store exceeds the maximum number of entries for the key.
Parameters:
- key: The key associated with the entry.
- vector: The embedding vector.
- result: The result to cache.
- ttl: The time-to-live for the entry.
Returns:
- error: An error if the operation fails (currently always nil).
Summary: Executes Add operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*SimpleVectorStore) Prune ¶
func (s *SimpleVectorStore) Prune(_ context.Context, key string)
Prune removes expired entries from the vector store for the given key.
Parameters:
- key: The key to prune entries for.
Summary: Executes Prune operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*SimpleVectorStore) Search ¶
func (s *SimpleVectorStore) Search(_ context.Context, key string, query []float32) (any, float32, bool)
Search searches for the most similar entry in the vector store for the given key and query vector. It returns the result, the similarity score, and a boolean indicating if a match was found.
Parameters:
- key: The key to search for.
- query: The query vector.
Returns:
- any: The cached result if found.
- float32: The similarity score (cosine similarity).
- bool: True if a match was found, false otherwise.
Summary: Executes Search operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
type SmartRecoveryMiddleware ¶
type SmartRecoveryMiddleware struct {
// contains filtered or unexported fields
}
SmartRecoveryMiddleware handles automatic error recovery using LLM.
Summary: Represents a SmartRecoveryMiddleware.
func NewSmartRecoveryMiddleware ¶
func NewSmartRecoveryMiddleware(config *configv1.SmartRecoveryConfig, toolManager tool.ManagerInterface) *SmartRecoveryMiddleware
NewSmartRecoveryMiddleware creates a new SmartRecoveryMiddleware.
Parameters:
- config (*configv1.SmartRecoveryConfig): The config parameter.
- toolManager (tool.ManagerInterface): The toolManager parameter.
Returns:
- *SmartRecoveryMiddleware: The resulting *SmartRecoveryMiddleware.
Errors:
- None
Side Effects:
- None
Summary: Initializes NewSmartRecoveryMiddleware operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
func (*SmartRecoveryMiddleware) Execute ¶
func (m *SmartRecoveryMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute executes the middleware logic.
Parameters:
- ctx (context.Context): The context for the request.
- req (*tool.ExecutionRequest): The request object.
- next (tool.ExecutionFunc): The next parameter.
Returns:
- any: The resulting any.
- error: An error if the operation fails.
Errors:
- Returns an error if the operation fails or is invalid.
Side Effects:
- None
Summary: Executes Execute operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
type StandardMiddlewares ¶
type StandardMiddlewares struct {
Audit *AuditMiddleware
GlobalRateLimit *GlobalRateLimitMiddleware
ContextOptimizer *ContextOptimizer
Debugger *Debugger
SmartRecovery *SmartRecoveryMiddleware
RecursiveContext *RecursiveContextManager
A2ABridge *A2ABridgeMiddleware
ESB *ESBMiddleware
CFIA *CFIAMiddleware
DiscoverySandbox *DiscoverySandboxMiddleware
Cleanup func() error
}
StandardMiddlewares holds the standard middlewares that might need to be updated.
Summary: Represents a StandardMiddlewares.
func InitStandardMiddlewares ¶
func InitStandardMiddlewares( authManager *auth.Manager, toolManager tool.ManagerInterface, auditConfig *configv1.AuditConfig, cachingMiddleware *CachingMiddleware, globalRateLimitConfig *configv1.RateLimitConfig, dlpConfig *configv1.DLPConfig, contextOptimizerConfig *configv1.ContextOptimizerConfig, debuggerConfig *configv1.DebuggerConfig, smartRecoveryConfig *configv1.SmartRecoveryConfig, cfiaConfig *CFIAConfig, discoverySandboxConfig *DiscoverySandboxConfig, ) (*StandardMiddlewares, error)
InitStandardMiddlewares registers standard middlewares.
Parameters:
- authManager (*auth.Manager): The authManager.
- toolManager (tool.ManagerInterface): The toolManager.
- auditConfig (*configv1.AuditConfig): The auditConfig.
- cachingMiddleware (*CachingMiddleware): The cachingMiddleware.
- globalRateLimitConfig (*configv1.RateLimitConfig): The globalRateLimitConfig.
- dlpConfig (*configv1.DLPConfig): The dlpConfig.
- contextOptimizerConfig (*configv1.ContextOptimizerConfig): The contextOptimizerConfig.
- debuggerConfig (*configv1.DebuggerConfig): The debuggerConfig.
- smartRecoveryConfig (*configv1.SmartRecoveryConfig): The smartRecoveryConfig.
Returns:
- (*StandardMiddlewares): The result.
- (error): An error if the operation fails.
Summary: Executes InitStandardMiddlewares operation.
Parameters:
- TODO: Document parameters.
Returns:
- TODO: Document returns.
Errors:
- TODO: Document errors.
Side Effects:
- None.
type ToolMetricsMiddleware ¶
type ToolMetricsMiddleware struct {
// contains filtered or unexported fields
}
ToolMetricsMiddleware provides detailed metrics for tool executions.
Summary: Middleware that records Prometheus metrics for tool execution calls.
func NewToolMetricsMiddleware ¶
func NewToolMetricsMiddleware(t tokenizer.Tokenizer) *ToolMetricsMiddleware
NewToolMetricsMiddleware creates a new ToolMetricsMiddleware.
Summary: Initializes the tool metrics middleware and registers metrics if not already registered.
Parameters:
- t: tokenizer.Tokenizer. The tokenizer used to count tokens in tool inputs and outputs. If nil, a simple default tokenizer is used.
Returns:
- *ToolMetricsMiddleware: A new instance of ToolMetricsMiddleware with metrics registered.
Side Effects:
- Registers Prometheus metrics (globally, once).
func (*ToolMetricsMiddleware) Execute ¶
func (m *ToolMetricsMiddleware) Execute(ctx context.Context, req *tool.ExecutionRequest, next tool.ExecutionFunc) (any, error)
Execute executes the tool metrics middleware.
Summary: Wraps tool execution to record latency, size, and token metrics.
Parameters:
- ctx: context.Context. The execution context.
- req: *tool.ExecutionRequest. The request containing tool execution details.
- next: tool.ExecutionFunc. The next handler in the execution chain.
Returns:
- any: The result of the tool execution.
- error: An error if the execution fails.
Side Effects:
- Updates Prometheus counters, histograms, and gauges.
- Measures execution duration.
type VectorEntry ¶
type VectorEntry struct {
// Vector is the embedding vector.
Vector []float32
// Result is the cached result associated with the vector.
Result any
// ExpiresAt is the timestamp when this entry expires.
ExpiresAt time.Time
// Norm is the precomputed Euclidean norm of the vector.
Norm float32
}
VectorEntry represents a single entry in the vector store.
Summary: Represents a VectorEntry.
type VectorStore ¶
type VectorStore interface {
// Add adds a new entry to the vector store.
//
// Parameters:
// - ctx: context.Context. The context for the request.
// - key: string. The unique key for the entry.
// - vector: []float32. The embedding vector.
// - result: any. The associated result data.
// - ttl: time.Duration. The time-to-live for the entry.
//
// Returns:
// - error: An error if the operation fails.
Add(ctx context.Context, key string, vector []float32, result any, ttl time.Duration) error
// Search searches for the most similar entry in the vector store.
//
// Parameters:
// - ctx: context.Context. The context for the request.
// - key: string. The key to restrict the search scope.
// - query: []float32. The query embedding vector.
//
// Returns:
// - any: The best matching result data.
// - float32: The similarity score (0.0 to 1.0).
// - bool: True if a match was found, false otherwise.
Search(ctx context.Context, key string, query []float32) (any, float32, bool)
// Prune removes expired entries.
//
// Parameters:
// - ctx: context.Context. The context for the request.
// - key: string. Optional key to restrict pruning scope.
Prune(ctx context.Context, key string)
}
VectorStore defines the interface for storing and searching vectors.
Summary: Interface for storage backends that support vector similarity search.
Source Files
¶
- a2a_bridge.go
- aia_broker.go
- audit.go
- auth.go
- binary_utils.go
- blackboard.go
- cache.go
- call_policy.go
- cfia.go
- compliance.go
- context_optimizer.go
- cors.go
- cors_http.go
- csrf.go
- debug.go
- debugger.go
- discovery_sandbox.go
- dlp.go
- dmr_hub.go
- error_mapping.go
- esb.go
- global_ratelimit.go
- guardrails.go
- gzip.go
- hitl.go
- http_ratelimit.go
- http_security.go
- ip_allowlist.go
- keys.go
- lazy_mcp.go
- logging.go
- msg.go
- project_config_guard.go
- protocol_metrics.go
- ratelimit.go
- ratelimit_local.go
- ratelimit_redis.go
- ratelimit_redis_strategy.go
- ratelimit_strategy.go
- rbac.go
- recovery.go
- recursive_context.go
- redactor.go
- registry.go
- resilience.go
- scopes.go
- semantic_cache.go
- semantic_cache_http.go
- semantic_cache_ollama.go
- semantic_cache_openai.go
- semantic_cache_postgres.go
- semantic_cache_sqlite.go
- smart_recovery.go
- sso.go
- tool_metrics.go
- trace.go
- vector_store_memory.go