mcp

package
v0.3.2 Latest Latest
Warning

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

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

Documentation

Overview

Package mcp is part of the GoFastr framework. See https://github.com/DonaldMurillo/gofastr for documentation.

Package mcp implements a Model Context Protocol server for GoFastr.

It provides tool registration, JSON-RPC 2.0 message handling, and transports for stdio and HTTP/SSE.

Index

Constants

View Source
const (
	ErrMethodNotFound = -32601
	ErrInvalidParams  = -32602
	ErrInternalError  = -32603
)

JSON-RPC 2.0 standard error codes.

Variables

This section is empty.

Functions

func RequestFromContext

func RequestFromContext(ctx context.Context) (*http.Request, bool)

RequestFromContext returns the original inbound *http.Request stashed by the transport, if any. Tool handlers that re-dispatch through an HTTP router use it to copy the caller's auth onto the internal request so session/JWT middleware re-resolves the same user instead of demoting to anonymous.

func StreamSSE

func StreamSSE(w io.Writer, event, data string)

StreamSSE writes a single SSE event to the writer. It is the hardened entry point for tool-result streaming and treats both arguments as untrusted:

  • the event name is truncated at the first CR/LF/NUL so the caller can't terminate the "event:" field and inject a forged directive below it.
  • data is collapsed to a single line (CR/LF/NUL stripped) and any occurrence of a literal SSE directive marker (e.g. "event:", "id:", "retry:", "data:") inside the payload has its colon replaced with " -" so the bytes can no longer be mistaken for — or substring-matched as — an injected directive.

func WithRequest

func WithRequest(ctx context.Context, r *http.Request) context.Context

WithRequest stashes the original inbound *http.Request in ctx so tool handlers can recover the caller's transport-level auth (Cookie / Authorization headers). The HTTP transports call this automatically; it is exported so non-HTTP callers (and tests) can populate the same slot.

Types

type RPCError

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

RPCError represents a JSON-RPC 2.0 error object.

func (*RPCError) Error

func (e *RPCError) Error() string

Error implements the error interface for RPCError.

type Request

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

Request represents a JSON-RPC 2.0 request.

type Response

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

Response represents a JSON-RPC 2.0 response.

type Server

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

Server is an MCP server with a tool registry.

func NewServer

func NewServer() *Server

NewServer creates a new MCP server with an empty tool registry.

func (*Server) CallTool

func (s *Server) CallTool(ctx context.Context, name string, params map[string]any) (any, error)

CallTool is the exported form of callTool: invokes a registered tool by name with the given params. Use this when calling MCP tools in-process (tests, server-side integrations) without going through the JSON-RPC transport layer.

func (*Server) HandleRequest

func (s *Server) HandleRequest(ctx context.Context, req Request) Response

HandleRequest routes a JSON-RPC 2.0 request to the correct handler and returns the appropriate response.

func (*Server) ListTools

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

ListTools returns all registered tools (handlers are nilled out for safety). This is the exported version of listTools for external consumption.

func (*Server) RegisterTool

func (s *Server) RegisterTool(name, description string, inputSchema map[string]any, fn ToolHandler) error

RegisterTool adds a tool to the server's registry. Returns an error if a tool with the same name already exists.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles HTTP POST requests for MCP JSON-RPC calls. It reads a JSON-RPC request from the body and writes the response.

func (*Server) ServeSSE

func (s *Server) ServeSSE(path string) http.Handler

ServeSSE sets up an HTTP handler that supports Server-Sent Events for streaming responses. The POST endpoint at path handles JSON-RPC calls, and the GET endpoint streams responses via SSE.

func (*Server) ServeStdio

func (s *Server) ServeStdio(ctx context.Context, in io.Reader, out io.Writer) error

ServeStdio reads JSON-RPC requests from in line-by-line and writes responses to out. It blocks until in returns EOF or ctx is cancelled.

type Tool

type Tool struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	InputSchema map[string]any `json:"inputSchema"`
	Handler     ToolHandler    `json:"-"`
}

Tool represents a registered MCP tool with its metadata and handler.

type ToolHandler

type ToolHandler func(ctx context.Context, params map[string]any) (any, error)

ToolHandler is the function signature for MCP tool handlers. It receives a context (carrying auth/tenant info) and a map of parameters, and returns an arbitrary result.

Jump to

Keyboard shortcuts

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