mcp

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2025 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrorCodeParseError     = -32700
	ErrorCodeInvalidRequest = -32600
	ErrorCodeMethodNotFound = -32601
	ErrorCodeInvalidParams  = -32602
	ErrorCodeInternalError  = -32603
)

Error codes

View Source
const (
	ResourceSchemaPrefix = "schema://"
	ResourceTablePrefix  = "table://"
	ResourceDataPrefix   = "data://"
	ResourceModelPrefix  = "model://"
)

Resource URI prefixes

View Source
const (
	MethodInitialize    = "initialize"
	MethodResourcesList = "resources/list"
	MethodResourcesRead = "resources/read"
	MethodToolsList     = "tools/list"
	MethodToolsCall     = "tools/call"
	MethodPromptsList   = "prompts/list"
	MethodPromptsGet    = "prompts/get"
)

Core MCP methods

Variables

This section is empty.

Functions

This section is empty.

Types

type BatchQuery

type BatchQuery struct {
	SQL        string        `json:"sql"`
	Parameters []interface{} `json:"parameters,omitempty"`
	Label      string        `json:"label,omitempty"`
}

Advanced tool types

type BatchQueryResult

type BatchQueryResult struct {
	Index     int                      `json:"index"`
	Label     string                   `json:"label,omitempty"`
	SQL       string                   `json:"sql"`
	Results   []map[string]interface{} `json:"results,omitempty"`
	Count     int                      `json:"count"`
	Error     string                   `json:"error,omitempty"`
	Success   bool                     `json:"success"`
	Truncated bool                     `json:"truncated,omitempty"`
}

type CallToolParams

type CallToolParams struct {
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
}

type Capabilities

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

type ClientBucket

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

ClientBucket represents a token bucket for a specific client

type ClientInfo

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

type ColumnStats

type ColumnStats struct {
	DataType     string        `json:"data_type"`
	NullCount    int           `json:"null_count"`
	UniqueCount  int           `json:"unique_count"`
	MinValue     interface{}   `json:"min_value,omitempty"`
	MaxValue     interface{}   `json:"max_value,omitempty"`
	SampleValues []interface{} `json:"sample_values,omitempty"`
}

type FieldDefinition

type FieldDefinition struct {
	Name       string      `json:"name"`
	Type       string      `json:"type"`
	Attributes []string    `json:"attributes,omitempty"`
	Default    interface{} `json:"default,omitempty"`
}

type GetPromptParams

type GetPromptParams struct {
	Name      string            `json:"name"`
	Arguments map[string]string `json:"arguments,omitempty"`
}

type GetPromptResult

type GetPromptResult struct {
	Messages []PromptMessage `json:"messages"`
}

type Handler

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

Handler processes JSON-RPC requests

func NewHandler

func NewHandler(server *Server) *Handler

NewHandler creates a new JSON-RPC handler

func (*Handler) Handle

func (h *Handler) Handle(ctx context.Context, message json.RawMessage) json.RawMessage

Handle processes a JSON-RPC request and returns a response

func (*Handler) Initialize

func (h *Handler) Initialize(ctx context.Context, params json.RawMessage) (interface{}, error)

Initialize handles the initialize method

func (*Handler) PromptsGet

func (h *Handler) PromptsGet(ctx context.Context, params json.RawMessage) (interface{}, error)

PromptsGet handles the prompts/get method

func (*Handler) PromptsList

func (h *Handler) PromptsList(ctx context.Context, params json.RawMessage) (interface{}, error)

PromptsList handles the prompts/list method

func (*Handler) ResourcesList

func (h *Handler) ResourcesList(ctx context.Context, params json.RawMessage) (interface{}, error)

ResourcesList handles the resources/list method

func (*Handler) ResourcesRead

func (h *Handler) ResourcesRead(ctx context.Context, params json.RawMessage) (interface{}, error)

ResourcesRead handles the resources/read method

func (*Handler) ToolsCall

func (h *Handler) ToolsCall(ctx context.Context, params json.RawMessage) (interface{}, error)

ToolsCall handles the tools/call method

func (*Handler) ToolsList

func (h *Handler) ToolsList(ctx context.Context, params json.RawMessage) (interface{}, error)

ToolsList handles the tools/list method

type HandlerFunc

type HandlerFunc func(ctx context.Context, params json.RawMessage) (interface{}, error)

HandlerFunc represents a JSON-RPC method handler

type IndexDefinition

type IndexDefinition struct {
	Name   string   `json:"name,omitempty"`
	Fields []string `json:"fields"`
	Type   string   `json:"type,omitempty"` // UNIQUE, INDEX, etc.
}

type InitializeParams

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

MCP protocol types

type InitializeResult

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

type JSONRPCError

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

func (*JSONRPCError) Error

func (e *JSONRPCError) Error() string

Error implements the error interface

type JSONRPCRequest

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

JSON-RPC 2.0 message types

type JSONRPCResponse

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

type ListPromptsResult

type ListPromptsResult struct {
	Prompts []Prompt `json:"prompts"`
}

type ListResourcesResult

type ListResourcesResult struct {
	Resources []Resource `json:"resources"`
}

type ListToolsResult

type ListToolsResult struct {
	Tools []Tool `json:"tools"`
}

type MigrationInfo

type MigrationInfo struct {
	Version   string    `json:"version"`
	Name      string    `json:"name"`
	AppliedAt time.Time `json:"applied_at,omitempty"`
	SQL       string    `json:"sql,omitempty"`
}

type ModelAddFieldInput

type ModelAddFieldInput struct {
	Model string          `json:"model"`
	Field FieldDefinition `json:"field"`
}

type ModelAddRelationInput

type ModelAddRelationInput struct {
	Model    string             `json:"model"`
	Relation RelationDefinition `json:"relation"`
}

type ModelCreateInput

type ModelCreateInput struct {
	Name       string               `json:"name"`
	Fields     []FieldDefinition    `json:"fields"`
	Relations  []RelationDefinition `json:"relations,omitempty"`
	Indexes    []IndexDefinition    `json:"indexes,omitempty"`
	Attributes []string             `json:"attributes,omitempty"`
}

type ModelDefinition

type ModelDefinition struct {
	Name       string               `json:"name"`
	Fields     []FieldDefinition    `json:"fields"`
	Relations  []RelationDefinition `json:"relations,omitempty"`
	Indexes    []IndexDefinition    `json:"indexes,omitempty"`
	Attributes []string             `json:"attributes,omitempty"`
}

ORM-based types for model management

type ModelDeleteInput

type ModelDeleteInput struct {
	Model string `json:"model"`
	Force bool   `json:"force,omitempty"`
}

type ModelRemoveFieldInput

type ModelRemoveFieldInput struct {
	Model     string `json:"model"`
	FieldName string `json:"field_name"`
}

type ModelUpdateInput

type ModelUpdateInput struct {
	Model   string                 `json:"model"`
	Changes map[string]interface{} `json:"changes"`
}

type ORMAggregateInput

type ORMAggregateInput struct {
	Model   string                 `json:"model"`
	Where   map[string]interface{} `json:"where,omitempty"`
	Count   bool                   `json:"count,omitempty"`
	Avg     map[string]bool        `json:"avg,omitempty"`
	Sum     map[string]bool        `json:"sum,omitempty"`
	Min     map[string]bool        `json:"min,omitempty"`
	Max     map[string]bool        `json:"max,omitempty"`
	GroupBy []string               `json:"groupBy,omitempty"`
}

type ORMCountInput

type ORMCountInput struct {
	Model string                 `json:"model"`
	Where map[string]interface{} `json:"where,omitempty"`
}

type ORMCreateInput

type ORMCreateInput struct {
	Model string                 `json:"model"`
	Data  map[string]interface{} `json:"data"`
}

type ORMDeleteInput

type ORMDeleteInput struct {
	Model string                 `json:"model"`
	Where map[string]interface{} `json:"where"`
}

type ORMFindManyInput

type ORMFindManyInput struct {
	Model   string                 `json:"model"`
	Where   map[string]interface{} `json:"where,omitempty"`
	Include map[string]interface{} `json:"include,omitempty"`
	OrderBy map[string]interface{} `json:"orderBy,omitempty"`
	Take    int                    `json:"take,omitempty"`
	Skip    int                    `json:"skip,omitempty"`
}

type ORMFindUniqueInput

type ORMFindUniqueInput struct {
	Model   string                 `json:"model"`
	Where   map[string]interface{} `json:"where"`
	Include map[string]interface{} `json:"include,omitempty"`
}

type ORMQuery

type ORMQuery struct {
	Model  string                 `json:"model"`
	Action string                 `json:"action"` // findMany, findUnique, create, update, delete, count, aggregate
	Query  map[string]interface{} `json:"query"`
}

ORM query types

type ORMUpdateInput

type ORMUpdateInput struct {
	Model string                 `json:"model"`
	Where map[string]interface{} `json:"where"`
	Data  map[string]interface{} `json:"data"`
}

type ORMWhereCondition

type ORMWhereCondition struct {
	Field    string              `json:"field,omitempty"`
	Operator string              `json:"operator,omitempty"`
	Value    interface{}         `json:"value,omitempty"`
	AND      []ORMWhereCondition `json:"AND,omitempty"`
	OR       []ORMWhereCondition `json:"OR,omitempty"`
	NOT      *ORMWhereCondition  `json:"NOT,omitempty"`
}

type Prompt

type Prompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description,omitempty"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

Prompt types

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

type PromptContent

type PromptContent struct {
	Type     string    `json:"type"`
	Text     string    `json:"text,omitempty"`
	Resource *Resource `json:"resource,omitempty"`
}

type PromptMessage

type PromptMessage struct {
	Role    string        `json:"role"`
	Content PromptContent `json:"content"`
}

type PromptsCapability

type PromptsCapability struct{}

type RateLimiter

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

RateLimiter implements token bucket rate limiting

func NewRateLimiter

func NewRateLimiter(requestsPerMin, burstLimit int) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

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

Allow checks if a request from the given client IP is allowed

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop stops the rate limiter cleanup routine

type ReadResourceParams

type ReadResourceParams struct {
	URI string `json:"uri"`
}

type ReadResourceResult

type ReadResourceResult struct {
	Contents []ResourceContent `json:"contents"`
}

type RelationDefinition

type RelationDefinition struct {
	Name       string   `json:"name"`
	Type       string   `json:"type"`
	Model      string   `json:"model"`
	Fields     []string `json:"fields,omitempty"`
	References []string `json:"references,omitempty"`
	Attributes []string `json:"attributes,omitempty"`
}

type Resource

type Resource struct {
	URI         string                 `json:"uri"`
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	MimeType    string                 `json:"mimeType,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

Resource types

type ResourceContent

type ResourceContent struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType"`
	Text     string `json:"text,omitempty"`
	Blob     string `json:"blob,omitempty"`
}

type ResourcesCapability

type ResourcesCapability struct{}

type SchemaDiffInput

type SchemaDiffInput struct {
	Detailed bool `json:"detailed,omitempty"`
}

type SchemaExportInput

type SchemaExportInput struct {
	Format string `json:"format,omitempty"` // "prisma" or "json"
}

type SchemaImportInput

type SchemaImportInput struct {
	Schema string `json:"schema"`
	Format string `json:"format,omitempty"` // "prisma" or "json"
}

type SchemaOperation

type SchemaOperation struct {
	Type    string                 `json:"type"` // create, update, delete
	Model   string                 `json:"model,omitempty"`
	Changes map[string]interface{} `json:"changes,omitempty"`
}

Schema management types

type SchemaSyncInput

type SchemaSyncInput struct {
	Force       bool `json:"force,omitempty"`
	DryRun      bool `json:"dry_run,omitempty"`
	IncludeDrop bool `json:"include_drop,omitempty"`
}

type SecurityConfig

type SecurityConfig struct {
	// Authentication
	EnableAuth   bool
	APIKey       string
	AllowedHosts []string

	// Rate limiting
	EnableRateLimit bool
	RequestsPerMin  int
	BurstLimit      int

	// Permissions
	AllowedTables   []string
	ForbiddenTables []string
	ReadOnlyMode    bool
	MaxQueryRows    int
	QueryTimeout    time.Duration

	// SQL validation
	AllowedPatterns  []string
	ForbiddenQueries []string
}

SecurityConfig holds security configuration

type SecurityManager

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

SecurityManager handles authentication, authorization, and rate limiting

func NewSecurityManager

func NewSecurityManager(config SecurityConfig) *SecurityManager

NewSecurityManager creates a new security manager

func (*SecurityManager) AuthenticateRequest

func (sm *SecurityManager) AuthenticateRequest(r *http.Request) error

AuthenticateRequest validates authentication for HTTP requests

func (*SecurityManager) CheckRateLimit

func (sm *SecurityManager) CheckRateLimit(clientIP string) error

CheckRateLimit verifies if the request is within rate limits

func (*SecurityManager) GetStats

func (sm *SecurityManager) GetStats() map[string]interface{}

GetStats returns security statistics

func (*SecurityManager) SecurityMiddleware

func (sm *SecurityManager) SecurityMiddleware(next http.Handler) http.Handler

SecurityMiddleware returns an HTTP middleware for security validation

func (*SecurityManager) ValidateHost

func (sm *SecurityManager) ValidateHost(r *http.Request) error

ValidateHost checks if the request comes from an allowed host

func (*SecurityManager) ValidateQuery

func (sm *SecurityManager) ValidateQuery(sql string) error

ValidateQuery performs SQL query validation

func (*SecurityManager) ValidateTableAccess

func (sm *SecurityManager) ValidateTableAccess(tableName string) error

ValidateTableAccess checks if access to a table is allowed

type Server

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

Server represents an MCP server instance

func NewServer

func NewServer(config ServerConfig) (*Server, error)

NewServer creates a new MCP server instance

func (*Server) CallTool

func (s *Server) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolResult, error)

CallTool executes a tool

func (*Server) GetDatabase

func (s *Server) GetDatabase() types.Database

GetDatabase returns the database instance

func (*Server) GetPrompt

func (s *Server) GetPrompt(ctx context.Context, name string, arguments map[string]string) (*GetPromptResult, error)

GetPrompt returns a prompt with filled template

func (*Server) GetSchemas

func (s *Server) GetSchemas() map[string]*schema.Schema

GetSchemas returns all loaded schemas

func (*Server) ListPrompts

func (s *Server) ListPrompts() []Prompt

ListPrompts returns available prompts

func (*Server) ListResources

func (s *Server) ListResources(ctx context.Context) ([]Resource, error)

ListResources returns available resources

func (*Server) ListTools

func (s *Server) ListTools() []Tool

ListTools returns available tools

func (*Server) ReadResource

func (s *Server) ReadResource(ctx context.Context, uri string) (*ResourceContent, error)

ReadResource handles resource read requests

func (*Server) RegisterSchema

func (s *Server) RegisterSchema(name string, sch *schema.Schema)

RegisterSchema registers a schema with the server

func (*Server) SetDatabase

func (s *Server) SetDatabase(db types.Database)

SetDatabase sets the database instance (for testing)

func (*Server) Start

func (s *Server) Start() error

Start starts the MCP server

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the MCP server

type ServerConfig

type ServerConfig struct {
	DatabaseURI   string
	SchemaPath    string
	Transport     string   // "stdio" or "http"
	Port          int      // For HTTP transport
	ReadOnly      bool     // Default: true
	MaxQueryRows  int      // Default: 1000
	AllowedTables []string // Empty = all tables
	LogLevel      string

	// Security settings
	Security SecurityConfig
}

ServerConfig holds MCP server configuration

type ServerInfo

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

type TableAnalysis

type TableAnalysis struct {
	Table      string                 `json:"table"`
	TotalRows  int64                  `json:"total_rows"`
	SampleSize int                    `json:"sample_size"`
	Schema     interface{}            `json:"schema"`
	Statistics map[string]ColumnStats `json:"statistics"`
}

type Tool

type Tool struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema"`
}

Tool types

type ToolContent

type ToolContent struct {
	Type     string                 `json:"type"`
	Text     string                 `json:"text,omitempty"`
	Blob     string                 `json:"blob,omitempty"`
	Resource *Resource              `json:"resource,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

type ToolResult

type ToolResult struct {
	Content []ToolContent `json:"content"`
	IsError bool          `json:"isError,omitempty"`
}

type ToolsCapability

type ToolsCapability struct{}

type Transport

type Transport interface {
	Start() error
	Stop() error
	Send(message json.RawMessage) error
	Receive() (json.RawMessage, error)
}

Transport interface for different communication methods

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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