mcpinspect

package
v0.0.0-...-230ac96 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package mcpinspect provides MCP (Model Context Protocol) message inspection for security monitoring.

The package intercepts MCP JSON-RPC messages to:

  • Parse tool definitions from tools/list responses
  • Track tool definitions with content hashing for rug pull detection
  • Detect suspicious patterns (credential theft, exfiltration, hidden instructions)
  • Emit audit events for tool discovery, changes, and security detections

Pattern Detection:

The detector scans tool descriptions and inputSchema for:

  • credential_theft: References to SSH keys, .env files, API keys, etc.
  • exfiltration: curl, wget, netcat patterns
  • hidden_instructions: HIDDEN:, IGNORE PREVIOUS, SYSTEM OVERRIDE
  • shell_injection: Command chaining, substitution patterns
  • path_traversal: ../.. sequences, /etc/, /root/ access

Example usage:

emitter := func(event interface{}) {
    // Log or store the event
}
inspector := mcpinspect.NewInspectorWithDetection("session-id", "server-id", emitter)
result, err := inspector.Inspect(messageBytes, mcpinspect.DirectionResponse)

internal/mcpinspect/events.go

internal/mcpinspect/hash.go

internal/mcpinspect/inspector.go

internal/mcpinspect/protocol.go

internal/mcpinspect/registry.go

Index

Constants

View Source
const (
	CategoryRead    = "read"
	CategoryWrite   = "write"
	CategorySend    = "send"
	CategoryCompute = "compute"
	CategoryUnknown = "unknown"
)

Tool categories used by the cross-server pattern detector.

Variables

This section is empty.

Functions

func CheckServerNameSimilarity

func CheckServerNameSimilarity(newID string, existingIDs []string, threshold float64) (match string, score float64)

CheckServerNameSimilarity checks a new server ID against existing IDs. Returns (similarID, score) or ("", 0) if none exceed the threshold.

func ComputeHash

func ComputeHash(tool ToolDefinition) string

ComputeHash computes a deterministic SHA-256 hash of a tool definition. The hash covers name, description, and inputSchema for change detection.

func NormalizedSimilarity

func NormalizedSimilarity(a, b string) float64

NormalizedSimilarity returns a similarity score between 0.0 and 1.0.

Types

type ArgInspection

type ArgInspection struct {
	// Resolve supplies the policy engine and its inspector for the current
	// call.
	//
	// It is a function rather than two stored pointers so the engine is
	// resolved per call. A captured engine keeps enforcing the policy that
	// was live when the inspector was built, which is the bug documented at
	// internal/api/session_policy.go:47 for the network, transparent-TCP
	// and DNS paths. This does not need to be a fourth instance of it.
	Resolve func() (*policy.Engine, policy.InspectChecker)

	// Redactor is the replacement strategy for on_violation: redact. Nil
	// uses inspect.PlaceholderRedactor, which retains nothing but also
	// destroys the value for the tool being called.
	Redactor inspect.Redactor
}

ArgInspection makes tools/call arguments subject to the policy's mcp_inspect_rules.

Without one installed, handleToolsCall behaves exactly as it did before: the pattern detector annotates the event and nothing is ever blocked. That alert-only behaviour was deliberate, but it means an agent could put a credential or a customer record into a tool argument and the only trace was a log line after the fact.

type BinaryPin

type BinaryPin struct {
	ServerID   string    `json:"server_id"`
	BinaryPath string    `json:"binary_path"`
	BinaryHash string    `json:"binary_hash"`
	TrustedAt  time.Time `json:"trusted_at"`
	TrustedBy  string    `json:"trusted_by,omitempty"`
}

BinaryPin represents a pinned server binary.

type CompiledPattern

type CompiledPattern struct {
	Name        string
	Category    string
	Severity    Severity
	Regex       *regexp.Regexp
	Description string
}

CompiledPattern is a pre-compiled detection pattern.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

ContentBlock represents a content block in an MCP tool result.

type CrossServerDecision

type CrossServerDecision struct {
	Blocked  bool
	Rule     string // "read_then_send", "burst", "cross_server_flow", "shadow_tool"
	Reason   string
	Severity string // "critical", "high", "medium"
	Related  []ToolCallRecord
}

CrossServerDecision is the output of SessionAnalyzer.CheckAndRecord. It describes which rule fired, the severity, and the related tool calls that contributed to the detection.

type DetectionResult

type DetectionResult struct {
	Pattern  string   `json:"pattern"`
	Category string   `json:"category"`
	Severity Severity `json:"severity"`
	Matches  []Match  `json:"matches"`
	Field    string   `json:"field"` // "description", "inputSchema", etc.
}

DetectionResult holds the result of pattern matching.

type Detector

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

Detector scans tool definitions for suspicious patterns.

func NewDetector

func NewDetector() *Detector

NewDetector creates a detector with built-in patterns.

func NewDetectorWithPatterns

func NewDetectorWithPatterns(custom []PatternConfig) *Detector

NewDetectorWithPatterns creates a detector with built-in plus custom patterns.

func (*Detector) Inspect

func (d *Detector) Inspect(tool ToolDefinition) []DetectionResult

Inspect scans a tool definition and returns any detections.

func (*Detector) InspectText

func (d *Detector) InspectText(text, field string) []DetectionResult

InspectText scans arbitrary text for suspicious patterns. field identifies the source (e.g., "arguments", "tool_result", "sampling_prompt").

type Direction

type Direction int

Direction indicates whether a message is a request or response.

const (
	DirectionRequest Direction = iota
	DirectionResponse
)

type EventEmitter

type EventEmitter func(event interface{})

EventEmitter is a function that emits events.

type FieldChange

type FieldChange struct {
	Field    string `json:"field"`
	Previous string `json:"previous"`
	New      string `json:"new"`
}

FieldChange describes what changed in a tool definition.

type InspectResult

type InspectResult struct {
	Action string // "allow" | "block" | "" (empty = allow)
	Reason string // Human-readable explanation when blocked

	// Rewritten is the message to forward in place of the original, set
	// only when content inspection redacted a tools/call argument. Nil
	// means forward the message unchanged.
	Rewritten []byte
}

InspectResult holds the outcome of inspecting an MCP message.

type Inspector

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

Inspector processes MCP messages and emits audit events.

func NewInspector

func NewInspector(sessionID, serverID string, emitter EventEmitter) *Inspector

NewInspector creates a new MCP inspector for a server connection.

func NewInspectorWithDetection

func NewInspectorWithDetection(sessionID, serverID string, emitter EventEmitter) *Inspector

NewInspectorWithDetection creates a new MCP inspector with pattern detection enabled.

func NewInspectorWithPolicy

func NewInspectorWithPolicy(sessionID, serverID string, emitter EventEmitter, cfg config.SandboxMCPConfig) *Inspector

NewInspectorWithPolicy creates an inspector with policy enforcement.

func (*Inspector) CheckPolicy

func (i *Inspector) CheckPolicy(toolName, hash string) (allowed bool, reason string)

CheckPolicy checks if a tool invocation is allowed by policy.

func (*Inspector) CheckRateLimit

func (i *Inspector) CheckRateLimit(toolName string) bool

CheckRateLimit checks if a tool call is within rate limits.

func (*Inspector) Inspect

func (i *Inspector) Inspect(ctx context.Context, data []byte, dir Direction) (*InspectResult, error)

Inspect processes an MCP message and emits relevant events. Returns an InspectResult indicating whether the message should be forwarded.

ctx bounds content inspection of tools/call arguments, which is the only thing on this path that does I/O. Callers with no deadline of their own pass context.Background(); the rule's own inspect.timeout still applies.

func (*Inspector) SetArgInspection

func (i *Inspector) SetArgInspection(a *ArgInspection)

SetArgInspection installs argument inspection. Pass nil to disable it.

type MCPCrossServerEvent

type MCPCrossServerEvent struct {
	Type      string    `json:"type"` // "mcp_cross_server_blocked"
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`

	// Which detection rule fired
	Rule     string `json:"rule"`     // "read_then_send", "burst", "cross_server_flow", "shadow_tool"
	Severity string `json:"severity"` // "critical", "high", "medium"

	// The tool call that was blocked
	BlockedServerID string `json:"blocked_server_id"`
	BlockedToolName string `json:"blocked_tool_name"`

	// Recent tool calls that contributed to the detection
	RelatedCalls []ToolCallRecord `json:"related_calls"`

	// Human-readable explanation of why the call was blocked
	Reason string `json:"reason"`
}

MCPCrossServerEvent is logged when a cross-server pattern is detected and a tool call is blocked due to suspicious multi-server interaction.

type MCPDetectionEvent

type MCPDetectionEvent struct {
	Type      string    `json:"type"` // "mcp_detection"
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`

	// Server and tool
	ServerID string `json:"server_id"`
	ToolName string `json:"tool_name"`

	// Detection details
	Detection DetectionResult `json:"detection"`

	// Action taken
	Action string `json:"action"` // "alert" | "warn" | "block"
}

MCPDetectionEvent is logged when suspicious patterns are detected.

type MCPSamplingRequestEvent

type MCPSamplingRequestEvent struct {
	Type         string            `json:"type"` // "mcp_sampling_request"
	Timestamp    time.Time         `json:"timestamp"`
	SessionID    string            `json:"session_id"`
	ServerID     string            `json:"server_id"`
	ModelHint    string            `json:"model_hint,omitempty"`
	MaxTokens    int               `json:"max_tokens"`
	MessageCount int               `json:"message_count"`
	Detections   []DetectionResult `json:"detections,omitempty"`
	Action       string            `json:"action"` // "allow" | "alert" | "block"
}

MCPSamplingRequestEvent is logged when a sampling/createMessage request is observed.

type MCPServerEnvFilteredEvent

type MCPServerEnvFilteredEvent struct {
	Type         string    `json:"type"` // "mcp_server_env_filtered"
	Timestamp    time.Time `json:"timestamp"`
	SessionID    string    `json:"session_id"`
	ServerID     string    `json:"server_id"`
	StrippedVars []string  `json:"stripped_vars"` // var names only, NOT values
	PassedCount  int       `json:"passed_count"`
}

MCPServerEnvFilteredEvent is logged when environment variables are filtered before starting an MCP server process.

type MCPServerNameSimilarityEvent

type MCPServerNameSimilarityEvent struct {
	Type      string    `json:"type"` // "mcp_server_name_similarity"
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`

	NewServerID     string  `json:"new_server_id"`
	SimilarServerID string  `json:"similar_server_id"`
	SimilarityScore float64 `json:"similarity_score"`
	Severity        string  `json:"severity"` // "warning"
}

MCPServerNameSimilarityEvent is logged when a new MCP server's name is suspiciously similar to an existing server (possible typosquatting).

type MCPToolCallInterceptedEvent

type MCPToolCallInterceptedEvent struct {
	Type      string    `json:"type"` // "mcp_tool_call_intercepted"
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`
	RequestID string    `json:"request_id"` // LLM proxy request ID
	Dialect   string    `json:"dialect"`    // "anthropic" | "openai"

	// From LLM response
	ToolName   string          `json:"tool_name"`
	ToolCallID string          `json:"tool_call_id"` // "toolu_..." or "call_..."
	Input      json.RawMessage `json:"input"`

	// From registry lookup
	ServerID   string `json:"server_id"`
	ServerType string `json:"server_type"` // "stdio" | "http" | "sse"
	ServerAddr string `json:"server_addr,omitempty"`
	ToolHash   string `json:"tool_hash"`

	// Policy decision
	Action string `json:"action"` // "allow" | "redact" | "block"
	Reason string `json:"reason,omitempty"`

	// Content inspection of the arguments, when an mcp_inspect_rules rule
	// matched the call. InspectDetail names the categories found and never
	// the matched text: this event is persisted and streamed to clients.
	InspectRule   string `json:"inspect_rule,omitempty"`
	InspectDetail string `json:"inspect_detail,omitempty"`
	InspectError  string `json:"inspect_error,omitempty"`

	// Cross-server detection metadata (populated when blocked by a cross-server rule).
	CrossServerRule     string           `json:"cross_server_rule,omitempty"`
	CrossServerSeverity string           `json:"cross_server_severity,omitempty"`
	CrossServerRelated  []ToolCallRecord `json:"cross_server_related,omitempty"`
}

MCPToolCallInterceptedEvent is logged when the LLM proxy detects a tool_use/tool_calls block that matches a registered MCP tool.

type MCPToolCalledEvent

type MCPToolCalledEvent struct {
	Type      string    `json:"type"` // "mcp_tool_called"
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`
	ServerID  string    `json:"server_id"`

	// From JSON-RPC request
	ToolName  string          `json:"tool_name"`
	JSONRPCID json.RawMessage `json:"jsonrpc_id"`
	Input     json.RawMessage `json:"input,omitempty"`

	// Detection results from argument scanning
	Detections  []DetectionResult `json:"detections,omitempty"`
	MaxSeverity string            `json:"max_severity,omitempty"`

	// Content inspection of the arguments, when an mcp_inspect_rules rule
	// matched the call. Action is allow, redact or block. InspectDetail
	// names the categories found and never the matched text: this event is
	// persisted and streamed to clients, and the matched text is what
	// inspection exists to contain.
	Action        string `json:"action,omitempty"`
	Reason        string `json:"reason,omitempty"`
	InspectRule   string `json:"inspect_rule,omitempty"`
	InspectDetail string `json:"inspect_detail,omitempty"`
	InspectError  string `json:"inspect_error,omitempty"`
}

MCPToolCalledEvent is logged when a tools/call JSON-RPC request is observed on an MCP server's stdin.

type MCPToolChangedEvent

type MCPToolChangedEvent struct {
	Type      string    `json:"type"` // "mcp_tool_changed"
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`

	// Server identity
	ServerID string `json:"server_id"`

	// Tool info
	ToolName     string `json:"tool_name"`
	PreviousHash string `json:"previous_hash"`
	NewHash      string `json:"new_hash"`

	// What changed
	Changes []FieldChange `json:"changes"`

	// New detection results
	Detections []DetectionResult `json:"detections,omitempty"`
}

MCPToolChangedEvent is logged when a tool definition changes (rug pull).

type MCPToolResultInspectedEvent

type MCPToolResultInspectedEvent struct {
	Type      string    `json:"type"` // "mcp_tool_result_inspected"
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`
	ServerID  string    `json:"server_id"`

	ToolName      string            `json:"tool_name"`
	JSONRPCID     json.RawMessage   `json:"jsonrpc_id"`
	Detections    []DetectionResult `json:"detections,omitempty"`
	MaxSeverity   string            `json:"max_severity,omitempty"`
	ContentLength int               `json:"content_length"`
	Action        string            `json:"action"` // "allow" | "alert" | "block"
}

MCPToolResultInspectedEvent is logged when a tools/call response is inspected.

type MCPToolSeenEvent

type MCPToolSeenEvent struct {
	Type      string    `json:"type"` // "mcp_tool_seen"
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`

	// Server identity
	ServerID   string `json:"server_id"`
	ServerType string `json:"server_type"` // "stdio" | "http"

	// Tool info
	ToolName    string `json:"tool_name"`
	ToolHash    string `json:"tool_hash"`
	Description string `json:"description,omitempty"`

	// Registration status
	Status string `json:"status"` // "new" | "unchanged" | "changed"

	// Detection results (if any)
	Detections []DetectionResult `json:"detections,omitempty"`

	// Severity (highest from detections)
	MaxSeverity string `json:"max_severity,omitempty"`
}

MCPToolSeenEvent is logged when a tool definition is observed.

type MCPToolsListChangedEvent

type MCPToolsListChangedEvent struct {
	Type      string    `json:"type"` // "mcp_tools_list_changed"
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`
	ServerID  string    `json:"server_id"`
}

MCPToolsListChangedEvent is logged when a notifications/tools/list_changed notification is received from an MCP server, indicating that the server's tool definitions may have changed. This is an alert-only event; actual re-evaluation happens when the client issues a new tools/list request.

type Match

type Match struct {
	Text     string `json:"text"`
	Position int    `json:"position"`
	Context  string `json:"context"` // Surrounding text
}

Match represents a single pattern match location.

type MessageType

type MessageType int

MessageType identifies the type of MCP message.

const (
	MessageUnknown MessageType = iota
	MessageToolsList
	MessageToolsListResponse
	MessageToolsCall
	MessageToolsCallResponse
	MessageSamplingRequest
	MessageToolsListChanged
)

func DetectMessageType

func DetectMessageType(data []byte) (MessageType, error)

DetectMessageType determines the MCP message type from raw JSON.

func (MessageType) String

func (m MessageType) String() string

String returns the string representation of MessageType.

type PatternConfig

type PatternConfig struct {
	Name        string
	Pattern     string
	Category    string
	Severity    Severity
	Description string
}

PatternConfig defines a custom detection pattern.

type Pin

type Pin struct {
	ServerID  string    `json:"server_id"`
	ToolName  string    `json:"tool_name"`
	Hash      string    `json:"hash"`
	TrustedAt time.Time `json:"trusted_at"`
	TrustedBy string    `json:"trusted_by,omitempty"`
}

Pin represents a pinned tool version.

type PinStatus

type PinStatus int

PinStatus indicates the result of a pin verification.

const (
	PinStatusNotPinned PinStatus = iota
	PinStatusMatch
	PinStatusMismatch
)

func (PinStatus) String

func (s PinStatus) String() string

type PinStore

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

PinStore manages persistent tool version pins.

func NewPinStore

func NewPinStore(path string) (*PinStore, error)

NewPinStore creates a new pin store at the given path.

func (*PinStore) Close

func (s *PinStore) Close() error

Close closes the pin store.

func (*PinStore) Get

func (s *PinStore) Get(serverID, toolName string) (*Pin, error)

Get returns a specific pin.

func (*PinStore) List

func (s *PinStore) List(serverFilter string) ([]Pin, error)

List returns all pins, optionally filtered by server.

func (*PinStore) ListBinaryPins

func (s *PinStore) ListBinaryPins() ([]BinaryPin, error)

ListBinaryPins returns all binary pins ordered by server ID.

func (*PinStore) Reset

func (s *PinStore) Reset(serverID, toolName string) error

Reset removes a tool's pin.

func (*PinStore) ResetAll

func (s *PinStore) ResetAll() error

ResetAll removes all pins.

func (*PinStore) ResetServer

func (s *PinStore) ResetServer(serverID string) error

ResetServer removes all pins for a server.

func (*PinStore) Trust

func (s *PinStore) Trust(serverID, toolName, hash string) error

Trust pins a tool at the given hash.

func (*PinStore) TrustBinary

func (s *PinStore) TrustBinary(serverID, binaryPath, hash string) error

TrustBinary pins a server binary at the given hash.

func (*PinStore) TrustWithOperator

func (s *PinStore) TrustWithOperator(serverID, toolName, hash, operatorID string) error

TrustWithOperator pins a tool with operator attribution.

func (*PinStore) Verify

func (s *PinStore) Verify(serverID, toolName, hash string) (*VerifyResult, error)

Verify checks if a tool hash matches its pin.

func (*PinStore) VerifyBinary

func (s *PinStore) VerifyBinary(serverID, hash string) (status, pinnedHash string, err error)

VerifyBinary checks if a server binary hash matches its pin. Returns status ("not_pinned", "match", "mismatch") and the pinned hash.

type PolicyDecision

type PolicyDecision struct {
	Allowed bool
	Reason  string
	Rule    *config.MCPToolRule // The rule that matched, if any
}

PolicyDecision represents the result of a policy evaluation.

type PolicyEvaluator

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

PolicyEvaluator evaluates MCP tool access based on configured policies.

func NewPolicyEvaluator

func NewPolicyEvaluator(cfg config.SandboxMCPConfig) *PolicyEvaluator

NewPolicyEvaluator creates a new policy evaluator.

func (*PolicyEvaluator) Evaluate

func (p *PolicyEvaluator) Evaluate(serverID, toolName, hash string) PolicyDecision

Evaluate performs a full policy evaluation and returns the decision. Evaluation order: server-level policy first, then tool-level policy.

func (*PolicyEvaluator) IsAllowed

func (p *PolicyEvaluator) IsAllowed(serverID, toolName string) bool

IsAllowed checks if a tool invocation is permitted.

func (*PolicyEvaluator) IsAllowedWithHash

func (p *PolicyEvaluator) IsAllowedWithHash(serverID, toolName, hash string) bool

IsAllowedWithHash checks if a tool invocation is permitted with hash verification.

type RateLimiterRegistry

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

RateLimiterRegistry manages rate limiters for MCP servers.

func NewRateLimiterRegistry

func NewRateLimiterRegistry(cfg config.MCPRateLimitsConfig) *RateLimiterRegistry

NewRateLimiterRegistry creates a new rate limiter registry.

func (*RateLimiterRegistry) Allow

func (r *RateLimiterRegistry) Allow(serverID, toolName string) bool

Allow checks if a call to a server/tool is allowed under rate limits.

func (*RateLimiterRegistry) AllowN

func (r *RateLimiterRegistry) AllowN(serverID, toolName string, n int) bool

AllowN checks if n calls are allowed.

func (*RateLimiterRegistry) Reset

func (r *RateLimiterRegistry) Reset()

Reset clears all limiters (useful for testing or config reload).

func (*RateLimiterRegistry) Stats

func (r *RateLimiterRegistry) Stats() map[string]float64

Stats returns current token counts for all tracked servers.

type RegisteredTool

type RegisteredTool struct {
	Name       string         `json:"name"`
	ServerID   string         `json:"server_id"`
	Hash       string         `json:"hash"`
	FirstSeen  time.Time      `json:"first_seen"`
	LastSeen   time.Time      `json:"last_seen"`
	Pinned     bool           `json:"pinned"`
	Definition ToolDefinition `json:"-"` // Current definition for change detection
}

RegisteredTool tracks a tool definition in the registry.

type RegistrationResult

type RegistrationResult struct {
	Status             RegistrationStatus
	Tool               *RegisteredTool
	Definition         ToolDefinition
	PreviousHash       string         // Only set when Status == StatusChanged
	NewHash            string         // Only set when Status == StatusChanged
	PreviousDefinition ToolDefinition // Only set when Status == StatusChanged
}

RegistrationResult is returned when registering a tool.

type RegistrationStatus

type RegistrationStatus int

RegistrationStatus indicates the result of registering a tool.

const (
	StatusNew RegistrationStatus = iota
	StatusUnchanged
	StatusChanged // Rug pull alert!
)

func (RegistrationStatus) String

func (s RegistrationStatus) String() string

String returns the string representation of RegistrationStatus.

type Registry

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

Registry tracks tool definitions for change detection.

func NewRegistry

func NewRegistry(pinOnFirstUse bool) *Registry

NewRegistry creates a new tool registry.

func (*Registry) Get

func (r *Registry) Get(serverID, toolName string) *RegisteredTool

Get retrieves a registered tool by server and name.

func (*Registry) List

func (r *Registry) List() []*RegisteredTool

List returns all registered tools.

func (*Registry) Register

func (r *Registry) Register(serverID string, tool ToolDefinition) *RegistrationResult

Register adds or updates a tool in the registry and returns the result.

type SamplingCreateMessageRequest

type SamplingCreateMessageRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Method  string          `json:"method"` // "sampling/createMessage"
	Params  struct {
		Messages         []SamplingMessage `json:"messages"`
		ModelPreferences *struct {
			Hints []struct {
				Name string `json:"name"`
			} `json:"hints"`
		} `json:"modelPreferences,omitempty"`
		MaxTokens int `json:"maxTokens"`
	} `json:"params"`
}

SamplingCreateMessageRequest is the JSON-RPC request for sampling/createMessage.

func ParseSamplingRequest

func ParseSamplingRequest(data []byte) (*SamplingCreateMessageRequest, error)

ParseSamplingRequest parses a sampling/createMessage request from raw JSON.

type SamplingMessage

type SamplingMessage struct {
	Role    string `json:"role"`
	Content struct {
		Type string `json:"type"`
		Text string `json:"text"`
	} `json:"content"`
}

SamplingMessage represents a message in a sampling/createMessage request.

type SessionAnalyzer

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

SessionAnalyzer detects cross-server attack patterns by analysing sequences of MCP tool calls within a session. It implements four detection rules: shadow tool, burst, read-then-send, and cross-server flow.

The analyzer starts in an inactive state. Call Activate() to allocate the sliding window and burst tracking state. Shadow tool tracking (via NotifyOverwrite) is always active regardless of activation state.

func NewSessionAnalyzer

func NewSessionAnalyzer(sessionID string, cfg config.CrossServerConfig) *SessionAnalyzer

NewSessionAnalyzer creates an inactive analyzer. The shadows map is initialized immediately (always active). The window and bursts fields remain nil until Activate() is called.

func (*SessionAnalyzer) Activate

func (a *SessionAnalyzer) Activate()

Activate allocates the sliding window and burst map. Sets active=true. This method is idempotent.

func (*SessionAnalyzer) CheckAndRecord

func (a *SessionAnalyzer) CheckAndRecord(serverID, toolName, toolCallID, requestID string) (*CrossServerDecision, string)

CheckAndRecord atomically evaluates all enabled cross-server rules and records the tool call in the sliding window. This single-lock operation eliminates the TOCTOU race between evaluating rules and recording.

The call is recorded with action="allow" initially. If the caller's PolicyEvaluator subsequently blocks the call, call MarkBlocked() to update the record (prevents a blocked read from triggering read-then-send for subsequent calls).

Returns the cross-server decision (nil if no rule triggers) and the tool's classified category.

When the feature is disabled, returns (nil, category) immediately. When inactive and no shadows exist, returns (nil, category) immediately. When inactive but shadows exist, only checks the shadow rule. When active, checks all enabled rules in order:

  1. Shadow tool (always, if enabled)
  2. Burst (if enabled)
  3. Read-then-send (if enabled, only when category is "send")
  4. Cross-server flow (if enabled, when category is write/send/compute/unknown from different server)

func (*SessionAnalyzer) CheckServerSimilarity

func (a *SessionAnalyzer) CheckServerSimilarity(newServerID string, threshold float64) (string, float64)

CheckServerSimilarity compares a new server ID against known servers. Known servers are collected from the sliding window and burst tracking. Returns (similarID, score) or ("", 0) if none exceed the threshold.

func (*SessionAnalyzer) Classify

func (a *SessionAnalyzer) Classify(toolName string) string

Classify returns the category for a tool name by delegating to the internal classifier. The classifier is immutable after construction, so this method is safe for concurrent use without locking.

func (*SessionAnalyzer) ClearShadow

func (a *SessionAnalyzer) ClearShadow(toolName string)

ClearShadow removes a shadow entry for a tool. Called when a server legitimately re-registers a tool (e.g., after restart) and the shadow is no longer valid. Thread-safe.

func (*SessionAnalyzer) MarkBlocked

func (a *SessionAnalyzer) MarkBlocked(serverID, toolName, toolCallID, requestID string)

MarkBlocked updates the most recent "allow" window entry for the given tool call to action="block". Called when the PolicyEvaluator blocks a call that the cross-server analyzer initially allowed. This prevents a blocked read from triggering read-then-send for subsequent calls.

When toolCallID is non-empty, it is used for precise matching. Otherwise falls back to (serverID, toolName, requestID). Thread-safe.

func (*SessionAnalyzer) NotifyOverwrite

func (a *SessionAnalyzer) NotifyOverwrite(toolName, oldServerID, newServerID string)

NotifyOverwrite records a tool name collision. This always works even before activation. Thread-safe.

func (*SessionAnalyzer) Record

func (a *SessionAnalyzer) Record(rec ToolCallRecord)

Record adds a tool call to the sliding window. This is used for test setup to inject records with specific timestamps and categories. Production code should use CheckAndRecord() which records atomically with rule evaluation.

type Severity

type Severity int

Severity levels for detections.

const (
	SeverityLow Severity = iota
	SeverityMedium
	SeverityHigh
	SeverityCritical
)

func (Severity) MarshalJSON

func (s Severity) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Severity.

func (Severity) String

func (s Severity) String() string

String returns the string representation of Severity.

type ToolCallRecord

type ToolCallRecord struct {
	Timestamp  time.Time `json:"timestamp"`
	ServerID   string    `json:"server_id"`
	ToolName   string    `json:"tool_name"`
	ToolCallID string    `json:"tool_call_id,omitempty"` // "toolu_..." or "call_..."
	RequestID  string    `json:"request_id"`
	Action     string    `json:"action"`   // "allow" or "block"
	Category   string    `json:"category"` // "read", "write", "send", "compute", "unknown"
}

ToolCallRecord captures a single tool call for cross-server analysis.

type ToolClassifier

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

ToolClassifier categorises MCP tool names into semantic buckets (read, write, send, compute, unknown) using prefix matching.

func NewToolClassifier

func NewToolClassifier() *ToolClassifier

NewToolClassifier returns a classifier using the default prefix table.

func (*ToolClassifier) Classify

func (c *ToolClassifier) Classify(toolName string) string

Classify returns the category for the given tool name. It uses simple prefix matching against the known patterns. Tools that don't match any pattern return "unknown".

type ToolDefinition

type ToolDefinition struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	InputSchema json.RawMessage `json:"inputSchema,omitempty"`
}

ToolDefinition represents an MCP tool from tools/list response.

type ToolsCallRequest

type ToolsCallRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Method  string          `json:"method"` // "tools/call"
	Params  struct {
		Name      string          `json:"name"`
		Arguments json.RawMessage `json:"arguments"`
	} `json:"params"`
}

ToolsCallRequest is the JSON-RPC request for tools/call.

func ParseToolsCallRequest

func ParseToolsCallRequest(data []byte) (*ToolsCallRequest, error)

ParseToolsCallRequest parses a tools/call request from raw JSON.

type ToolsCallResponse

type ToolsCallResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Result  struct {
		Content []ContentBlock `json:"content"`
	} `json:"result"`
}

ToolsCallResponse is the JSON-RPC response to tools/call.

func ParseToolsCallResponse

func ParseToolsCallResponse(data []byte) (*ToolsCallResponse, error)

ParseToolsCallResponse parses a tools/call response from raw JSON.

type ToolsListResponse

type ToolsListResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Result  struct {
		Tools []ToolDefinition `json:"tools"`
	} `json:"result"`
}

ToolsListResponse is the JSON-RPC response to tools/list.

func ParseToolsListResponse

func ParseToolsListResponse(data []byte) (*ToolsListResponse, error)

ParseToolsListResponse parses a tools/list response from raw JSON.

type VerifyResult

type VerifyResult struct {
	Status      PinStatus
	PinnedHash  string
	CurrentHash string
}

VerifyResult is returned from pin verification.

Jump to

Keyboard shortcuts

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