Documentation
¶
Overview ¶
Package mcp wires the sofarpc tool surface into the MCP SDK. Each handler lives in its own file (open.go, describe.go, ...); this file owns construction, the shared Options, and the input-only types that describe the tool schemas. See docs/architecture.md §3.
Index ¶
- func New(opts Options) *sdkmcp.Server
- type Capabilities
- type ContractBanner
- type DescribeDiagnostics
- type DescribeInput
- type DescribeOutput
- type DoctorAction
- type DoctorCheck
- type DoctorInput
- type DoctorOutput
- type InitProjectGitignore
- type InitProjectInput
- type InitProjectOutput
- type InvokeInput
- type InvokeLimiter
- func (l *InvokeLimiter) Acquire(ctx context.Context, phase string, plan invoke.Plan) (func(), InvokeLimiterDiagnostics, error)
- func (l *InvokeLimiter) Diagnostics() InvokeLimiterDiagnostics
- func (l *InvokeLimiter) DiagnosticsForPlan(plan invoke.Plan) InvokeLimiterDiagnostics
- func (l *InvokeLimiter) DiagnosticsForTarget(targetKey string) InvokeLimiterDiagnostics
- type InvokeLimiterConfig
- type InvokeLimiterDiagnostics
- type InvokeOutput
- type OpenInput
- type OpenOutput
- type Options
- type PlanCaptureResult
- type PlanEntry
- type ReplayInput
- type ReplayOutput
- type Session
- type SessionStore
- func (s *SessionStore) Cap() int
- func (s *SessionStore) CapturePlan(id string, plan invoke.Plan) PlanCaptureResult
- func (s *SessionStore) Create(session Session) Session
- func (s *SessionStore) Get(id string) (Session, bool)
- func (s *SessionStore) MaxPlanBytes() int64
- func (s *SessionStore) PlanBudget() (used, limit int64)
- func (s *SessionStore) PlanByID(sessionID, planID string) (PlanEntry, bool)
- func (s *SessionStore) Size() int
- func (s *SessionStore) UpdatePlan(id string, plan invoke.Plan) bool
- func (s *SessionStore) WithClock(fn func() time.Time) *SessionStore
- func (s *SessionStore) WithIDFunc(fn func() string) *SessionStore
- func (s *SessionStore) WithMaxPlanBytes(maxBytes int64) *SessionStore
- type TargetInput
- type TargetOutput
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Capabilities ¶
type Capabilities struct {
DirectInvoke bool `json:"directInvoke"`
Describe bool `json:"describe"`
Replay bool `json:"replay"`
}
Capabilities is an up-front capability banner so agents know which tools will succeed without round-tripping. Keep field names stable.
type ContractBanner ¶
type ContractBanner struct {
Attached bool `json:"attached"`
Source string `json:"source,omitempty"`
ContractRoot string `json:"contractRoot,omitempty"`
IndexedClasses int `json:"indexedClasses,omitempty"`
IndexedFiles int `json:"indexedFiles,omitempty"`
ParsedClasses int `json:"parsedClasses,omitempty"`
IndexFailures map[string]string `json:"indexFailures,omitempty"`
ParseFailures map[string]string `json:"parseFailures,omitempty"`
LoadError string `json:"loadError,omitempty"`
}
ContractBanner gives agents an up-front view of contract readiness and sourcecontract health at workspace-open time.
LoadError is set when the entrypoint tried to materialize a store but failed (missing project root, unreadable directory, etc). Agents can branch on it before falling back to trusted-mode invoke.
type DescribeDiagnostics ¶
type DescribeDiagnostics struct {
ContractSource string `json:"contractSource,omitempty"`
CacheHit bool `json:"cacheHit,omitempty"`
Contract ContractBanner `json:"contract,omitempty"`
}
DescribeDiagnostics surfaces contract-source metadata so agents can understand whether the answer came from attached contract guidance.
type DescribeInput ¶
type DescribeInput struct {
Cwd string `json:"cwd,omitempty"`
Project string `json:"project,omitempty"`
SessionID string `json:"sessionId,omitempty"`
Service string `json:"service,omitempty"`
Method string `json:"method,omitempty"`
Types []string `json:"types,omitempty"`
}
DescribeInput is the input shape for sofarpc_describe. Types is the paramType list the agent may supply to disambiguate overloads. Method is optional: without it, describe lists the service's callable methods, and without service it lists the method-bearing interfaces in the contract index.
type DescribeOutput ¶
type DescribeOutput struct {
Service string `json:"service,omitempty"`
Method string `json:"method,omitempty"`
Overloads []javamodel.Method `json:"overloads,omitempty"`
Selected int `json:"selected,omitempty"`
Skeleton []any `json:"skeleton,omitempty"`
Methods []javamodel.Method `json:"methods,omitempty"`
Services []string `json:"services,omitempty"`
Diagnostics DescribeDiagnostics `json:"diagnostics,omitempty"`
Error *errcode.Error `json:"error,omitempty"`
}
DescribeOutput is the structured payload for sofarpc_describe. For a full service+method describe, Overloads + Selected + Skeleton are populated. When method is omitted, Methods lists the service's callable methods; when service is also omitted, Services lists the method-bearing interfaces in the contract index. On failure, Error is set and the CallToolResult reports IsError=true.
type DoctorAction ¶
DoctorAction is a minimal nextStep payload — kept separate from errcode.Hint because doctor is advisory, not an error response.
type DoctorCheck ¶
type DoctorCheck struct {
Name string `json:"name"`
Ok bool `json:"ok"`
Detail string `json:"detail,omitempty"`
Data map[string]any `json:"data,omitempty"`
NextStep *DoctorAction `json:"nextStep,omitempty"`
}
DoctorCheck is one diagnostic line. NextStep is omitted when the check passed; when it fails, the agent should prefer this over guessing.
type DoctorInput ¶
type DoctorInput struct {
Cwd string `json:"cwd,omitempty"`
Project string `json:"project,omitempty"`
SessionID string `json:"sessionId,omitempty"`
Service string `json:"service,omitempty"`
Profile string `json:"profile,omitempty"`
InvocationProperties invocationprops.Declarations `json:"invocationProperties,omitempty"`
}
DoctorInput is the input shape for sofarpc_doctor. Service is optional: when set, doctor biases target resolution toward a per-service uniqueId. Profile selects the Target Profile to diagnose; empty inherits the session's Active Target Profile (when called by sessionId) and then defaultProfile.
type DoctorOutput ¶
type DoctorOutput struct {
Ok bool `json:"ok"`
Summary string `json:"summary"`
Checks []DoctorCheck `json:"checks"`
Error *errcode.Error `json:"error,omitempty"`
}
DoctorOutput is the structured payload for sofarpc_doctor. Each Check is self-describing so agents can iterate and fix one problem at a time. Ok at the top is the AND of every check.Ok.
type InitProjectGitignore ¶
type InitProjectInput ¶
type InitProjectInput struct {
Cwd string `json:"cwd,omitempty"`
Project string `json:"project,omitempty"`
SessionID string `json:"sessionId,omitempty"`
ConfigFile string `json:"config,omitempty"`
Force bool `json:"force,omitempty"`
DryRun bool `json:"dryRun,omitempty"`
// Profile, when set, switches init_project into profile mode: the target
// fields below are written into profiles[name] (merged into the existing
// file) instead of the base settings. SetDefault also records it as the
// project's defaultProfile.
Profile string `json:"profile,omitempty"`
SetDefault bool `json:"setDefault,omitempty"`
DirectURL string `json:"directUrl,omitempty"`
Protocol string `json:"protocol,omitempty"`
Serialization string `json:"serialization,omitempty"`
UniqueID string `json:"uniqueId,omitempty"`
TimeoutMS int `json:"timeoutMs,omitempty"`
ConnectTimeoutMS int `json:"connectTimeoutMs,omitempty"`
}
type InitProjectOutput ¶
type InitProjectOutput struct {
Ok bool `json:"ok"`
ProjectRoot string `json:"projectRoot,omitempty"`
ConfigFile string `json:"configFile,omitempty"`
ConfigPath string `json:"configPath,omitempty"`
DryRun bool `json:"dryRun,omitempty"`
Wrote bool `json:"wrote,omitempty"`
Existing bool `json:"existing,omitempty"`
Overwrote bool `json:"overwrote,omitempty"`
ProjectConfig projectconfig.Config `json:"projectConfig,omitempty"`
ProjectResolution *workspace.JavaProjectDiscovery `json:"projectResolution,omitempty"`
Gitignore *InitProjectGitignore `json:"gitignore,omitempty"`
NextSteps []string `json:"nextSteps,omitempty"`
Error *errcode.Error `json:"error,omitempty"`
}
type InvokeInput ¶
type InvokeInput struct {
Cwd string `json:"cwd,omitempty"`
Project string `json:"project,omitempty"`
Service string `json:"service,omitempty"`
Method string `json:"method,omitempty"`
Types []string `json:"types,omitempty"`
Args any `json:"args,omitempty"`
Version string `json:"version,omitempty"`
TargetAppName string `json:"targetAppName,omitempty"`
InvocationProperties invocationprops.Declarations `json:"invocationProperties,omitempty"`
Profile string `json:"profile,omitempty"`
DirectURL string `json:"directUrl,omitempty"`
TimeoutMS int `json:"timeoutMs,omitempty"`
DryRun bool `json:"dryRun,omitempty"`
Trusted bool `json:"trusted,omitempty"`
ContractMode string `json:"contractMode,omitempty"`
// SessionID, when set, tags the resulting plan onto the session so
// sofarpc_replay can replay it without re-sending the payload.
SessionID string `json:"sessionId,omitempty"`
}
InvokeInput is the input shape for sofarpc_invoke. Args is any because runtime decoding preserves legacy input forms, but the public MCP schema advertises a JSON array argument vector. Invalid shapes are rejected as input.args-invalid. Version and TargetAppName are optional transport hints for direct invoke paths.
type InvokeLimiter ¶
type InvokeLimiter struct {
// contains filtered or unexported fields
}
InvokeLimiter is a workload-aware bulkhead shared by real invoke and replay. It deliberately limits application work before the SOFARPC runtime path; dry-run planning does not acquire a slot.
func NewInvokeLimiter ¶
func NewInvokeLimiter(cfg InvokeLimiterConfig) *InvokeLimiter
func NewInvokeLimiterFromEnv ¶
func NewInvokeLimiterFromEnv() *InvokeLimiter
func (*InvokeLimiter) Acquire ¶
func (l *InvokeLimiter) Acquire(ctx context.Context, phase string, plan invoke.Plan) (func(), InvokeLimiterDiagnostics, error)
func (*InvokeLimiter) Diagnostics ¶
func (l *InvokeLimiter) Diagnostics() InvokeLimiterDiagnostics
func (*InvokeLimiter) DiagnosticsForPlan ¶
func (l *InvokeLimiter) DiagnosticsForPlan(plan invoke.Plan) InvokeLimiterDiagnostics
func (*InvokeLimiter) DiagnosticsForTarget ¶
func (l *InvokeLimiter) DiagnosticsForTarget(targetKey string) InvokeLimiterDiagnostics
type InvokeLimiterConfig ¶
InvokeLimiterConfig controls admission for real invoke/replay work. A zero limit disables that dimension; New() uses NewInvokeLimiterFromEnv, whose defaults keep a bounded queue instead of allowing unbounded fan-out.
type InvokeLimiterDiagnostics ¶
type InvokeLimiterDiagnostics struct {
Enabled bool `json:"enabled"`
GlobalLimit int `json:"globalLimit,omitempty"`
GlobalInUse int `json:"globalInUse"`
PerTargetLimit int `json:"perTargetLimit,omitempty"`
Target string `json:"target,omitempty"`
TargetInUse int `json:"targetInUse,omitempty"`
QueueTimeoutMS int64 `json:"queueTimeoutMs"`
WaitingForRelease bool `json:"waitingForRelease,omitempty"`
}
InvokeLimiterDiagnostics is surfaced in tool diagnostics and doctor output so agents can distinguish a busy runtime from transport or serialization failures.
type InvokeOutput ¶
type InvokeOutput struct {
Ok bool `json:"ok"`
Plan *invoke.Plan `json:"plan,omitempty"`
Preflight *invoke.Preflight `json:"preflight,omitempty"`
Result any `json:"result,omitempty"`
Diagnostics map[string]any `json:"diagnostics,omitempty"`
Error *errcode.Error `json:"error,omitempty"`
}
InvokeOutput is the structured payload for sofarpc_invoke. Ok=true means the invocation (dry-run or real) produced a usable outcome — either a Plan to inspect or a Result from the direct transport.
type OpenInput ¶
type OpenInput struct {
RefreshContract bool `json:"refreshContract,omitempty"`
Cwd string `json:"cwd,omitempty"`
Project string `json:"project,omitempty"`
// Profile selects the Active Target Profile for this session; sessionId
// calls inherit it. Empty falls back to the project's defaultProfile.
Profile string `json:"profile,omitempty"`
}
OpenInput is the input shape for sofarpc_open. All fields are optional; Cwd defaults to the process CWD, Project falls back to Cwd.
type OpenOutput ¶
type OpenOutput struct {
SessionID string `json:"sessionId"`
ProjectRoot string `json:"projectRoot"`
Target target.Config `json:"target,omitempty"`
Layers []target.Layer `json:"layers,omitempty"`
ConfigErrors []target.ConfigError `json:"configErrors,omitempty"`
Capabilities Capabilities `json:"capabilities"`
Contract ContractBanner `json:"contract"`
// ActiveProfile is the Target Profile resolved for this session;
// AvailableProfiles lists every profile defined across both config files;
// ProfileError is set (and no session is opened) when the requested
// profile is defined in neither file.
ActiveProfile string `json:"activeProfile,omitempty"`
AvailableProfiles []string `json:"availableProfiles,omitempty"`
ProfileError string `json:"profileError,omitempty"`
Error *errcode.Error `json:"error,omitempty"`
}
OpenOutput is the structured payload for sofarpc_open. It returns the resolved workspace, the ambient target, and a capability banner the agent can branch on before its first invoke.
type Options ¶
type Options struct {
TargetSources target.Sources
ServerVersion string
Sessions *SessionStore
InvokeLimiter *InvokeLimiter
Contract contract.Store
ContractLoadError error
ContractLoader func() (contract.Store, error)
// ProjectContractLoader loads a contract store for the resolved
// projectRoot of a tool call or session. When set, project/session-scoped
// calls use it instead of the process-global ContractLoader.
ProjectContractLoader func(projectRoot string) (contract.Store, error)
}
Options carries the ambient state the handlers need. The entrypoint (cmd/sofarpc-mcp) fills this from SOFARPC_* env — the server itself does no I/O at construction.
ServerVersion, when set, is surfaced through the MCP implementation metadata. Release builds should pass the same value printed by the CLI version command.
ContractLoadError, when non-nil, signals that the entrypoint tried to materialize a contract store but failed. Handlers surface it in sofarpc_open / sofarpc_doctor so agents see the reason without having to scrape the server's stderr.
ContractLoader, when non-nil, is called lazily on the first tool path that asks for the contract store. A store (and any error) it returns replaces any synchronously-supplied Contract / ContractLoadError, so large Java trees do not delay MCP server startup or tool registration. When nil, the sync Contract fields are used as-is.
type PlanCaptureResult ¶
type PlanCaptureResult struct {
Captured bool `json:"captured"`
Reason string `json:"reason,omitempty"`
PlanID string `json:"planId,omitempty"`
PlanBytes int64 `json:"planBytes,omitempty"`
MaxBytes int64 `json:"maxBytes,omitempty"`
}
PlanCaptureResult reports whether an invoke plan was attached to a session for sessionId replay. Failed capture is advisory: invoke/dry-run can still return the full plan to the caller, and payload replay remains available. PlanID is the handle sofarpc_replay accepts to replay this exact plan later, even after newer invokes capture newer plans.
type PlanEntry ¶
type PlanEntry struct {
ID string `json:"id"`
CapturedAt time.Time `json:"capturedAt"`
Plan invoke.Plan `json:"plan"`
// contains filtered or unexported fields
}
PlanEntry is one captured invoke plan in a session's bounded history, addressable by ID through sofarpc_replay and the session plan resources.
type ReplayInput ¶
type ReplayInput struct {
SessionID string `json:"sessionId,omitempty"`
PlanID string `json:"planId,omitempty"`
Cwd string `json:"cwd,omitempty"`
Project string `json:"project,omitempty"`
Payload any `json:"payload,omitempty"`
DryRun bool `json:"dryRun,omitempty"`
}
ReplayInput is the input shape for sofarpc_replay. SessionID can either select the captured session plan or, when Payload is present, provide the project/safety context for that literal plan. PlanID selects a specific plan from the session's captured history instead of the most recent one. DryRun mirrors sofarpc_invoke.
type ReplayOutput ¶
type ReplayOutput struct {
Ok bool `json:"ok"`
Source string `json:"source,omitempty"`
Plan *invoke.Plan `json:"plan,omitempty"`
Preflight *invoke.Preflight `json:"preflight,omitempty"`
Result any `json:"result,omitempty"`
Diagnostics map[string]any `json:"diagnostics,omitempty"`
Error *errcode.Error `json:"error,omitempty"`
}
ReplayOutput is the structured payload for sofarpc_replay. Ok=true means the plan executed (or, in dryRun, was extracted cleanly) and Result / Diagnostics mirror sofarpc_invoke.
type Session ¶
type Session struct {
ID string `json:"id"`
ProjectRoot string `json:"projectRoot"`
Target target.Config `json:"target,omitempty"`
// Profile is the Active Target Profile resolved at sofarpc_open time.
// sessionId-based calls inherit it unless they pass their own profile.
Profile string `json:"profile,omitempty"`
CreatedAt time.Time `json:"createdAt"`
// LastPlan is the most recent plan produced by sofarpc_invoke for
// this session. sofarpc_replay reads it when called with sessionId.
LastPlan *invoke.Plan `json:"lastPlan,omitempty"`
// Plans is the newest-first bounded history of captured plans. LastPlan
// mirrors Plans[0] except after an oversized capture, which clears
// LastPlan (no implicit latest) while explicit planId replay of older
// entries stays available.
Plans []PlanEntry `json:"plans,omitempty"`
// contains filtered or unexported fields
}
Session is a per-workspace snapshot the agent can refer back to by ID in subsequent calls, so it does not have to re-specify project/context or rebuild the invocation plan. Sessions live only in memory — they are recreated on every process start.
type SessionStore ¶
type SessionStore struct {
// contains filtered or unexported fields
}
SessionStore is a bounded in-memory registry keyed by session ID.
GC runs on-write (Create / UpdatePlan) — no background goroutine, so there is no Stop() lifecycle to manage. Three dimensions bound memory:
- Idle TTL: sessions whose lastUsed is older than ttl are dropped on the next write. Bumped by Get and UpdatePlan so active sessions survive.
- Capacity: when len reaches cap, the LRU entry is evicted to make room. A zero ttl or cap disables that dimension (unbounded growth in tests only).
- Captured plan bytes: sessionId replay keeps only plans whose JSON representation fits the per-plan limit. A zero per-plan limit still leaves the aggregate storage limit in effect.
Safe for concurrent use.
func NewSessionStore ¶
func NewSessionStore() *SessionStore
NewSessionStore returns a store with default TTL (24h), capacity (256), and both plan byte limits. SOFARPC_SESSION_PLAN_MAX_BYTES overrides only the per-plan limit. Set it to 0 to use only the aggregate limit.
func NewSessionStoreWithLimits ¶
func NewSessionStoreWithLimits(ttl time.Duration, capacity int) *SessionStore
NewSessionStoreWithLimits returns a store with explicit idle TTL and capacity. A zero value for either disables that dimension of GC. Use NewSessionStore in production — this exists for tests and for callers that need to tune the bounds.
func (*SessionStore) Cap ¶
func (s *SessionStore) Cap() int
Cap returns the configured capacity. Zero means unbounded. sofarpc_doctor surfaces this alongside Size so agents can see how close they are to LRU pressure.
func (*SessionStore) CapturePlan ¶
func (s *SessionStore) CapturePlan(id string, plan invoke.Plan) PlanCaptureResult
CapturePlan attaches the most recent invoke plan to a session so that sofarpc_replay can replay it by sessionId. Oversized plans are not stored, but the session is still treated as active and the caller can replay by passing the returned dry-run plan as payload.
func (*SessionStore) Create ¶
func (s *SessionStore) Create(session Session) Session
Create records a new session and returns it with an ID and timestamp populated. The caller-supplied session's ID, CreatedAt, and lastUsed are ignored. GC runs before the insert so a long-idle server doesn't grow without bound.
func (*SessionStore) Get ¶
func (s *SessionStore) Get(id string) (Session, bool)
Get returns a copy of the stored session and bumps its LRU timestamp so that subsequent capacity pressure doesn't evict actively-used IDs. ok=false means no such ID (either never existed or already expired).
func (*SessionStore) MaxPlanBytes ¶
func (s *SessionStore) MaxPlanBytes() int64
MaxPlanBytes returns the configured per-plan byte limit. Zero means that only the aggregate limit applies.
func (*SessionStore) PlanBudget ¶
func (s *SessionStore) PlanBudget() (used, limit int64)
PlanBudget reports the retained serialized size and the store-wide limit.
func (*SessionStore) PlanByID ¶
func (s *SessionStore) PlanByID(sessionID, planID string) (PlanEntry, bool)
PlanByID returns the captured plan entry with the given ID from a session's history. ok=false covers both an unknown session and an unknown (or rotated-out) plan ID.
func (*SessionStore) Size ¶
func (s *SessionStore) Size() int
Size returns the number of live sessions. Useful for diagnostics and for tests that need to observe GC behaviour.
func (*SessionStore) UpdatePlan ¶
func (s *SessionStore) UpdatePlan(id string, plan invoke.Plan) bool
UpdatePlan attaches the most recent invoke plan to a session so that sofarpc_replay can replay it by sessionId. It is a no-op (returning false) when the session does not exist or the plan exceeds the captured-plan byte limit — callers treat replay capture as advisory and should not fail the invoke on this. Also bumps the LRU timestamp since a plan write attempt is a clear "session is alive" signal.
func (*SessionStore) WithClock ¶
func (s *SessionStore) WithClock(fn func() time.Time) *SessionStore
WithClock swaps the clock for tests that need deterministic TTL behaviour. Production callers should leave the default (time.Now).
func (*SessionStore) WithIDFunc ¶
func (s *SessionStore) WithIDFunc(fn func() string) *SessionStore
WithIDFunc sets the ID generator (tests use this to get deterministic IDs).
func (*SessionStore) WithMaxPlanBytes ¶
func (s *SessionStore) WithMaxPlanBytes(maxBytes int64) *SessionStore
WithMaxPlanBytes swaps the per-plan byte limit. Zero uses only the aggregate limit. Production callers should prefer SOFARPC_SESSION_PLAN_MAX_BYTES.
type TargetInput ¶
type TargetInput struct {
Cwd string `json:"cwd,omitempty"`
Project string `json:"project,omitempty"`
SessionID string `json:"sessionId,omitempty"`
Service string `json:"service,omitempty"`
Profile string `json:"profile,omitempty"`
DirectURL string `json:"directUrl,omitempty"`
Protocol string `json:"protocol,omitempty"`
Serialization string `json:"serialization,omitempty"`
TimeoutMS int `json:"timeoutMs,omitempty"`
ConnectTimeoutMS int `json:"connectTimeoutMs,omitempty"`
Explain bool `json:"explain,omitempty"`
}
TargetInput mirrors architecture.md §3.3. Fields are optional; omitted values fall through to env / defaults.
type TargetOutput ¶
type TargetOutput struct {
ProjectRoot string `json:"projectRoot,omitempty"`
Target target.Config `json:"target"`
Service string `json:"service,omitempty"`
Layers []target.Layer `json:"layers,omitempty"`
ConfigErrors []target.ConfigError `json:"configErrors,omitempty"`
Reachability target.ProbeResult `json:"reachability"`
Explain []string `json:"explain,omitempty"`
// Trace is a per-field record of which layer won and which lower
// layers carried a shadowed value. Populated only when explain=true
// — agents can branch on it without parsing Explain strings.
Trace []target.FieldTrace `json:"trace,omitempty"`
// ActiveProfile is the selected Target Profile; AvailableProfiles lists
// every profile defined across both config files; ProfileError is set
// when ActiveProfile names a profile defined in neither file.
ActiveProfile string `json:"activeProfile,omitempty"`
AvailableProfiles []string `json:"availableProfiles,omitempty"`
ProfileError string `json:"profileError,omitempty"`
Error *errcode.Error `json:"error,omitempty"`
}
TargetOutput is the structured payload for sofarpc_target. It combines the resolver's layered report with the probe result so a single call tells the agent both "what target was picked" and "is it reachable".