go-mcp is a Go library for creating Model Context Protocol servers compatible
with MCP 2026-07-28, while retaining the 2025-11-25 legacy protocol era. It
supports newline-delimited stdio, Streamable HTTP, and legacy HTTP+SSE.
See DOC.md for the complete English API reference, lifecycle details, and developer use cases. A Russian version is available in DOC.ru.md.
- Features
- Installation
- Documentation
- Quick start
- Middleware and authorization
- Transports
- Client
- Configuration
- Examples
- Development
- License
- MCP revision 2026-07-28 and JSON-RPC 2.0, with 2025-11-25 legacy support.
- Typed tools with JSON Schema generated from Go structs and tags.
- Tool annotations, icons, and output schemas via
RegisterToolWithOptions. - Static and dynamic resources, resource templates, and prompts.
- Modern per-request metadata, discovery, result types, multi-round-trip input, and filtered change subscriptions.
- Legacy client features for sampling, roots, elicitation, logging, and experimental durable Tasks.
- Stdio, stateless Streamable HTTP, legacy session-based Streamable HTTP, and legacy SSE transports.
- Strict JSON-RPC request validation, bounded stdio framing, and optional request observers.
- Shared middleware pipeline with authorization errors mapped to protocol and HTTP status codes.
- Configuration from MCP_* environment variables or flat YAML.
- Graceful signal-aware shutdown through Server.Run.
go get go.osspkg.com/mcp- English API and developer guide
- Russian API and developer guide
- go-mcp development skill
- Runnable examples
- MCP 2026-07-28 specification
- MCP 2025-11-25 transport specification
Use ordinary Go structs for typed tool models. encoding/json reads their
json tags to determine wire names and optional fields; mcp tags supply
schema descriptions and can mark primitive inputs for modern HTTP header
mirroring with header=....
type greetingInput struct {
Name string `json:"name" mcp:"description=Name to greet"`
}
type greetingOutput struct { Greeting string `json:"greeting"` }
server, _ := mcp.New(mcp.ServerInfo{Name: "greetings", Version: "1.0.0"})
_ = mcp.RegisterTool(server, "greet", "Returns a greeting",
func(_ context.Context, in *greetingInput) (*greetingOutput, error) {
return &greetingOutput{Greeting: "Hello, " + in.Name}, nil
},
)Middleware runs for every JSON-RPC MCP method, including initialization and
catalog listings. For HTTP and SSE, request headers are available through
request.Meta.Headers.
server, _ := mcp.New(mcp.ServerInfo{Name: "secured", Version: "1.0.0"},
mcp.WithMiddleware(func(next mcp.Handler) mcp.Handler {
return func(ctx context.Context, request mcp.Request) (any, error) {
if request.Meta.Headers["Authorization"] == "" {
return nil, mcp.ErrUnauthorized
}
return next(ctx, request)
}
}),
)Legacy SSE GET /sse is a transport handshake and does not run MCP middleware.
For a protected SSE endpoint, configure sse.Config.AuthorizeSession to apply
the same authorization decision before session allocation. A nil callback
leaves session creation public.
The transport adapters implement mcp.Transport and can be passed directly to
Server.Run. Do not write logs to the stdio output writer; it is reserved for
JSON-RPC protocol data.
transport := stdio.NewTransport(os.Stdin, os.Stdout)
err := server.Run(transport)transport := mcphttp.NewTransport(mcphttp.Config{
Address: ":8080",
Path: "/mcp",
})
err := server.Run(transport)Modern clients send one stateless POST /mcp per request with protocol
metadata and mirrored method headers. Requests may return JSON or a
request-scoped SSE stream; accepted notifications return 202 Accepted with
an empty body. Long-lived change events use subscriptions/listen. The
2025-11-25 compatibility path retains session headers, GET /mcp, and
Last-Event-ID resumption. Set AllowedOrigins to the exact origins accepted
by the endpoint; non-empty unlisted origins receive HTTP 403, and requests with
multiple Origin values are rejected. The legacy path issues a session ID only
after a valid initialize request with an ID receives a successful result.
Server-to-client features use RequestFromContext(ctx) inside a typed handler:
if request, ok := mcp.RequestFromContext(ctx); ok {
_ = request.SendProgress(ctx, "job-1", 1, nil, "started")
_, _ = request.Sample(ctx, mcp.CreateMessageParams{MaxTokens: 64})
}OAuth 2.0 Protected Resource Metadata and OAuth/OIDC discovery documents are
available through mcp.MarshalMetadata and the HTTP package's
NewProtectedResourceMetadataHandler / NewAuthorizationServerMetadataHandler.
transport := sse.NewTransport(sse.Config{
Address: ":8080",
SSEPath: "/sse",
MessagePath: "/message",
})
err := server.Run(transport)Each SSE session uses a bounded queue of 16 messages. Expired sessions are
removed by a background cleanup goroutine according to SessionTTL; associated
SSE streams are closed, and POST waits for queue capacity or request context
cancellation. Transport shutdown also closes active SSE sessions and stops the
cleanup goroutine. The GET /sse handshake allocates a session without running
MCP middleware. Configure AuthorizeSession to authenticate it when the SSE
endpoint is protected; a nil callback leaves session creation public. Use
AllowedOrigins to restrict both /sse and /message to exact browser origins.
Unlisted non-empty origins receive HTTP 403, and multiple Origin values are
rejected. In NewTransportWithSSE, an empty SSE AllowedOrigins list inherits
the HTTP transport list. For JSON-RPC replies, legacy HTTP and SSE inspect the
top-level error.code; nested tool output cannot misclassify a successful
result.
For one listener serving both Streamable HTTP and legacy SSE, use
NewTransportWithSSE:
transport := mcphttp.NewTransportWithSSE(
mcphttp.Config{Address: ":8080", Path: "/mcp"},
sse.Config{SSEPath: "/sse", MessagePath: "/message"},
)
err := server.Run(transport)Server.Run(transports...) creates a signal-aware context internally, stops
on os.Interrupt or SIGTERM, cancels all transports, and waits for every
transport to finish before returning. A signal-triggered shutdown returns
context.Canceled, which is normally treated as a clean exit:
err := server.Run(transports...)
if err != nil && !errors.Is(err, context.Canceled) {
log.Fatal(err)
}Use Server.RunContext(ctx, transports...) when the application owns the
parent context and cancellation policy. RunContext is also useful for
embedding the server in another process or for tests:
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err := server.RunContext(ctx, transport)The go.osspkg.com/mcp/client package connects to modern and legacy servers
over the supported transports. Connect discovers the modern protocol and
falls back to the legacy initialize handshake when needed. Typed helpers list
and call tools, read resources, and render prompts; Task helpers and
server-initiated request handlers apply to the legacy protocol era.
transport, _ := client.NewHTTPTransport("http://127.0.0.1:8080/mcp", client.HTTPConfig{})
mcpClient, _ := client.New(transport)
defer mcpClient.Close()
_ = mcpClient.Start(ctx)
_ = mcpClient.Connect(ctx)
tools, _ := mcpClient.ListTools(ctx)
if len(tools.Tools) > 0 {
_, _ = mcpClient.CallTool(ctx, tools.Tools[0].Name, map[string]any{}, nil)
}Use client.NewCommandTransport to launch a child-process stdio server,
client.NewStdioTransport to connect to already-open streams, and
client.NewSSETransport for legacy /sse endpoints. Register
OnRequest("sampling/createMessage", ...), OnRequest("roots/list", ...), or
OnRequest("elicitation/create", ...) before making calls that can trigger
legacy server-to-client requests; modern input uses MRTR and change streams use
subscriptions/listen. Use OnNotification for request-scoped and legacy
notifications.
Load exactly one source; do not merge the results of LoadEnv and LoadYAML.
Environment variables use the MCP_ prefix, for example MCP_NAME,
MCP_VERSION, MCP_ENABLE_HTTP, and MCP_HTTP_ADDRESS.
configuration, err := config.LoadEnv()
if err != nil {
log.Fatal(err)
}
transports, err := config.Transports(configuration, server, os.Stdin, os.Stdout)
if err != nil {
log.Fatal(err)
}
err = server.Run(transports...)For YAML configuration, replace the loader with:
configuration, err := config.LoadYAML("server.yaml")The YAML reader intentionally supports only flat scalar values:
name: greetings
version: 1.0.0
enable_stdio: false
enable_http: true
http_address: 127.0.0.1:8080Nested YAML, lists, aliases, and unknown keys are rejected rather than parsed with ambiguous semantics.
Runnable servers for each transport, middleware, and both configuration
sources are in example/. They use only this module and
the Go standard library.
The library runtime has no non-standard-library imports. Run the project gates:
make lint
make tests
go test -race ./...go-mcp is distributed under the BSD 3-Clause License. See the license file for the complete copyright and redistribution terms.