mcp

package
v0.0.52 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2026 License: GPL-3.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ConfigFileName is the per-repo MCP server configuration file.
	ConfigFileName = ".mcp.json"
)

Variables

This section is empty.

Functions

func BlockedServerMessage

func BlockedServerMessage(server string, breakGlassEnabled bool) string

func BlockedToolMessage

func BlockedToolMessage(server, tool string, breakGlassEnabled bool) string

func BreakGlassActions

func BreakGlassActions() json.RawMessage

func BuildBreakGlassQuestion

func BuildBreakGlassQuestion(request BreakGlassRequest, cfg BreakGlassPolicy) string

func BuildToolName

func BuildToolName(serverName, toolName string) string

BuildToolName builds an MCP-qualified tool name: mcp__<normalized-server>__<normalized-tool>

The final name is truncated and hashed when needed to fit the 64-char limit.

func BuildTools

func BuildTools(manager ToolManager) []agentsdk.Tool

BuildTools converts connected MCP descriptors into SDK tools.

func ConfigPathForWorkDir

func ConfigPathForWorkDir(workDir string) string

ConfigPathForWorkDir returns the .mcp.json path for a workspace.

func EnsureUniqueToolName

func EnsureUniqueToolName(candidate string, used map[string]struct{}) string

EnsureUniqueToolName ensures the generated tool name is unique in this registry. Caps collision search at 1000 attempts to avoid an unbounded loop on pathological configs; falls back to appending a hash of the iteration count.

func FilterCredentialEnv

func FilterCredentialEnv(env map[string]string, allow []string) (map[string]string, []string)

FilterCredentialEnv removes credential-bearing names from env, except those explicitly listed in allow. It returns the filtered map and the list of blocked names (sorted by caller if needed).

func FormatBreakGlassTarget

func FormatBreakGlassTarget(server, tool string) string

func FormatCallToolResult

func FormatCallToolResult(workDir string, desc ToolDescriptor, result *mcpsdk.CallToolResult) (string, error)

FormatCallToolResult renders an MCP tool call response as model-safe text/JSON.

func FormatReadResourceResult

func FormatReadResourceResult(workDir, serverName string, result *mcpsdk.ReadResourceResult) (string, error)

FormatReadResourceResult renders an MCP read-resource response as model-safe JSON.

func IsCredentialEnvName

func IsCredentialEnvName(name string) bool

IsCredentialEnvName reports whether the env-var name matches the credential denylist used to filter MCP child process environment.

func NormalizeNameForMCP

func NormalizeNameForMCP(name string) string

NormalizeNameForMCP normalizes server/tool names to satisfy API tool-name constraints.

func SanitizeMCPDisplay

func SanitizeMCPDisplay(serverName, raw string) string

SanitizeMCPDisplay returns a one-line, control-character-free, length-bounded rendering of an MCP-supplied string (description, title, etc.) suitable for use in approval-prompt UI text. It always prefixes the result with a "[from MCP server: <name>]" provenance tag so that operators cannot be tricked into thinking server-supplied text originated from the agent itself.

func SanitizeMCPToolDescription

func SanitizeMCPToolDescription(serverName, toolName, raw string) string

SanitizeMCPToolDescription returns a bounded tool description for model prompts. MCP servers supply this text, so it is flattened, provenance-tagged, and explicitly framed as untrusted descriptive text rather than instructions.

func SummarizeBreakGlassTarget

func SummarizeBreakGlassTarget(verb, server, tool string) string

Types

type BreakGlassCatalog

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

BreakGlassCatalog contains the connected MCP servers/tools that can be requested through a break-glass workflow.

func NewBreakGlassCatalog

func NewBreakGlassCatalog(descriptors []ToolDescriptor, servers []string) BreakGlassCatalog

func (BreakGlassCatalog) Validate

func (c BreakGlassCatalog) Validate(server, tool string) error

type BreakGlassPolicy

type BreakGlassPolicy struct {
	RequireAuditReason bool
}

BreakGlassPolicy describes host-neutral MCP break-glass display rules.

type BreakGlassRequest

type BreakGlassRequest struct {
	Server string
	Tool   string
	Reason string
}

BreakGlassRequest is the SDK-native shape for requesting temporary MCP access.

type BreakGlassRequestResult

type BreakGlassRequestResult struct {
	Content     string
	IsError     bool
	ShouldPause bool
}

BreakGlassRequestResult is the host-neutral result returned by a BreakGlassSink after it persists or rejects a request.

type BreakGlassSink

type BreakGlassSink interface {
	RequestMCPBreakGlass(ctx context.Context, request BreakGlassRequest) (BreakGlassRequestResult, error)
}

BreakGlassSink persists a break-glass request in the host platform and, when appropriate, asks the host UI to collect approval.

type Config

type Config struct {
	MCPServers map[string]ServerConfig `json:"mcpServers"`
}

Config represents .mcp.json.

func LoadConfig

func LoadConfig(path string) (cfg Config, exists bool, err error)

LoadConfig loads and parses .mcp.json.

The returned exists flag is false when the file is not present.

type ConfigSnapshot

type ConfigSnapshot struct {
	// Path is the path passed to LoadConfigSnapshot, as supplied by the caller.
	Path string
	// AbsPath is the resolved absolute path to .mcp.json. Pinned at load time.
	AbsPath string
	// ContentSHA256 is the digest of the file bytes at load time.
	ContentSHA256 []byte
	// LoadedAt is the wall-clock time when the snapshot was taken.
	LoadedAt time.Time
	// Config is the parsed configuration.
	Config Config
	// AgentWritable is true when the .mcp.json file resides inside the
	// agent-writable workspace and is therefore subject to in-run mutation. The
	// caller has been warned via the standard logger.
	AgentWritable bool
}

ConfigSnapshot is an immutable view of an .mcp.json load taken at a single instant. The snapshot pins the absolute file path and a SHA-256 of the file content; callers must NOT silently reload the file mid-run. Use VerifyUnchanged to detect tampering before re-reading.

func LoadConfigSnapshot

func LoadConfigSnapshot(path string) (ConfigSnapshot, error)

LoadConfigSnapshot reads and parses .mcp.json, pinning the absolute path and content hash. The returned snapshot is immutable; callers must treat .mcp.json as immutable for the rest of the run.

If the file does not exist, the returned snapshot has an empty Config and nil ContentSHA256, but AbsPath is still pinned.

func LoadConfigSnapshotInWorkspace

func LoadConfigSnapshotInWorkspace(path, workspaceRoot string) (ConfigSnapshot, error)

LoadConfigSnapshotInWorkspace is like LoadConfigSnapshot but additionally flags the snapshot when the resolved .mcp.json path lives inside the agent-writable workspace. A warning is also logged in that case.

func (ConfigSnapshot) VerifyUnchanged

func (s ConfigSnapshot) VerifyUnchanged() error

VerifyUnchanged re-reads the pinned file and returns an error if the bytes have changed since the snapshot was taken. Use this before honouring any caller-requested reload of .mcp.json — silent reloads are refused; the caller must explicitly re-snapshot if they truly intend to swap config.

type DynamicTool

type DynamicTool struct {
	Manager    ToolManager
	Descriptor ToolDescriptor
}

DynamicTool exposes one MCP descriptor as an SDK tool.

func (*DynamicTool) Description

func (t *DynamicTool) Description() string

func (*DynamicTool) Execute

func (t *DynamicTool) Execute(ctx context.Context, input json.RawMessage, workDir string) (agentsdk.ToolResult, error)

func (*DynamicTool) InputSchema

func (t *DynamicTool) InputSchema() json.RawMessage

func (*DynamicTool) IsEnabled

func (t *DynamicTool) IsEnabled(ctx *agentsdk.RunContext) bool

func (*DynamicTool) IsReadOnly

func (t *DynamicTool) IsReadOnly() bool

func (*DynamicTool) Name

func (t *DynamicTool) Name() string

func (*DynamicTool) NeedsApproval

func (t *DynamicTool) NeedsApproval() bool

func (*DynamicTool) TimeoutSeconds

func (t *DynamicTool) TimeoutSeconds() int

type ListResourcesTool

type ListResourcesTool struct {
	Manager ToolManager
}

ListResourcesTool lists resources available from connected MCP servers.

func (*ListResourcesTool) Description

func (t *ListResourcesTool) Description() string

func (*ListResourcesTool) Execute

func (*ListResourcesTool) InputSchema

func (t *ListResourcesTool) InputSchema() json.RawMessage

func (*ListResourcesTool) IsEnabled

func (t *ListResourcesTool) IsEnabled(_ *agentsdk.RunContext) bool

func (*ListResourcesTool) IsReadOnly

func (t *ListResourcesTool) IsReadOnly() bool

func (*ListResourcesTool) Name

func (t *ListResourcesTool) Name() string

func (*ListResourcesTool) NeedsApproval

func (t *ListResourcesTool) NeedsApproval() bool

func (*ListResourcesTool) TimeoutSeconds

func (t *ListResourcesTool) TimeoutSeconds() int

type Manager

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

Manager holds connected MCP sessions and their exposed tools/resources.

func NewManager

func NewManager(ctx context.Context, workDir string, opts ...ManagerOption) (*Manager, error)

NewManager reads .mcp.json from workDir and connects supported servers.

It returns (nil, nil) when no config file exists or no servers are configured. When some servers fail but others connect, a non-nil Manager is returned along with a non-nil warning error.

func NewManagerFromConfig

func NewManagerFromConfig(ctx context.Context, workDir string, cfg Config, opts ...ManagerOption) (*Manager, error)

NewManagerFromConfig creates a manager from the provided config.

func (*Manager) CallTool

func (m *Manager) CallTool(ctx context.Context, qualifiedName string, args map[string]any) (*mcpsdk.CallToolResult, error)

CallTool calls a dynamic MCP tool by its qualified name.

func (*Manager) Close

func (m *Manager) Close() error

Close closes all active MCP sessions.

func (*Manager) ConfigSnapshot

func (m *Manager) ConfigSnapshot() ConfigSnapshot

ConfigSnapshot returns the pinned snapshot of .mcp.json, if any. Callers should treat this as immutable — use snapshot.VerifyUnchanged to detect in-run mutation; do NOT silently reload.

func (*Manager) ConnectedServerNames

func (m *Manager) ConnectedServerNames() []string

ConnectedServerNames returns connected server names sorted alphabetically.

func (*Manager) HasResources

func (m *Manager) HasResources() bool

HasResources reports whether any connected server exposes resources.

func (*Manager) ListResources

func (m *Manager) ListResources(ctx context.Context, serverName string) ([]ResourceDescriptor, error)

ListResources returns available resources for all servers or a specific server.

func (*Manager) ReadResource

func (m *Manager) ReadResource(ctx context.Context, serverName, uri string) (*mcpsdk.ReadResourceResult, error)

ReadResource reads a specific resource from a specific server.

func (*Manager) ToolDescriptors

func (m *Manager) ToolDescriptors() []ToolDescriptor

ToolDescriptors returns all MCP-backed dynamic tool descriptors.

type ManagerOption

type ManagerOption func(*managerOptions)

ManagerOption configures MCP subprocess execution.

func WithCommandExecutor

func WithCommandExecutor(executor sandbox.Executor) ManagerOption

WithCommandExecutor sets the command executor used for MCP stdio subprocesses.

func WithPermissionMode

func WithPermissionMode(mode policy.PermissionMode) ManagerOption

WithPermissionMode sets the filesystem mode used for MCP stdio subprocesses.

type ReadResourceTool

type ReadResourceTool struct {
	Manager ToolManager
}

ReadResourceTool reads a specific resource from an MCP server.

func (*ReadResourceTool) Description

func (t *ReadResourceTool) Description() string

func (*ReadResourceTool) Execute

func (t *ReadResourceTool) Execute(ctx context.Context, input json.RawMessage, workDir string) (agentsdk.ToolResult, error)

func (*ReadResourceTool) InputSchema

func (t *ReadResourceTool) InputSchema() json.RawMessage

func (*ReadResourceTool) IsEnabled

func (t *ReadResourceTool) IsEnabled(_ *agentsdk.RunContext) bool

func (*ReadResourceTool) IsReadOnly

func (t *ReadResourceTool) IsReadOnly() bool

func (*ReadResourceTool) Name

func (t *ReadResourceTool) Name() string

func (*ReadResourceTool) NeedsApproval

func (t *ReadResourceTool) NeedsApproval() bool

func (*ReadResourceTool) TimeoutSeconds

func (t *ReadResourceTool) TimeoutSeconds() int

type RequestBreakGlassTool

type RequestBreakGlassTool struct {
	Sink BreakGlassSink
}

RequestBreakGlassTool is the SDK-owned shell for MCP break-glass requests. Hosts provide only the persistence/approval sink.

func (*RequestBreakGlassTool) Description

func (t *RequestBreakGlassTool) Description() string

func (*RequestBreakGlassTool) Execute

func (*RequestBreakGlassTool) InputSchema

func (t *RequestBreakGlassTool) InputSchema() json.RawMessage

func (*RequestBreakGlassTool) IsEnabled

func (t *RequestBreakGlassTool) IsEnabled(_ *agentsdk.RunContext) bool

func (*RequestBreakGlassTool) IsReadOnly

func (t *RequestBreakGlassTool) IsReadOnly() bool

func (*RequestBreakGlassTool) Name

func (t *RequestBreakGlassTool) Name() string

func (*RequestBreakGlassTool) NeedsApproval

func (t *RequestBreakGlassTool) NeedsApproval() bool

func (*RequestBreakGlassTool) TimeoutSeconds

func (t *RequestBreakGlassTool) TimeoutSeconds() int

type ResourceDescriptor

type ResourceDescriptor struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	MIMEType    string `json:"mimeType,omitempty"`
	Description string `json:"description,omitempty"`
	Server      string `json:"server"`
}

ResourceDescriptor describes an MCP resource entry.

type ServerConfig

type ServerConfig struct {
	Type    string            `json:"type,omitempty"`
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
	// Enabled can explicitly disable a configured server without removing it
	// from .mcp.json. Nil preserves compatibility and treats the server as
	// enabled when the runtime MCP feature itself is enabled.
	Enabled *bool `json:"enabled,omitempty"`
	// AllowEnv is the explicit opt-in list of env names that may pass through
	// the credential denylist (see FilterCredentialEnv). Names listed here are
	// trusted to be set via cfg.Env even if they look like credentials.
	AllowEnv          []string `json:"allowEnv,omitempty"`
	TrustReadOnlyHint bool     `json:"trustReadOnlyHint,omitempty"`
	// AllowedTools, when non-empty, exposes only the listed raw MCP tool names
	// for this server. Empty preserves compatibility and exposes all server
	// tools once MCP is enabled by the runtime.
	AllowedTools []string `json:"allowedTools,omitempty"`
}

ServerConfig represents a single MCP server config. Only stdio transport is supported right now.

type ToolDescriptor

type ToolDescriptor struct {
	QualifiedName string
	ServerName    string
	ToolName      string
	Description   string
	// DisplayDescription is the sanitized, length-bounded, provenance-tagged
	// rendering of Description for use in approval UI text. Use this — never
	// the raw Description — anywhere an MCP-supplied string is shown to a
	// human operator confirming a sensitive action.
	DisplayDescription string
	// DisplayTitle is the sanitized, provenance-tagged tool title for the
	// approval UI.
	DisplayTitle string
	InputSchema  json.RawMessage
	ReadOnly     bool
}

ToolDescriptor describes an MCP tool exposed to the LLM.

type ToolManager

type ToolManager interface {
	ToolDescriptors() []ToolDescriptor
	ConnectedServerNames() []string
	HasResources() bool
	CallTool(ctx context.Context, qualifiedName string, args map[string]any) (*mcpsdk.CallToolResult, error)
	ListResources(ctx context.Context, serverName string) ([]ResourceDescriptor, error)
	ReadResource(ctx context.Context, serverName, uri string) (*mcpsdk.ReadResourceResult, error)
}

ToolManager is the MCP manager surface needed by SDK MCP tools.

Jump to

Keyboard shortcuts

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