mcp

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CodeParseError     = -32700
	CodeInvalidRequest = -32600
	CodeMethodNotFound = -32601
	CodeInvalidParams  = -32602
	CodeInternalError  = -32603
	CodeServerError    = -32000
)

Standard JSON-RPC 2.0 error codes.

Variables

View Source
var ErrSessionNotFound = errors.New("session not found")

ErrSessionNotFound is returned when a session ID does not exist in the store.

Functions

func MarshalResponse

func MarshalResponse(resp *Response) ([]byte, error)

MarshalResponse serializes a JSON-RPC 2.0 response to bytes. It ensures the jsonrpc field is always set to "2.0".

Types

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"` // "text", "image", "resource"
	Text string `json:"text,omitempty"`
}

ContentBlock is a content item in a tool result.

type DynamoSessionStore

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

DynamoSessionStore implements SessionStore using DynamoDB via TableTheory.

func (*DynamoSessionStore) Delete

func (d *DynamoSessionStore) Delete(ctx context.Context, id string) error

Delete removes a session by ID.

func (*DynamoSessionStore) Get

func (d *DynamoSessionStore) Get(ctx context.Context, id string) (*Session, error)

Get retrieves a session by ID. Returns ErrSessionNotFound if the session does not exist.

func (*DynamoSessionStore) Put

func (d *DynamoSessionStore) Put(ctx context.Context, session *Session) error

Put stores a session. Overwrites any existing session with the same ID.

type MemorySessionStore

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

MemorySessionStore is an in-memory SessionStore for testing and local development.

func NewMemorySessionStore

func NewMemorySessionStore(opts ...MemorySessionStoreOption) *MemorySessionStore

NewMemorySessionStore creates an in-memory session store.

func (*MemorySessionStore) Delete

func (m *MemorySessionStore) Delete(_ context.Context, id string) error

Delete removes a session by ID. It is a no-op if the session does not exist.

func (*MemorySessionStore) Get

Get retrieves a session by ID. It returns ErrSessionNotFound if the session does not exist or has expired.

func (*MemorySessionStore) Put

func (m *MemorySessionStore) Put(_ context.Context, session *Session) error

Put stores a session. It overwrites any existing session with the same ID.

type MemorySessionStoreOption

type MemorySessionStoreOption func(*MemorySessionStore)

MemorySessionStoreOption configures a MemorySessionStore.

func WithClock

WithClock sets the clock used for TTL expiration checks.

type RPCError

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

RPCError is a JSON-RPC 2.0 error object.

type Request

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

Request is a JSON-RPC 2.0 request message.

func ParseBatchRequest

func ParseBatchRequest(data []byte) ([]*Request, error)

ParseBatchRequest parses a JSON-RPC batch request (array of requests) from raw bytes. If the input is a single object (not an array), it returns a slice containing that single parsed request.

func ParseRequest

func ParseRequest(data []byte) (*Request, error)

ParseRequest parses a single JSON-RPC 2.0 request from raw bytes. It validates the required fields: jsonrpc must be "2.0", method must be non-empty, and id must be present.

type Response

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

Response is a JSON-RPC 2.0 response message.

func NewErrorResponse

func NewErrorResponse(id any, code int, message string) *Response

NewErrorResponse creates a JSON-RPC error response with the given request ID and error details.

func NewResultResponse

func NewResultResponse(id any, result any) *Response

NewResultResponse creates a JSON-RPC success response with the given request ID and result value.

type SSEEvent

type SSEEvent struct {
	Data any
}

SSEEvent is a progress event emitted by a streaming tool handler.

type Server

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

Server is the MCP protocol handler. It dispatches JSON-RPC 2.0 messages to the appropriate MCP method handlers (initialize, tools/list, tools/call).

func NewServer

func NewServer(name, version string, opts ...ServerOption) *Server

NewServer creates an MCP server with the given name, version, and options.

func (*Server) Handler

func (s *Server) Handler() apptheory.Handler

Handler returns an apptheory.Handler that processes MCP JSON-RPC requests. It handles session management via the Mcp-Session-Id header and dispatches to initialize, tools/list, and tools/call method handlers.

When the Accept header is text/event-stream and the method is tools/call, the response is formatted as SSE. Otherwise, a buffered JSON response is returned.

func (*Server) Registry

func (s *Server) Registry() *ToolRegistry

Registry returns the server's tool registry for registering tools.

type ServerOption

type ServerOption func(*Server)

ServerOption configures a Server.

func WithLogger

func WithLogger(logger *slog.Logger) ServerOption

WithLogger sets the structured logger for the server.

func WithServerIDGenerator

func WithServerIDGenerator(gen apptheory.IDGenerator) ServerOption

WithIDGenerator sets the ID generator for session IDs.

func WithSessionStore

func WithSessionStore(store SessionStore) ServerOption

WithSessionStore sets the session store for the server.

type Session

type Session struct {
	ID        string            `json:"id"`
	CreatedAt time.Time         `json:"createdAt"`
	ExpiresAt time.Time         `json:"expiresAt"`
	Data      map[string]string `json:"data,omitempty"`
}

Session holds per-session state for an MCP connection.

type SessionStore

type SessionStore interface {
	Get(ctx context.Context, id string) (*Session, error)
	Put(ctx context.Context, session *Session) error
	Delete(ctx context.Context, id string) error
}

SessionStore is the interface for session persistence backends.

func NewDynamoSessionStore

func NewDynamoSessionStore(db tablecore.DB) SessionStore

NewDynamoSessionStore creates a DynamoDB-backed session store.

type StreamingToolHandler

type StreamingToolHandler func(ctx context.Context, args json.RawMessage, emit func(SSEEvent)) (*ToolResult, error)

StreamingToolHandler is a tool handler that can emit progress events via SSE.

type ToolDef

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

ToolDef defines an MCP tool's metadata and input schema.

type ToolHandler

type ToolHandler func(ctx context.Context, args json.RawMessage) (*ToolResult, error)

ToolHandler is the function signature for tool implementations.

type ToolRegistry

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

ToolRegistry manages registered MCP tools.

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates an empty tool registry.

func (*ToolRegistry) Call

func (r *ToolRegistry) Call(ctx context.Context, name string, args json.RawMessage) (*ToolResult, error)

Call looks up a tool by name and invokes its handler with the given arguments. It returns an error if the tool is not found.

func (*ToolRegistry) CallStreaming

func (r *ToolRegistry) CallStreaming(ctx context.Context, name string, args json.RawMessage, emit func(SSEEvent)) (*ToolResult, error)

CallStreaming looks up a tool by name and invokes its streaming handler if available, otherwise falls back to the regular handler (discarding emit).

func (*ToolRegistry) List

func (r *ToolRegistry) List() []ToolDef

List returns all registered tool definitions in registration order.

func (*ToolRegistry) RegisterStreamingTool

func (r *ToolRegistry) RegisterStreamingTool(def ToolDef, handler StreamingToolHandler) error

RegisterStreamingTool registers a tool that supports SSE streaming. When invoked with Accept: text/event-stream, progress events are streamed. When invoked with Accept: application/json (or absent), the handler runs to completion and returns a buffered JSON response.

func (*ToolRegistry) RegisterTool

func (r *ToolRegistry) RegisterTool(def ToolDef, handler ToolHandler) error

RegisterTool adds a tool to the registry. It returns an error if a tool with the same name is already registered.

type ToolResult

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

ToolResult is the result of a tool invocation.

Jump to

Keyboard shortcuts

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