mcp

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Overview

Package mcp loads, authorizes, and connects Coding Agent MCP integrations.

Index

Constants

View Source
const (
	// DefinitionSchema is the current strict MCP definition file schema: a
	// portable `mcpServers` object shared with Agent Plugins mcp.json.
	DefinitionSchema = "pips.mcp/v1alpha2"
	// LegacyDefinitionSchema is the original `servers`-array schema. It is
	// still accepted with unchanged rules and fingerprints.
	LegacyDefinitionSchema = "pips.mcp/v1alpha1"
	// PermissionSchema is the strict project-local permission file schema.
	PermissionSchema = "pips.permissions/v1alpha1"
)
View Source
const ReadOnlyWildcard = "*"

ReadOnlyWildcard in ConnectionOptions.ReadOnlyTools marks every tool of a server as read-only.

Variables

View Source
var (
	// ErrInvalid reports malformed definitions, permissions, or options.
	ErrInvalid = errors.New("coding mcp: invalid")
	// ErrLimitExceeded reports a bounded file, entry, or scalar limit.
	ErrLimitExceeded = errors.New("coding mcp: limit exceeded")
	// ErrDuplicate reports an identity collision without precedence.
	ErrDuplicate = errors.New("coding mcp: duplicate")
	// ErrUnsafeFile reports a symlink, tracked file, broad permissions, or
	// unsupported filesystem object at a security boundary.
	ErrUnsafeFile = errors.New("coding mcp: unsafe file")
)
View Source
var ErrUnsupportedTransport = errors.New("coding mcp: unsupported transport")

ErrUnsupportedTransport reports a well-formed entry whose transport pips does not implement, such as the legacy HTTP+SSE transport.

Functions

func LoadDefinitions

func LoadDefinitions(ctx context.Context, options LoadOptions) (Definitions, []ConnectionDiagnostic, error)

LoadDefinitions decodes strict user and trusted-project MCP definition files. An untrusted project file is never inspected. File-level violations fail the load; a pips.mcp/v1alpha2 entry that is invalid, unsupported, or duplicates an earlier derived ID is skipped and reported as a diagnostic.

func ServerID added in v0.1.5

func ServerID(name string) string

ServerID derives the native server ID from an `mcpServers` name. The name is lowercased and every run of characters outside [a-z0-9_] becomes one hyphen so the ID satisfies the native pattern; names that would exceed the length limit are truncated and suffixed with a short content hash so two long names stay distinct.

Types

type ConnectedServer

type ConnectedServer struct {
	ID          string
	Fingerprint string
	Visibility  Visibility
	Entries     []catalog.Entry
}

ConnectedServer is a detached, credential-free view of one successfully connected server in the current snapshot.

type ConnectionDiagnostic

type ConnectionDiagnostic struct {
	ServerID string
	Stage    string
	Code     string
	Message  string
}

ConnectionDiagnostic is a safe, non-fatal server lifecycle condition.

type ConnectionOptions

type ConnectionOptions struct {
	Workspace      workspace.Workspace
	Implementation *sdk.Implementation
	HTTPClient     *http.Client
	TempRoot       string
	Environment    func(string) (string, bool)
	TerminateAfter time.Duration
	MaxTools       int
	Transport      TransportFactory
	Diagnostics    []ConnectionDiagnostic
	// ReadOnlyTools marks tools, keyed by server ID, as read-only so they may
	// run concurrently within one model response. Values are remote MCP tool
	// names or ReadOnlyWildcard. Risk stays privileged; remote readOnlyHint
	// annotations are never consulted.
	ReadOnlyTools map[string][]string
}

ConnectionOptions configure concrete MCP transports and client bounds.

type Connections

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

Connections owns MCP clients and one atomic, versioned tool snapshot. Every enabled server connects concurrently in the background: a server joins the snapshot as soon as it settles, and individual failures are diagnostics that do not disable unrelated servers.

func OpenConnections

func OpenConnections(
	ctx context.Context,
	resolved []ResolvedDefinition,
	options ConnectionOptions,
) (*Connections, error)

OpenConnections validates options and every enabled definition, installs an empty initial snapshot, and starts one background connect per enabled server. It returns before any server has connected; callers that need the complete set use Wait.

Background connects derive from a detached copy of ctx so a request-scoped caller context cannot abort them; Close is the only stop.

func (*Connections) Close

func (c *Connections) Close() error

Close cancels in-flight connects, waits for them, and closes connected clients and their resources in reverse resolved order.

func (*Connections) ConnectedServers

func (c *Connections) ConnectedServers(visibility Visibility) []ConnectedServer

ConnectedServers returns credential-free bindings for successfully connected servers. Entry snapshots reflect the latest successfully installed snapshot.

func (*Connections) Diagnostics

func (c *Connections) Diagnostics() []ConnectionDiagnostic

Diagnostics returns every safe lifecycle diagnostic in a deterministic order: option diagnostics, then one per failed server in resolved order, then refresh diagnostics. Goroutine completion order never changes it.

func (*Connections) Entries

func (c *Connections) Entries(visibility Visibility) []catalog.Entry

Entries returns a detached current catalog filtered by configured visibility. Unknown visibility values return no entries.

func (*Connections) RefreshChanged

func (c *Connections) RefreshChanged(
	ctx context.Context,
) (agentmcp.RegistrySnapshot, bool, error)

RefreshChanged consumes pending tool list-change notifications only at an application-selected safe boundary. Only the servers that signaled are listed again. A failed refresh preserves the prior snapshot and emits one coalesced diagnostic until a later successful attempt.

func (*Connections) Servers added in v0.1.5

func (c *Connections) Servers() []ServerStatus

Servers returns a credential-free status for every configured definition in resolved order, including pending and disabled servers.

func (*Connections) Settled added in v0.1.5

func (c *Connections) Settled() bool

Settled reports whether every enabled server has connected or failed.

func (*Connections) Snapshot

func (c *Connections) Snapshot() agentmcp.RegistrySnapshot

Snapshot returns the latest successfully installed tool snapshot.

func (*Connections) TakeDiagnostics added in v0.1.5

func (c *Connections) TakeDiagnostics() []ConnectionDiagnostic

TakeDiagnostics returns the option and failed-server diagnostics that no earlier call has returned, in the same order as Diagnostics. Refresh diagnostics are excluded because the caller reports refresh failures inline at the interaction boundary.

func (*Connections) Wait added in v0.1.5

func (c *Connections) Wait(ctx context.Context) error

Wait blocks until every enabled server has connected or failed, or until ctx ends. A nil receiver has nothing to wait for.

type Definition

type Definition struct {
	ID             string
	Scope          Scope
	Transport      TransportType
	Visibility     Visibility
	Command        string
	Args           []string
	Environment    []execution.EnvVar
	WorkingDir     string
	PluginRoot     string
	PluginData     string
	URL            string
	Headers        []HTTPHeader
	ConnectTimeout time.Duration
}

Definition is one validated MCP server declaration.

func (Definition) EffectiveVisibility

func (d Definition) EffectiveVisibility() Visibility

EffectiveVisibility returns the normalized visibility used by validation, fingerprinting, and catalog filtering. The zero value preserves the pre-private-MCP ambient behavior for programmatic callers.

func (Definition) Fingerprint

func (d Definition) Fingerprint() string

Fingerprint returns the normalized semantic SHA-256 identity of a Definition.

type Definitions

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

Definitions is an immutable validated definition set.

func NewDefinitions

func NewDefinitions(values []Definition, maximum int) (Definitions, error)

NewDefinitions returns an immutable validated definition set.

func (Definitions) List

func (d Definitions) List() []Definition

List returns definitions in user-file then project-file order.

func (Definitions) Merge

func (d Definitions) Merge(other Definitions, maximum int) (Definitions, error)

Merge returns one immutable definition set and rejects cross-set collisions.

type HTTPHeader

type HTTPHeader struct {
	Name  string
	Value string
}

HTTPHeader is one validated header from an Agent Plugin or native MCP entry. Native values may contain ${env:NAME} credential references.

type Limits

type Limits struct {
	MaxFileBytes int64
	MaxServers   int
}

Limits bound MCP definition discovery and decoding.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns conservative MCP definition limits.

type LoadOptions

type LoadOptions struct {
	Paths          paths.Layout
	Tree           *workspace.Tree
	ProjectTrusted bool
	Limits         Limits
}

LoadOptions select user and optional trusted-project MCP files.

type PermissionOptions

type PermissionOptions struct {
	Workspace workspace.Workspace
	Tree      *workspace.Tree
	Store     *workspace.Store
	Git       ProjectGit
	Limits    Limits
}

PermissionOptions bind project decisions to one Workspace and user store.

type Permissions

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

Permissions resolves and records dual project/user MCP decisions.

func NewPermissions

func NewPermissions(options PermissionOptions) (*Permissions, error)

NewPermissions constructs a dual-record permission manager.

func (*Permissions) Decide

func (p *Permissions) Decide(
	ctx context.Context,
	definition Definition,
	decision workspace.PermissionDecision,
) error

Decide writes the project-local record first and user workspace authority second. A crash or error between them leaves a harmless pending state.

func (*Permissions) Resolve

func (p *Permissions) Resolve(
	ctx context.Context,
	definitions Definitions,
) ([]ResolvedDefinition, error)

Resolve evaluates user definitions as enabled and project definitions by intersecting the project-local and user workspace-store records.

type ProjectGit

type ProjectGit interface {
	Tracked(context.Context, string) (bool, bool, error)
	ExcludeLocal(context.Context, string) error
}

ProjectGit provides the narrow Git-local safety boundary needed by the project permissions file. A false repository value permits non-Git projects.

type ResolvedDefinition

type ResolvedDefinition struct {
	Definition Definition
	Status     Status
}

ResolvedDefinition attaches the effective permission status.

type Scope

type Scope string

Scope identifies who supplied an MCP definition.

const (
	ScopeUser        Scope = "user"
	ScopeProject     Scope = "project"
	ScopeSession     Scope = "session"
	ScopeAgentPlugin Scope = "agent-plugin"
)

Supported MCP definition scopes.

type ServerDialect added in v0.1.5

type ServerDialect uint8

ServerDialect selects the configuration format that owns one `mcpServers` entry. Both dialects share field names, closed variants, and the remote URL and header rules, so a server behaves the same wherever it is declared.

const (
	// DialectAgentPlugin is the exact Agent Plugins 1.0.0 mcp.json entry.
	DialectAgentPlugin ServerDialect = iota + 1
	// DialectNative is a pips.mcp/v1alpha2 entry: the portable shape plus an
	// optional stdio `type`, the `http` alias, `visibility`, and
	// `connect_timeout`.
	DialectNative
)

type ServerEntry added in v0.1.5

type ServerEntry struct {
	Transport TransportType
	Command   string
	Args      []string
	// Environment is sorted by name.
	Environment []execution.EnvVar
	// WorkingDir is the Agent Plugin `cwd` as written; HasWorkingDir reports
	// whether it was present.
	WorkingDir    string
	HasWorkingDir bool
	// URL is the normalized remote endpoint.
	URL string
	// Headers are sorted by name.
	Headers    []HTTPHeader
	Visibility Visibility
	// ConnectTimeout is zero when the native entry omits connect_timeout.
	ConnectTimeout time.Duration
}

ServerEntry is one validated `mcpServers` member. Values are kept as written: Agent Plugin placeholders and native credential references are expanded by their owners, never here.

func DecodeServerEntry added in v0.1.5

func DecodeServerEntry(raw json.RawMessage, dialect ServerDialect) (ServerEntry, error)

DecodeServerEntry validates one `mcpServers` member for dialect.

type ServerState added in v0.1.5

type ServerState string

ServerState is the closed lifecycle state of one configured server.

const (
	// ServerStatePending means the project permission record is missing or
	// stale, so the server was never started.
	ServerStatePending ServerState = "pending"
	// ServerStateDisabled means the project permission decision is deny.
	ServerStateDisabled ServerState = "disabled"
	// ServerStateConnecting means the background connect is still running.
	ServerStateConnecting ServerState = "connecting"
	// ServerStateConnected means the server's tools are in the snapshot.
	ServerStateConnected ServerState = "connected"
	// ServerStateFailed means the server disabled only itself with a safe
	// diagnostic.
	ServerStateFailed ServerState = "failed"
)

Supported server lifecycle states.

type ServerStatus added in v0.1.5

type ServerStatus struct {
	ID         string        `json:"id"`
	Scope      Scope         `json:"scope"`
	Transport  TransportType `json:"transport"`
	Visibility Visibility    `json:"visibility"`
	State      ServerState   `json:"state"`
	// Tools lists the advertised (prefixed) tool names of a connected server.
	Tools []string `json:"tools,omitempty"`
	// Stage, Code, and Message describe a failed server; they hold the same
	// fixed safe text as the matching ConnectionDiagnostic.
	Stage   string `json:"stage,omitempty"`
	Code    string `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
	// StartedAt is zero for pending and disabled servers. SettledAt is zero
	// while the server is still connecting.
	StartedAt time.Time `json:"started_at,omitzero"`
	SettledAt time.Time `json:"settled_at,omitzero"`
}

ServerStatus is a detached, credential-free projection of one configured server. It never carries URL, headers, command, args, environment, or working directory.

type Status

type Status string

Status is the effective local state of one MCP definition.

const (
	StatusPending  Status = "pending"
	StatusEnabled  Status = "enabled"
	StatusDisabled Status = "disabled"
)

Supported effective MCP states.

type TransportFactory

type TransportFactory func(context.Context, Definition) (sdk.Transport, io.Closer, error)

TransportFactory prepares one definition transport and optional resource that must be closed after its MCP client.

type TransportType

type TransportType string

TransportType identifies the configured MCP transport.

const (
	TransportStdio          TransportType = "stdio"
	TransportStreamableHTTP TransportType = "streamable_http"
)

Supported P0 MCP transports.

type Visibility

type Visibility string

Visibility controls which Coding model catalog may describe one configured server. It is application policy, not MCP protocol metadata.

const (
	// VisibilityAmbient exposes tools to the parent Coding interaction and to
	// custom children selected through the ordinary capability intersection.
	VisibilityAmbient Visibility = "ambient"
	// VisibilityAgentPrivate keeps tools out of the parent catalog. A custom
	// Agent must bind the exact server ID and fingerprint before its tools can
	// enter that child's capability intersection.
	VisibilityAgentPrivate Visibility = "agent_private"
)

Jump to

Keyboard shortcuts

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