mcp

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package mcp is a generic stdio MCP (Model Context Protocol) client: it spawns any MCP server that speaks JSON-RPC 2.0 over newline-delimited stdio, performs the initialize handshake, and exposes tools/list + tools/call. It is the reusable substrate behind Aura's MCP-to-agent-tool bridge for stdio MCP servers declared in the mcpServers config.

It generalizes the single-purpose mcp-neo4j-cypher client (internal/knowledge): the framing (one JSON object per line, serialized via mu since a stdio pipe pair cannot interleave) is identical, but the server, tool set, and arguments are not hard-coded. Unlike that client, readResponse skips interleaved notifications (e.g. logging) so a chatty server cannot desync the request/response stream.

A subprocess crash is surfaced as a wrapped error; the bridge decides policy.

Index

Constants

View Source
const (
	ManagedConfigVersion = 2
	DefaultMCPProfile    = "default"

	ServerTypeStdio          = "stdio"
	ServerTypeStreamableHTTP = "streamable_http"

	TrustTrustedRecipe  = "trusted_recipe"
	TrustTrustedLocal   = "trusted_local"
	TrustSandboxedLocal = "sandboxed_local"
	TrustRemoteHTTP     = "remote_http"
	TrustBlocked        = "blocked"

	RuntimeKindLocal         = "local"
	RuntimeKindDocker        = "docker"
	RuntimeKindDockerGateway = "docker_gateway"
)

Managed config schema constants: the registry version, default profile name, and the recognized server type, trust class, and runtime kind enum values.

Variables

View Source
var ErrTransport = errors.New("mcp transport error")

ErrTransport marks a broken MCP transport pipe/session. Callers use IsTransportError rather than matching opaque OS error strings.

Functions

func IsKnownTrust

func IsKnownTrust(class string) bool

IsKnownTrust reports whether class is a recognized trust class. It lets callers outside this package (e.g. the manager runtime) gate an explicit Trust.Class the same way NormalizedTrust does, instead of trusting an arbitrary string.

func IsTransportError

func IsTransportError(err error) bool

IsTransportError reports whether err wraps ErrTransport.

func ManagedConfigPath

func ManagedConfigPath() (string, error)

ManagedConfigPath returns Aura's managed MCP config path. AURA_MCP_CONFIG is a test/operator override; otherwise the file lives beside Aura's other user config.

func RedactSecrets

func RedactSecrets(s string) string

RedactSecrets masks secret-bearing values in a string before it is logged or surfaced in errors, replacing the values of token/secret/key-style env entries and Authorization: Bearer headers with <redacted>.

func SaveManagedConfig

func SaveManagedConfig(path string, doc ManagedConfig) error

SaveManagedConfig writes path as indented JSON with user-only permissions. MCP env entries commonly hold tokens, so the file should not be group/world-readable.

Types

type Client

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

Client wraps one MCP server subprocess. The zero value is unusable; use Open.

func Open

func Open(ctx context.Context, name string, cfg ServerConfig) (*Client, error)

Open spawns the server described by cfg and completes the initialize handshake. name is a short label used in error messages (the mcpServers key). On any failure the subprocess is reaped before returning.

func (*Client) CallTool

func (c *Client) CallTool(ctx context.Context, name string, args map[string]any) (string, error)

CallTool invokes one tool and returns its concatenated text content. A tool that reports isError=true is returned as an error carrying that text, so the caller never mistakes a tool-level failure for success.

func (*Client) Close

func (c *Client) Close() error

Close shuts the subprocess down by closing stdin and waiting for exit; if the server has not exited within closeWaitTimeout it is killed and the wait result is drained. Safe to call on a test client (no cmd) and idempotent enough for defer.

func (*Client) ListTools

func (c *Client) ListTools(ctx context.Context) ([]ToolDef, error)

ListTools returns the server's advertised tools (tools/list).

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping issues an MCP ping round-trip to confirm the subprocess is alive and responsive; used by the bridge as a liveness probe.

type HTTPClient

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

HTTPClient speaks the Streamable-HTTP MCP transport to one remote server, tracking the negotiated protocol version and Mcp-Session-Id across requests. The zero value is unusable; use OpenHTTP.

func OpenHTTP

func OpenHTTP(ctx context.Context, name string, cfg HTTPConfig) (*HTTPClient, error)

OpenHTTP connects to the Streamable-HTTP MCP server at cfg.URL and completes the initialize handshake, capturing the session id and negotiated protocol version. name is a short label used in error messages (the mcpServers key).

func (*HTTPClient) CallTool

func (c *HTTPClient) CallTool(ctx context.Context, name string, args map[string]any) (string, error)

CallTool invokes one tool (tools/call) and returns its concatenated text content; a result with isError=true is returned as an error carrying that text.

func (*HTTPClient) Close

func (c *HTTPClient) Close() error

Close terminates the MCP session with an HTTP DELETE when one is open; a server that does not support session deletion (405/404) is treated as already closed.

func (*HTTPClient) ListTools

func (c *HTTPClient) ListTools(ctx context.Context) ([]ToolDef, error)

ListTools returns the server's advertised tools (tools/list).

func (*HTTPClient) Ping

func (c *HTTPClient) Ping(ctx context.Context) error

Ping issues an MCP ping round-trip to confirm the remote server is reachable and the session is still valid.

type HTTPConfig

type HTTPConfig struct {
	URL         string
	Headers     map[string]string
	BearerToken string
	Client      *http.Client
}

HTTPConfig declares how to reach a Streamable-HTTP MCP server: its endpoint URL plus optional static headers, bearer token, and an override http.Client.

type ManagedConfig

type ManagedConfig struct {
	Version       int                       `json:"version,omitempty"`
	ActiveProfile string                    `json:"activeProfile,omitempty"`
	Profiles      map[string]ManagedProfile `json:"profiles,omitempty"`
	MCPServers    map[string]ManagedServer  `json:"mcpServers"`
}

ManagedConfig is Aura's durable MCP server registry. It intentionally keeps the Claude-Desktop mcpServers shape so users can recognize and migrate config, while adding small Aura-owned metadata such as enabled/source.

func LoadManagedConfig

func LoadManagedConfig(path string) (ManagedConfig, error)

LoadManagedConfig reads path, returning an empty registry when it does not yet exist. A malformed file is an error because chat/tools must not silently ignore operator-intended MCP servers.

func (ManagedConfig) ActiveProfileName

func (c ManagedConfig) ActiveProfileName() string

ActiveProfileName returns the configured active profile, falling back to DefaultMCPProfile when none is set.

func (ManagedConfig) EnabledServers

func (c ManagedConfig) EnabledServers() (map[string]ServerConfig, error)

EnabledServers returns only enabled servers as runtime launch configs.

func (ManagedConfig) NormalizedTrust

func (c ManagedConfig) NormalizedTrust(name string) string

NormalizedTrust resolves a server's effective trust class, inferring it from the recipe source or HTTP type when unset and defaulting to TrustBlocked for unknown or missing servers.

func (ManagedConfig) ProfileServerNames

func (c ManagedConfig) ProfileServerNames(profile string) []string

ProfileServerNames returns the sorted, de-duplicated server names selected by the given profile (defaulting to the active profile); when the profile is undefined it falls back to all enabled servers.

type ManagedProfile

type ManagedProfile struct {
	Servers []string `json:"servers,omitempty"`
}

ManagedProfile is a named selection of servers, letting an operator scope which MCP servers are active at once.

type ManagedRuntime

type ManagedRuntime struct {
	Kind    string   `json:"kind,omitempty"`
	Image   string   `json:"image,omitempty"`
	Command []string `json:"command,omitempty"`
	Mounts  []string `json:"mounts,omitempty"`
	Network []string `json:"network,omitempty"`
	CPUs    string   `json:"cpus,omitempty"`
	Memory  string   `json:"memory,omitempty"`
	Profile string   `json:"profile,omitempty"`
}

ManagedRuntime describes how a stdio server is launched (local process, Docker container, or Docker gateway) and the container isolation knobs that apply.

type ManagedServer

type ManagedServer struct {
	Command string         `json:"command"`
	Args    []string       `json:"args,omitempty"`
	Env     []string       `json:"env,omitempty"`
	Enabled *bool          `json:"enabled,omitempty"`
	Source  string         `json:"source,omitempty"`
	Type    string         `json:"type,omitempty"`
	URL     string         `json:"url,omitempty"`
	Trust   ManagedTrust   `json:"trust,omitempty"`
	Runtime ManagedRuntime `json:"runtime,omitempty"`
}

ManagedServer is one configured MCP server in Aura's local registry. When Enabled is nil the server is enabled, matching the least-surprising behavior for imported Claude-style config.

type ManagedTrust

type ManagedTrust struct {
	Class      string `json:"class,omitempty"`
	ApprovedBy string `json:"approvedBy,omitempty"`
	ApprovedAt string `json:"approvedAt,omitempty"`
	Reason     string `json:"reason,omitempty"`
}

ManagedTrust records the trust class assigned to a server and the audit trail for that decision (who approved it, when, and why).

type ServerConfig

type ServerConfig struct {
	Command string   `json:"command"`
	Args    []string `json:"args,omitempty"`
	Env     []string `json:"env,omitempty"`
}

ServerConfig declares how to launch one stdio MCP server (Claude-Desktop shape). Env entries ("KEY=value") are explicit operator-declared child environment.

type ToolAnnotations

type ToolAnnotations struct {
	ReadOnlyHint bool `json:"readOnlyHint"`
}

ToolAnnotations carries optional trust/action hints advertised by an MCP server for one tool.

type ToolDef

type ToolDef struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema"`
	Annotations ToolAnnotations `json:"annotations"`
}

ToolDef is one entry from tools/list: the LLM-facing name, description, raw JSON-Schema, and annotations the bridge translates into an Aura tool schema.

type Transport

type Transport interface {
	ListTools(context.Context) ([]ToolDef, error)
	CallTool(context.Context, string, map[string]any) (string, error)
	Ping(context.Context) error
	Close() error
}

Transport is the common interface over an MCP server connection, implemented by both the stdio Client and the Streamable-HTTP HTTPClient.

func OpenServer

func OpenServer(ctx context.Context, name string, server ManagedServer) (Transport, error)

OpenServer opens the appropriate transport for a managed server, dispatching to OpenHTTP for streamable-HTTP servers (deriving auth from env) and to Open for stdio servers.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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