mcpserver

package
v0.0.0-...-4912550 Latest Latest
Warning

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

Go to latest
Published: May 6, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Standard JSON-RPC 2.0 error codes
	ErrorCodeParseError     = -32700 // Invalid JSON was received by the server
	ErrorCodeInvalidRequest = -32600 // The JSON sent is not a valid Request object
	ErrorCodeMethodNotFound = -32601 // The method does not exist / is not available
	ErrorCodeInvalidParams  = -32602 // Invalid method parameter(s)
	ErrorCodeInternalError  = -32603 // Internal JSON-RPC error

	// MCP-specific error codes (from MCP specification)
	// See: https://spec.modelcontextprotocol.io/specification/basic/errors/
	ErrorCodeResourceNotFound = -32002 // Requested resource was not found

	// Custom Cosmo MCP server error codes
	// These use the reserved range -32000 to -32099 for implementation-defined server errors
	ErrorCodeAuthenticationRequired = -32001 // Authentication required (OAuth/JWT)
	ErrorCodeInsufficientScope      = -32003 // Token lacks required OAuth scopes (RFC 6750)
)

JSON-RPC 2.0 and MCP error codes

Error code ranges: - Standard JSON-RPC 2.0: -32768 to -32000 (reserved by JSON-RPC spec) - Server errors (implementation-defined): -32000 to -32099 (within JSON-RPC reserved range) - Application errors: Must use codes outside -32768 to -32000 to avoid conflicts with JSON-RPC reserved codes

View Source
const (
	ErrorMessageAuthenticationRequired = "Authentication required"
	ErrorMessageInsufficientScope      = "Insufficient scope"
	ErrorMessageResourceNotFound       = "Resource not found"
	ErrorMessageInvalidParams          = "Invalid params"
	ErrorMessageInternalError          = "Internal error"
)

Error messages

Variables

This section is empty.

Functions

func GetClaimsFromContext

func GetClaimsFromContext(ctx context.Context) (authentication.Claims, bool)

GetClaimsFromContext retrieves authenticated user claims from context.

func WithCORS

func WithCORS(corsCfg cors.Config) func(*Options)

func WithEnableArbitraryOperations

func WithEnableArbitraryOperations(enableArbitraryOperations bool) func(*Options)

WithEnableArbitraryOperations sets the enable arbitrary operations option

func WithExcludeMutations

func WithExcludeMutations(excludeMutations bool) func(*Options)

WithExcludeMutations sets the exclude mutations option

func WithExposeSchema

func WithExposeSchema(exposeSchema bool) func(*Options)

WithExposeSchema sets the expose schema option

func WithGraphName

func WithGraphName(graphName string) func(*Options)

WithGraphName sets the graph name

func WithListenAddr

func WithListenAddr(listenAddr string) func(*Options)

WithListenAddr sets the listen address

func WithLogger

func WithLogger(logger *zap.Logger) func(*Options)

func WithOAuth

func WithOAuth(oauthCfg *config.MCPOAuthConfiguration) func(*Options)

WithOAuth sets the OAuth configuration

func WithOmitToolNamePrefix

func WithOmitToolNamePrefix(omitToolNamePrefix bool) func(*Options)

WithOmitToolNamePrefix sets the omit tool name prefix option

func WithOperationsDir

func WithOperationsDir(operationsDir string) func(*Options)

WithOperationsDir sets the operations directory

func WithResourceDocumentation

func WithResourceDocumentation(url string) func(*Options)

WithResourceDocumentation sets the human-readable documentation URL for RFC 9728 metadata

func WithServerBaseURL

func WithServerBaseURL(baseURL string) func(*Options)

WithServerBaseURL sets the server base URL for OAuth discovery

func WithStateless

func WithStateless(stateless bool) func(*Options)

WithStateless sets the stateless option

Types

type ExecuteGraphQLInput

type ExecuteGraphQLInput struct {
	Query     string          `json:"query"`
	Variables json.RawMessage `json:"variables,omitempty"`
}

ExecuteGraphQLInput defines the input structure for the execute_graphql tool

type FieldScopeRequirement

type FieldScopeRequirement struct {
	TypeName  string
	FieldName string
	OrScopes  [][]string
}

FieldScopeRequirement represents the scope requirement for a single field. OrScopes is a list of AND-groups — satisfy any one group to access the field. e.g., [["a", "b"], ["c"]] means (a AND b) OR (c)

type GraphQLError

type GraphQLError struct {
	Message string `json:"message"`
}

GraphQLError represents an error returned in a GraphQL response

type GraphQLOperationInfoInput

type GraphQLOperationInfoInput struct {
	OperationName string `json:"operationName"`
}

GraphQLOperationInfoInput defines the input structure for the graphql_operation_info tool.

type GraphQLOperationInfoResponse

type GraphQLOperationInfoResponse struct {
	Name           string          `json:"name"`
	Description    string          `json:"description"`
	OperationType  string          `json:"operationType"`
	HasSideEffects bool            `json:"hasSideEffects"`
	Schema         json.RawMessage `json:"schema,omitempty"`
	Query          string          `json:"query"`
	LLMGuidance    LLMGuidance     `json:"llmGuidance"`
	Endpoint       string          `json:"endpoint"`
	RequiredScopes [][]string      `json:"requiredScopes,omitempty"`
}

GraphQLOperationInfoResponse is the response structure for the graphql_operation_info tool.

type GraphQLResponse

type GraphQLResponse struct {
	Errors []GraphQLError  `json:"errors"`
	Data   json.RawMessage `json:"data"`
}

GraphQLResponse represents a GraphQL response structure

type GraphQLSchemaServer

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

GraphQLSchemaServer represents an MCP server that works with GraphQL schemas and operations

func NewGraphQLSchemaServer

func NewGraphQLSchemaServer(ctx context.Context, routerGraphQLEndpoint string, opts ...func(*Options)) (*GraphQLSchemaServer, error)

NewGraphQLSchemaServer creates a new GraphQL schema server

func (*GraphQLSchemaServer) GetResourceMetadataURL

func (s *GraphQLSchemaServer) GetResourceMetadataURL() string

GetResourceMetadataURL returns the URL for the OAuth 2.0 Protected Resource Metadata endpoint

func (*GraphQLSchemaServer) Reload

func (s *GraphQLSchemaServer) Reload(schema *ast.Document, fieldConfigs []*nodev1.FieldConfiguration) error

Reload reloads the operations and schema, and computes per-tool scope requirements from @requiresScopes directives in the field configurations.

func (*GraphQLSchemaServer) Serve

func (s *GraphQLSchemaServer) Serve() (*http.Server, error)

Serve starts the server with the configured options and returns the HTTP server.

func (*GraphQLSchemaServer) SetHTTPClient

func (s *GraphQLSchemaServer) SetHTTPClient(client *http.Client)

SetHTTPClient allows setting a custom HTTP client (useful for testing)

func (*GraphQLSchemaServer) Start

func (s *GraphQLSchemaServer) Start() error

Start loads operations and starts the server

func (*GraphQLSchemaServer) Stop

Stop gracefully shuts down the MCP server

type LLMGuidance

type LLMGuidance struct {
	HTTPUsage      string   `json:"httpUsage"`
	GraphQLRequest string   `json:"graphqlRequest"`
	ExecutionTips  []string `json:"executionTips"`
}

LLMGuidance provides guidance for LLMs on how to use the GraphQL operations

type Logger

type Logger interface {
	Infof(format string, v ...any)
	Errorf(format string, v ...any)
}

Logger interface as expected by the server.WithLogger function

type MCPAuthMiddleware

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

MCPAuthMiddleware provides HTTP-level authentication and scope enforcement for MCP.

func NewMCPAuthMiddleware

func NewMCPAuthMiddleware(tokenDecoder authentication.TokenDecoder, resourceMetadataURL string, scopes config.MCPOAuthScopesConfiguration, scopeChallengeIncludeTokenScopes bool) (*MCPAuthMiddleware, error)

NewMCPAuthMiddleware creates a new authentication middleware.

func (*MCPAuthMiddleware) HTTPMiddleware

func (m *MCPAuthMiddleware) HTTPMiddleware(next http.Handler) http.Handler

HTTPMiddleware wraps HTTP handlers with authentication for ALL MCP operations. Per MCP spec: "authorization MUST be included in every HTTP request from client to server"

func (*MCPAuthMiddleware) SetScopeExtractor

func (m *MCPAuthMiddleware) SetScopeExtractor(extractor *ScopeExtractor)

SetScopeExtractor atomically replaces the scope extractor used for runtime scope checking of execute_graphql arbitrary operations.

func (*MCPAuthMiddleware) SetToolScopes

func (m *MCPAuthMiddleware) SetToolScopes(scopes map[string][][]string)

SetToolScopes atomically replaces the per-tool scope map.

type OperationInfo

type OperationInfo struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Schema      json.RawMessage `json:"schema,omitempty"`
	Query       string          `json:"query"`
}

OperationInfo contains metadata about a GraphQL operation

type OperationsManager

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

OperationsManager handles the loading and preparation of GraphQL operations

func NewOperationsManager

func NewOperationsManager(schemaDoc *ast.Document, logger *zap.Logger, excludeMutations bool) *OperationsManager

NewOperationsManager creates a new operations manager

func (*OperationsManager) ComputeToolScopes

func (om *OperationsManager) ComputeToolScopes(fieldConfigs []*nodev1.FieldConfiguration, maxScopeCombinations int) error

ComputeToolScopes runs the scope extractor against all loaded operations, populating each operation's RequiredScopes from @requiresScopes directives. Returns an error if any operation exceeds the scope combination limit, which indicates a pathological @requiresScopes configuration that should be simplified.

func (*OperationsManager) GetFilteredOperations

func (om *OperationsManager) GetFilteredOperations() []schemaloader.Operation

GetFilteredOperations returns operations filtered by excludeMutations setting

func (*OperationsManager) GetOperation

func (om *OperationsManager) GetOperation(name string) *schemaloader.Operation

GetOperation gets a specific operation by name

func (*OperationsManager) GetOperations

func (om *OperationsManager) GetOperations() []schemaloader.Operation

GetOperations returns all loaded operations

func (*OperationsManager) GetSchema

func (om *OperationsManager) GetSchema() *ast.Document

GetSchema returns the schema document used by the operations manager

func (*OperationsManager) LoadOperationsFromDirectory

func (om *OperationsManager) LoadOperationsFromDirectory(operationsDir string) error

LoadOperationsFromDirectory loads operations from a specified directory

type OperationsResponse

type OperationsResponse struct {
	Operations  []OperationInfo `json:"operations"`
	Usage       string          `json:"usage"`
	LLMGuidance LLMGuidance     `json:"llmGuidance"`
	Endpoint    string          `json:"endpoint"`
}

OperationsResponse is the response structure for the listGraphQLOperations tool

type Options

type Options struct {
	// GraphName is the name of the graph to be served
	GraphName string
	// OperationsDir is the directory where GraphQL operations are stored
	OperationsDir string
	// ListenAddr is the address where the server should listen to
	ListenAddr string
	// Enabled determines whether the MCP server should be started
	Enabled bool
	// Logger is the logger to be used
	Logger *zap.Logger
	// RequestTimeout is the timeout for HTTP requests
	RequestTimeout time.Duration
	// ExcludeMutations determines whether mutation operations should be excluded
	ExcludeMutations bool
	// EnableArbitraryOperations determines whether arbitrary GraphQL operations can be executed
	EnableArbitraryOperations bool
	// ExposeSchema determines whether the GraphQL schema is exposed
	ExposeSchema bool
	// OmitToolNamePrefix removes the "execute_operation_" prefix from MCP tool names
	OmitToolNamePrefix bool
	// Stateless determines whether the MCP server should be stateless
	Stateless bool
	// CorsConfig is the CORS configuration for the MCP server
	CorsConfig cors.Config
	// OAuthConfig is the OAuth/JWKS configuration for authentication
	OAuthConfig *config.MCPOAuthConfiguration
	// ServerBaseURL is the base URL of this MCP server (for resource metadata)
	ServerBaseURL string
	// ResourceDocumentation is a URL to a human-readable page describing this resource
	ResourceDocumentation string
}

Options represents configuration options for the GraphQLSchemaServer

type ProtectedResourceMetadata

type ProtectedResourceMetadata struct {
	Resource               string   `json:"resource"`
	AuthorizationServers   []string `json:"authorization_servers"`
	BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
	ResourceDocumentation  string   `json:"resource_documentation,omitempty"`
	ScopesSupported        []string `json:"scopes_supported"`
}

ProtectedResourceMetadata represents the OAuth 2.0 Protected Resource Metadata (RFC 9728)

type SchemaCompiler

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

SchemaCompiler handles JSON schema compilation and validation

func NewSchemaCompiler

func NewSchemaCompiler(logger *zap.Logger) *SchemaCompiler

NewSchemaCompiler creates a new schema compiler with the given logger

func (*SchemaCompiler) CompileJSONSchema

func (sc *SchemaCompiler) CompileJSONSchema(jsonSchema []byte, schemaName string) (*jsonschema.Schema, error)

CompileJSONSchema compiles a JSON schema from raw bytes

func (*SchemaCompiler) ValidateInput

func (sc *SchemaCompiler) ValidateInput(data []byte, compiledSchema *jsonschema.Schema) error

ValidateInput validates input data against a compiled schema

func (*SchemaCompiler) ValidateJSONSchema

func (sc *SchemaCompiler) ValidateJSONSchema(jsonSchema []byte) error

ValidateJSONSchema validates that the provided bytes are a valid JSON schema

type ScopeExtractor

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

ScopeExtractor walks operations and extracts per-field scope requirements from FieldConfigurations.

func NewScopeExtractor

func NewScopeExtractor(fieldConfigs []*nodev1.FieldConfiguration, schemaDoc *ast.Document, maxScopeCombinations int) *ScopeExtractor

NewScopeExtractor creates a new ScopeExtractor.

func (*ScopeExtractor) ComputeCombinedScopes

func (e *ScopeExtractor) ComputeCombinedScopes(fieldReqs []FieldScopeRequirement) ([][]string, error)

ComputeCombinedScopes computes the Cartesian product of OR-groups across fields, deduplicating scopes within each combined AND-group. Returns an error if the number of combinations exceeds MaxScopeCombinations, which prevents pathological scope configurations from consuming unbounded resources.

func (*ScopeExtractor) ExtractScopesForOperation

func (e *ScopeExtractor) ExtractScopesForOperation(operation *ast.Document) ([]FieldScopeRequirement, error)

ExtractScopesForOperation walks the operation's selection set and returns per-field scope requirements for fields that have @requiresScopes. Returns an error if the walker fails, so callers can fail closed rather than acting on a partially-populated result.

type ZapAdapter

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

ZapAdapter struct that wraps a zap.SugaredLogger to implement the Logger interface

func NewZapAdapter

func NewZapAdapter(zapLogger *zap.Logger) *ZapAdapter

NewZapAdapter creates a new ZapAdapter from a zap.Logger

func (*ZapAdapter) Errorf

func (z *ZapAdapter) Errorf(format string, v ...any)

Errorf logs an error message using Zap

func (*ZapAdapter) Infof

func (z *ZapAdapter) Infof(format string, v ...any)

Infof logs an informational message using Zap

Jump to

Keyboard shortcuts

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