Skip to content

Complete API Reference

Overview

This document provides a comprehensive API reference for all mcp-scan packages and components.

Package Index

Package Description Import Path
scanner Public API for scanning github.com/mcphub/mcp-scan/pkg/scanner
types Shared type definitions github.com/mcphub/mcp-scan/internal/types
ast AST representation github.com/mcphub/mcp-scan/internal/ast
parser Tree-sitter parsing github.com/mcphub/mcp-scan/internal/parser
surface MCP surface extraction github.com/mcphub/mcp-scan/internal/surface
taint Taint analysis engine github.com/mcphub/mcp-scan/internal/taint
pattern Pattern-based detection github.com/mcphub/mcp-scan/internal/pattern
typeinfo Type inference github.com/mcphub/mcp-scan/internal/typeinfo
imports Import resolution github.com/mcphub/mcp-scan/internal/imports
callgraph Call graph analysis github.com/mcphub/mcp-scan/internal/callgraph
lsp LSP client github.com/mcphub/mcp-scan/internal/lsp
codeql CodeQL integration github.com/mcphub/mcp-scan/internal/codeql
ml ML classifier github.com/mcphub/mcp-scan/internal/ml
llm LLM detection github.com/mcphub/mcp-scan/internal/llm
catalog Sources/sinks catalog github.com/mcphub/mcp-scan/internal/catalog
reporter Output formatting github.com/mcphub/mcp-scan/internal/reporter

types Package

Severity

type Severity string

const (
    SeverityInfo     Severity = "info"
    SeverityLow      Severity = "low"
    SeverityMedium   Severity = "medium"
    SeverityHigh     Severity = "high"
    SeverityCritical Severity = "critical"
)

// SeverityFromString parses a severity string
func SeverityFromString(s string) Severity

// Level returns numeric level for comparison
func (s Severity) Level() int

Confidence

type Confidence string

const (
    ConfidenceLow    Confidence = "low"
    ConfidenceMedium Confidence = "medium"
    ConfidenceHigh   Confidence = "high"
)

VulnClass

type VulnClass string

const (
    ClassA       VulnClass = "A"       // RCE
    ClassB       VulnClass = "B"       // Filesystem
    ClassC       VulnClass = "C"       // SSRF/Network
    ClassD       VulnClass = "D"       // SQL Injection
    ClassE       VulnClass = "E"       // Secrets
    ClassF       VulnClass = "F"       // Auth/OAuth
    ClassG       VulnClass = "G"       // Tool Poisoning
    ClassH       VulnClass = "H"       // Declaration vs Behavior
    ClassI       VulnClass = "I"       // Multi-tool Flows
    ClassJ       VulnClass = "J"       // Memory Injection
    ClassK       VulnClass = "K"       // Task Queue
    ClassL       VulnClass = "L"       // Plugin Lifecycle
    ClassM       VulnClass = "M"       // Hidden Network
    ClassN       VulnClass = "N"       // Supply Chain
    ClassUnknown VulnClass = "unknown"
)

Language

type Language string

const (
    Python     Language = "python"
    TypeScript Language = "typescript"
    JavaScript Language = "javascript"
    Go         Language = "go"
)

Location

type Location struct {
    File      string `json:"file"`
    StartLine int    `json:"start_line"`
    StartCol  int    `json:"start_col"`
    EndLine   int    `json:"end_line"`
    EndCol    int    `json:"end_col"`
}

func (l Location) String() string

Finding

type Finding struct {
    ID          string      `json:"id"`
    RuleID      string      `json:"rule_id"`
    Title       string      `json:"title,omitempty"`
    Severity    Severity    `json:"severity"`
    Confidence  Confidence  `json:"confidence"`
    Class       VulnClass   `json:"class,omitempty"`
    Language    Language    `json:"language"`
    Location    Location    `json:"location"`
    MCPContext  *MCPContext `json:"mcp_context,omitempty"`
    Trace       *TaintTrace `json:"trace,omitempty"`
    Evidence    Evidence    `json:"evidence"`
    Description string      `json:"description"`
    Remediation string      `json:"remediation"`
}

func (f *Finding) GenerateID() string

Evidence

type Evidence struct {
    Snippet         string      `json:"snippet,omitempty"`
    SnippetHash     string      `json:"snippet_hash,omitempty"`
    Trace           []TraceStep `json:"trace,omitempty"`
    LLMAnalysis     string      `json:"llm_analysis,omitempty"`
    LLMConfidence   float64     `json:"llm_confidence,omitempty"`
    LLMCategory     string      `json:"llm_category,omitempty"`
    CodeQLConfirmed bool        `json:"codeql_confirmed,omitempty"`
}

TraceStep

type TraceStep struct {
    Location Location `json:"location"`
    Action   string   `json:"action"`
    Variable string   `json:"variable,omitempty"`
}

TaintTrace

type TaintTrace struct {
    Source Location    `json:"source"`
    Sink   Location    `json:"sink"`
    Steps  []TraceStep `json:"steps"`
}

MCPContext

type MCPContext struct {
    ToolName    string `json:"tool_name,omitempty"`
    HandlerName string `json:"handler_name,omitempty"`
    Transport   string `json:"transport,omitempty"`
}

Summary

type Summary struct {
    Total      int            `json:"total"`
    BySeverity map[string]int `json:"by_severity"`
    ByClass    map[string]int `json:"by_class"`
    ByLanguage map[string]int `json:"by_language"`
}

func NewSummary() *Summary
func (s *Summary) Add(f *Finding, class VulnClass)

typeinfo Package

TypeKind

type TypeKind string

const (
    TypeString   TypeKind = "string"
    TypeInt      TypeKind = "int"
    TypeFloat    TypeKind = "float"
    TypeBool     TypeKind = "bool"
    TypeList     TypeKind = "list"
    TypeDict     TypeKind = "dict"
    TypeSet      TypeKind = "set"
    TypeTuple    TypeKind = "tuple"
    TypeObject   TypeKind = "object"
    TypeCallable TypeKind = "callable"
    TypeNone     TypeKind = "none"
    TypeAny      TypeKind = "any"
    TypeUnion    TypeKind = "union"
    TypeOptional TypeKind = "optional"
    TypeUnknown  TypeKind = "unknown"
)

TypeInfo

type TypeInfo struct {
    Kind        TypeKind
    Name        string
    ElementType *TypeInfo
    KeyType     *TypeInfo
    ValueType   *TypeInfo
    UnionTypes  []*TypeInfo
    ClassName   string
    Module      string
    Generic     []*TypeInfo
    Nullable    bool
}

func (t *TypeInfo) String() string
func (t *TypeInfo) IsNumeric() bool
func (t *TypeInfo) IsCollection() bool
func (t *TypeInfo) IsDangerous() bool

TypeContext

type TypeContext struct {
    Variables map[string]*TypeInfo
    Functions map[string]*FunctionType
    Classes   map[string]*ClassType
    Imports   map[string]*TypeInfo
}

func NewTypeContext() *TypeContext
func (c *TypeContext) AddVariable(name string, typ *TypeInfo)
func (c *TypeContext) GetVariable(name string) *TypeInfo
func (c *TypeContext) AddFunction(name string, fn *FunctionType)
func (c *TypeContext) GetFunction(name string) *FunctionType

FunctionType

type FunctionType struct {
    Name       string
    Parameters []*ParameterType
    ReturnType *TypeInfo
    IsAsync    bool
    IsMethod   bool
    ClassName  string
}

Inferrer Interface

type Inferrer interface {
    InferExpression(expr ast.Expression, ctx *TypeContext) *TypeInfo
    InferAssignment(stmt *ast.Assignment, ctx *TypeContext) *TypeInfo
    InferFunction(fn *ast.Function) *FunctionType
    InferCall(call *ast.Call, ctx *TypeContext) *TypeInfo
}

Language-Specific Inferrers

// Python inferrer
func NewPythonInferrer() *PythonInferrer
func (p *PythonInferrer) InferExpression(expr ast.Expression, ctx *TypeContext) *TypeInfo

// TypeScript inferrer
func NewTypeScriptInferrer() *TypeScriptInferrer
func (t *TypeScriptInferrer) InferExpression(expr ast.Expression, ctx *TypeContext) *TypeInfo

imports Package

ImportResolver

type ImportResolver struct {
    // private fields
}

func NewResolver(rootPath string, language types.Language) *ImportResolver
func (r *ImportResolver) ResolveImport(imp *ast.Import, fromFile string) (*ResolvedImport, error)
func (r *ImportResolver) IndexFiles(files []*ast.File)
func (r *ImportResolver) GetModulePath(module string) string
func (r *ImportResolver) ListModules() []string

ResolvedImport

type ResolvedImport struct {
    SourceFile   string
    SourceModule string
    ImportedAs   string
    Symbols      []ImportedSymbol
    IsPackage    bool
}

ImportedSymbol

type ImportedSymbol struct {
    Name       string
    Alias      string
    Definition interface{}
    Location   types.Location
    Kind       SymbolKind
}

type SymbolKind string

const (
    SymbolFunction SymbolKind = "function"
    SymbolClass    SymbolKind = "class"
    SymbolVariable SymbolKind = "variable"
    SymbolType     SymbolKind = "type"
    SymbolModule   SymbolKind = "module"
)

callgraph Package

CallGraph

type CallGraph struct {
    Nodes    map[string]*Node
    Edges    map[string][]*Edge
    Files    map[string][]string
    Version  string
    Metadata *Metadata
}

func NewCallGraph() *CallGraph
func (g *CallGraph) AddNode(node *Node)
func (g *CallGraph) AddEdge(from, to string, callSite types.Location)
func (g *CallGraph) GetNode(id string) *Node
func (g *CallGraph) GetCallers(funcID string) []*Edge
func (g *CallGraph) GetCallees(funcID string) []*Edge

Node

type Node struct {
    ID        string
    Name      string
    File      string
    Class     string
    Line      int
    Signature string
    IsPublic  bool
    IsTool    bool
    Summary   *FunctionSummary
}

Edge

type Edge struct {
    From     string
    To       string
    CallSite types.Location
    Type     EdgeType
}

type EdgeType string

const (
    EdgeDirect   EdgeType = "direct"
    EdgeMethod   EdgeType = "method"
    EdgeCallback EdgeType = "callback"
    EdgeDynamic  EdgeType = "dynamic"
)

Builder

type Builder struct {
    // private fields
}

func NewBuilder(resolver *imports.ImportResolver) *Builder
func (b *Builder) Build(files []*ast.File) *CallGraph
func (b *Builder) BuildIncremental(graph *CallGraph, changedFiles []*ast.File) error

Persistence

func (g *CallGraph) Save(path string) error
func Load(path string) (*CallGraph, error)
func (g *CallGraph) IsValid(fileHashes map[string]string) bool
func (g *CallGraph) InvalidatedFiles(fileHashes map[string]string) []string

lsp Package

Client

type Client struct {
    // private fields
}

func NewClient(ctx context.Context, language, rootPath string) (*Client, error)
func (c *Client) Close() error
func (c *Client) Call(ctx context.Context, method string, params, result interface{}) error
func (c *Client) Notify(ctx context.Context, method string, params interface{}) error

Client Operations

func (c *Client) GetHover(ctx context.Context, uri string, line, character uint32) (*Hover, error)
func (c *Client) GetTypeInfo(ctx context.Context, uri string, line, character uint32) (*TypeInfo, error)
func (c *Client) GetDefinition(ctx context.Context, uri string, line, character uint32) ([]Definition, error)
func (c *Client) GetReferences(ctx context.Context, uri string, line, character uint32, includeDecl bool) ([]Definition, error)
func (c *Client) GetDocumentSymbols(ctx context.Context, uri string) ([]Symbol, error)
func (c *Client) PrepareCallHierarchy(ctx context.Context, uri string, line, character uint32) ([]CallHierarchyItem, error)
func (c *Client) GetIncomingCalls(ctx context.Context, item CallHierarchyItem) ([]CallHierarchyIncomingCall, error)
func (c *Client) GetOutgoingCalls(ctx context.Context, item CallHierarchyItem) ([]CallHierarchyOutgoingCall, error)
func (c *Client) BuildCallGraph(ctx context.Context, uri string, line, character uint32, maxDepth int) (*CallGraphNode, error)

Manager

type Manager struct {
    // private fields
}

func NewManager(rootPath string) *Manager
func (m *Manager) GetClient(ctx context.Context, language string) (*Client, error)
func (m *Manager) CloseAll() error

Types

type Position struct {
    Line      uint32 `json:"line"`
    Character uint32 `json:"character"`
}

type Range struct {
    Start Position `json:"start"`
    End   Position `json:"end"`
}

type Location struct {
    URI   string `json:"uri"`
    Range Range  `json:"range"`
}

type Hover struct {
    Contents MarkupContent `json:"contents"`
    Range    *Range        `json:"range,omitempty"`
}

type TypeInfo struct {
    Signature   string
    ReturnType  string
    Parameters  []string
    Description string
    Kind        string
}

type Definition struct {
    URI         string
    StartLine   uint32
    StartColumn uint32
    EndLine     uint32
    EndColumn   uint32
}

type CallGraphNode struct {
    Name    string
    URI     string
    Kind    SymbolKind
    Range   Range
    Callers []*CallGraphEdge
    Callees []*CallGraphEdge
}

codeql Package

Client

type Client struct {
    // private fields
}

type Config struct {
    BinaryPath string
    Timeout    time.Duration
    QueriesDir string
    Cache      bool
}

func DefaultConfig() Config
func NewClient(cfg Config) (*Client, error)
func IsAvailable() bool
func (c *Client) Version(ctx context.Context) (string, error)
func (c *Client) CreateDatabase(ctx context.Context, sourcePath, dbPath, language string) error
func (c *Client) AnalyzeDatabase(ctx context.Context, dbPath, outputPath string, queries ...string) error
func (c *Client) ScanDirectory(ctx context.Context, sourcePath, language string, queries ...string) (*SARIFReport, error)
func (c *Client) RunQuery(ctx context.Context, dbPath, queryPath string) (*SARIFReport, error)
func (c *Client) SupportedLanguages(ctx context.Context) ([]string, error)

SARIF Types

type SARIFReport struct {
    Schema  string `json:"$schema"`
    Version string `json:"version"`
    Runs    []Run  `json:"runs"`
}

func ParseSARIFFile(path string) (*SARIFReport, error)
func ParseSARIF(data []byte) (*SARIFReport, error)
func (s *SARIFReport) GetResults() []Result
func (s *SARIFReport) GetRules() []Rule
func (s *SARIFReport) FindRule(id string) *Rule

type Result struct {
    RuleID    string     `json:"ruleId"`
    Level     string     `json:"level"`
    Message   Message    `json:"message"`
    Locations []Location `json:"locations"`
    CodeFlows []CodeFlow `json:"codeFlows,omitempty"`
}

Analyzer

type AnalyzerConfig struct {
    QueriesDir    string
    Languages     []string
    CustomQueries []string
    MinSeverity   float64
}

type Analyzer struct {
    // private fields
}

func NewAnalyzer(cfg AnalyzerConfig) (*Analyzer, error)
func (a *Analyzer) Analyze(ctx context.Context, sourcePath string) ([]types.Finding, error)

ml Package

Classifier

type Classifier struct {
    // private fields
}

func LoadClassifier() (*Classifier, error)
func LoadClassifierFromFile(path string) (*Classifier, error)
func (c *Classifier) Predict(text string) (bool, float64)
func (c *Classifier) PredictBatch(texts []string) []PredictionResult

type PredictionResult struct {
    IsInjection bool
    Probability float64
}

Features

type Features struct {
    UnigramCounts    map[string]int
    BigramCounts     map[string]int
    TrigramCounts    map[string]int
    Length           int
    WordCount        int
    AvgWordLength    float64
    UppercaseRatio   float64
    DigitRatio       float64
    SpecialCharRatio float64
    KeywordCount     int
    DelimiterCount   int
    QuestionCount    int
    ImperativeCount  int
    CharEntropy      float64
    WordEntropy      float64
    StartsWithKeyword bool
    EndsWithQuestion  bool
}

func ExtractFeatures(text string) *Features
func (f *Features) ToVector(vocab map[string]int) []float64

llm Package

Client

type Client struct {
    // private fields
}

type Config struct {
    BaseURL string
    Model   string
    Timeout time.Duration
}

func DefaultConfig() Config
func NewClient(cfg Config) *Client
func (c *Client) IsAvailable() bool
func (c *Client) Generate(ctx context.Context, prompt string) (string, error)
func (c *Client) GenerateJSON(ctx context.Context, prompt string, result interface{}) error
func (c *Client) ListModels(ctx context.Context) ([]string, error)
func (c *Client) SetModel(model string)
func (c *Client) GetModel() string

Detector

type Detector struct {
    // private fields
}

type DetectorConfig struct {
    Threshold float64
}

type InjectionResult struct {
    IsInjection bool    `json:"is_injection"`
    Confidence  float64 `json:"confidence"`
    Category    string  `json:"category"`
    Reason      string  `json:"reason"`
}

func NewDetector(client *Client, cfg DetectorConfig) *Detector
func (d *Detector) Analyze(ctx context.Context, text string) (*InjectionResult, error)
func (d *Detector) IsInjection(ctx context.Context, text string) (bool, float64, error)
func (d *Detector) BatchAnalyze(ctx context.Context, texts []string) ([]*InjectionResult, error)
func (d *Detector) SetThreshold(threshold float64)
func (d *Detector) GetThreshold() float64

pattern Package

Engine

type Engine struct {
    // private fields
}

func New() *Engine
func (e *Engine) AddRule(rule *Rule)
func (e *Engine) SetSeverityOverride(ruleID string, severity types.Severity)
func (e *Engine) SetDisabledRule(ruleID string)
func (e *Engine) IsRuleDisabled(ruleID string) bool
func (e *Engine) GetEffectiveSeverity(ruleID string, defaultSeverity types.Severity) types.Severity
func (e *Engine) AddCustomRule(id, pattern string, severity types.Severity, confidence types.Confidence, description, remediation string, languages []types.Language, class types.VulnClass) error
func (e *Engine) GetRules() []*Rule
func (e *Engine) Analyze(files []*ast.File, surf *surface.MCPSurface) []types.Finding
func (e *Engine) AnalyzeFile(file *ast.File, surf *surface.MCPSurface) []types.Finding

Rule

type Rule struct {
    ID          string
    Class       types.VulnClass
    Language    []types.Language
    Severity    types.Severity
    Confidence  types.Confidence
    Description string
    Remediation string
    Detector    Detector
}

Match

type Match struct {
    Location    types.Location
    Snippet     string
    Context     string
    Confidence  types.Confidence
    RuleID      string
    Title       string
    Description string
    Severity    types.Severity
    Class       types.VulnClass
    Remediation string
    Evidence    Evidence
}

type Evidence struct {
    Snippet         string
    Trace           []TraceStep
    LLMAnalysis     string
    LLMConfidence   float64
    LLMCategory     string
    CodeQLConfirmed bool
}

Detector Interface

type Detector interface {
    Detect(file *ast.File, surface *surface.MCPSurface) []Match
}

Specialized Detectors

// LSP Detector
type LSPDetectorConfig struct {
    RootPath  string
    Languages []string
}

func NewLSPDetector(cfg LSPDetectorConfig) (*LSPDetector, error)
func (d *LSPDetector) Detect(ctx context.Context, file *ast.File, mcpSurface *surface.MCPSurface) []Match
func (d *LSPDetector) IsEnabled() bool
func (d *LSPDetector) Close() error

// CodeQL Detector
type CodeQLDetectorConfig struct {
    QueriesDir    string
    Languages     []string
    CustomQueries []string
    MinSeverity   float64
}

func NewCodeQLDetector(cfg CodeQLDetectorConfig) (*CodeQLDetector, error)
func (d *CodeQLDetector) DetectProject(ctx context.Context, sourcePath string) ([]Match, error)
func (d *CodeQLDetector) IsEnabled() bool

// LLM Detector
type LLMDetectorConfig struct {
    BaseURL   string
    Model     string
    Threshold float64
    MaxLength int
}

func NewLLMDetector(cfg LLMDetectorConfig) (*LLMDetector, error)
func (d *LLMDetector) Detect(ctx context.Context, file *ast.File, surface *surface.MCPSurface) []Match
func (d *LLMDetector) IsEnabled() bool

// ML Detector
func NewMLInjectionDetector() (*MLInjectionDetector, error)
func (d *MLInjectionDetector) Detect(file *ast.File, surface *surface.MCPSurface) []Match
func (d *MLInjectionDetector) IsEnabled() bool

// Extended Injection Detector
func NewExtendedInjectionDetector() *ExtendedInjectionDetector
func (d *ExtendedInjectionDetector) Detect(file *ast.File, surface *surface.MCPSurface) []Match

// Prompt Flow Detector
func NewPromptFlowDetector() *PromptFlowDetector
func (d *PromptFlowDetector) Detect(file *ast.File, surface *surface.MCPSurface) []Match

// Exfiltration Detector
func NewExfiltrationDetector() *ExfiltrationDetector
func (d *ExfiltrationDetector) Detect(file *ast.File, surface *surface.MCPSurface) []Match

catalog Package

Source Definitions

type SourceDef struct {
    ID        string
    Language  types.Language
    Pattern   string
    Receiver  string
    Function  string
    Category  SourceCategory
}

type SourceCategory string

const (
    SourceToolInput   SourceCategory = "tool_input"
    SourceEnvVar      SourceCategory = "env_var"
    SourceHTTPRequest SourceCategory = "http_request"
    SourceFileContent SourceCategory = "file_content"
    SourceDBResult    SourceCategory = "db_result"
)

func GetSources(language types.Language) []SourceDef
func GetAllSources() []SourceDef

Sink Definitions

type SinkDef struct {
    ID        string
    Language  types.Language
    Receiver  string
    Function  string
    Category  SinkCategory
    Severity  types.Severity
    ArgIndex  int
    ArgName   string
    VulnClass types.VulnClass
}

type SinkCategory string

const (
    SinkExec       SinkCategory = "exec"
    SinkEval       SinkCategory = "eval"
    SinkFilesystem SinkCategory = "filesystem"
    SinkNetwork    SinkCategory = "network"
    SinkDatabase   SinkCategory = "database"
    SinkLLMPrompt  SinkCategory = "llm_prompt"
)

func GetSinks(language types.Language) []SinkDef
func GetAllSinks() []SinkDef
func GetLLMSinks() []SinkDef

Sanitizer Definitions

type SanitizerDef struct {
    ID       string
    Language types.Language
    Pattern  string
    Receiver string
    Function string
    Category SanitizerCategory
    Breaks   []SinkCategory
}

type SanitizerCategory string

const (
    SanitizerShellEscape   SanitizerCategory = "shell_escape"
    SanitizerHTMLEscape    SanitizerCategory = "html_escape"
    SanitizerSQLParam      SanitizerCategory = "sql_param"
    SanitizerPathNormalize SanitizerCategory = "path_normalize"
)

func GetSanitizers(language types.Language) []SanitizerDef
func GetAllSanitizers() []SanitizerDef

Error Types

Common Errors

var (
    ErrFileNotFound     = errors.New("file not found")
    ErrParseError       = errors.New("parse error")
    ErrUnsupportedLang  = errors.New("unsupported language")
    ErrLSPNotAvailable  = errors.New("LSP server not available")
    ErrCodeQLNotFound   = errors.New("CodeQL CLI not found")
    ErrOllamaNotRunning = errors.New("Ollama server not running")
    ErrTimeout          = errors.New("operation timed out")
)

See Also