mcp

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2025 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// JSON-RPC 2.0 standard error codes
	ParseError     = -32700 // Invalid JSON was received
	InvalidRequest = -32600 // The JSON sent is not a valid Request object
	MethodNotFound = -32601 // The method does not exist
	InvalidParams  = -32602 // Invalid method parameters
	InternalError  = -32603 // Internal JSON-RPC error

	// Custom domain error codes (10xxx range)
	LanguageNotFound = 10001 // No provider for the specified language
	SyntaxError      = 10002 // Source code parsing failed
	NoMatches        = 10003 // Query returned no results
	TransformFailed  = 10004 // Transformation operation failed
	StageNotFound    = 10005 // Staging ID doesn't exist
	StageExpired     = 10006 // Staging has expired
	AlreadyApplied   = 10007 // Stage was already applied
	DatabaseError    = 10008 // Database operation failed
	ConfidenceTooLow = 10009 // Confidence below threshold
	ValidationFailed = 10010 // Code validation failed
)

Error codes following JSON-RPC 2.0 standard and custom domain errors

Variables

This section is empty.

Functions

This section is empty.

Types

type AsyncStagingManager

type AsyncStagingManager struct {
	*StagingManager
	// contains filtered or unexported fields
}

AsyncStagingManager handles staging with goroutine pool

func NewAsyncStagingManager

func NewAsyncStagingManager(db *gorm.DB, config Config) *AsyncStagingManager

NewAsyncStagingManager creates concurrent staging manager

func (*AsyncStagingManager) BatchCreateStages

func (asm *AsyncStagingManager) BatchCreateStages(stages []*models.Stage) []error

BatchCreateStages creates multiple stages concurrently

func (*AsyncStagingManager) Close

func (asm *AsyncStagingManager) Close()

Close shuts down worker pool

func (*AsyncStagingManager) CreateStageAsync

func (asm *AsyncStagingManager) CreateStageAsync(stage *models.Stage) <-chan error

CreateStageAsync stages transformation without blocking

type AuthMode added in v1.1.0

type AuthMode string

AuthMode represents the authentication mode

const (
	AuthModeNone   AuthMode = "none"   // --no-auth
	AuthModeAPIKey AuthMode = "apikey" // --api-key (default)
	AuthModeOAuth  AuthMode = "oauth"  // --oauth-provider
)

type ClientRegistrationRequest added in v1.1.0

type ClientRegistrationRequest struct {
	RedirectURIs            []string `json:"redirect_uris"`
	GrantTypes              []string `json:"grant_types,omitempty"`
	ResponseTypes           []string `json:"response_types,omitempty"`
	Scope                   string   `json:"scope,omitempty"`
	ClientName              string   `json:"client_name,omitempty"`
	ClientURI               string   `json:"client_uri,omitempty"`
	LogoURI                 string   `json:"logo_uri,omitempty"`
	Contacts                []string `json:"contacts,omitempty"`
	TosURI                  string   `json:"tos_uri,omitempty"`
	PolicyURI               string   `json:"policy_uri,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method,omitempty"`
	ApplicationType         string   `json:"application_type,omitempty"`
}

ClientRegistrationRequest represents RFC7591 client registration request

type ClientRegistrationResponse added in v1.1.0

type ClientRegistrationResponse struct {
	ClientID                string   `json:"client_id"`
	ClientSecret            string   `json:"client_secret,omitempty"`
	ClientSecretExpiresAt   int64    `json:"client_secret_expires_at"`
	RedirectURIs            []string `json:"redirect_uris"`
	GrantTypes              []string `json:"grant_types"`
	ResponseTypes           []string `json:"response_types"`
	Scope                   string   `json:"scope,omitempty"`
	ClientName              string   `json:"client_name,omitempty"`
	ClientURI               string   `json:"client_uri,omitempty"`
	LogoURI                 string   `json:"logo_uri,omitempty"`
	Contacts                []string `json:"contacts,omitempty"`
	TosURI                  string   `json:"tos_uri,omitempty"`
	PolicyURI               string   `json:"policy_uri,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method"`
	ApplicationType         string   `json:"application_type"`
}

ClientRegistrationResponse represents RFC7591 client registration response

type Config

type Config struct {
	// Database
	DatabaseURL string

	// Auto-apply settings
	AutoApplyEnabled   bool
	AutoApplyThreshold float64

	// Staging
	StagingTTL time.Duration

	// Session limits
	MaxStagesPerSession  int
	MaxAppliesPerSession int

	// Debug
	Debug bool
}

Config holds the MCP server configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a config with sensible defaults

type Error

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

Error represents a JSON-RPC 2.0 error

type GoogleUserInfo added in v1.1.0

type GoogleUserInfo struct {
	Sub           string `json:"sub"`
	Email         string `json:"email"`
	EmailVerified bool   `json:"email_verified"`
	Name          string `json:"name"`
	Picture       string `json:"picture"`
	GivenName     string `json:"given_name"`
	FamilyName    string `json:"family_name"`
}

GoogleUserInfo represents Google userinfo response

type HTTPServer

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

HTTPServer handles MCP communication over HTTP

func NewHTTPServer

func NewHTTPServer(
	config Config,
	host string,
	port int,
	apiKey, corsOrigin string,
	noAuth bool,
	oauthConfig *OAuthConfig,
) (*HTTPServer, error)

NewHTTPServer creates a new HTTP server that provides MCP functionality via REST API

func (*HTTPServer) Close

func (s *HTTPServer) Close() error

Close closes the HTTP server and cleans up resources

func (*HTTPServer) Start

func (s *HTTPServer) Start() error

Start starts the HTTP server

type JWK added in v1.1.0

type JWK struct {
	Kty string   `json:"kty"` // Key Type
	Kid string   `json:"kid"` // Key ID
	Use string   `json:"use"` // Public Key Use
	N   string   `json:"n"`   // RSA Modulus
	E   string   `json:"e"`   // RSA Exponent
	X5c []string `json:"x5c"` // X.509 Certificate Chain
}

JWK represents a JSON Web Key

type JWKSet added in v1.1.0

type JWKSet struct {
	Keys []JWK `json:"keys"`
}

JWKSet represents a JSON Web Key Set

type MCPError

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

MCPError represents a structured error for the MCP protocol

func NewMCPError

func NewMCPError(code int, message string, data ...any) *MCPError

NewMCPError creates a new MCP error with optional data

func WrapError

func WrapError(code int, message string, err error) *MCPError

WrapError wraps a regular error into an MCP error

func (*MCPError) Error

func (e *MCPError) Error() string

Error implements the error interface

type Notification

type Notification struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

Notification is a request without an ID (no response expected)

type OAuthConfig added in v1.1.0

type OAuthConfig struct {
	Provider     OAuthProvider
	ClientID     string
	ClientSecret string
	IssuerURL    string
	JWKSURL      string
	Audience     string
	Scopes       []string

	// Provider-specific
	Domain string // For Auth0

	// Validation settings
	SkipIssuerCheck   bool
	SkipAudienceCheck bool
	AllowExpired      bool // DANGEROUS: only for testing
}

OAuthConfig holds OAuth configuration

type OAuthProvider added in v1.1.0

type OAuthProvider string

OAuthProvider represents different OAuth providers

const (
	OAuthProviderOpenAI OAuthProvider = "openai"
	OAuthProviderGitHub OAuthProvider = "github"
	OAuthProviderGoogle OAuthProvider = "google"
	OAuthProviderAuth0  OAuthProvider = "auth0"
	OAuthProviderCustom OAuthProvider = "custom"
)

type OAuthSession added in v1.1.0

type OAuthSession struct {
	State         string    `json:"state"`          // CSRF protection
	CodeVerifier  string    `json:"code_verifier"`  // PKCE verifier
	CodeChallenge string    `json:"code_challenge"` // PKCE challenge
	Provider      string    `json:"provider"`       // oauth provider
	RedirectURI   string    `json:"redirect_uri"`   // where to redirect after auth
	Scopes        []string  `json:"scopes"`         // requested scopes
	Resource      string    `json:"resource"`       // RFC 8707 resource indicator
	ExpiresAt     time.Time `json:"expires_at"`     // session expiration

	// Client context
	ClientID string            `json:"client_id,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

OAuthSession represents an active OAuth flow session

type OAuthSessionStore added in v1.1.0

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

OAuthSessionStore manages active OAuth sessions

func NewOAuthSessionStore added in v1.1.0

func NewOAuthSessionStore(cleanupInterval time.Duration) *OAuthSessionStore

NewOAuthSessionStore creates a new session store

func (*OAuthSessionStore) Close added in v1.1.0

func (s *OAuthSessionStore) Close()

Close stops the session store

func (*OAuthSessionStore) ConsumeSession added in v1.1.0

func (s *OAuthSessionStore) ConsumeSession(state string) (*OAuthSession, bool)

ConsumeSession retrieves and deletes a session (one-time use)

func (*OAuthSessionStore) CreateSession added in v1.1.0

func (s *OAuthSessionStore) CreateSession(
	provider, redirectURI, resource string,
	scopes []string,
) (*OAuthSession, error)

CreateSession creates a new OAuth session with PKCE

func (*OAuthSessionStore) CreateSessionWithChatGPTPKCE added in v1.1.0

func (s *OAuthSessionStore) CreateSessionWithChatGPTPKCE(
	state, provider string,
	scopes []string,
	codeChallenge, challengeMethod string,
) (*OAuthSession, error)

CreateSessionWithChatGPTPKCE creates session using ChatGPT's PKCE parameters (MCP flow)

func (*OAuthSessionStore) CreateSessionWithState added in v1.1.0

func (s *OAuthSessionStore) CreateSessionWithState(
	state, provider string,
	scopes []string,
) (*OAuthSession, error)

CreateSessionWithState creates OAuth session using provided state (for MCP)

func (*OAuthSessionStore) GetSession added in v1.1.0

func (s *OAuthSessionStore) GetSession(state string) (*OAuthSession, bool)

GetSession retrieves a session by state

func (*OAuthSessionStore) Stats added in v1.1.0

func (s *OAuthSessionStore) Stats() map[string]any

Stats returns session store statistics

type OAuthValidator added in v1.1.0

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

OAuthValidator validates OAuth tokens

func NewOAuthValidator added in v1.1.0

func NewOAuthValidator(config *OAuthConfig, debug bool) (*OAuthValidator, error)

NewOAuthValidator creates a new OAuth validator

func (*OAuthValidator) ExtractScopes added in v1.1.0

func (v *OAuthValidator) ExtractScopes(claims jwt.MapClaims) []string

ExtractScopes extracts scopes from claims

func (*OAuthValidator) GetSubject added in v1.1.0

func (v *OAuthValidator) GetSubject(claims jwt.MapClaims) string

GetSubject extracts the subject (user ID) from claims

func (*OAuthValidator) HasScope added in v1.1.0

func (v *OAuthValidator) HasScope(claims jwt.MapClaims, requiredScope string) bool

HasScope checks if the token has a specific scope

func (*OAuthValidator) ValidateToken added in v1.1.0

func (v *OAuthValidator) ValidateToken(tokenString string) (jwt.MapClaims, error)

ValidateToken validates an OAuth token

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
	ID      any             `json:"id"`
}

Request represents a JSON-RPC 2.0 request

type Response

type Response struct {
	JSONRPC string `json:"jsonrpc"`
	Result  any    `json:"result,omitempty"`
	Error   *Error `json:"error,omitempty"`
	ID      any    `json:"id"`
}

Response represents a JSON-RPC 2.0 response

func ErrorResponse

func ErrorResponse(id any, code int, message string) Response

ErrorResponse creates a JSON-RPC error response

func ErrorResponseWithData

func ErrorResponseWithData(id any, code int, message string, data any) Response

ErrorResponseWithData creates a JSON-RPC error response with additional data

func SuccessResponse

func SuccessResponse(id, result any) Response

Standard JSON-RPC error codes SuccessResponse creates a success response

type StagingManager

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

StagingManager handles staging and applying transformations

func NewStagingManager

func NewStagingManager(db *gorm.DB, config Config) *StagingManager

NewStagingManager creates a new staging manager

func (*StagingManager) ApplyStage

func (sm *StagingManager) ApplyStage(stageID string, autoApplied bool) (*models.Apply, error)

ApplyStage applies a staged transformation

func (*StagingManager) CleanupExpiredStages

func (sm *StagingManager) CleanupExpiredStages() error

CleanupExpiredStages marks expired stages

func (*StagingManager) CreateStage

func (sm *StagingManager) CreateStage(stage *models.Stage) error

CreateStage creates a new staged transformation

func (*StagingManager) GetStage

func (sm *StagingManager) GetStage(id string) (*models.Stage, error)

GetStage retrieves a stage by ID

func (*StagingManager) ListPendingStages

func (sm *StagingManager) ListPendingStages(sessionID string) ([]models.Stage, error)

ListPendingStages lists all pending stages for a session

type StdioServer

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

StdioServer handles MCP communication over stdio

func NewStdioServer

func NewStdioServer(config Config) (*StdioServer, error)

NewStdioServer creates a new MCP server that communicates over stdio

func (*StdioServer) Close

func (s *StdioServer) Close() error

Close cleans up resources

func (*StdioServer) RegisterTool

func (s *StdioServer) RegisterTool(name string, handler ToolHandler)

RegisterTool adds a custom tool handler

func (*StdioServer) Start

func (s *StdioServer) Start() error

Start begins processing JSON-RPC requests from stdin

type ToolDefinition

type ToolDefinition struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	InputSchema map[string]any `json:"inputSchema"`
}

ToolDefinition describes a tool for the client

func GetToolDefinitions

func GetToolDefinitions() []ToolDefinition

GetToolDefinitions returns all available tool definitions

type ToolHandler

type ToolHandler func(params json.RawMessage) (any, error)

ToolHandler represents a function that handles a tool call

Jump to

Keyboard shortcuts

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