mcp

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 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 (
	ErrStreamNotFound = errors.New("stream not found")
	ErrEventNotFound  = errors.New("event not found")
)
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", "audio", "resource_link", "resource"

	// Text content (type = "text").
	Text string `json:"text,omitempty"`

	// Image/audio content (type = "image" or "audio").
	Data     string `json:"data,omitempty"`     // base64-encoded
	MimeType string `json:"mimeType,omitempty"` // e.g. "image/png"

	// Resource link content (type = "resource_link").
	URI         string `json:"uri,omitempty"`
	Name        string `json:"name,omitempty"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Size        int64  `json:"size,omitempty"`

	// Embedded resource content (type = "resource").
	Resource *ResourceContent `json:"resource,omitempty"`
}

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 MemoryStreamStore added in v0.11.1

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

MemoryStreamStore is an in-memory StreamStore for testing and local development.

It assigns monotonically increasing numeric event IDs per session (as strings).

func NewMemoryStreamStore added in v0.11.1

func NewMemoryStreamStore(opts ...MemoryStreamStoreOption) *MemoryStreamStore

func (*MemoryStreamStore) Append added in v0.11.1

func (m *MemoryStreamStore) Append(_ context.Context, sessionID, streamID string, data json.RawMessage) (string, error)

func (*MemoryStreamStore) Close added in v0.11.1

func (m *MemoryStreamStore) Close(_ context.Context, sessionID, streamID string) error

func (*MemoryStreamStore) Create added in v0.11.1

func (m *MemoryStreamStore) Create(_ context.Context, sessionID string) (string, error)

func (*MemoryStreamStore) DeleteSession added in v0.11.1

func (m *MemoryStreamStore) DeleteSession(_ context.Context, sessionID string) error

func (*MemoryStreamStore) StreamForEvent added in v0.11.1

func (m *MemoryStreamStore) StreamForEvent(_ context.Context, sessionID, eventID string) (string, error)

func (*MemoryStreamStore) Subscribe added in v0.11.1

func (m *MemoryStreamStore) Subscribe(ctx context.Context, sessionID, streamID, afterEventID string) (<-chan StreamEvent, error)

type MemoryStreamStoreOption added in v0.11.1

type MemoryStreamStoreOption func(*MemoryStreamStore)

func WithStreamIDGenerator added in v0.11.1

func WithStreamIDGenerator(gen apptheory.IDGenerator) MemoryStreamStoreOption

type OriginValidator added in v0.11.1

type OriginValidator func(origin string) bool

OriginValidator validates an HTTP Origin header value.

If a request includes an Origin header and the validator returns false, the server should reject the request (fail closed).

func AllowOrigins added in v0.11.1

func AllowOrigins(origins ...string) OriginValidator

type PromptArgument added in v0.11.0

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

PromptArgument defines an argument a prompt can accept.

type PromptDef added in v0.11.0

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

PromptDef defines an MCP prompt's metadata.

type PromptHandler added in v0.11.0

type PromptHandler func(ctx context.Context, args json.RawMessage) (*PromptResult, error)

PromptHandler renders a prompt given optional arguments.

type PromptMessage added in v0.11.0

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

PromptMessage is a single message returned from prompts/get.

type PromptRegistry added in v0.11.0

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

PromptRegistry manages registered MCP prompts.

func NewPromptRegistry added in v0.11.0

func NewPromptRegistry() *PromptRegistry

NewPromptRegistry creates an empty prompt registry.

func (*PromptRegistry) Get added in v0.11.0

func (r *PromptRegistry) Get(ctx context.Context, name string, args json.RawMessage) (*PromptResult, error)

Get resolves a prompt by name and renders it.

func (*PromptRegistry) Len added in v0.11.0

func (r *PromptRegistry) Len() int

Len returns the number of registered prompts.

func (*PromptRegistry) List added in v0.11.0

func (r *PromptRegistry) List() []PromptDef

List returns all registered prompt definitions in registration order.

func (*PromptRegistry) RegisterPrompt added in v0.11.0

func (r *PromptRegistry) RegisterPrompt(def PromptDef, handler PromptHandler) error

RegisterPrompt registers a prompt by name.

type PromptResult added in v0.11.0

type PromptResult struct {
	Description string          `json:"description,omitempty"`
	Messages    []PromptMessage `json:"messages"`
}

PromptResult is the result payload returned from prompts/get.

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,omitempty"`
	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" and method must be non-empty.

This function accepts both JSON-RPC requests and notifications: - Requests include an "id" field. - Notifications omit the "id" field.

If an "id" field is present, it MUST NOT be null.

type ResourceContent added in v0.11.0

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

ResourceContent is a single content item returned from resources/read.

Exactly one of Text or Blob should be set. Blob is expected to be a base64-encoded payload (client-decoded).

type ResourceDef added in v0.11.0

type ResourceDef struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	MimeType    string `json:"mimeType,omitempty"`
	Size        int64  `json:"size,omitempty"`
}

ResourceDef defines an MCP resource's metadata.

type ResourceHandler added in v0.11.0

type ResourceHandler func(ctx context.Context) ([]ResourceContent, error)

ResourceHandler resolves and returns the content for a resource.

type ResourceRegistry added in v0.11.0

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

ResourceRegistry manages registered MCP resources.

func NewResourceRegistry added in v0.11.0

func NewResourceRegistry() *ResourceRegistry

NewResourceRegistry creates an empty resource registry.

func (*ResourceRegistry) Len added in v0.11.0

func (r *ResourceRegistry) Len() int

Len returns the number of registered resources.

func (*ResourceRegistry) List added in v0.11.0

func (r *ResourceRegistry) List() []ResourceDef

List returns all registered resource definitions in registration order.

func (*ResourceRegistry) Read added in v0.11.0

Read resolves a resource by URI and returns its content.

func (*ResourceRegistry) RegisterResource added in v0.11.0

func (r *ResourceRegistry) RegisterResource(def ResourceDef, handler ResourceHandler) error

RegisterResource registers a resource by URI.

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.

func ParseResponse added in v0.11.1

func ParseResponse(data []byte) (*Response, error)

ParseResponse parses a single JSON-RPC 2.0 response from raw bytes.

It validates: - jsonrpc must be "2.0" - id must be present (it may be null for certain error cases) - exactly one of result or error is present

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.

Streamable HTTP semantics: - POST /mcp accepts JSON-RPC requests, notifications, and responses. - GET /mcp replays/resumes previously interrupted SSE streams via Last-Event-ID. - DELETE /mcp terminates a session.

Notes:

  • Clients must initialize first; the server issues Mcp-Session-Id on the initialize response and requires it thereafter.
  • Disconnects are not treated as cancellation. Streaming tool execution is decoupled from the connection and can be resumed with GET.

func (*Server) Prompts added in v0.11.0

func (s *Server) Prompts() *PromptRegistry

Prompts returns the server's prompt registry for registering prompts.

func (*Server) Registry

func (s *Server) Registry() *ToolRegistry

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

func (*Server) Resources added in v0.11.0

func (s *Server) Resources() *ResourceRegistry

Resources returns the server's resource registry for registering resources.

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 WithOriginValidator added in v0.11.1

func WithOriginValidator(v OriginValidator) ServerOption

WithOriginValidator sets the Origin validator for browser-based callers.

If an Origin header is present, the request is rejected unless it passes validation (fail closed).

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.

func WithStreamStore added in v0.11.1

func WithStreamStore(store StreamStore) ServerOption

WithStreamStore sets the stream 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 StreamEvent added in v0.11.1

type StreamEvent struct {
	ID   string
	Data json.RawMessage
}

StreamEvent is a single server->client JSON-RPC message framed as an SSE event.

ID is the SSE event id (used for resumability via Last-Event-ID). Data is the raw JSON payload (a single JSON-RPC message).

type StreamStore added in v0.11.1

type StreamStore interface {
	Create(ctx context.Context, sessionID string) (streamID string, err error)
	Append(ctx context.Context, sessionID, streamID string, data json.RawMessage) (eventID string, err error)
	Close(ctx context.Context, sessionID, streamID string) error

	// Subscribe streams events after afterEventID. If afterEventID is empty,
	// it streams from the beginning.
	Subscribe(ctx context.Context, sessionID, streamID, afterEventID string) (<-chan StreamEvent, error)

	// StreamForEvent returns the stream id that the given event id belongs to.
	StreamForEvent(ctx context.Context, sessionID, eventID string) (streamID string, err error)

	// DeleteSession removes all stream state for a session.
	DeleteSession(ctx context.Context, sessionID string) error
}

StreamStore persists stream events so a disconnected client can replay them via GET + Last-Event-ID.

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"`
	StructuredContent map[string]any `json:"structuredContent,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