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 ¶
- Constants
- type BinaryResourceHandler
- type BinaryResourceTemplateHandler
- type CompletionFunc
- type Content
- func NewAudioContent(data, mimeType string) Content
- func NewEmbeddedBlobResource(uri, mimeType, blob string) Content
- func NewEmbeddedResource(uri, mimeType, text string) Content
- func NewImageContent(data, mimeType string) Content
- func NewResourceLink(uri, name, mimeType string) Content
- func NewTextContent(text string) Content
- func (c Content) IsAudio() bool
- func (c Content) IsImage() bool
- func (c Content) IsResource() bool
- func (c Content) IsText() bool
- func (c Content) WithAnnotations(a ContentAnnotations) Content
- func (c Content) WithAudience(audience ...string) Content
- func (c Content) WithPriority(priority float64) Content
- type ContentAnnotations
- type Context
- func (c *Context) CreateMessage(params CreateMessageParams) (*CreateMessageResult, error)
- func (c *Context) Debug(data any) error
- func (c *Context) Error(data any) error
- func (c *Context) Info(data any) error
- func (c *Context) ListRoots() ([]Root, error)
- func (c *Context) Log(level string, data any) error
- func (c *Context) Progress(progress, total float64, message string) error
- func (c *Context) Request() *Request
- func (c *Context) Server() *Server
- func (c *Context) Warning(data any) error
- type CreateMessageParams
- type CreateMessageResult
- type Error
- type Notification
- type Option
- type PromptArgument
- type PromptHandler
- type PromptMessage
- type Request
- type ResourceContents
- type ResourceHandler
- type ResourceTemplateHandler
- type Response
- type Root
- type SamplingMessage
- type Server
- func (s *Server) BinaryResource(uri, name, description, mimeType string, handler BinaryResourceHandler)
- func (s *Server) BinaryResourceTemplate(uriTemplate, name, description, mimeType string, ...)
- func (s *Server) CompletePrompt(name string, fn CompletionFunc)
- func (s *Server) CompleteResourceTemplate(uriTemplate string, fn CompletionFunc)
- func (s *Server) Dispatch(c *Context) *Response
- func (s *Server) HTTPHandler() http.Handler
- func (s *Server) Name() string
- func (s *Server) NotifyPromptsChanged()
- func (s *Server) NotifyResourceUpdated(uri string)
- func (s *Server) NotifyResourcesChanged()
- func (s *Server) NotifyToolsChanged()
- func (s *Server) Prompt(name, description string, handler PromptHandler, args ...PromptArgument)
- func (s *Server) Resource(uri, name, description, mimeType string, handler ResourceHandler)
- func (s *Server) ResourceTemplate(uriTemplate, name, description, mimeType string, ...)
- func (s *Server) Run(ctx context.Context) error
- func (s *Server) ServeHTTP(addr string) error
- func (s *Server) ServeStdio(ctx context.Context, r io.Reader, w io.Writer) error
- func (s *Server) Tool(name, description string, handler any)
- func (s *Server) ToolWithOutput(name, description string, handler any)
- func (s *Server) Version() string
Examples ¶
Constants ¶
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.
const DefaultVersion = "0.2.0"
DefaultVersion is the server version reported when none is supplied.
const JSONRPCVersion = "2.0"
JSONRPCVersion is the JSON-RPC protocol version string used by MCP.
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
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
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
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
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
NewEmbeddedResource returns a "resource" Content block that embeds a textual resource's contents inline.
func NewImageContent ¶
NewImageContent returns an image Content block from base64-encoded data.
func NewResourceLink ¶ added in v0.4.0
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 ¶
NewTextContent returns a text Content block.
func (Content) IsResource ¶ added in v0.4.0
IsResource reports whether the block embeds a resource ("resource") or links to one ("resource_link").
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
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
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 ¶
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 ¶
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) ListRoots ¶ added in v0.2.0
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 ¶
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
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.
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.
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 ¶
WithInstructions sets human-readable usage instructions returned to clients during initialization.
func WithVersion ¶
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 ¶
PromptHandler renders a prompt into a sequence of messages given the caller's string arguments.
type PromptMessage ¶
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 ¶
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 ¶
ResourceHandler reads a static resource and returns its textual contents.
type ResourceTemplateHandler ¶
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 SamplingMessage ¶ added in v0.2.0
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 (*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 ¶
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 ¶
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) 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
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 ¶
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 ¶
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 ¶
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 ¶
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
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.
Source Files
¶
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. |