Annotation-driven MCP server generator for
Go. Write plain handler functions, sprinkle @MCP.* comments on top, and
GoMCP generates a runnable main package serving a spec-compliant
Streamable HTTP MCP endpoint with tools, resources and prompts.
Run it where you want: remote or local. The same annotated code runs as an HTTP server that many clients reach over the network, or as a local process that one client (Claude Desktop, an IDE, an agent) starts itself over stdin and stdout. You pick when you start it, the code does not change.
Supported spec: MCP 2026-07-28 — the stateless
revision (no sessions, no initialize, every request carries its protocol version and client capabilities).
Older revisions are not supported.
Status: v0.x. The exported API of
pkg/mcpmay still change between minor versions. Requires Go 1.26.2 or newer. Code snippets in this document are abbreviated; runnable code is inexamples/.
Fastest start: gomcp init hello && cd hello && gomcp serve . (see Install). Or write this in a Go module that requires GoMCP (go get github.com/StevenCyb/GoMCP):
package api
import "github.com/StevenCyb/GoMCP/pkg/mcp"
type HelloIn struct {
Name string `json:"name" desc:"Who to greet"`
}
// @MCP.Tool("hello", description="Greets someone")
func Hello(ctx mcp.Context, in HelloIn) (string, error) {
return "Hello " + in.Name, nil
}Run:
gomcp serve .Get:
- A Streamable HTTP MCP endpoint at
/mcpwithtools/listandtools/call. - Input and output schemas derived from your Go types.
- Auto-generated bootstrap (
main, transport, auth, lifecycle wiring).
More runnable servers are in
examples/(index with how to run each):
You write the handler, GoMCP writes everything around it.
- Handlers stay plain Go. A function with a typed input and output plus an
@MCP.Toolcomment is the whole tool. Schemas, validation, registration and the servermainare generated from your types. - Nothing lands in your module. The generated code is built with Go's overlay mechanism: no generated files to commit or review, and no
go:generatestep. - Remote or local from one codebase. The same code runs as an HTTP server for many clients (
gomcp serve) or as a local process that one client starts (gomcp stdio). - The newest spec. It implements MCP 2026-07-28 (stateless,
server/discover, multi round-trip requests, tasks) from day one. - Tested end to end. The
examples/featuresproject runs through a test client over HTTP and stdio in CI on Linux and Windows, and a smoke test of every merged commit runs on Linux, Windows and macOS.
It has its own runtime (pkg/mcp), so you can also skip the annotations and register tools in code. If you prefer to write every registration yourself, or need a revision older than 2026-07-28, another MCP library for Go is the better fit.
go install github.com/StevenCyb/GoMCP/cmd/gomcp@latestThe binary is called gomcp. Then scaffold a first server in one step:
gomcp init hello && cd hello
gomcp serve .- See It In 5 Seconds
- Why GoMCP
- Install
- Basics
- CLI
- Transports
- Server
- Authentication
- Tools
- Resources
- Prompts and completion
- Runtime
- Contributing
Annotations are comment lines. One optional positional value, the rest is key="value", key=1 or a bare flag. The doc comment above is the description. Types in the signature become the JSON schemas.
// Adds a short text note.
//
// @MCP.Tool("add_note", title="Add note")
// @MCP.AuthScopes("notes:write")
func Add(ctx mcp.Context, in AddIn) (Note, error) { ... }
type AddIn struct {
Text string `json:"text" desc:"Note body" min:"1" max:"500"` // required: no omitempty
Tag string `json:"tag,omitempty" enum:"work,idea" default:"idea"` // optional
}Struct tags: desc enum min max default format. A period at the end of an annotation line is ignored.
gomcp reads your annotations, generates a main package in memory, and builds it with go build -overlay, so nothing is written into your module.
flowchart LR
A["your .go files<br/>+ @MCP.* comments"] -->|parse| B["project model"] -->|generate| C["main.go (in memory)"] -->|"go build -overlay"| D["binary"] -->|"run + .env"| E["MCP server"]
init <dir> creates a new project: go.mod, an annotated api.go with one hello tool, .gitignore and a README.md. It then runs go get for this gomcp's version and go mod tidy. It refuses a directory that already has files. If go get fails (offline), the files stay and the error says what to run.
gomcp init ./hello # module example.com/hello
gomcp init ./hello --module github.com/me/hello
gomcp init ./hello --no-get # only write the filesbuild compiles a single binary, serve builds and runs it as an HTTP server, watch rebuilds and restarts on every .go change and keeps the old server if a rebuild fails. stdio builds and runs it for a local client, see Local or remote.
gomcp build ./examples/features ./bin/notes # one binary, contains both transports
gomcp serve ./examples/features # build + run over HTTP, Ctrl-C stops gracefully
gomcp watch ./examples/features # rebuild on change (HTTP only)
gomcp stdio ./examples/features # build + run over stdin and stdout
gomcp call ./examples/features # list the tools
gomcp call ./examples/features add_note '{"text":"hi"}' # call a tool, print the result
gomcp versioncall tries a project without an AI client: it builds the project, starts it over stdio, lists the tools or calls one and stops the server. Text results go to stdout, build logs and errors to stderr. Arguments are a JSON object (- reads it from stdin), --json prints the raw result, and the exit code is 1 when the tool returns an error or the server a protocol error. Tools that ask the client for input (forms, sampling) are reported, not answered; --root <dir> answers roots/list.
flowchart LR
W["file change"] --> P["parse + generate + build"]
P -->|ok| R["restart server"]
P -->|error| K["keep old server, print error"]
--tags/-t forwards build tags. serve, watch, stdio and call also take --dotenv/-e (default <module>/.env; real environment wins). serve and watch take --addr/-a (sets GOMCP_ADDR, default 127.0.0.1:8080, loopback only; set it to expose the server and configure @MCP.Auth first).
gomcp serve ./examples/features --addr 127.0.0.1:8765 --dotenv ./dev.envOne annotated project, two ways to run it. HTTP is the default and serves many clients over the network. With stdio the client starts the server as a child process and talks to it over stdin and stdout, which is how desktop clients and IDEs run local tools.
gomcp serve ./proj # remote: HTTP on 127.0.0.1:8080 (or --addr)
gomcp stdio ./proj # local: stdin and stdout, for a client that starts it
gomcp build ./proj ./bin/notes # one binary, both ways:
./bin/notes # HTTP (default)
./bin/notes --stdio # stdio (or GOMCP_TRANSPORT=stdio)flowchart LR
subgraph remote ["Remote: HTTP"]
C1[client] & C2[client] -->|"POST /mcp"| S1["notes server<br/>(auth, scopes)"]
end
subgraph local ["Local: stdio"]
C3["client<br/>(starts the process)"] -->|"stdin / stdout"| S2["notes server<br/>(child process)"]
end
A client config for a local server. Build once and start the binary, because gomcp stdio ./proj compiles on every start:
{ "command": "./bin/notes", "args": ["--stdio"] }What changes with stdio:
- No authentication. The caller is the process that started the server, so
@MCP.Authis ignored and@MCP.AuthScopesare not checked. Anyone who can start the binary can use every feature. - One client per process. There are no HTTP headers, origins or listen address (
--addrdoes not apply). - Only protocol messages on stdout. Log to stderr (the
logpackage does). Afmt.Printlnin your code or setup breaks the connection. - No
gomcp watch. A restart would end the client's connection, sowatchrefuses stdio. - Relative icons are left out. They need the server's URL, which stdio does not have. Use absolute or
data:URLs. - Same behaviour otherwise. Tools, resources, prompts, elicitation, sampling, roots, tasks and
subscriptions/listenwork the same. A listen request stays open until the client cancels it withnotifications/cancelled, and a cancelled request gets no response.
Name, version and instructions of the server. Clients show the name and may add the instructions to the model's system prompt. Package-level, any comment block in the package.
// @MCP.Server("notes", title="Notes", version="1.0.0", website="https://example.com")
// @MCP.Icon("assets/notes.svg")
// @MCP.Instructions("Use the notes tools to create and read short notes.")
package apiNo sessions and no initialize. Every request carries the protocol version and the client's capabilities, so any instance can answer it. Headers Mcp-Protocol-Version, Mcp-Method and Mcp-Name mirror the body for gateways. Mismatch is -32020, unknown version -32022.
// nothing to write: gomcp validates headers and _meta, and answers server/discoversequenceDiagram
participant C as Client
participant S as Server
C->>S: server/discover
S-->>C: versions, capabilities, instructions
C->>S: tools/call + _meta {protocolVersion, clientCapabilities}
S-->>C: result {resultType: "complete"}
These settings apply to HTTP; over stdio there is no endpoint, origin or keep-alive (Local or remote). One endpoint, POST only (GET and DELETE answer 405). Origins are checked (403), lists are paged, listen streams get keep-alive comments.
// @MCP.Endpoint("/mcp")
// @MCP.AllowedOrigin("https://claude.ai")
// @MCP.KeepAlive("30s")
// @MCP.PageSize(50)
package apiTells clients how long discover, list and read results may be reused (ttlMs) and by whom (cacheScope: private by default, public only if you say scope="public").
// @MCP.Cache("5m", scope="private")
package apiWraps calls for logging, metrics or rate limits. Declare with @MCP.Middleware, attach with @MCP.Use(fn) at package level (everything) or on one feature.
// @MCP.Middleware
func Logging(ctx mcp.Context, req mcp.Request, next mcp.Handler) (any, error) {
log.Printf("%s %s", req.Kind, req.Name)
return next(ctx, req)
}
// package level: @MCP.Use(api.Logging) on a feature: @MCP.Use(api.Logging)flowchart LR
R["request"] --> O["origin check"] --> A["auth"] --> G["package middleware"] --> F["feature middleware"] --> H["your handler"]
Run code once when the server starts and stops, for example to open and close a database. Setup may return an error that stops the start.
// @MCP.Setup
func Setup() error { db = open(); return nil }
// @MCP.Teardown
func Teardown() { db.Close() }flowchart LR
S1["Setup"] --> S2["listen on GOMCP_ADDR"] --> S3["serve"] --> S4["SIGINT / SIGTERM"] --> S5["close streams, HTTP shutdown"] --> S6["Teardown"]
Serve embedded files (icons, images) from the same server. Relative icon paths on any feature resolve to the served URL.
// @MCP.ServeAssets("/assets")
//go:embed assets
var Assets embed.FS
// @MCP.Tool("add_note")
// @MCP.Icon("assets/add.svg") // becomes http://host/assets/add.svgFor internal tokens and API keys: your verifier checks the token and returns the caller. Failure is a plain 401. Several @MCP.Auth are allowed, the first success wins.
// @MCP.Auth(type="bearer")
func VerifyAPIKey(ctx context.Context, token string) (mcp.Principal, error) {
if token != os.Getenv("API_KEY") { return mcp.Principal{}, errors.New("invalid") }
return mcp.Principal{Subject: "service", Scopes: []string{"notes:read"}}, nil
}gomcp verifies tokens, it never issues them. Authentication belongs to HTTP: over stdio it is ignored (Local or remote). It serves the protected resource metadata, challenges unauthenticated calls and checks scopes. Needs resource=, an authorization server and scopes.
// @MCP.Auth(type="oauth", resource="https://notes.example.com/mcp")
// @MCP.AuthServer("https://auth.example.com")
// @MCP.AuthScope("notes:read", description="Read notes", default)
func VerifyToken(ctx context.Context, token string) (mcp.Principal, error) { ... }sequenceDiagram
participant C as Client
participant S as Server
participant A as Authorization server
C->>S: POST /mcp (no token)
S-->>C: 401 + WWW-Authenticate (metadata)
C->>A: sign in, get token
C->>S: POST /mcp + Bearer token
S-->>C: result
Limit a feature to callers with certain scopes. A missing scope gives 403 insufficient_scope, so the client can ask the user for more permission. In handlers, ctx.Principal() is the caller.
// @MCP.Tool("delete_note")
// @MCP.AuthScopes("notes:write")
func Delete(ctx mcp.Context, in IDIn) (mcp.Empty, error) {
who := ctx.Principal().Subject
...
}A tool lets the model do something. Input schema comes from the input struct; a struct result also gives an output schema. Invalid arguments become tool errors the model can fix itself.
// @MCP.Tool("get_note", description="Returns a note by id")
func Get(ctx mcp.Context, in IDIn) (Note, error) { ... } // func(ctx, In) (Out, error)flowchart LR
A["Go signature + tags"] -->|gomcp| B["inputSchema / outputSchema"]
D["tools/call arguments"] -->|validated| B
B -->|invalid| E["tool error, model retries"]
B -->|valid| F["your handler"]
Hints tell clients what a tool does (readOnly, destructive, idempotent, openWorld). @MCP.Requires names client capabilities the tool needs; without them the call fails early with -32021.
// @MCP.Tool("delete_note")
// @MCP.Hint(destructive)
// @MCP.Requires(elicitation) // also: sampling, roots, elicitation="url"
// @MCP.Meta(team="docs")Return a struct (structured + text), a string, or mcp.Result[T] to add content such as links. mcp.ToolError is shown to the model; protocol errors go to the client.
Any error a tool returns, not only
mcp.ToolError, is sent to the model as text. Never put secrets, DSNs or file paths in error messages.
func Get(ctx mcp.Context, in IDIn) (mcp.Result[Note], error) {
n, ok := notes[in.ID]
if !ok { return mcp.Result[Note]{}, mcp.ToolError("note not found") } // model sees it
return mcp.Result[Note]{Structured: n, Content: []mcp.Content{mcp.ResourceLink("note:///" + n.ID)}}, nil
}The server cannot call the client. Calls that need an answer return mcp.ErrInputRequired: return it unchanged. gomcp sends input_required, the client answers and retries, and your handler runs again from the top with the answer. Ask first, act after.
ans, action, err := mcp.Elicit[Confirm](ctx, "Delete it?")
if err != nil { return out, err } // ErrInputRequired: gomcp asks, then rerunssequenceDiagram
participant C as Client
participant S as Server
C->>S: tools/call
S-->>C: input_required {inputRequests, requestState}
Note over C: asks the user or its model
C->>S: tools/call + inputResponses + requestState
Note over S: handler runs again, call returns the answer
S-->>C: result
Ask the user a question or confirmation. T is a flat struct; tags (enum, min, max, default) shape the form. The action is mcp.Accept, mcp.Decline or mcp.Cancel.
type Confirm struct {
Confirm bool `json:"confirm" desc:"Really delete?" default:"false"`
}
ans, action, err := mcp.Elicit[Confirm](ctx, "Delete "+in.ID+"?")
if err != nil { return mcp.Empty{}, err }
if action != mcp.Accept || !ans.Confirm { return mcp.Empty{}, mcp.ToolError("not confirmed") }Send the user to your own web page (sign-in, payment). The page's backend calls mcp.CompleteElicitation(id) when done; the waiting handler continues. Approving before the client retries is fine.
id, err := ctx.ElicitURL("Sign in", "https://example.com/connect?e={id}") // {id} is filled in
if err != nil { return out, err }
select {
case <-ctx.ElicitDone(id): // closed by mcp.CompleteElicitation(id) on your page
case <-ctx.Done(): // never closes for an unknown or expired id: always keep a way out
return out, ctx.Err()
case <-time.After(10 * time.Minute):
return out, mcp.ToolError("sign-in timed out")
}sequenceDiagram
participant U as User
participant C as Client
participant S as Server
S-->>C: input_required (url with ?e=id)
C->>U: open this page?
U->>S: your page calls CompleteElicitation(id)
C->>S: retry with accept
Note over S: ElicitDone(id) closed, handler continues
S-->>C: result
Ask the client's own model for a completion, so your server needs no model access. The client must declare sampling; use @MCP.Requires(sampling).
res, err := ctx.Sample(mcp.SampleReq{
System: "Summarize in one sentence.",
Messages: []mcp.SampleMsg{mcp.SampleText(mcp.RoleUser, text)},
MaxTokens: 120,
})
if err != nil { return out, err }
return Out{Summary: res.Text}, nilRead the client's project roots, for example to know which folders to work on.
roots, err := ctx.Roots() // @MCP.Requires(roots)
if err != nil { return out, err }
for _, r := range roots { use(r.URI) }Report progress when the client sent a progress token. Logs are sent only when the request asks for a log level.
for i, item := range items {
ctx.Progress(float64(i+1), float64(len(items)), "importing "+item)
}
ctx.Log().Info("import done", "count", len(items))Extension io.modelcontextprotocol/tasks. With @MCP.Task the server decides: a client that supports tasks gets a handle at once and polls; others get the result directly. Watch ctx.Done() for cancellation.
// @MCP.Tool("import_notes")
// @MCP.Task(optional, ttl="10m", poll="2s") // optional | required
func Import(ctx mcp.Context, _ mcp.Empty) (int, error) {
if ctx.Err() != nil { return 0, ctx.Err() } // tasks/cancel
...
}stateDiagram-v2
[*] --> working: tools/call returns a task handle
working --> input_required: Roots / Elicit / Sample
input_required --> working: tasks/update
working --> completed: result (tool errors too)
working --> failed: protocol error
working --> cancelled: tasks/cancel
Data the application reads, such as files or records. A fixed URI or an RFC 6570 template; {id} binds to a uri:"id" field. An exact URI wins over a template.
// @MCP.Resource("note:///{id}", title="Note", mime="text/plain")
func Read(ctx mcp.Context, u NoteURI) (mcp.Contents, error) { // NoteURI{ID string `uri:"id"`}
n, ok := notes[u.ID]
if !ok { return nil, mcp.ErrNotFound } // -32602 with data.uri
return mcp.Contents{mcp.TextContent(n.Text)}, nil
}
// @MCP.Resource("note:///index", mime="application/json")
func Index(ctx mcp.Context) (mcp.Contents, error) { return mcp.JSONContents(ids()) }flowchart LR
RD["resources/read note:///7"] --> M{match}
M -->|exact URI first| S["static resource"]
M -->|else template| H["handler, id=7"]
Make concrete URIs discoverable through resources/list, paged with a cursor.
// @MCP.ResourceList("note:///{id}")
func List(ctx mcp.Context, page mcp.PageReq) (mcp.Page[mcp.ResourceRef], error) {
return mcp.Paginate(refs(), page), nil
}There is no push channel. A client opens subscriptions/listen with what it cares about; the stream is acknowledged first and stays open. Mark a resource @MCP.Subscribable and call ctx.ResourceUpdated(uri) when it changes.
// @MCP.Resource("note:///{id}")
// @MCP.Subscribable
...
ctx.ResourceUpdated("note:///" + id) // subscribers of that URI
ctx.ResourcesChanged() // list changed (also ToolsChanged, PromptsChanged)sequenceDiagram
participant C as Client
participant S as Server
C->>S: subscriptions/listen {resourceSubscriptions, resourcesListChanged}
S-->>C: acknowledged
Note over S: a tool calls ctx.ResourceUpdated(uri)
S-->>C: notifications/resources/updated
ctx.ResourceUpdated(uri)reaches every listener subscribed to that exact URI (subject to the scopes of the resource). Per-user data needs per-user URIs that the resource handler authorizes viactx.Principal().
Conversation starters the user picks, like a slash command with arguments. A prompt returns messages, optionally with resources embedded.
// @MCP.Prompt("summarize_notes", title="Summarize note")
func SummarizeNotes(ctx mcp.Context, a Args) (mcp.Messages, error) { // Args{ID string; Style string `json:",omitempty"`}
return mcp.Messages{
mcp.UserText("Summarize this note (" + a.Style + "):"),
mcp.User(mcp.EmbedResource("note:///" + a.ID)),
}, nil
}sequenceDiagram
participant U as User
participant C as Client
participant S as Server
U->>C: picks /summarize_notes, fills arguments
C->>S: prompts/get
S-->>C: messages [user, resource]
C->>U: starts the chat with them
Autocomplete for a prompt argument or a resource template variable. Fixed values on the prompt, or a function for computed ones (for is the prompt name or the URI template).
// @MCP.Complete(arg="style", values="short,bullets") // on the prompt
// @MCP.Complete(for="note:///{id}", arg="id")
// @MCP.Complete(for="summarize_notes", arg="id")
func CompleteID(ctx mcp.Context, partial string, resolved map[string]string) (mcp.Completion, error) {
return mcp.Values(idsWithPrefix(partial)...), nil
}sequenceDiagram
participant U as User
participant C as Client
participant S as Server
U->>C: types "sh" in style
C->>S: completion/complete {ref, argument, value}
S-->>C: ["short"]
Annotations only generate calls to pkg/mcp, so you can use it directly, for example inside an existing HTTP server.
srv := mcp.NewServer(mcp.Info{Name: "notes", Version: "1.0.0"}, mcp.WithPageSize(50))
_ = mcp.AddTool(srv, mcp.ToolDef{Name: "add_note"}, Add) // also AddResource, AddPrompt, srv.Use, ...
mux := http.NewServeMux()
srv.Mount(mux, "/mcp")
log.Fatal(http.ListenAndServe(":8080", mux))| Option | Effect |
|---|---|
WithInstructions(text) |
instructions of server/discover |
WithAllowedOrigins(...) |
accepted Origin values (default: localhost) |
WithKeepAlive(d) |
keep-alive of listen streams |
WithPageSize(n) |
page size of list operations |
WithBaseURL(url) |
base of relative icon sources |
WithCache(ttl, scope) |
ttlMs and cacheScope hints |
WithLimits(mcp.Limits{...}) |
caps for tasks (Tasks 1000, TasksPerCaller 100, TaskTTL 1h, TaskInputTimeout 15m), listen streams (Streams 1000, StreamsPerCaller 20, ListenEntries 100 per request) and open URL elicitations (Elicitations 10000, ElicitationsPerCaller 100); zero keeps the default, over the cap the request fails with a "try again later" error |
WithStateKey(key) |
secret for requestState; share it between instances (GOMCP_STATE_KEY in generated servers) |
WithAuth(schemes...) |
authentication schemes |
Tool errors are results with isError: true. Protocol errors are JSON-RPC errors: -32602 invalid params (also resource not found), -32603 internal, -32020 header mismatch, -32021 missing client capability, -32022 unsupported protocol version.
return out, mcp.ToolError("note not found") // the model sees it
return out, mcp.ErrInvalidParams("bad id") // the client sees it
return nil, mcp.ErrNotFound // resources: -32602 + data.uriAutomatic: discover, header and version checks, resultType, cache hints, listen streams, schemas and argument validation, origin check, OAuth metadata and challenges, scope checks, tasks, icon resolution.
Not supported, removed by 2026-07-28: sessions and initialize, ping, logging/setLevel, resources/subscribe, the GET stream and resumability, server-to-client requests, batching, legacy HTTP+SSE. Older revisions answer -32022. Client registration and issuing tokens belong to your authorization server.
Checks, tests and how to try a change with a real client: README_DEV.md. Issues and pull requests are welcome; security problems go through SECURITY.md.