# How to build an MCP server in Go over an existing HTTP client

> Register MCP tools over a Go API client with the official Go SDK, return failures as tool results, and make every in-flight request end when the host hangs up.

Source: https://voxgig.com/howto/build-an-mcp-server-in-go

- Audience: api-producer
- Level: intermediate
- Languages: go
- Verified: 2026-11-20
- Published: 2026-11-20

## 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](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp) 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](https://learn.microsoft.com/en-us/openapi/kiota/quickstarts/go) | 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`](https://pkg.go.dev/github.com/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](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp) | 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](https://github.com/voxgig/sdkgen/blob/main/docs/reference/model.md) | 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](https://www.speakeasy.com/docs/sdks/languages/golang/methodology-go) | 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.

```go title="server/server.go"
// 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](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)
calls a tool execution error, the kind a model can correct.

```go title="server/server.go"
	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

```bash
go build -o bin/parcel-mcp ./cmd/parcel-mcp && ls bin
```

```text output
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.

```bash
go run ./cmd/try calls
```

```text output
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.

```bash
go run ./cmd/try cancel
```

```text output
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.

```go title="server/stdio.go"
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
}
```

```bash
go run ./cmd/try hangup
```

```text output
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.

```bash
grep -rh '^func (m \*[A-Za-z]*) Get(ctx' testdata/kiota-go | cut -d'(' -f1-3 | sort
```

```text output
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](https://learn.microsoft.com/en-us/openapi/kiota/quickstarts/go) 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](https://www.speakeasy.com/docs/sdks/languages/golang/methodology-go) 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

```bash
go test -count=1 -v ./... | grep -o -- '--- PASS: [A-Za-z]*'
```

```text output
--- 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.

```bash
grep -n 'func runOp' testdata/sdkgen/go-mcp/tools.go && grep -n 'http.NewRequest' testdata/sdkgen/go/utility/fetcher.go
```

```text output
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

- [Choose between stdio and Streamable HTTP for an MCP server](/howto/choose-an-mcp-transport)

- [Generate an MCP server from an OpenAPI document](/howto/generate-an-mcp-server-from-openapi)

- [Design error responses an autonomous agent can act on](/howto/error-responses-an-agent-can-act-on)

- [Keep an agent informed while an MCP tool runs for minutes](/howto/report-progress-from-a-long-running-tool)

- [Generate an MCP server from a semantic model with sdkgen](/howto/generate-an-mcp-server-from-a-semantic-model)

## 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.

[^1]: The SDK's `jsonrpc2` package wraps the context a connection is built with in a type called
`notDone`, defined near the end of
[conn.go](https://github.com/modelcontextprotocol/go-sdk/blob/v1.6.0/internal/jsonrpc2/conn.go).
It passes the parent's values through and answers `Done` and `Err` with nil and `Deadline` with
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.

[^2]: The [quickstart reference](https://www.speakeasy.com/docs/speakeasy-reference/cli/quickstart)
lists eleven targets, from `cli` to `typescript`, with `mcp-typescript` between `java` and `php`.
`postman` and `terraform` sit in the same list, so the flag names outputs rather than languages.