mcp

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package mcp implements the Model Context Protocol (MCP) server for OpenPass. It provides AI agent integration via stdio and HTTP transports with configurable access control, audit logging, and vault operations.

Package mcp implements the Model Context Protocol (MCP) for OpenPass.

Index

Constants

View Source
const (
	LatestSupportedProtocolVersion = "2025-11-25"
	DefaultHTTPProtocolVersion     = "2025-03-26"
)
View Source
const (
	ErrCodeParseError     = -32700
	ErrCodeInvalidRequest = -32600
	ErrCodeMethodNotFound = -32601
	ErrCodeInvalidParams  = -32602
	ErrCodeInternalError  = -32603
	ErrCodeServerError    = -32000
)

JSON-RPC error codes

Variables

View Source
var (
	ErrTransportClosed = fmt.Errorf("transport closed")
)

Common errors

Functions

func AgentFromContext

func AgentFromContext(ctx context.Context) string

func AgentHeaderMiddleware

func AgentHeaderMiddleware(next http.Handler) http.Handler

func BearerAuthMiddleware

func BearerAuthMiddleware(token string, next http.Handler) http.Handler

func IsSupportedProtocolVersion added in v1.1.1

func IsSupportedProtocolVersion(version string) bool

func IsTTYPresent

func IsTTYPresent() bool

IsTTYPresent checks if a TTY is available for reading and writing. Uses go-tty for cross-platform support (works on Unix and Windows).

func LoadOrCreateToken

func LoadOrCreateToken(path string) (string, error)

func NewMCPServer

func NewMCPServer(name, version string, opts ...serverOption) *mcpServer

NewMCPServer creates a new mcpServer instance

func OriginValidationMiddleware added in v1.1.1

func OriginValidationMiddleware(serverAddr string, next http.Handler) http.Handler

func RateLimiterMiddleware added in v1.1.0

func RateLimiterMiddleware(rl *RateLimiter, next http.Handler) http.Handler

func RotateToken added in v1.0.3

func RotateToken(path string) (string, error)

RotateToken generates a new token and writes it to the token file. This invalidates the previous token - any MCP clients using the old token will need to be updated with the new token.

func SecureInputPrompt added in v1.1.1

func SecureInputPrompt(prompt string, timeout time.Duration) (string, error)

SecureInputPrompt reads sensitive data from the user via TTY without echoing input. It displays a prompt on the terminal and reads the response with character hiding. The value is never exposed to the agent or logged. If TTY is not available, returns an error.

func ServeStdio

func ServeStdio(_ *mcpServer) error

ServeStdio is a no-op stub; OpenPass uses its own stdio transport

func TokenFilePath added in v1.0.3

func TokenFilePath(vaultDir string) string

TokenFilePath returns the default token file path for a vault directory.

func WithLogging

func WithLogging() serverOption

WithLogging is a no-op placeholder

func WithPromptCapabilities

func WithPromptCapabilities(_ bool) serverOption

WithPromptCapabilities is a no-op placeholder

func WithResourceCapabilities

func WithResourceCapabilities(_, _ bool) serverOption

WithResourceCapabilities is a no-op placeholder

func WithToolCapabilities

func WithToolCapabilities(_ bool) serverOption

WithToolCapabilities is a no-op placeholder

Types

type ApprovalRequest

type ApprovalRequest struct {
	Operation string
	Details   string
	Timeout   time.Duration
}

ApprovalRequest represents a request for user approval of a sensitive operation

type ApprovalResult

type ApprovalResult struct {
	Error    error
	Approved bool
}

ApprovalResult represents the outcome of an approval request

func RequestApproval

func RequestApproval(req ApprovalRequest) ApprovalResult

RequestApproval prompts the user via TTY for approval of a sensitive operation. It displays the operation details and waits for user input (y/yes to approve). The prompt times out after the specified duration (defaults to 30 seconds). If TTY is not available, the operation is denied with an error.

type CallToolRequest

type CallToolRequest struct {
	Arguments map[string]any
}

CallToolRequest represents a request to call an MCP tool

func (CallToolRequest) GetBool

func (r CallToolRequest) GetBool(key string, def bool) bool

func (CallToolRequest) GetFloat

func (r CallToolRequest) GetFloat(key string, def float64) float64

func (CallToolRequest) GetString

func (r CallToolRequest) GetString(key, def string) string

func (CallToolRequest) RequireFloat

func (r CallToolRequest) RequireFloat(key string) (float64, error)

func (CallToolRequest) RequireString

func (r CallToolRequest) RequireString(key string) (string, error)

type CallToolResult

type CallToolResult struct {
	Text    string
	IsError bool
}

CallToolResult represents the result of calling an MCP tool

func NewToolResultError

func NewToolResultError(msg string) *CallToolResult

NewToolResultError creates a new tool result representing an error

func NewToolResultText

func NewToolResultText(text string) *CallToolResult

NewToolResultText creates a new tool result containing text

type ClientInfo

type ClientInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ClientInfo represents information about the MCP client

type InitializeParams

type InitializeParams struct {
	ClientInfo      *ClientInfo     `json:"clientInfo"`
	ProtocolVersion string          `json:"protocolVersion"`
	Capabilities    json.RawMessage `json:"capabilities"`
}

InitializeParams represents the parameters of an initialize request

type InitializeResult

type InitializeResult struct {
	Capabilities    *ServerCapabilities `json:"capabilities"`
	ServerInfo      *ServerInfo         `json:"serverInfo"`
	ProtocolVersion string              `json:"protocolVersion"`
}

InitializeResult represents the result of an initialize request

type LoggingCapability

type LoggingCapability struct{}

LoggingCapability represents logging support

type Message

type Message struct {
	Error   *RPCError       `json:"error,omitempty"`
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method,omitempty"`
	ID      json.RawMessage `json:"id,omitempty"`
	Params  json.RawMessage `json:"params,omitempty"`
	Result  json.RawMessage `json:"result,omitempty"`
}

Message represents a JSON-RPC 2.0 message

func NewErrorResponse

func NewErrorResponse(id json.RawMessage, code int, message string, data any) *Message

NewErrorResponse creates a new JSON-RPC error response message

func NewRequest

func NewRequest(id any, method string, params any) (*Message, error)

NewRequest creates a new JSON-RPC request message

func NewResponse

func NewResponse(id json.RawMessage, result any) (*Message, error)

NewResponse creates a new JSON-RPC response message

func (*Message) IsNotification

func (m *Message) IsNotification() bool

IsNotification returns true if the message is a notification (no ID)

func (*Message) IsRequest

func (m *Message) IsRequest() bool

IsRequest returns true if the message is a request (has method and ID)

func (*Message) IsResponse

func (m *Message) IsResponse() bool

IsResponse returns true if the message is a response (has result or error)

func (*Message) ParseParams

func (m *Message) ParseParams(target any) error

ParseParams unmarshals the params into the given target

type MessageHandler

type MessageHandler func(ctx context.Context, msg *Message) (*Message, error)

MessageHandler is called for each incoming JSON-RPC message It should return the result or error to be sent back

type PromptsCapability

type PromptsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

PromptsCapability represents prompts support

type ProtocolHandler

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

ProtocolHandler handles MCP protocol messages

func NewProtocolHandler

func NewProtocolHandler(serverName, serverVersion string, tools *Server) *ProtocolHandler

NewProtocolHandler creates a new MCP protocol handler

func (*ProtocolHandler) Close

func (h *ProtocolHandler) Close() error

func (*ProtocolHandler) HandleMessage

func (h *ProtocolHandler) HandleMessage(ctx context.Context, msg *Message) (*Message, error)

HandleMessage handles incoming JSON-RPC messages

type RPCError

type RPCError struct {
	Data    any    `json:"data,omitempty"`
	Message string `json:"message"`
	Code    int    `json:"code"`
}

RPCError represents a JSON-RPC 2.0 error

func (*RPCError) Error

func (e *RPCError) Error() string

Error implements the error interface

type RateLimiter added in v1.1.0

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

func NewRateLimiter added in v1.1.0

func NewRateLimiter(limit int, dur time.Duration) *RateLimiter

func (*RateLimiter) Allow added in v1.1.0

func (rl *RateLimiter) Allow(ip string) bool

func (*RateLimiter) Cleanup added in v1.1.0

func (rl *RateLimiter) Cleanup()

func (*RateLimiter) CleanupCount added in v1.1.1

func (rl *RateLimiter) CleanupCount() int64

CleanupCount returns the total number of entries cleaned up since startup.

func (*RateLimiter) Close added in v1.1.0

func (rl *RateLimiter) Close() error

func (*RateLimiter) StartCleanup added in v1.1.1

func (rl *RateLimiter) StartCleanup(ctx context.Context, interval time.Duration) func()

StartCleanup starts a background goroutine that periodically calls Cleanup. It cleans up expired rate limit entries every interval duration until the context is canceled. Returns a cancellable stop function.

type ResourcesCapability

type ResourcesCapability struct {
	Subscribe   bool `json:"subscribe,omitempty"`
	ListChanged bool `json:"listChanged,omitempty"`
}

ResourcesCapability represents resources support

type Server

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

Server provides the MCP server functionality for OpenPass. It handles agent authentication, vault access, and tool execution.

func New

func New(v *vault.Vault, agentName string, transport string) (*Server, error)

New creates a new MCP server instance with the specified vault and agent configuration.

func (*Server) Build

func (s *Server) Build() *mcpServer

Build creates and configures an MCP server instance with tool capabilities.

func (*Server) Close

func (s *Server) Close() error

Close shuts down the server and closes the audit log.

func (*Server) RegisterTools

func (s *Server) RegisterTools(srv *mcpServer)

func (*Server) ServeStdio

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

ServeStdio runs the MCP server using stdio transport.

type ServerCapabilities

type ServerCapabilities struct {
	Tools     *ToolsCapability     `json:"tools,omitempty"`
	Resources *ResourcesCapability `json:"resources,omitempty"`
	Prompts   *PromptsCapability   `json:"prompts,omitempty"`
	Logging   *LoggingCapability   `json:"logging,omitempty"`
}

ServerCapabilities represents the capabilities of the MCP server

type ServerInfo

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ServerInfo represents information about the MCP server

type StdioTransport

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

StdioTransport implements MCP transport over stdin/stdout

func NewStdioTransport

func NewStdioTransport() *StdioTransport

NewStdioTransport creates a new stdio transport that reads from stdin and writes to stdout

func NewStdioTransportWithIO

func NewStdioTransportWithIO(input io.Reader, output io.Writer) *StdioTransport

NewStdioTransportWithIO creates a new stdio transport with custom input/output streams

func (*StdioTransport) Start

func (t *StdioTransport) Start(ctx context.Context, handler MessageHandler) error

Start begins reading from stdin and handling messages

func (*StdioTransport) Stop

func (t *StdioTransport) Stop(ctx context.Context) error

Stop gracefully shuts down the transport

type Tool

type Tool struct {
	Name        string
	Description string
}

Tool represents an MCP tool definition

func NewTool

func NewTool(name string, opts ...ToolOption) Tool

NewTool creates a new Tool with the given name and options

type ToolOption

type ToolOption func(*Tool)

ToolOption configures a Tool

func Default

func Default(_ any) ToolOption

Default is a no-op placeholder for default parameter values

func DefaultBool

func DefaultBool(_ bool) ToolOption

DefaultBool is a no-op placeholder for default boolean values

func DefaultNumber

func DefaultNumber(_ float64) ToolOption

DefaultNumber is a no-op placeholder for default number values

func Description

func Description(_ string) ToolOption

Description is a no-op placeholder for parameter descriptions

func Enum

func Enum(_ ...string) ToolOption

Enum is a no-op placeholder for enum parameter values

func Required

func Required() ToolOption

Required is a no-op placeholder for required parameter definitions

func WithBoolean

func WithBoolean(_ string, opts ...ToolOption) ToolOption

WithBoolean is a no-op placeholder for boolean parameter definitions

func WithDescription

func WithDescription(description string) ToolOption

WithDescription sets the tool description

func WithNumber

func WithNumber(_ string, opts ...ToolOption) ToolOption

WithNumber is a no-op placeholder for number parameter definitions

func WithString

func WithString(_ string, opts ...ToolOption) ToolOption

WithString is a no-op placeholder for string parameter definitions

type ToolsCapability

type ToolsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

ToolsCapability represents tools support

type Transport

type Transport interface {
	// Start begins the transport and blocks until Stop is called or an error occurs
	Start(ctx context.Context, handler MessageHandler) error
	// Stop gracefully shuts down the transport
	Stop(ctx context.Context) error
}

Transport defines the interface for MCP transports

Jump to

Keyboard shortcuts

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