mcp

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const ServerInstructions = `` /* 1217-byte string literal not displayed */

ServerInstructions is returned in the initialize response to teach MCP clients how to navigate the server. Agentic clients consume this as part of their system prompt, so it trades some verbosity for clarity.

Variables

View Source
var SupportedProtocolVersions = []string{
	"2025-06-18",
	"2025-03-26",
	"2024-11-05",
}

SupportedProtocolVersions lists MCP protocol versions this server can negotiate, newest first. The first entry is returned as the default when the client does not send a protocolVersion. When a client requests an unsupported version, we echo back the newest supported version — clients that cannot downgrade will treat that as an error and disconnect, which is the spec-compliant behaviour.

Functions

func ServeMetrics added in v0.6.0

func ServeMetrics(ctx context.Context, opts MetricsServerOptions) error

func ServeStreamableHTTP added in v0.6.0

func ServeStreamableHTTP(ctx context.Context, opts StreamableHTTPOptions) error

func WithProgressToken

func WithProgressToken(ctx context.Context, token ProgressToken) context.Context

WithProgressToken attaches the client-supplied progressToken (if any) to ctx so downstream tool handlers can emit notifications/progress keyed off the same value.

Types

type Activator added in v0.6.0

type Activator interface {
	// IsGroupAllowed reports whether a Tier 2 group may be activated.
	IsGroupAllowed(group string) bool
	// OnActivate is called when tools are dynamically registered.
	OnActivate(names []string)
}

Activator handles dynamic tool activation (group enable, visibility toggle). A nil Activator means activation is unrestricted.

type AuditEvent added in v0.6.0

type AuditEvent struct {
	Tool        string
	Action      string
	Outcome     string
	Reason      string
	ResourceIDs map[string]string
	Metadata    map[string]string
}

type Auditor added in v0.6.0

type Auditor interface {
	RecordAudit(AuditEvent)
}

type Enforcement added in v0.6.0

type Enforcement interface {
	// FilterTool reports whether a tool should be listed in tools/list.
	FilterTool(name string, hints ToolHints) bool
	// BeforeCall runs before the tool handler. It may:
	//   - block the call by returning a non-nil error
	//   - short-circuit with a result (e.g., dry-run preview)
	//   - return (nil, noop, nil) to proceed normally
	// The returned release function must be called when the call completes.
	BeforeCall(ctx context.Context, name string, args map[string]any, hints ToolHints, lookupHandler func(string) (ToolHandler, bool)) (result any, release func(), err error)
	// AfterCall post-processes a successful tool result (e.g., truncation).
	AfterCall(result any) (any, error)
}

Enforcement handles the tool-call enforcement pipeline. The server delegates all filtering, gating, and post-processing to this interface, keeping the protocol core free of domain logic.

A nil Enforcement means no filtering or enforcement.

type InitializeParams

type InitializeParams struct {
	ProtocolVersion string         `json:"protocolVersion,omitempty"`
	Capabilities    map[string]any `json:"capabilities,omitempty"`
	ClientInfo      map[string]any `json:"clientInfo,omitempty"`
	Meta            *RequestMeta   `json:"_meta,omitempty"`
}

type MetricsServerOptions added in v0.6.0

type MetricsServerOptions struct {
	Bind        string
	AuthMode    string
	BearerToken string
}

type Notifier

type Notifier interface {
	Notify(method string, params any) error
}

Notifier delivers server-initiated notifications (e.g. tools/list_changed) to the connected client. Transports implement this: the stdio transport writes through the shared JSON encoder, while the legacy HTTP POST-only transport logs + counts drops until a real SSE channel is wired by the Streamable HTTP transport rewrite.

type ProgressToken

type ProgressToken = any

ProgressToken is the opaque client-supplied token echoed back on every notifications/progress. Either a string or a number per the MCP spec.

func ProgressTokenFromContext

func ProgressTokenFromContext(ctx context.Context) (ProgressToken, bool)

ProgressTokenFromContext returns the progressToken supplied in the current tools/call _meta, or (nil, false) when the client did not opt in.

type Prompt

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

Prompt is a registered prompt template with canned messages whose bodies may contain `{{name}}` placeholders substituted at prompts/get time.

type PromptArgument

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

PromptArgument describes one substitution variable a prompt accepts.

type PromptMessage

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

PromptMessage is one turn in a prompt's canned message sequence. Role is typically "user" or "assistant"; content mirrors the MCP content-part shape.

type PromptMessagePart

type PromptMessagePart struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

PromptMessagePart is a single content part inside a PromptMessage. Only text content is supported in this server; clients that want images or resource links can request a richer prompt via a follow-up tool call.

type RPCError

type RPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type Request

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

type RequestMeta

type RequestMeta struct {
	ProgressToken any `json:"progressToken,omitempty"`
}

RequestMeta is the MCP _meta object that can attach side-channel hints to any request. progressToken is the only field used today — clients supply one to opt into notifications/progress from long-running tool handlers.

type Resource

type Resource struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	MimeType    string `json:"mimeType,omitempty"`
}

Resource describes a concrete, static MCP resource. Dynamic (parametric) resources should be surfaced via ResourceTemplate instead.

type ResourceContents

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

ResourceContents is one chunk of resource body. Text and Blob are mutually exclusive — text/* content uses Text, binary content uses base64 in Blob.

type ResourceProvider

type ResourceProvider interface {
	ListResources(ctx context.Context) ([]Resource, error)
	ListResourceTemplates(ctx context.Context) ([]ResourceTemplate, error)
	ReadResource(ctx context.Context, uri string) ([]ResourceContents, error)
}

ResourceProvider backs the MCP resources/* method family. Implementations live outside the protocol core (tools.Service implements it for Clockify). A nil ResourceProvider on Server means the resources capability is off.

type ResourceTemplate

type ResourceTemplate struct {
	URITemplate string `json:"uriTemplate"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	MimeType    string `json:"mimeType,omitempty"`
}

ResourceTemplate describes a parametric MCP resource using RFC 6570 URI template syntax — e.g. `clockify://workspace/{workspaceId}/entry/{entryId}`.

type Response

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

type Server

type Server struct {
	Version      string
	Enforcement  Enforcement                     // nil = no filtering or enforcement
	Activator    Activator                       // nil = activation unrestricted
	ToolTimeout  time.Duration                   // per-call timeout; 0 = default 45s
	ReadyChecker func(ctx context.Context) error // optional upstream health check for /ready

	// ResourceProvider backs resources/* method handlers. nil disables the
	// resources capability (server omits it from initialize.result.capabilities).
	ResourceProvider ResourceProvider

	// MaxInFlightToolCalls bounds the number of concurrently-running
	// tools/call goroutines spawned by the stdio dispatch loop.
	// Acquired before the goroutine is created so bursty input cannot
	// amplify goroutine count. 0 = unlimited.
	MaxInFlightToolCalls int

	// StrictHostCheck enables DNS rebinding protection on the HTTP
	// transport: the inbound Host header must match either a loopback
	// literal or one of the configured allowed-origin hostnames. Defaults
	// to off so that reverse-proxy deployments that rewrite Host are
	// unaffected; flip on (MCP_STRICT_HOST_CHECK=1) in localhost-bound
	// production deployments to get the strict guarantee.
	StrictHostCheck bool

	Auditor        Auditor
	AuditTenantID  string
	AuditSubject   string
	AuditSessionID string
	AuditTransport string
	// contains filtered or unexported fields
}

func NewServer

func NewServer(version string, descriptors []ToolDescriptor, enforcement Enforcement, activator Activator) *Server

func (*Server) ActivateGroup added in v0.6.0

func (s *Server) ActivateGroup(groupName string, descriptors []ToolDescriptor) error

ActivateGroup registers a group of tool descriptors dynamically and sends a tools/list_changed notification to the client.

func (*Server) ActivateTier1Tool added in v0.6.0

func (s *Server) ActivateTier1Tool(name string) error

ActivateTier1Tool marks a single registered tool as visible.

func (*Server) ClientInfo

func (s *Server) ClientInfo() (name, version string)

ClientInfo returns the client name and version sent during initialize.

func (*Server) InFlightToolCalls

func (s *Server) InFlightToolCalls() int

InFlightToolCalls reports the current depth of the stdio dispatch semaphore. Returns 0 when the semaphore is disabled.

func (*Server) InflightCount

func (s *Server) InflightCount() int

InflightCount returns the number of tracked in-flight tools/call requests. Used by tests to verify the map is cleaned up.

func (*Server) IsReadyCached added in v0.6.0

func (s *Server) IsReadyCached() bool

IsReadyCached reports whether the last cached readiness probe resulted in success. Scrapers should prefer /ready for fresh probes; this method only reads the cached value so /metrics does not trigger upstream calls on every scrape.

func (*Server) NegotiatedProtocolVersion added in v0.6.0

func (s *Server) NegotiatedProtocolVersion() string

NegotiatedProtocolVersion returns the MCP protocol version agreed with the client, or empty string before initialize runs.

func (*Server) Notify

func (s *Server) Notify(method string, params any) error

Notify forwards a server-initiated notification through the currently installed Notifier. Drops silently when no notifier is wired. Satisfies the Notifier interface so the tools layer can treat Server as its notification sink without hard-coding the transport.

func (*Server) NotifyResourceUpdated

func (s *Server) NotifyResourceUpdated(uri string)

NotifyResourceUpdated publishes notifications/resources/updated if the URI has an active subscription. Transports/tool handlers call this after a mutation that invalidates a cached resource view. Safe to call before the notifier is wired — the call silently no-ops.

func (*Server) Run

func (s *Server) Run(ctx context.Context, r io.Reader, w io.Writer) error

Run processes JSON-RPC requests from r and writes responses to w. It respects ctx cancellation for graceful shutdown — when ctx is cancelled, the loop exits even if stdin is blocking.

func (*Server) ServeHTTP added in v0.6.0

func (s *Server) ServeHTTP(ctx context.Context, bind, bearerToken string, allowedOrigins []string, allowAnyOrigin bool, maxBodySize int64) error

ServeHTTP starts an HTTP server that wraps the MCP server's handle() method. It requires a non-empty bearerToken for authentication on the /mcp endpoint. When allowAnyOrigin is false and allowedOrigins is empty, cross-origin requests are rejected (secure default).

func (*Server) SetNotifier

func (s *Server) SetNotifier(n Notifier)

SetNotifier installs a notification sink. Transports call this during startup. Safe to call once per server lifetime; later calls replace the sink without synchronisation, so transports must call before traffic flows.

type StreamableHTTPOptions added in v0.6.0

type StreamableHTTPOptions struct {
	Version         string
	Bind            string
	MaxBodySize     int64
	AllowedOrigins  []string
	AllowAnyOrigin  bool
	StrictHostCheck bool
	SessionTTL      time.Duration
	ReadyChecker    func(context.Context) error
	Authenticator   authn.Authenticator
	ControlPlane    *controlplane.Store
	Factory         StreamableSessionFactory
	// ProtectedResource is the unauthenticated handler for the
	// /.well-known/oauth-protected-resource metadata document. When
	// non-nil it is mounted at the canonical RFC 9728 path. nil =
	// endpoint omitted (e.g. server does not advertise OAuth 2.1
	// resource discovery).
	ProtectedResource http.Handler
}

type StreamableSessionFactory added in v0.6.0

type StreamableSessionFactory func(context.Context, authn.Principal, string) (*StreamableSessionRuntime, error)

type StreamableSessionRuntime added in v0.6.0

type StreamableSessionRuntime struct {
	Server          *Server
	Close           func()
	TenantID        string
	WorkspaceID     string
	ClockifyBaseURL string
}

type Tool

type Tool struct {
	Name         string         `json:"name"`
	Description  string         `json:"description"`
	InputSchema  map[string]any `json:"inputSchema,omitempty"`
	OutputSchema map[string]any `json:"outputSchema,omitempty"`
	Annotations  map[string]any `json:"annotations,omitempty"`
}

type ToolCallParams

type ToolCallParams struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
	Meta      *RequestMeta   `json:"_meta,omitempty"`
}

type ToolDescriptor

type ToolDescriptor struct {
	Tool            Tool
	Handler         ToolHandler
	ReadOnlyHint    bool
	DestructiveHint bool
	IdempotentHint  bool
}

type ToolHandler

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

type ToolHints added in v0.6.0

type ToolHints struct {
	ReadOnly    bool
	Destructive bool
	Idempotent  bool
}

ToolHints carries semantic hints about a tool's behavior.

Jump to

Keyboard shortcuts

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