mcp

package
v0.16.11 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: BSD-3-Clause, GPL-3.0 Imports: 45 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 mcp implements a Model Context Protocol server that exposes netcap's analytical capabilities as tools, resources, and prompts.

The server is consumed in two deployment modes:

  • "net mcp" CLI subcommand: stdio transport for desktop LLM clients (Claude Desktop, Claude Code, mcp-inspector). PCAP files are ingested locally; an embedded webui.Server is spawned on a loopback port.

  • "net capture --service" HTTP transport at /mcp, protected by a single admin bearer token. Intended for operator access on shared instances (e.g. try.netcap.io). The endpoint is only mounted when a token is configured.

Tool handlers are intentionally thin: they call into the existing webui HTTP API over loopback (token-forwarding pattern) so analytical logic lives in exactly one place.

Index

Constants

View Source
const MaxCarveBytes = 16 << 20 // 16 MiB

MaxCarveBytes caps the per-call sub-PCAP size we'll buffer in memory. Larger carves return a "too big" error and a hint to filter further; shells / external tools can still hit the download_url directly.

View Source
const MaxIOCExtractBytes = 16 << 20

MaxIOCExtractBytes caps the file size we'll process for IOC extraction. Carved files can be large (PE binaries, certificates, etc.); 16 MiB is plenty for the kinds of payloads where IOC hunting makes sense.

View Source
const MaxResponseBytes = 256 * 1024

MaxResponseBytes caps the size of any single tool response body after marshalling. Larger payloads are replaced with a short summary that instructs the LLM to paginate.

Variables

This section is empty.

Functions

This section is empty.

Types

type BackendError added in v0.16.8

type BackendError struct {
	Method, Path string
	StatusCode   int
	Body         json.RawMessage
	// contains filtered or unexported fields
}

BackendError preserves the HTTP status and bounded backend diagnostic body.

func (*BackendError) Error added in v0.16.8

func (e *BackendError) Error() string

func (*BackendError) Unwrap added in v0.16.11

func (e *BackendError) Unwrap() error

type CVELookup

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

CVELookup encapsulates the NVD JSON 2.0 API lookup plus an in-process LRU-ish cache so repeated lookups for the same CVE during one session don't hammer NVD.

NVD's public CVE 2.0 API:

https://services.nvd.nist.gov/rest/json/cves/2.0?cveId=CVE-YYYY-NNNN

The endpoint is anonymous (rate-limited to 5 req / 30 s). For higher throughput an API key would be set via NVD_API_KEY but we don't require one in v1.

func NewCVELookup

func NewCVELookup(enabled bool) *CVELookup

NewCVELookup constructs a lookup helper. When enabled=false (or NETCAP_MCP_DISABLE_NETWORK=1), all calls return a clear "disabled" error instead of making outbound HTTP requests; useful for air-gapped service-mode deployments.

func (*CVELookup) Lookup

func (c *CVELookup) Lookup(cveID string) (map[string]any, error)

Lookup retrieves and normalises one CVE record. The returned map is safe to ship straight to an LLM (id, description, references, CVSS, CWEs, published/lastModified). Errors are returned for transport failure or rate-limiting; an unknown CVE id produces a successful result with `found: false`.

type CarveStore

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

CarveStore keeps carved sub-PCAPs around between MCP requests so the LLM can ask for their bytes via the netcap://carve/{id} resource URI.

Entries are kept in memory; the on-disk copy (if any) lives under CarveStore.dir (defaults to os.TempDir()/netcap-mcp-carve).

A trivial cap is enforced (maxEntries, maxAge) to prevent the LLM from unbounded carving from filling memory or disk. Eviction is FIFO by insertion time.

func NewCarveStore

func NewCarveStore(dir string, maxEntries int, maxAge time.Duration) *CarveStore

NewCarveStore initialises a store; dir defaults when empty.

func (*CarveStore) DeleteSessions added in v0.16.9

func (c *CarveStore) DeleteSessions(ids ...string)

func (*CarveStore) Get

func (c *CarveStore) Get(id string) *carveEntry

Get returns the entry for id, or nil if not found / evicted.

func (*CarveStore) Put

func (c *CarveStore) Put(sessionID, kind, source string, body []byte) (*carveEntry, string, error)

Put stores a carved PCAP and returns the canonical entry plus an MCP resource URI suitable for inclusion in tool responses.

func (*CarveStore) PutTyped added in v0.16.8

func (c *CarveStore) PutTyped(sessionID, kind, source, mime string, body []byte) (*carveEntry, string, error)

func (*CarveStore) Stats

func (c *CarveStore) Stats() (count int, totalBytes int64)

Stats returns counters useful for observability and tests.

type Metrics

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

Metrics aggregates the Prometheus collectors the MCP server publishes. Each Server holds its own *Metrics so multiple MCP instances in one process (e.g. test cases) don't fight over a shared global registry.

Exposed on the operator's choice of mount point — by default we attach promhttp at /mcp/metrics. The mount only happens when an admin token is set, mirroring the auth posture of the MCP endpoint itself: nobody without the token can scrape the metrics.

func NewMetrics

func NewMetrics() *Metrics

NewMetrics constructs a fresh registry plus the canonical collector set. Labels are kept short (tool name, status) so cardinality stays bounded by the tool catalogue size.

func (*Metrics) Handler

func (m *Metrics) Handler() http.Handler

Handler returns an http.Handler exposing the registered collectors in Prometheus text format.

type NetcapClient

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

NetcapClient is a thin HTTP client that talks to a netcap webui.Server over loopback. It exists so MCP tool handlers stay 5-line transformers and the analytical logic remains in exactly one place (the webui handlers).

func NewAuthenticatedNetcapClient added in v0.16.7

func NewAuthenticatedNetcapClient(baseURL, token string) *NetcapClient

func NewNetcapClient

func NewNetcapClient(baseURL string) *NetcapClient

NewNetcapClient constructs a client targeting baseURL (e.g. "http://127.0.0.1:54321"). The default timeout is generous (5 minutes) because some endpoints (YARA, reanalyze) genuinely take that long.

func (*NetcapClient) BaseURL

func (c *NetcapClient) BaseURL() string

BaseURL returns the configured webui base URL, useful for forming downloadable artefact URLs in tool responses.

func (*NetcapClient) Get

func (c *NetcapClient) Get(path string, query url.Values) (json.RawMessage, error)

Get performs GET <path>?<query> against the webui and returns the raw response body. Non-2xx responses are returned as errors with a truncated body for context.

func (*NetcapClient) GetAs

func (c *NetcapClient) GetAs[T any](path string, query url.Values) (T, error)

GetAs performs Get and decodes the response, returning the zero value on error.

func (*NetcapClient) GetContext added in v0.16.0

func (c *NetcapClient) GetContext(ctx context.Context, path string, query url.Values) (json.RawMessage, error)

func (*NetcapClient) GetRaw

func (c *NetcapClient) GetRaw(path string, query url.Values) ([]byte, string, error)

GetRaw returns the response bytes for endpoints that don't reply in JSON (e.g. /api/extracted-files/download/<id> which streams binary).

func (*NetcapClient) GetRawContext added in v0.16.8

func (c *NetcapClient) GetRawContext(ctx context.Context, path string, query url.Values) ([]byte, string, error)

func (*NetcapClient) PostEmpty

func (c *NetcapClient) PostEmpty(path string, query url.Values) (json.RawMessage, error)

PostEmpty sends a POST with no body and optional query params — used to trigger actions that take no body (yara scan, execute rules).

func (*NetcapClient) PostEmptyContext added in v0.16.8

func (c *NetcapClient) PostEmptyContext(ctx context.Context, path string, query url.Values) (json.RawMessage, error)

func (*NetcapClient) PostForm

func (c *NetcapClient) PostForm(path string, form url.Values) (json.RawMessage, error)

PostForm sends an application/x-www-form-urlencoded POST.

func (*NetcapClient) PostJSON

func (c *NetcapClient) PostJSON(path string, body any) (json.RawMessage, error)

PostJSON sends a JSON-encoded POST request and returns the raw response.

func (*NetcapClient) PostJSONContext added in v0.16.0

func (c *NetcapClient) PostJSONContext(ctx context.Context, path string, body any) (json.RawMessage, error)

func (*NetcapClient) StreamAuditRecords

func (c *NetcapClient) StreamAuditRecords(auditType string, q url.Values, maxBytes int) (records []json.RawMessage, completeJSON json.RawMessage, terminalEvent string, err error)

StreamAuditRecords consumes /api/audit/<auditType>/stream as Server-Sent Events and returns the slice of "record" events plus the terminal "complete" payload. It rejects records beyond the requested limit and reads up to maxBytes from the wire.

Server SSE event semantics:

event: record    -> data is one JSON-encoded audit record
event: progress  -> data is {count, scanned}
event: complete  -> data is {total, scanned, executionTimeMs}
event: error     -> data is {error}

Returns:

  • records: the per-record JSON payloads
  • completeJSON: the JSON object from the final "complete" event (or "error" payload if that came first)
  • terminalEvent: "complete" or "error"
  • err: transport or parse error (not an SSE "event: error" — that's surfaced in terminalEvent)

func (*NetcapClient) UploadPCAP

func (c *NetcapClient) UploadPCAP(pcapPath string) (json.RawMessage, error)

UploadPCAP uploads a PCAP/PCAPNG file via the webui's /api/upload multipart endpoint. The file is streamed from disk; no in-memory copy.

func (*NetcapClient) UploadPCAPContext added in v0.16.8

func (c *NetcapClient) UploadPCAPContext(ctx context.Context, pcapPath string) (json.RawMessage, error)

type Options

type Options struct {
	// BaseURL of the netcap webui API. Required.
	BaseURL string
	// AdminToken, if non-empty, is required as a Bearer token on the HTTP
	// transport. Ignored by the stdio transport.
	AdminToken string
	// BackendToken authenticates internal API requests; defaults to AdminToken.
	BackendToken string
	// ActiveSession marks a single pre-loaded session as the default for
	// the CLI stdio server (so LLMs can discover it without arguments).
	// May be a 32-char hex (service id) or an absolute PCAP path (local).
	ActiveSession string
	// AllowedTools / DisallowedTools optionally restrict which tools are
	// registered (post-name validation). Empty lists mean no restriction.
	AllowedTools    []string
	DisallowedTools []string
	// Logger receives diagnostic messages. Defaults to stderr.
	Logger *log.Logger

	// AllowNetwork enables outbound HTTP for tools that talk to the
	// public internet (e.g. lookup_cve hits NVD). Default false in
	// air-gapped service-mode operators' environments. Set
	// NETCAP_MCP_DISABLE_NETWORK=1 to force-disable regardless of this
	// field.
	AllowNetwork bool

	// CarveDir overrides the on-disk location for carved sub-PCAPs.
	// Default: os.TempDir()/netcap-mcp-carve.
	CarveDir string
}

Options configures a Server.

type SSERecord

type SSERecord struct {
	Event string          // "record", "progress", "complete", "error"
	Data  json.RawMessage // event payload (verbatim JSON)
}

SSERecord is one decoded event from the audit-record stream endpoint.

type Server

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

Server is the top-level MCP server. A single Server instance can be exposed via either an HTTP handler (service mode) or stdio (CLI).

func New

func New(opts Options) (*Server, error)

New constructs a Server, registers tools/resources/prompts, and returns it. The returned Server has not yet been bound to a transport; call HTTPHandler or ServeStdio.

func (*Server) AuthedMetricsHandler

func (s *Server) AuthedMetricsHandler() http.Handler

AuthedMetricsHandler wraps MetricsHandler in the same admin-token middleware as the /mcp endpoint. This is what operators want for production: scrapers inside the trust boundary include the token, random internet doesn't get to read tool-call latencies.

func (*Server) Close added in v0.16.8

func (s *Server) Close()

Close cancels owned bounded listener/proxy jobs; it does not remove evidence.

func (*Server) GenerateToolDocs

func (s *Server) GenerateToolDocs(header string) string

GenerateToolDocs produces the canonical markdown tool catalogue derived from the live registered tool set. The output is intended for docs/mcp/tools.md; a CI parity test (TestToolDocsUpToDate) compares this to the on-disk file and fails the build if they drift.

The format is stable: tool sections are alphabetical, argument tables are emitted in JSON-schema property order. Hand-edit the markdown header by passing it as `header`; the body is fully regenerated.

func (*Server) HTTPHandler

func (s *Server) HTTPHandler() http.Handler

HTTPHandler returns an http.Handler that serves the MCP endpoint over streamable HTTP at /mcp. The returned handler wraps the mcp-go transport in admin-token authentication.

func (*Server) Logger

func (s *Server) Logger() *log.Logger

Logger returns the diagnostic logger (mainly for tests).

func (*Server) MetricsHandler

func (s *Server) MetricsHandler() http.Handler

MetricsHandler returns the Prometheus scrape handler, ready to be mounted at /mcp/metrics (or any operator-chosen path). Does NOT include auth — callers that want the standard /mcp admin-token posture should use AuthedMetricsHandler.

func (*Server) ServeStdio

func (s *Server) ServeStdio(ctx context.Context) error

ServeStdio runs the server over stdio until the context is cancelled or stdin is closed. Intended for `net mcp` CLI usage with desktop clients.

func (*Server) TokenFingerprint

func (s *Server) TokenFingerprint() string

TokenFingerprint returns the first 8 hex chars of the SHA-256 of the admin token, suitable for logging at startup. Empty string when no token is configured.

type SessionRef

type SessionRef struct {
	ID string
	// contains filtered or unexported fields
}

SessionRef is the abstraction the MCP server uses to address an analysis across both webui deployment modes:

  • Uploaded analyses: opaque id in both service and local modes.
  • Legacy local inputs: absolute filesystem path to a PCAP/PCAPNG.

The webui's session_resolver.resolveOutDirFromRequest accepts either shape via the ?sessionId= and ?inputFile= query parameters, so the MCP layer only needs to know which kind it has.

Directories

Path Synopsis
Package bindings implements immutable operator-enrolled MCP authorities.
Package bindings implements immutable operator-enrolled MCP authorities.

Jump to

Keyboard shortcuts

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