Skip to main content
Beato
  1. All Articles/

Build and Distribute an MCP Server in Go

·8 mins

This article is compiled from a complete discussion about Model Context Protocol (MCP), covering the core concepts of MCP, Go implementation, external release, natural language registration, remote serviceization, as well as the relationship and selection of MCP and Agent Skill.

1. What is MCP: “USB-C port” for AI applications #

Model Context Protocol (MCP) is an open protocol launched by Anthropic in November 2024 to standardize the integration method between large language models and external data sources and tools. It is often compared to the “USB-C port for AI applications”: just like USB-C unifies the connection methods of devices and accessories, MCP unifies the docking standards for AI models and external services.

MCP is based on JSON-RPC 2.0 and defines a three-layer architecture:

  • Hosts: LLM application that initiates the connection, such as AI IDE, chat interface.
  • Clients: Connector inside the Host, each Client maintains an independent session.
  • Servers: Services that provide context and capabilities. They can be local processes or remote services.

MCP Server exposes three types of core capabilities to clients:

CapabilitiesDescription
ResourcesContext data that can be read by AI, such as file content and database records
PromptsPredefined templated messages and workflows
ToolsFunctions that can be called by the AI model, such as querying the database, calling API, reading and writing files

In terms of transport layer, MCP supports:

  • stdio: Standard input and output, suitable for local tools, zero network configuration.
  • Streamable HTTP: Recommended remote transmission method, single HTTP endpoint, accepts POST, returns JSON or SSE stream.
  • HTTP + SSE: Deprecated dual endpoint mode.

MCP is inspired by the Language Server Protocol (LSP): LSP unifies the editor’s support for programming languages, and MCP unifies the integration of external tools and data by AI applications in a similar way.

2. Use Go to implement the simplest MCP Server #

The simplest way is to use MCP official Go SDK: github.com/modelcontextprotocol/go-sdk.

2.1 Initialization project #

mkdir mcp-demo && cd mcp-demo
go mod init mcp-demo
go get github.com/modelcontextprotocol/go-sdk@latest

2.2 Writing server code #

The following MCP server provides a tool that returns the current time:

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
    // 1. 创建 MCP 服务器实例
    server := mcp.NewServer("mcp-demo", "1.0.0")

    // 2. 注册 "getCurrentTime" 工具
    server.AddTool(mcp.Tool{
        Name:        "getCurrentTime",
        Description: "获取当前时间(支持时区参数)",
        InputSchema: map[string]interface{}{
            "type": "object",
            "properties": map[string]interface{}{
                "timezone": map[string]interface{}{
                    "type":        "string",
                    "description": "时区名称,如 'Asia/Shanghai',默认为本地时区",
                    "default":     "Local",
                },
            },
            "required": []string{},
        },
        Handler: func(ctx context.Context, args map[string]interface{}) (interface{}, error) {
            tzName, _ := args["timezone"].(string)
            loc := time.Local

            if tzName != "" && tzName != "Local" {
                var err error
                loc, err = time.LoadLocation(tzName)
                if err != nil {
                    return nil, fmt.Errorf("无效时区: %v", err)
                }
            }

            now := time.Now().In(loc).Format("2006-01-02 15:04:05 MST")
            return map[string]string{"time": now}, nil
        },
    })

    // 3. 通过 stdio 启动服务器
    if err := server.ServeStdio(); err != nil {
        fmt.Println("服务器错误:", err)
    }
}

is very straightforward:

  • mcp.NewServer Create a server instance.
  • AddTool Registration tool, including name, description, input JSON Schema and processing functions.
  • ServeStdio communicates via standard input and output.

2.3 Running and testing #

go run main.go

After the server starts, it waits for JSON-RPC requests through stdin. You can send it manually:

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"getCurrentTime","arguments":{"timezone":"Asia/Shanghai"}}}

When configuring MCP Server in VS Code, you can add in .vscode/mcp.json:

{
  "servers": {
    "mcp-demo": {
      "type": "stdio",
      "command": "go",
      "args": ["run", "main.go"]
    }
  }
}

3. External release: Let users “download and use” #

If you want users to download the binary files of the corresponding platforms and use them directly, the core idea is: cross-compile multi-platform binaries, host them through GitHub Releases, and then use a package manager or Bundle format to lower the installation threshold.

3.1 Cross-compile multi-platform binaries #

Cross-compilation of

Go only requires setting GOOS and GOARCH. It is recommended to close CGO and generate pure static files:

# Linux amd64
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w" -o mcp-demo-linux-amd64

# macOS Apple Silicon
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w" -o mcp-demo-darwin-arm64

# Windows amd64
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w" -o mcp-demo-windows-amd64.exe

At a minimum, consider building for these platforms:

platformGOOSGOARCH
Linux x64linuxamd64
Linux ARM64linuxarm64
macOS Inteldarwinamd64
macOS Apple Silicondarwinarm64
Windows x64windowsamd64

3.2 Automated release with GoReleaser #

Manual compilation and uploading one by one is prone to errors. It is recommended to use GoReleaser, which can complete multi-platform construction, packaging and archiving, generating checksums and uploading GitHub Releases with one command.

initialization:

goreleaser init

Configure GitHub Actions: .github/workflows/release.yml

name: Release
on:
  push:
    tags: ['v*']
jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-go@v5
        with:
          go-version: 'stable'
      - uses: goreleaser/goreleaser-action@v6
        with:
          args: release --clean
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Tag and push will automatically publish:

git tag v0.1.0 && git push origin v0.1.0

3.3 Lowering the installation threshold: Package manager and Bundle format #

With the GitHub Releases product, you can further access the distribution channel:

  • Homebrew Tap: self-built tap warehouse, installed by user brew install with one command.
  • Scoop / Winget (Windows), APT/YUM Warehouse(Linux): Select according to target user group.
  • npm package: Even if the tool is written in Go, you can send an npm package and download the corresponding binary by platform during installation - this is the mode adopted by many CLI tools (such as esbuild).
  • MCP Bundle (.mcpb): A packaging format introduced by Anthropic, which combines MCP Server and its dependencies into one file. Users can install it with one click in Claude Desktop. It is suitable for distribution to non-developer users.

4. Natural language registration: let AI install MCP by itself #

As the MCP ecosystem matures, the gameplay of “using natural language to describe requirements → AI automatically finds and configures MCP Server” has emerged. Typical process:

  1. user said in natural language in a client that supports MCP (such as Claude Code, Cursor): “Help me connect to an MCP tool that can check GitHub Issues.”
  2. Client/AI retrieves matching Server via MCP Registry (official registry) or community directory.
  3. AI generates configuration (stdio command or remote URL), writes mcp.json, and guides to complete OAuth authorization if necessary.
  4. After restarting the session, the new tool can be called by the model.

To make your Server “searched” by natural language, the key is:

  • Submit Server metadata (name, description, transfer method, installation method) in MCP Registry.
  • Description Write clearly what the tool does and what the parameters mean - the model relies on these descriptions to decide when to call it.
  • Keep naming semantics and avoid meaningless abbreviations.

5. Remote service: Streamable HTTP #

stdio mode requires the Server and the client to run on the same machine. When tools need to share status, access intranet data, or be used by multiple people, MCP Server needs to be deployed as a remote HTTP service.

5.1 Go implements Streamable HTTP endpoint #

official Go SDK provides Streamable HTTP transmission, just replace ServeStdio with HTTP handler:

func main() {
    server := mcp.NewServer("mcp-demo", "1.0.0")
    // ... 同前注册 Tool ...

    handler := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
        return server
    }, nil)

    http.Handle("/mcp", handler)
    log.Println("MCP server listening on :8080/mcp")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

client configuration:

{
  "servers": {
    "mcp-demo": {
      "type": "http",
      "url": "https://mcp.example.com/mcp"
    }
  }
}

5.2 Deployment Points #

  • Authentication: MCP authorization is based on OAuth 2.1; public network deployment must be authenticated at the gateway layer, and streaking is not allowed.
  • Session Management: Streamable HTTP maintains sessions through the Mcp-Session-Id header. When horizontally expanding, it is necessary to ensure that the same session is routed to the same instance or shared session state.
  • SSE streaming response: If the tool execution takes a long time, the SSE stream can be returned. Note that the reverse proxy (Nginx, etc.) must turn off buffering.
  • Deployment form: Single binary + systemd/container can be used; when deploying Kubernetes, it cooperates with HPA to expand and shrink according to the number of connections or CPU.

6. MCP and Agent Skill: Relationship and Selection #

In addition to the

MCP, Anthropic also launched the Agent Skills(SKILL.md format). The two are often compared, but their actual positioning is different:

DimensionsMCPAgent Skill
EssenceTool/Data Access Protocol (JSON-RPC)command + script knowledge package (Markdown)
running stateindependent process or remote serviceFiles loaded on demand in the client
is suitable for providingDynamic capabilities: query database, adjust API, real-time dataStatic knowledge: workflow, domain specifications, operation manual
integration costneeds to implement protocol and deployment servicesJust copy a directory
Ecologycross-vendor open standard, wide client supportis currently mainly used in Claude series clients

Collaborative mode: The two are not competitive. A typical combination is - Skill teaches the Agent “how to do it” (process, specifications), and MCP provides “what to do it with” (tools, data). For example, an operation and maintenance troubleshooting skill defines troubleshooting steps, in which the “check log” step calls MCP’s log query tool.

Selection suggestions:

  • To expose dynamic capabilities/private data to any client that supports MCP → Write MCP Server.
  • needs to accumulate team process and domain knowledge, and is mainly used in the Claude ecosystem → write Skill.
  • Complex Agent product → Use both, Skill orchestration process, MCP supply capability.

7. Summary #

MCP changes the integration of “AI application ↔ external tools” from N×M private docking to N+M standard docking. The realistic path for individuals and teams is:

  1. uses dozens of lines of official Go SDK code to write a minimal Server, and stdio runs through local tools.
  2. GoReleaser + GitHub Releases complete multi-platform distribution and access the package manager or.mcpb on demand.
  3. Submits MCP Registry metadata to make the Server searchable and installable by natural language.
  4. When there is a need for sharing/intranet, switch to Streamable HTTP remote and do a good job in OAuth and session management.
  5. is combined with Agent Skill on demand: Skill manages knowledge and MCP manages abilities.

From local stdio to remote services, from manual installation to natural language registration, the MCP ecosystem is rapidly completing the complete “release-discovery-use” link. The integration costs invested now will continue to be diluted in the future as client support becomes more popular.


Written by Jermine. View original text.