mcp

package
v0.1.124 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Overview

Package mcp implements the csx MCP stdio server (plan contract C8, goal.md §12.4): newline-delimited JSON-RPC 2.0 over a provided reader and writer, exposing the eight local tools coding agents consume. The server is transport-only here; the actual behavior is injected through Deps so the daemonless in-process wiring (NewDeps) and tests share one protocol path. `publish_public_sample` is deliberately absent — MCP must never be able to publish autonomously (goal.md §3.11, §12.4).

Index

Constants

View Source
const ProtocolVersion = "2025-06-18"

ProtocolVersion is the MCP protocol revision this server speaks.

View Source
const ServerName = "codesamplex"

ServerName is the serverInfo.name reported by initialize.

Variables

View Source
var ErrAnomalyLocalOnly = errors.New(
	"this install is local-only, so nothing is uploaded and no verification can be requested. " +
		"The mismatch you found is real and worth acting on locally; `csx init --community` " +
		"is what would let the network re-verify it")

ErrAnomalyLocalOnly is returned in local-only mode. It is not a failure: the mode exists to send nothing, and a report is a thing that is sent.

View Source
var ErrCSXIssueLocalOnly = errors.New(
	"this install is local-only, so nothing is uploaded and no report can be submitted. " +
		"The problem you found is still real; `csx init --community` is what would let it be reported")

ErrCSXIssueLocalOnly mirrors ErrAnomalyLocalOnly: the mode exists to send nothing, and a report is a thing that is sent.

Functions

func PrepareAnomalyReport added in v0.1.46

func PrepareAnomalyReport(report domain.AnomalyReport, rawErrorText string,
	machine domain.EnvironmentFingerprint) (domain.AnomalyReport, bool, error)

PrepareAnomalyReport turns tool arguments into a submittable report, or says why it cannot be one.

Redaction happens BEFORE validation deliberately. A report is refused for what it does not measure, never for what it accidentally included — and the thing it accidentally included must be gone either way, including from the error message.

func PrepareCSXIssueReport added in v0.1.46

func PrepareCSXIssueReport(report domain.CSXIssueReport) (domain.CSXIssueReport, bool, error)

PrepareCSXIssueReport redacts the prose and applies the admission test before anything reaches the wire.

func SetUpdateNotice added in v0.1.12

func SetUpdateNotice(text string)

SetUpdateNotice records that a verified replacement is on disk. The stdio process remains client-owned and deliberately never terminates itself.

func ToolNames added in v0.1.70

func ToolNames() []string

ToolNames is every tool this server registers, in the order it offers them.

Exported so the public page that documents the MCP surface can be checked against the surface itself. It claimed to be complete and listed eight of ten: report_anomaly and report_csx_issue were added to the server and never to the page, and nothing could notice because the page's list was hand-kept.

Types

type AnomalySubmission added in v0.1.46

type AnomalySubmission struct {
	ReportID          int64  `json:"reportId"`
	Status            string `json:"status"`
	ReportStatus      string `json:"reportStatus,omitempty"`
	Verdict           string `json:"verdict,omitempty"`
	VerificationState string `json:"verificationState"`
	VerificationJobID int64  `json:"verificationJobId,omitempty"`
	MatchedReportID   int64  `json:"matchedReportId,omitempty"`
	Submissions       int64  `json:"submissions,omitempty"`
	RetryAfterSeconds int64  `json:"retryAfterSeconds,omitempty"`
	Redacted          bool   `json:"redacted,omitempty"`
	Reason            string `json:"reason,omitempty"`
	Note              string `json:"note"`
}

AnomalySubmission is the server's answer, as an agent needs to read it.

VerificationState and Note travel because the failure mode this channel has is not a lost report, it is an agent telling its user "I reported the bug" in a sentence that sounds like "the bug is fixed". Nothing else can prevent that except the words that come back.

func SubmitAnomalyReport added in v0.1.46

func SubmitAnomalyReport(ctx context.Context, client *http.Client, serverURL, epoch, anonID string,
	report domain.AnomalyReport) (AnomalySubmission, error)

SubmitAnomalyReport posts one prepared report and returns the server's answer. It never retries: a lost response is answered by asking again, and the fingerprint makes that safe.

type CSXIssueSubmission added in v0.1.46

type CSXIssueSubmission struct {
	ReportID          int64  `json:"reportId"`
	Status            string `json:"status"`
	ReportStatus      string `json:"reportStatus,omitempty"`
	Verdict           string `json:"verdict,omitempty"`
	CanonicalRef      string `json:"canonicalRef,omitempty"`
	Occurrences       int64  `json:"occurrences,omitempty"`
	MatchedReportID   int64  `json:"matchedReportId,omitempty"`
	RetryAfterSeconds int64  `json:"retryAfterSeconds,omitempty"`
	Redacted          bool   `json:"redacted,omitempty"`
	ReplayReason      string `json:"replayReason,omitempty"`
	Note              string `json:"note"`
}

CSXIssueSubmission is the server's answer to a product-defect report.

TicketFiled does not exist as a field because no ticket is ever filed. What travels instead is CanonicalRef — set only when an operator has already linked this defect to a bug — and a Note that tells the agent, in the words the client renders, not to claim otherwise.

func SubmitCSXIssueReport added in v0.1.46

func SubmitCSXIssueReport(ctx context.Context, client *http.Client, serverURL, epoch, anonID string,
	report domain.CSXIssueReport) (CSXIssueSubmission, error)

SubmitCSXIssueReport posts one prepared report. Like the anomaly path it never retries: the fingerprint makes asking again safe.

type Deps

type Deps struct {
	// Search runs the C7 pipeline over the local store. offerID is an opaque
	// local-only capability for the recorded top result; it is empty on a
	// miss or when local recording failed.
	Search func(ctx context.Context, req domain.SearchRequest) (resp domain.SearchResponse, offerID string)
	// SearchRaw performs retrieval without recording a hit/offer. toolSearch
	// uses this two-phase path so the relevance gate can run before the
	// user-visible outcome is recorded.
	SearchRaw func(ctx context.Context, req domain.SearchRequest) domain.SearchResponse
	// RecordSearchOutcome records only the response that normal output
	// actually exposed after relevance filtering.
	RecordSearchOutcome func(ctx context.Context, req domain.SearchRequest, resp domain.SearchResponse) string
	// GetSample returns a cached sample's manifest and its files
	// (path → content, ≤64KB per file, binaries skipped).
	GetSample func(ctx context.Context, id string) (domain.SampleManifest, map[string]string, error)
	// Explain renders a compatibility explanation for one package/symbol
	// from locally cached shards, with observation and verification
	// evidence kept separate. snapshot is the underlying JSON (may be null).
	Explain func(ctx context.Context, purl, symbol string, env domain.EnvironmentFingerprint) (text string, snapshot json.RawMessage, err error)
	// Overview summarizes cached evidence for several packages at once. It
	// turns a search miss into a useful answer instead of an empty one; nil
	// simply falls back to the bare NO_SAFE_MATCH text.
	Overview func(ctx context.Context, purls []string, env domain.EnvironmentFingerprint) ([]PackageOverview, error)
	// LocalReadiness reports the install mode and how many compatibility
	// shards are cached. An agent launched straight from a registry — with
	// the binary but no `csx init` — would otherwise see every search miss
	// with no way to tell an empty cache from an empty network.
	LocalReadiness func(ctx context.Context) (mode string, shards int, err error)
	// RunObserved wraps one command in the evidence loop (scan → run →
	// record). sanitized carries only sanitizer output — never raw stderr.
	RunObserved func(ctx context.Context, argv []string, cwd string) (exitCode int, stage, result string, sanitized []string, output evidence.CommandOutput, err error)
	// ReportAdoption records what happened to a returned sample. The outcome
	// can call a failure "avoided" only when the local correlation proves all
	// four stages; the upload remains the existing anonymous adoption event.
	ReportAdoption func(ctx context.Context, offerID, sampleID string, applied bool, buildPass *bool) (localdb.InterventionOutcome, error)
	// ReportAnomaly submits a verification REQUEST after an agent watched a
	// CSX answer and its own machine disagree. It redacts locally, refuses
	// anything with no measured local outcome behind it, and returns the
	// server's answer verbatim — including the part that says nothing has
	// been verified yet.
	ReportAnomaly func(ctx context.Context, report domain.AnomalyReport, rawErrorText string) (AnomalySubmission, error)
	// ReportCSXIssue submits a candidate defect in THIS PRODUCT — an answer
	// that hid the caller's own failure, a tool contract that misled a
	// model. Deliberately conservative: no ticket is created, nothing
	// instructs an agent to call it on every failure, and zero reports is a
	// normal week.
	ReportCSXIssue func(ctx context.Context, report domain.CSXIssueReport) (CSXIssueSubmission, error)
	// Propose builds a sanitized clean-room spec + prompt and creates an
	// empty workspace. It NEVER publishes (goal.md §12.4).
	Propose func(ctx context.Context, goal string, pkgs, symbols []string) (spec samples.SanitizedSpec, prompt string, workdir string, err error)
	// LocalHits lists recent local search hits.
	LocalHits func(ctx context.Context) ([]localdb.HitRow, error)
	// LocalStats returns the local dashboard stats.
	LocalStats func(ctx context.Context) (map[string]any, error)
	// MachineEnv reports this host's environment. nil means collect it.
	MachineEnv func(ctx context.Context) domain.EnvironmentFingerprint
	// Mode reports the configured mode ("community", "local-only", or "").
	// Tools consult it before telling a caller that anything will be sent.
	Mode func() string
	// MarkMCPReady records S4 of the activation funnel: this stdio session
	// completed the MCP protocol lifecycle (docs/activation-funnel.md §7).
	// It is called once per session, on the transition, and never at startup
	// — opening the store proves only that a process ran. Local-only by
	// contract: what agent tooling a developer uses is §2.3 never-collected,
	// so this records that a client completed the handshake and never which
	// one. nil is allowed and means the caller keeps no ledger.
	MarkMCPReady func(ctx context.Context)
}

Deps injects tool behavior into the transport so tests fake it and the real wiring (NewDeps) stays daemon-free. Every function takes the request context; none may retain it.

func NewDeps

func NewDeps(home string) (*Deps, func() error, error)

NewDeps wires the real tool implementations over one CSX home, the same stores the daemon uses but constructed in-process — the MCP server keeps working with no daemon running (goal.md §3.9). The returned close func releases the database handle.

type PackageOverview

type PackageOverview struct {
	PURL         string  `json:"purl"`
	Cached       bool    `json:"cached"`
	Observations int64   `json:"observations"`
	PeerBuckets  int64   `json:"peerBuckets"`
	PassRate     float64 `json:"passRate"`
	Samples      int     `json:"samples"`
	TopFailure   string  `json:"topFailure,omitempty"`
}

PackageOverview is the compact "what does the network know about this package" summary attached to a miss. Counts are observation evidence: projects that compiled with the package present, never proof that a specific symbol executed (goal.md §3.5).

type Server

type Server struct {
	In      io.Reader
	Out     io.Writer
	Deps    *Deps
	Version string
	// contains filtered or unexported fields
}

Server serves MCP over In/Out. Deps supplies tool behavior; Version is the build stamp reported in serverInfo (default "dev").

func (*Server) Serve

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

Serve reads newline-delimited JSON-RPC requests until In reaches EOF. Requests are handled serially (permitted by C8: arrival may be concurrent, serial handling is fine). Handler panics never kill the transport; they surface as -32603 responses.

Jump to

Keyboard shortcuts

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