An agent asks your Go MCP server for a parcel, the API takes ten seconds to answer, and the user closes the chat. The host ends the session and closes the server’s stdin, but the HTTP request keeps running until the API responds. A host that retries starts a second one beside it, and the API’s slowest endpoint pays for both.
What you get
You will end up with a single-binary stdio server whose tools wrap an existing Go client and return failures as results an agent can act on. Its HTTP requests end when the host hangs up. This is for you if you own the API’s Go client.
Short answer
Register each tool with mcp.AddTool and a typed argument struct, call your existing client with
the handler’s context, and return failures as errors so the SDK sends them as tool results. Then
wrap stdin so its end cancels a server-wide context, and derive each call’s context from it too:
the Go SDK v1.6.0 lets a running call finish after the host closes stdin.
You will need
Go, and an HTTP client for your API whose calls take a context.Context. The Go MCP SDK v1.6.0
declares Go 1.25 in its go.mod. Verified 2026-11-20 against Go 1.25.0, the
official Go MCP SDK v1.6.0, and
github.com/google/jsonschema-go v0.4.3. The sample’s client, parcels, calls a Parcels API with
two operations, and a stand-in for that API runs on 127.0.0.1 with one parcel, p-slow, that
takes two seconds to answer.
Approaches compared
| Approach | When it fits | What it costs you | When to pick something else |
|---|---|---|---|
| Kiota client wrapped in tools | You generate the Go client with Kiota and want typed request builders under each tool | Kiota’s runtime packages in the binary, and every tool written by hand | You do not already generate clients with Kiota |
mark3labs/mcp-go | You prefer a builder API, such as mcp.NewTool with RequireString, and its examples | A community module tracking the protocol separately from the specification’s own SDK | You want the SDK the protocol’s maintainers publish |
| modelcontextprotocol/go-sdk | You want schemas from structs and validation before your handler runs | A context that ends on a cancel notification, not when stdin closes, so you wire that yourself | A generator already writes the tools you need |
| sdkgen go-mcp target | You generate your Go SDK with sdkgen and want the server from the same model | Its tool shapes, one per operation, and handlers that drop the call’s context | Requests must stop when the agent gives up |
| Speakeasy Go SDK wrapped in tools | You generate the Go client with Speakeasy and want a Go server around it | An account-backed generator, and an MCP target in TypeScript rather than Go | You want the MCP server generated too, in TypeScript |
Voxgig maintains sdkgen. It is one of five options here, not the recommendation.
The two SDK rows cost the same handler code and differ in style: the official one derives the
schema from a struct, mark3labs/mcp-go builds it with option functions. The generated rows trade
that code for the generator’s tool shapes. A wrapped Kiota or Speakeasy client keeps hand-written
tools and generated HTTP code, which suits a client you already ship.
Register the tools over the client
Each tool takes a struct. The SDK infers the input schema from the fields and their tags, and rejects a call that does not match it before the handler runs.
// GetParcelArgs is what an agent sends to get_parcel. The struct is the input
// schema: the SDK derives it from the fields and tags, and validates every call
// against it before the handler runs.
type GetParcelArgs struct {
ParcelID string `json:"parcel_id" jsonschema:"the parcel's id, as printed on its label, such as p-1001"`
}
The handler passes its context to the existing client and turns each failure into an error that
says what to do next. An error returned by a handler registered with mcp.AddTool becomes a
result with isError set, which the
tools specification
calls a tool execution error, the kind a model can correct.
mcp.AddTool(s, &mcp.Tool{
Name: "get_parcel",
Description: "Look up one parcel by the id on its label and return its status and depot. Read only.",
Annotations: &mcp.ToolAnnotations{ReadOnlyHint: true},
}, func(ctx context.Context, req *mcp.CallToolRequest, args GetParcelArgs) (*mcp.CallToolResult, parcels.Parcel, error) {
ctx, done := within(ctx, life)
defer done()
p, err := client.GetParcel(ctx, args.ParcelID)
if errors.Is(err, parcels.ErrInvalidID) {
return nil, p, fmt.Errorf("parcel_id %q is not a parcel id; ids look like p-1001", args.ParcelID)
}
if errors.Is(err, parcels.ErrNotFound) {
return nil, p, fmt.Errorf("no parcel %q; call list_parcels to see the ids that exist", args.ParcelID)
}
if err != nil {
return nil, p, fmt.Errorf("could not reach the parcels API: %w", err)
}
return nil, p, nil
})
within merges the call’s context with the server’s lifetime, which the hang-up section below
explains. The client escapes the id as one path segment and refuses "", ., and ...
Build one binary and call it over stdio
go build -o bin/parcel-mcp ./cmd/parcel-mcp && ls bin
parcel-mcp
cmd/try starts the binary as a host does, with PARCELS_BASE pointing at the stand-in, then
lists the tools and calls them.
go run ./cmd/try calls
2 tools from bin/parcel-mcp
get_parcel {"additionalProperties":false,"properties":{"parcel_id":{"description":"the parcel's id, as printed on its label, such as p-1001","type":"string"}},"required":["parcel_id"],"type":"object"}
list_parcels {"additionalProperties":false,"properties":{"status":{"description":"only parcels in this status; omit it for every parcel","enum":["in_transit","delivered","held"],"type":"string"}},"type":"object"}
call get_parcel {"parcel_id":"p-1001"}
API received: GET /v1/parcels/p-1001
isError=false {"depot":"Leith","id":"p-1001","status":"in_transit"}
call get_parcel {"parcel_id":"p-9999"}
API received: GET /v1/parcels/p-9999
isError=true no parcel "p-9999"; call list_parcels to see the ids that exist
call get_parcel {"parcel_id":".."}
API received: nothing
isError=true parcel_id ".." is not a parcel id; ids look like p-1001
call list_parcels {"status":"delivered"}
API received: GET /v1/parcels?status=delivered
isError=false {"parcels":[{"depot":"Govan","id":"p-1002","status":"delivered"}]}
call list_parcels {"status":"lost"}
API received: nothing
isError=true validating "arguments": validating root: validating /properties/status: enum: lost does not equal any of: [in_transit delivered held]
Every failure arrived as a result, not a JSON-RPC error. The SDK rejected the status outside the
enum itself, so the API never saw it. list_parcels wraps the list in an object, which keeps its
structured content an object for clients on the 2025-11-25 revision of the specification.
Cancel the request when the call ends
Two cases end a call early. The agent’s client cancels it, which sends notifications/cancelled.
Or the host hangs up, which closes stdin. The first works once the handler passes its context on.
go run ./cmd/try cancel
handler passes ctx to the client
agent's call: deadline exceeded after 200ms
API request: cancelled by the caller
handler uses context.Background()
agent's call: deadline exceeded after 200ms
API request: ran to completion
The second needs one more step. The SDK stops reading at the end of stdin and lets calls already
running finish, and its connection detaches each call’s context from the one passed to Run.
Serve wraps stdin so its end cancels a server-wide context.
func Serve(ctx context.Context, client *parcels.Client, r io.ReadCloser, w io.Writer) error {
life, cancel := context.WithCancel(ctx)
defer cancel()
transport := &mcp.IOTransport{Reader: cancelAtEOF{r, cancel}, Writer: nopClose{w}}
err := New(life, client).Run(life, transport)
if life.Err() != nil {
return nil
}
return err
}
go run ./cmd/try hangup
mcp.IOTransport on the pipes, as mcp.StdioTransport is
host closed stdin 300ms into the call
API request: ran to completion
server.Serve, which ends the calls at end of stdin
host closed stdin 300ms into the call
API request: cancelled by the caller
The first server passes its context through and still finishes the request, because nothing cancelled that context.1
Wrap a Kiota or Speakeasy client the same way
Kiota has no MCP output, so its Go client takes the place of parcels. Run on the sample’s
api.json, Kiota 1.38.0 wrote request builders whose Get takes the context first.
grep -rh '^func (m \*[A-Za-z]*) Get(ctx' testdata/kiota-go | cut -d'(' -f1-3 | sort
func (m *ParcelsRequestBuilder) Get(ctx context.Context, requestConfiguration *ParcelsRequestBuilderGetRequestConfiguration)
func (m *WithParcelItemRequestBuilder) Get(ctx context.Context, requestConfiguration *WithParcelItemRequestBuilderGetRequestConfiguration)
In a handler that is client.Parcels().ByParcelId(id).Get(ctx, nil), with NewParcelsClient
given a request adapter from Kiota’s Go runtime, as the
Go quickstart sets it up.
Speakeasy generates MCP servers, but the target list in its quickstart names mcp-typescript
and no Go server.2 For Go, generate its Go SDK and wrap it. Its
Go methodology page lists
context-aware method calls for timeouts and cancellation, with parameters after the context
object. Speakeasy was not run, because generation needs a login.
Check it worked
go test -count=1 -v ./... | grep -o -- '--- PASS: [A-Za-z]*'
--- PASS: TestHangUpCancelsTheInFlightRequest
--- PASS: TestRefusesToStartWithoutABaseURL
--- PASS: TestToolsAndSchemas
--- PASS: TestGetParcelReturnsTheRecord
--- PASS: TestFailuresAreToolResults
--- PASS: TestAnIDStaysOnePathSegment
--- PASS: TestCancellingTheCallCancelsTheRequest
--- PASS: TestTheSDKLetsACallRunPastEndOfInput
--- PASS: TestCancellingRunsContextLeavesTheCallRunning
--- PASS: TestServeCancelsTheCallAtEndOfInput
TestHangUpCancelsTheInFlightRequest builds the binary, writes initialize and a slow
tools/call to its stdin, closes the pipe, and expects the stand-in to report
cancelled by the caller. TestTheSDKLetsACallRunPastEndOfInput and
TestCancellingRunsContextLeavesTheCallRunning pin the SDK behavior the wrapper works around:
a call outlives the end of stdin, and outlives a cancel of the context passed to Run. Either
fails when an SDK release changes that.
When it goes wrong
The binary’s output breaks the host’s parser. Anything written to stdout that is not JSON-RPC
corrupts the stream, so log writes to stderr and nothing in the tools prints.
An agent loops on a failure. A tool error that says only 404 gives the model nothing to do
next, so name the tool that finds valid ids, as get_parcel does.
The generated sdkgen server keeps requests running. Its handlers discard the context, and the Go SDK it wraps builds requests without one.
grep -n 'func runOp' testdata/sdkgen/go-mcp/tools.go && grep -n 'http.NewRequest' testdata/sdkgen/go/utility/fetcher.go
60:func runOp(_ context.Context, client *sdk.ParcelsSDK, op string, entity string, input map[string]any) (*mcp.CallToolResult, any, error) {
115: req, err := http.NewRequest(method, fullurl, bodyReader)
When not to do this
Do not hand-write the server when sdkgen already generates your Go SDK and its operation tools are the ones agents need. The generated server tracks the spec on every regeneration. The cost is the context, which its handlers drop, so do not use it where a slow endpoint must stop when the agent gives up.
Do not write the server in Go to wrap a client that exists only in TypeScript. Speakeasy’s
mcp-typescript target generates that server, and Kiota or Speakeasy Go clients only help when
the Go client is what you ship.
Do not rely on a host’s cancel notification alone. A host that crashes sends none, and only the end of stdin tells the server.
Related how-tos
Last verified
Verified 2026-11-20 against Go 1.25.0, the Go MCP SDK v1.6.0, and github.com/google/jsonschema-go
v0.4.3. Every output block is what the command preceding it printed. Kiota 1.38.0 and
@voxgig/sdkgen 4.44.3 ran once, and the files the page greps are committed under testdata/.
mark3labs/mcp-go was read from its documentation and not run. Speakeasy was not run. Its options come from its documentation.
Footnotes
-
The SDK’s
jsonrpc2package wraps the context a connection is built with in a type callednotDone, defined near the end of conn.go. It passes the parent’s values through and answersDoneandErrwith nil andDeadlinewith none, so every request context built on it inherits the values and none of the cancellation. Its doc comment puts the whole arrangement in one line: a wrapper that returns a nil Done channel. ↩︎ Back to text -
The quickstart reference lists eleven targets, from
clitotypescript, withmcp-typescriptbetweenjavaandphp.postmanandterraformsit in the same list, so the flag names outputs rather than languages. ↩︎ Back to text