fastmcp

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 14 Imported by: 0

README

fastmcp

Go Test Go Lint Go Vuln Go Reference Go Report Card Go Version Release Last Commit Code Size PRs Welcome Docs

A from-scratch, standard-library-only Go framework for building Model Context Protocol (MCP) servers — an idiomatic Go port of Python's FastMCP.

Installation

go get github.com/malcolmston/fastmcp

Quick start

Create a server, register an add tool, and serve it over stdio (the default transport):

package main

import (
	"context"
	"log"

	"github.com/malcolmston/fastmcp"
)

// AddArgs are the tool arguments. Field tags drive the reflected JSON schema.
type AddArgs struct {
	A int `json:"a" jsonschema:"description=the first addend"`
	B int `json:"b" jsonschema:"description=the second addend"`
}

func main() {
	s := fastmcp.New("demo", fastmcp.WithVersion("1.0.0"))

	s.Tool("add", "Add two integers together",
		func(ctx context.Context, args AddArgs) (any, error) {
			return args.A + args.B, nil
		})

	if err := s.Run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

The server speaks newline-delimited JSON-RPC on stdin/stdout. Send it an initialize, then call the tool:

{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"add","arguments":{"a":2,"b":3}}}
{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"5"}]}}

Features

  • JSON-RPC 2.0 — a complete implementation of the wire protocol, including batch requests and notifications.
  • MCP protocol — capability negotiation (initialize), discovery, and invocation for the full server surface.
  • Tools, resources & prompts — register plain Go functions as callable tools, URI-addressable resources (and parameterized resource templates), and reusable prompt templates.
  • stdio + HTTP transports — run over stdin/stdout or the MCP Streamable HTTP transport (POST for messages, GET/SSE for the server-to-client channel). The stdio transport is fully bidirectional.
  • MCP client — a companion client package connects to any MCP server over stdio (attached streams or a spawned subprocess) or Streamable HTTP: Initialize, ListTools, CallTool, ListResources, ReadResource, ListPrompts, GetPrompt, Ping, and more.
  • Progress notifications — handlers report incremental progress with Context.Progress, correlated with the caller's progress token.
  • List-changed & subscriptions — broadcast notifications/*/list_changed with NotifyToolsChanged / NotifyResourcesChanged / NotifyPromptsChanged, and deliver notifications/resources/updated to resources/subscribers via NotifyResourceUpdated.
  • Completion — answer completion/complete for prompt arguments and resource-template variables with a registerable callback.
  • Structured tool outputToolWithOutput reflects an output schema from the handler's return type and emits structuredContent alongside text.
  • Binary & image resourcesBinaryResource serves base64 blob contents, not just text.
  • Sampling & roots — over a bidirectional transport, Context.CreateMessage asks the client to sample a completion and Context.ListRoots queries the client's roots.
  • Reflection-based schemas — a tool's JSON input schema is generated from its Go argument struct via reflection and json / jsonschema struct tags, so you never hand-write schemas.
  • Zero dependencies — pure Go standard library; nothing to audit but the toolchain.

Registering capabilities

s := fastmcp.New("example-server", fastmcp.WithVersion("1.0.0"))

// A tool with a reflected struct schema.
s.Tool("add", "Add two integers", func(ctx context.Context, a AddArgs) (any, error) {
	return a.A + a.B, nil
})

// A static resource.
s.Resource("greeting://hello", "greeting", "A friendly greeting", "text/plain",
	func(ctx context.Context) (string, error) {
		return "Hello, world!", nil
	})

// A prompt template.
s.Prompt("code_review", "Review a code snippet",
	func(ctx context.Context, args map[string]string) ([]fastmcp.PromptMessage, error) {
		return []fastmcp.PromptMessage{
			fastmcp.NewUserMessage("Please review this code."),
		}, nil
	})

See examples/main.go for a complete server exposing a tool, a resource, a resource template, and a prompt.

Transports

Every registered server can be served over either transport without changing your capability code.

stdio (default)
// Serve over os.Stdin / os.Stdout, blocking until EOF or ctx cancellation.
s.Run(ctx)

// Or serve over any reader/writer pair.
s.ServeStdio(ctx, in, out)
Streamable HTTP
// Obtain an http.Handler and mount it wherever you like.
http.Handle("/mcp", s.HTTPHandler())

// Or use the convenience listener.
s.ServeHTTP(":8080")

POST carries a single JSON-RPC message or a batch array and returns an application/json response (notifications get 202 Accepted). GET opens a text/event-stream (SSE) channel for server-initiated messages, including list-changed and resource-updated notifications.

Client

The client package talks to any MCP server. Connect over stdio (attach to a reader/writer pair or spawn a subprocess) or Streamable HTTP:

import "github.com/malcolmston/fastmcp/client"

// Spawn a server process and talk to it over its stdio.
c, err := client.NewCommand(ctx, "./my-mcp-server", nil)
if err != nil {
	log.Fatal(err)
}
defer c.Close()

if _, err := c.Initialize(ctx); err != nil {
	log.Fatal(err)
}

tools, _ := c.ListTools(ctx)
res, _ := c.CallTool(ctx, "add", map[string]any{"a": 2, "b": 3})
fmt.Println(res.Content[0].Text) // "5"

Over the bidirectional stdio transport the client answers the server's sampling/createMessage and roots/list requests via client.WithSamplingHandler and client.WithRoots / client.WithRootsHandler, and receives server notifications through client.WithNotificationHandler.

Framework subpackages

Around the root server and client sit eight framework subpackages that mirror Python FastMCP 2.x. Each is standard-library-only, imports only the root fastmcp package (and at most one sibling), and carries full godoc, tests and runnable examples. Import the ones you need:

import (
    "github.com/malcolmston/fastmcp"
    "github.com/malcolmston/fastmcp/auth"
    "github.com/malcolmston/fastmcp/middleware"
)
  • auth — token-based authentication. A small TokenVerifier turns a bearer token into a validated AccessToken (subject, scopes, expiry); ships StaticTokenVerifier and a JWTVerifier (HS256 + RS256 via local keys or a remote JWKS). BearerMiddleware/Protect guard a server and ProtectedResourceMetadata serves the RFC 9728 discovery document.
  • middleware — a server-side middleware pipeline (Middleware, Chain, Handler, Dispatcher) with built-ins for logging, timing, rate limiting, panic recovery, error mapping and metrics.
  • proxyNew builds a server that transparently forwards every request to a backend MCP server reached through a client.Client, discovering its tools, resources and prompts at construction.
  • openapiFromOpenAPI generates a server from an OpenAPI 3 document, one tool per operation, with a handler that performs the real HTTP call.
  • mountImport/Mount compose several servers behind one parent (mirrors import_server and mount).
  • transportInMemory wires a client.Client directly to a server in-process, with no sockets, subprocess or network (the Go analogue of FastMCPTransport).
  • elicit — server-side elicitation: a handler asks the client to collect structured input mid-request, with SchemaFromStruct deriving the schema.
  • contrib — optional batteries: a bulk tool caller, retry/timeout wrappers and an MCPMixin helper.

Documentation

License

MIT

Documentation

Overview

Package fastmcp is a from-scratch, standard-library-only Go framework for building Model Context Protocol (MCP) servers. It is an idiomatic Go port of Python's FastMCP, trading decorators for reflection-driven registration methods while preserving the same ergonomic feel.

Overview

MCP is a JSON-RPC 2.0 protocol that lets language-model clients discover and invoke server-provided capabilities: tools (callable functions), resources (readable data identified by URI), and prompts (reusable message templates). FastMCP handles the wire protocol, capability negotiation, JSON schema generation, and transport plumbing so that a server author only writes plain Go functions.

Getting started

Create a server, register capabilities, and run it over stdio (the default transport):

type AddArgs struct {
	A int `json:"a" jsonschema:"description=the first addend"`
	B int `json:"b" jsonschema:"description=the second addend"`
}

func main() {
	s := fastmcp.New("demo", fastmcp.WithVersion("1.0.0"))

	s.Tool("add", "Add two integers",
		func(ctx context.Context, args AddArgs) (any, error) {
			return args.A + args.B, nil
		})

	s.Resource("greeting://hello", "greeting", "A friendly greeting", "text/plain",
		func(ctx context.Context) (string, error) {
			return "Hello, world!", nil
		})

	if err := s.Run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

Tools

A tool handler is an ordinary Go function. Two shapes are accepted:

func(ctx context.Context, args T) (any, error)      // struct-argument form
func(ctx context.Context, args map[string]any) (any, error)  // dynamic form

For the struct form, FastMCP reflects over T's exported fields to build the tool's JSON input schema. The json tag controls the property name, the jsonschema tag supplies metadata such as "description=...", and non-pointer fields are marked required. A handler's first return value becomes the tool's result: strings are wrapped as text content and every other value is JSON-encoded into text content.

Resources and prompts

Static resources are registered with Server.Resource; parameterized ones use Server.ResourceTemplate with an RFC 6570 style URI template such as "users://{id}/profile" whose path variables are extracted and passed to the handler. Prompts are registered with Server.Prompt and return a slice of PromptMessage values.

Transports

Server.Run serves the newline-delimited JSON-RPC stdio transport. Server.HTTPHandler returns an net/http.Handler implementing the Streamable HTTP transport (JSON-RPC over POST, with an optional SSE GET stream), and Server.ServeHTTP is a convenience that binds it to an address. The stdio transport is bidirectional and correlates server-initiated requests with their responses.

Progress, list-changed and subscriptions

Handlers report incremental progress with Context.Progress, which emits a notifications/progress correlated with the caller's progress token. The server broadcasts capability changes with Server.NotifyToolsChanged, Server.NotifyResourcesChanged, and Server.NotifyPromptsChanged. Clients may subscribe to a resource with resources/subscribe; a subsequent Server.NotifyResourceUpdated delivers notifications/resources/updated to the subscribers.

Completion

Register a CompletionFunc with Server.CompletePrompt or Server.CompleteResourceTemplate to answer completion/complete requests for a prompt argument or resource-template variable.

Structured tool output

Server.ToolWithOutput reflects a JSON output schema from the handler's (struct) return type; each call then returns that value in the response's structuredContent field alongside the usual text content.

Binary resources

Server.BinaryResource and Server.BinaryResourceTemplate serve raw bytes (base64-encoded blob resource contents), for images and other non-textual data.

Sampling and roots

Over a bidirectional transport, Context.CreateMessage asks the connected client to sample a completion (sampling/createMessage) and Context.ListRoots queries the client's roots.

Client

The subpackage github.com/malcolmston/fastmcp/client provides an MCP client that connects over stdio (attached streams or a spawned process) or Streamable HTTP, correlates JSON-RPC ids, answers server sampling and roots requests, and delivers server notifications.

Framework subpackages

Beyond the core server and github.com/malcolmston/fastmcp/client, eight framework subpackages mirror the corresponding features of Python's FastMCP 2.x. Each is standard-library-only and builds on the root package (plus, at most, the client):

  • github.com/malcolmston/fastmcp/auth — token-based authentication. A small TokenVerifier interface turns a bearer token into a validated AccessToken; StaticTokenVerifier and a JWTVerifier (HS256/RS256, with a shared secret, RSA key, or remote JWKS) are provided. BearerMiddleware and Protect guard an HTTP-served server and publish RFC 9728 protected-resource metadata.
  • github.com/malcolmston/fastmcp/middleware — a server-side middleware pipeline (Middleware, Chain, Dispatcher) with a generic and operation-specific hooks, shipping logging, timing, rate-limiting, panic recovery, error-mapping and metrics middlewares.
  • github.com/malcolmston/fastmcp/proxy — proxy.New builds a server that transparently forwards every request to a backend reached through a client.Client, re-advertising the backend's tools, resources and prompts.
  • github.com/malcolmston/fastmcp/openapi — openapi.FromOpenAPI generates a server from an OpenAPI 3 document, registering one tool per operation whose handler performs the real upstream HTTP call.
  • github.com/malcolmston/fastmcp/mount — Import (a one-time copy) and Mount (a live passthrough) compose several child servers behind one parent under a name prefix.
  • github.com/malcolmston/fastmcp/transport — an in-memory, in-process transport that wires a client.Client directly to a Server with no sockets, subprocess or network (transport.InMemory / Connect), ideal for tests and same-address-space composition.
  • github.com/malcolmston/fastmcp/elicit — server-side elicitation: a handler asks the connected client to collect structured input mid-request, with SchemaFromStruct deriving the request schema from a Go struct.
  • github.com/malcolmston/fastmcp/contrib — optional higher-level batteries: a bulk tool caller (BulkToolCaller, CallToolsBulk), retry/timeout call wrappers, and an MCPMixin for grouping tool registrations.

The framework depends only on the Go standard library.

Index

Examples

Constants

View Source
const (
	// ErrParse indicates invalid JSON was received by the server.
	ErrParse = -32700
	// ErrInvalidRequest indicates the JSON is not a valid Request object.
	ErrInvalidRequest = -32600
	// ErrMethodNotFound indicates the requested method does not exist.
	ErrMethodNotFound = -32601
	// ErrInvalidParams indicates invalid method parameters.
	ErrInvalidParams = -32602
	// ErrInternal indicates an internal JSON-RPC error.
	ErrInternal = -32603
)

Standard JSON-RPC 2.0 error codes plus the MCP-specific extensions.

View Source
const DefaultVersion = "0.2.0"

DefaultVersion is the server version reported when none is supplied.

View Source
const JSONRPCVersion = "2.0"

JSONRPCVersion is the JSON-RPC protocol version string used by MCP.

View Source
const ProtocolVersion = "2024-11-05"

ProtocolVersion is the MCP protocol version implemented by this package.

Variables

This section is empty.

Functions

This section is empty.

Types

type BinaryResourceHandler added in v0.2.0

type BinaryResourceHandler func(ctx context.Context) ([]byte, error)

BinaryResourceHandler reads a static resource and returns its raw bytes, which FastMCP base64-encodes into a blob resource content. Use it for images and other non-textual data.

type BinaryResourceTemplateHandler added in v0.2.0

type BinaryResourceTemplateHandler func(ctx context.Context, params map[string]string) ([]byte, error)

BinaryResourceTemplateHandler reads a templated binary resource.

type CompletionFunc added in v0.2.0

type CompletionFunc func(ctx context.Context, argument, value string) []string

CompletionFunc produces completion suggestions for an argument. argument is the name of the prompt argument or resource-template variable being completed, and value is the partial text the user has entered so far. The returned slice is the ordered list of candidate values.

type Content

type Content struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`
	MIMEType string `json:"mimeType,omitempty"`

	// URI and Name are populated for "resource_link" content blocks.
	URI  string `json:"uri,omitempty"`
	Name string `json:"name,omitempty"`

	// Resource is populated for "resource" (embedded resource) content blocks.
	Resource *ResourceContents `json:"resource,omitempty"`

	// Annotations carries optional client hints (intended audience and
	// display priority) about the block. It is nil when unset.
	Annotations *ContentAnnotations `json:"annotations,omitempty"`
}

Content is a single piece of MCP content, such as a block of text, an embedded image or audio clip, a link to a resource, or an embedded resource. The Type field selects which of the remaining fields are meaningful ("text", "image", "audio", "resource_link", "resource").

func NewAudioContent added in v0.4.0

func NewAudioContent(data, mimeType string) Content

NewAudioContent returns an audio Content block from base64-encoded data and its MIME type (for example "audio/wav"). It is the audio counterpart of NewImageContent.

func NewEmbeddedBlobResource added in v0.4.0

func NewEmbeddedBlobResource(uri, mimeType, blob string) Content

NewEmbeddedBlobResource returns a "resource" Content block that embeds a binary resource's contents inline as a base64-encoded blob.

func NewEmbeddedResource added in v0.4.0

func NewEmbeddedResource(uri, mimeType, text string) Content

NewEmbeddedResource returns a "resource" Content block that embeds a textual resource's contents inline.

func NewImageContent

func NewImageContent(data, mimeType string) Content

NewImageContent returns an image Content block from base64-encoded data.

func NewResourceLink(uri, name, mimeType string) Content

NewResourceLink returns a "resource_link" Content block that references a resource by URI without embedding its contents. The name is a human-readable label; mimeType may be empty when unknown.

func NewTextContent

func NewTextContent(text string) Content

NewTextContent returns a text Content block.

func (Content) IsAudio added in v0.4.0

func (c Content) IsAudio() bool

IsAudio reports whether the block is an audio block.

func (Content) IsImage added in v0.4.0

func (c Content) IsImage() bool

IsImage reports whether the block is an image block.

func (Content) IsResource added in v0.4.0

func (c Content) IsResource() bool

IsResource reports whether the block embeds a resource ("resource") or links to one ("resource_link").

func (Content) IsText added in v0.4.0

func (c Content) IsText() bool

IsText reports whether the block is a text block.

func (Content) WithAnnotations added in v0.4.0

func (c Content) WithAnnotations(a ContentAnnotations) Content

WithAnnotations returns a copy of the content block carrying the given annotations. The receiver is not modified.

func (Content) WithAudience added in v0.4.0

func (c Content) WithAudience(audience ...string) Content

WithAudience returns a copy of the content block whose annotations declare the intended audience, preserving any existing priority.

func (Content) WithPriority added in v0.4.0

func (c Content) WithPriority(priority float64) Content

WithPriority returns a copy of the content block whose annotations declare the given display priority (clamped to [0,1]), preserving any existing audience.

type ContentAnnotations added in v0.4.0

type ContentAnnotations struct {
	Audience []string `json:"audience,omitempty"`
	Priority float64  `json:"priority,omitempty"`
}

ContentAnnotations carries optional, non-authoritative hints a server may attach to a content block: the intended Audience (a subset of "user" and "assistant") and a display Priority in the range [0,1], where 1 is most important. A zero-valued ContentAnnotations conveys no hints.

type Context

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

Context is the per-request handler context. It embeds a context.Context so it can be passed anywhere a standard context is expected, and additionally carries the originating server, the raw request, and a channel for sending logging and progress notifications back to the client.

func FromContext

func FromContext(ctx context.Context) *Context

FromContext recovers the FastMCP Context previously stored in ctx, or nil if ctx did not originate from a FastMCP request. Handlers that take a plain context.Context can use this to reach logging helpers.

func (*Context) CreateMessage added in v0.2.0

func (c *Context) CreateMessage(params CreateMessageParams) (*CreateMessageResult, error)

CreateMessage asks the connected client to sample a completion from its language model (the sampling/createMessage request). It blocks until the client responds or the context is cancelled. It requires a bidirectional transport (stdio); over transports without a server-to-client channel it returns an error.

func (*Context) Debug

func (c *Context) Debug(data any) error

Debug logs data at the "debug" level.

func (*Context) Error

func (c *Context) Error(data any) error

Error logs data at the "error" level.

func (*Context) Info

func (c *Context) Info(data any) error

Info logs data at the "info" level.

func (*Context) ListRoots added in v0.2.0

func (c *Context) ListRoots() ([]Root, error)

ListRoots queries the connected client for the roots it exposes (the roots/list request). Like Context.CreateMessage it requires a bidirectional transport.

func (*Context) Log

func (c *Context) Log(level string, data any) error

Log sends a logging notification (notifications/message) to the client at the given level ("debug", "info", "warning", "error", ...) carrying arbitrary data. It is a no-op when the transport cannot deliver notifications.

func (*Context) Progress added in v0.2.0

func (c *Context) Progress(progress, total float64, message string) error

Progress emits a notifications/progress message correlated with the current request's progressToken. total may be zero when the endpoint is unknown, and message may be empty. It is a no-op when the client did not supply a progress token (in the request's _meta) or when the transport cannot deliver notifications.

func (*Context) Request

func (c *Context) Request() *Request

Request returns the raw JSON-RPC request being handled.

func (*Context) Server

func (c *Context) Server() *Server

Server returns the server handling the current request.

func (*Context) Warning

func (c *Context) Warning(data any) error

Warning logs data at the "warning" level.

type CreateMessageParams added in v0.2.0

type CreateMessageParams struct {
	Messages         []SamplingMessage `json:"messages"`
	SystemPrompt     string            `json:"systemPrompt,omitempty"`
	IncludeContext   string            `json:"includeContext,omitempty"`
	Temperature      float64           `json:"temperature,omitempty"`
	MaxTokens        int               `json:"maxTokens,omitempty"`
	StopSequences    []string          `json:"stopSequences,omitempty"`
	ModelPreferences any               `json:"modelPreferences,omitempty"`
	Metadata         any               `json:"metadata,omitempty"`
}

CreateMessageParams are the parameters of a sampling/createMessage request sent from the server to the client. Only Messages is required; the remaining fields are optional hints honoured at the client's discretion.

type CreateMessageResult added in v0.2.0

type CreateMessageResult struct {
	Role       string  `json:"role"`
	Content    Content `json:"content"`
	Model      string  `json:"model"`
	StopReason string  `json:"stopReason,omitempty"`
}

CreateMessageResult is the client's response to a sampling/createMessage request: the sampled message plus the model that produced it.

type Error

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

Error is a JSON-RPC 2.0 error object.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type Notification

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

Notification is a JSON-RPC 2.0 notification sent from server to client, such as a logging message. Notifications never carry an ID.

type Option

type Option func(*Server)

Option configures a Server during construction.

func WithInstructions

func WithInstructions(instructions string) Option

WithInstructions sets human-readable usage instructions returned to clients during initialization.

func WithVersion

func WithVersion(version string) Option

WithVersion sets the server version reported to clients during initialization.

type PromptArgument

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

PromptArgument declares a named argument accepted by a prompt.

type PromptHandler

type PromptHandler func(ctx context.Context, args map[string]string) ([]PromptMessage, error)

PromptHandler renders a prompt into a sequence of messages given the caller's string arguments.

type PromptMessage

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

PromptMessage is one message in a prompt's rendered conversation. Role is typically "user" or "assistant".

func NewAssistantMessage

func NewAssistantMessage(text string) PromptMessage

NewAssistantMessage is a convenience constructor for an assistant-role text message.

func NewUserMessage

func NewUserMessage(text string) PromptMessage

NewUserMessage is a convenience constructor for a user-role text message.

type Request

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

Request is a JSON-RPC 2.0 request or notification. A message is a notification when its ID is absent (nil).

func (*Request) IsNotification

func (r *Request) IsNotification() bool

IsNotification reports whether the request is a notification, i.e. it carries no ID and therefore expects no response.

type ResourceContents added in v0.4.0

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

ResourceContents is the payload of an embedded "resource" content block or of a resources/read result: a URI-identified document carried either as Text or as a base64 Blob, with an optional MIME type.

type ResourceHandler

type ResourceHandler func(ctx context.Context) (string, error)

ResourceHandler reads a static resource and returns its textual contents.

type ResourceTemplateHandler

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

ResourceTemplateHandler reads a templated resource. The params map holds the values extracted from the request URI according to the resource's URI template.

type Response

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

Response is a JSON-RPC 2.0 response. Exactly one of Result or Error is set.

type Root added in v0.2.0

type Root struct {
	URI  string `json:"uri"`
	Name string `json:"name,omitempty"`
}

Root is a filesystem or URI root exposed by the client.

type SamplingMessage added in v0.2.0

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

SamplingMessage is one message in a sampling conversation sent to the client.

type Server

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

Server is a Model Context Protocol server. It holds the registered tools, resources, and prompts and dispatches incoming JSON-RPC requests against them. A Server is safe for concurrent use once configured; registration is typically done during startup before serving begins.

func New

func New(name string, opts ...Option) *Server

New creates a Server with the given name and options.

func (*Server) BinaryResource added in v0.2.0

func (s *Server) BinaryResource(uri, name, description, mimeType string, handler BinaryResourceHandler)

BinaryResource registers a static binary resource identified by a fixed URI. The handler returns raw bytes that are base64-encoded into a blob resource content. It is the binary counterpart of Server.Resource; use it for images (with an image/* mimeType) and other non-textual data.

func (*Server) BinaryResourceTemplate added in v0.2.0

func (s *Server) BinaryResourceTemplate(uriTemplate, name, description, mimeType string, handler BinaryResourceTemplateHandler)

BinaryResourceTemplate registers a parameterized binary resource, the binary counterpart of Server.ResourceTemplate.

func (*Server) CompletePrompt added in v0.2.0

func (s *Server) CompletePrompt(name string, fn CompletionFunc)

CompletePrompt attaches a completion callback to a previously registered prompt, enabling completion/complete for its arguments. It has no effect if no prompt with the given name is registered.

func (*Server) CompleteResourceTemplate added in v0.2.0

func (s *Server) CompleteResourceTemplate(uriTemplate string, fn CompletionFunc)

CompleteResourceTemplate attaches a completion callback to a previously registered resource template, enabling completion/complete for its URI variables. uriTemplate must match the template string passed to Server.ResourceTemplate or Server.BinaryResourceTemplate.

func (*Server) Dispatch

func (s *Server) Dispatch(c *Context) *Response

Dispatch routes a single parsed request against the server's registries and returns the response. For notifications (requests without an ID) it returns nil, since notifications receive no reply. The provided Context carries the parent context and the notification sender for the current connection.

func (*Server) HTTPHandler

func (s *Server) HTTPHandler() http.Handler

HTTPHandler returns an http.Handler implementing the MCP Streamable HTTP transport. POST requests carry a single JSON-RPC message (or a batch array) and receive an application/json response; notifications receive 202 Accepted with no body. A GET request opens a text/event-stream (SSE) channel that stays open until the client disconnects, which clients may use for server-initiated messages.

func (*Server) Name

func (s *Server) Name() string

Name returns the server's name.

func (*Server) NotifyPromptsChanged added in v0.2.0

func (s *Server) NotifyPromptsChanged()

NotifyPromptsChanged broadcasts a notifications/prompts/list_changed notification to all connected clients.

func (*Server) NotifyResourceUpdated added in v0.2.0

func (s *Server) NotifyResourceUpdated(uri string)

NotifyResourceUpdated broadcasts a notifications/resources/updated notification for uri to every client currently subscribed to it via resources/subscribe.

func (*Server) NotifyResourcesChanged added in v0.2.0

func (s *Server) NotifyResourcesChanged()

NotifyResourcesChanged broadcasts a notifications/resources/list_changed notification to all connected clients.

func (*Server) NotifyToolsChanged added in v0.2.0

func (s *Server) NotifyToolsChanged()

NotifyToolsChanged broadcasts a notifications/tools/list_changed notification to all connected clients, prompting them to re-fetch tools/list. Call it after registering or removing tools at runtime.

func (*Server) Prompt

func (s *Server) Prompt(name, description string, handler PromptHandler, args ...PromptArgument)

Prompt registers a reusable prompt template. The optional args describe the arguments the prompt accepts and are advertised to clients via prompts/list.

func (*Server) Resource

func (s *Server) Resource(uri, name, description, mimeType string, handler ResourceHandler)

Resource registers a static resource identified by a fixed URI. The handler is invoked when a client reads that exact URI.

func (*Server) ResourceTemplate

func (s *Server) ResourceTemplate(uriTemplate, name, description, mimeType string, handler ResourceTemplateHandler)

ResourceTemplate registers a parameterized resource whose URI is an RFC 6570 style template such as "users://{id}/profile". Path variables enclosed in braces are extracted from a matching read request and passed to the handler.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run serves the newline-delimited JSON-RPC stdio transport over os.Stdin and os.Stdout. It is the default transport and blocks until stdin reaches EOF or ctx is cancelled.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(addr string) error

ServeHTTP binds the Streamable HTTP handler to addr and blocks serving. Note that this is a convenience listener and is distinct from the net/http.Handler interface; use HTTPHandler to obtain the handler itself.

func (*Server) ServeStdio

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

ServeStdio serves the stdio transport over the given reader and writer. Each input line is a single JSON-RPC message; each response is written as one line. Writes are serialized so that responses and asynchronous notifications never interleave.

The transport is bidirectional: it correlates responses to server-initiated requests (such as sampling/createMessage and roots/list) and dispatches each inbound request on its own goroutine, so a handler blocked awaiting a server-to-client response does not stall the read loop. ServeStdio blocks until stdin reaches EOF or ctx is cancelled and waits for in-flight handlers to finish before returning.

Example

ExampleServer_ServeStdio demonstrates driving a FastMCP server over the stdio transport by feeding it newline-delimited JSON-RPC and reading the replies.

package main

import (
	"bytes"
	"context"
	"fmt"
	"strings"

	"github.com/malcolmston/fastmcp"
)

func main() {
	type AddArgs struct {
		A int `json:"a" jsonschema:"description=first"`
		B int `json:"b" jsonschema:"description=second"`
	}

	s := fastmcp.New("demo", fastmcp.WithVersion("1.0.0"))
	s.Tool("add", "add two ints", func(ctx context.Context, a AddArgs) (any, error) {
		return a.A + a.B, nil
	})

	in := strings.NewReader(strings.Join([]string{
		`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`,
		`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"add","arguments":{"a":2,"b":3}}}`,
	}, "\n") + "\n")

	var out bytes.Buffer
	if err := s.ServeStdio(context.Background(), in, &out); err != nil {
		fmt.Println("error:", err)
		return
	}

	// Requests are dispatched concurrently, so responses may arrive in any
	// order; select the tools/call reply (id 2) by its content.
	for _, line := range strings.Split(strings.TrimSpace(out.String()), "\n") {
		if strings.Contains(line, `"id":2`) {
			fmt.Println(line)
		}
	}

}
Output:
{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"5"}]}}

func (*Server) Tool

func (s *Server) Tool(name, description string, handler any)

Tool registers a callable tool. The handler must be a function of one of the following shapes:

func(ctx context.Context, args T) (any, error)              // T is a struct
func(ctx context.Context, args map[string]any) (any, error) // dynamic args

For the struct form, the tool's JSON input schema is reflected from T (see the package documentation for tag handling). The handler's first return value is converted to MCP content: a string becomes text content and any other value is JSON-encoded. Tool panics if the handler does not match a supported shape, so registration errors surface immediately at startup.

func (*Server) ToolWithOutput added in v0.2.0

func (s *Server) ToolWithOutput(name, description string, handler any)

ToolWithOutput registers a tool exactly like Server.Tool but additionally reflects a JSON output schema from the handler's non-error return type, which must be a struct (or pointer to struct). Such a tool advertises its outputSchema in tools/list and, on each call, returns the handler's value in the response's structuredContent field alongside the usual text content — so clients that understand structured output can consume the typed value while older clients still receive text.

func (*Server) Version

func (s *Server) Version() string

Version returns the server's reported version.

Directories

Path Synopsis
Package auth adds token-based authentication to FastMCP servers, mirroring the authentication support of Python's FastMCP 2.x.
Package auth adds token-based authentication to FastMCP servers, mirroring the authentication support of Python's FastMCP 2.x.
Package client is a standard-library-only Model Context Protocol client for talking to MCP servers, including those built with the parent fastmcp package.
Package client is a standard-library-only Model Context Protocol client for talking to MCP servers, including those built with the parent fastmcp package.
Package contrib provides optional, higher-level utilities built on top of the stdlib-only FastMCP Go port.
Package contrib provides optional, higher-level utilities built on top of the stdlib-only FastMCP Go port.
docs
gen command
Command gendocs generates a static HTML documentation site for a Go module using only the standard library (go/doc, go/parser).
Command gendocs generates a static HTML documentation site for a Go module using only the standard library (go/doc, go/parser).
Package elicit implements Model Context Protocol elicitation for servers built with the parent github.com/malcolmston/fastmcp package: a server that, in the middle of handling a request, asks the connected client to collect structured input from its user and return it.
Package elicit implements Model Context Protocol elicitation for servers built with the parent github.com/malcolmston/fastmcp package: a server that, in the middle of handling a request, asks the connected client to collect structured input from its user and return it.
Command example is a small but complete FastMCP server.
Command example is a small but complete FastMCP server.
Package jsonschema provides a small, standard-library-only JSON Schema builder and validator.
Package jsonschema provides a small, standard-library-only JSON Schema builder and validator.
Package mcperror provides the JSON-RPC 2.0 and Model Context Protocol error taxonomy as typed Go errors, using only the standard library.
Package mcperror provides the JSON-RPC 2.0 and Model Context Protocol error taxonomy as typed Go errors, using only the standard library.
Package mcplog implements the Model Context Protocol logging model — the RFC 5424 severity levels used by logging/setLevel and the notifications/message log record — using only the standard library.
Package mcplog implements the Model Context Protocol logging model — the RFC 5424 severity levels used by logging/setLevel and the notifications/message log record — using only the standard library.
Package middleware provides a server-side middleware pipeline for the FastMCP Go framework (github.com/malcolmston/fastmcp), mirroring the middleware system of Python's FastMCP 2.x.
Package middleware provides a server-side middleware pipeline for the FastMCP Go framework (github.com/malcolmston/fastmcp), mirroring the middleware system of Python's FastMCP 2.x.
Package mount composes FastMCP servers, mirroring the server-composition features of Python's FastMCP 2.x: import_server and mount.
Package mount composes FastMCP servers, mirroring the server-composition features of Python's FastMCP 2.x: import_server and mount.
Package openapi generates a Model Context Protocol server from an OpenAPI 3 document, mirroring FastMCP 2.x's FastMCP.from_openapi.
Package openapi generates a Model Context Protocol server from an OpenAPI 3 document, mirroring FastMCP 2.x's FastMCP.from_openapi.
Package proxy builds a FastMCP server that transparently forwards every request to a backend Model Context Protocol server, mirroring the behaviour of Python FastMCP 2.x's FastMCP.as_proxy.
Package proxy builds a FastMCP server that transparently forwards every request to a backend Model Context Protocol server, mirroring the behaviour of Python FastMCP 2.x's FastMCP.as_proxy.
Package transport provides FastMCP's in-memory, in-process transport: it wires a client.Client directly to a root fastmcp.Server with no sockets, no subprocess, and no network.
Package transport provides FastMCP's in-memory, in-process transport: it wires a client.Client directly to a root fastmcp.Server with no sockets, no subprocess, and no network.
Package uritemplate implements RFC 6570 URI Templates using only the Go standard library.
Package uritemplate implements RFC 6570 URI Templates using only the Go standard library.

Jump to

Keyboard shortcuts

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