Skip to content
Back to search

go-mcp

deprecated: use the official MCP sdk! (https://github.com/modelcontextprotocol/go-sdk) / ⚡ A type-safe, intuitive Go SDK for building MCP servers with ease and confidence

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/ktr0731--go-mcp/badge.svg)](/listings/ktr0731--go-mcp)

HTML

<a href="/listings/ktr0731--go-mcp"><img src="/api/listings/ktr0731--go-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Creating an MCP server with go‑mcp is straightforward!

Directory structure

Below is an example directory structure for a temperature‑conversion MCP server:

.
├── cmd
│   ├── mcpgen
│   │   └── main.go
│   └── temperature
│       └── main.go
├── mcp.gen.go
└── temperature.go

1. Define the MCP server

First, create `cmd/mcpgen/main.go` for code generation. Running this file will automatically generate the necessary code.

package main

import (
    "log"
    "os"
    "path/filepath"

    "github.com/ktr0731/go-mcp/codegen"
)

func main() {
    // Create output directory
    outDir := "."
    if err := os.MkdirAll(outDir, 0o755); err != nil {
        log.Fatalf("failed to create output directory: %v", err)
    }

    // Create output file
    f, err := os.Create(filepath.Join(outDir, "mcp.gen.go"))
    if err != nil {
        log.Fatalf("failed to create file: %v", err)
    }
    defer f.Close()

    // Server definition
    def := &codegen.ServerDefinition{
        Capabilities: codegen.ServerCapabilities{
            Tools:   &codegen.ToolCapability{},
            Logging: &codegen.LoggingCapability{},
        },
        Implementation: codegen.Implementation{
            Name:    "Temperature MCP Server",
            Version: "1.0.0",
        },
        // Tool definitions (declared with Go structs)
        Tools: []codegen.Tool{
            {
                Name:        "convert_temperature",
                Description: "Convert temperature between Celsius and Fahrenheit",
                InputSchema: struct {
                    Temperature float64 `json:"temperature" jsonschema:"description=Temperature value to convert"`
                    FromUnit    string  `json:"from_unit"  jsonschema:"description=Source temperature unit,enum=celsius,enum=fahrenheit"`
                    ToUnit      string  `json:"to_unit"    jsonschema:"description=Target temperature unit,enum=celsius,enum=fahrenheit"`
                }{},
            },
        },
    }

    // Generate code
    if err := codegen.Generate(f, def, "temperature"); err != nil {
        log.Fatalf("failed to generate code: %v", err)
    }
}

Generate the code:

go run ./cmd/mcpgen

2. Implement the MCP server

Next, implement the server logic in `cmd/temperature/main.go`:

package main

import (
    "context"
    "fmt"
    "log"
    "math"

    mcp "github.com/ktr0731/go-mcp"
    "golang.org/x/exp/jsonrpc2"
)

type toolHandler struct{}

func (h *toolHandler) HandleToolConvertTemperature(ctx context.Context, req *ToolConvertTemperatureRequest) (*mcp.CallToolResult, error) {
    temperature := req.Temperature
    fromUnit := req.FromUnit
    toUnit := req.ToUnit

    var result float64
    switch {
    case fromUnit == ConvertTemperatureFromUnitTypeCelsius && toUnit == ConvertTemperatureToUnitTypeFahrenheit:
        // °C → °F: (C × 9/5) + 32
        result = (temperature*9/5 + 32)
    case fromUnit == ConvertTemperatureFromUnitTypeFahrenheit && toUnit == ConvertTemperatureToUnitTypeCelsius:
        // °F → °C: (F − 32) × 5/9
        result = (temperature - 32) * 5 / 9
    case fromUnit == toUnit:
        result = temperature
    default:
        return nil, fmt.Errorf("unsupported conversion: %s to %s", fromUnit, toUnit)
    }

    // Round to two decimal places
    result = math.Round(result*100) / 100

    resultText := fmt.Sprintf("%.2f %s = %.2f %s", temperature, fromUnit, result, toUnit)

    return &mcp.CallToolResult{
        Content: []mcp.CallToolContent{
            mcp.TextContent{Text: resultText},
        },
    }, nil
}

func main() {
    handler := NewHandler(&toolHandler{})

    ctx, listener, binder := mcp.NewStdioTransport(context.Background(), handler, nil)
    srv, err := jsonrpc2.Serve(ctx, listener, binder)
    if err != nil {
        log.Fatalf("failed to serve: %v", err)
    }

    srv.Wait()
}

Run the server:

go run ./cmd/temperature

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 230 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # ⚡ go-mcp
  2. <div align="center">
  3. <h3>A type‑safe, intuitive Go SDK for MCP server development</h3>
  4. </div>
  5. <p align="center">
  6. <a href="#-what-is-go-mcp">🤔 What is go‑mcp?</a> •
  7. <a href="#-features">✨ Features</a> •
  8. <a href="#-quick-start">🏁 Quick Start</a> •
  9. <a href="#-examples">🔍 Examples</a> •
  10. <a href="#-supported-features">✅ Supported Features</a> •
  11. <a href="#-contributing">🤝 Contributing</a>
  12. </p>
  13. ---
  14. ## 🤔 What is go‑mcp?
  15. **go‑mcp** is a Go SDK for building MCP (Model Context Protocol) servers with ease and confidence. It provides a type‑safe, intuitive interface that makes server development a breeze.
  16. ---
  17. ## ✨ Features
  18. - 🔒 **Type‑Safe** – Code generation ensures your tools and prompt parameters are statically typed, so errors are caught at compile time instead of at runtime.
  19. - 🧩 **Simple & Intuitive API** – A natural, idiomatic Go interface that lets you build servers quickly without a steep learning curve.
  20. - 🔌 **Developer‑Friendly** – Designed with API ergonomics in mind, making it approachable.
  21. ---
  22. ## 🏁 Quick Start
  23. Creating an MCP server with go‑mcp is straightforward!
  24. ### Directory structure
  25. Below is an example directory structure for a temperature‑conversion MCP server:
  26. ```
  27. .
  28. ├── cmd
  29. │   ├── mcpgen
  30. │   │   └── main.go
  31. │   └── temperature
  32. │   └── main.go
  33. ├── mcp.gen.go
  34. └── temperature.go
  35. ```
  36. ### 1. Define the MCP server
  37. First, create `cmd/mcpgen/main.go` for code generation. Running this file will automatically generate the necessary code.
  38. ```go
  39. package main
  40. import (
  41. "log"
  42. "os"
  43. "path/filepath"
  44. "github.com/ktr0731/go-mcp/codegen"
  45. )
  46. func main() {
  47. // Create output directory
  48. outDir := "."
  49. if err := os.MkdirAll(outDir, 0o755); err != nil {
  50. log.Fatalf("failed to create output directory: %v", err)
  51. }
  52. // Create output file
  53. f, err := os.Create(filepath.Join(outDir, "mcp.gen.go"))
  54. if err != nil {
  55. log.Fatalf("failed to create file: %v", err)
  56. }
  57. defer f.Close()
  58. // Server definition
  59. def := &codegen.ServerDefinition{
  60. Capabilities: codegen.ServerCapabilities{
  61. Tools: &codegen.ToolCapability{},
  62. Logging: &codegen.LoggingCapability{},
  63. },
  64. Implementation: codegen.Implementation{
  65. Name: "Temperature MCP Server",
  66. Version: "1.0.0",
  67. },
  68. // Tool definitions (declared with Go structs)
  69. Tools: []codegen.Tool{
  70. {
  71. Name: "convert_temperature",
  72. Description: "Convert temperature between Celsius and Fahrenheit",
  73. InputSchema: struct {
  74. Temperature float64 `json:"temperature" jsonschema:"description=Temperature value to convert"`
  75. FromUnit string `json:"from_unit" jsonschema:"description=Source temperature unit,enum=celsius,enum=fahrenheit"`
  76. ToUnit string `json:"to_unit" jsonschema:"description=Target temperature unit,enum=celsius,enum=fahrenheit"`
  77. }{},
  78. },
  79. },
  80. }
  81. // Generate code
  82. if err := codegen.Generate(f, def, "temperature"); err != nil {
  83. log.Fatalf("failed to generate code: %v", err)
  84. }
  85. }
  86. ```
  87. Generate the code:
  88. ```bash
  89. go run ./cmd/mcpgen
  90. ```
  91. ### 2. Implement the MCP server
  92. Next, implement the server logic in `cmd/temperature/main.go`:
  93. ```go
  94. package main
  95. import (
  96. "context"
  97. "fmt"
  98. "log"
  99. "math"
  100. mcp "github.com/ktr0731/go-mcp"
  101. "golang.org/x/exp/jsonrpc2"
  102. )
  103. type toolHandler struct{}
  104. func (h *toolHandler) HandleToolConvertTemperature(ctx context.Context, req *ToolConvertTemperatureRequest) (*mcp.CallToolResult, error) {
  105. temperature := req.Temperature
  106. fromUnit := req.FromUnit
  107. toUnit := req.ToUnit
  108. var result float64
  109. switch {
  110. case fromUnit == ConvertTemperatureFromUnitTypeCelsius && toUnit == ConvertTemperatureToUnitTypeFahrenheit:
  111. // °C → °F: (C × 9/5) + 32
  112. result = (temperature*9/5 + 32)
  113. case fromUnit == ConvertTemperatureFromUnitTypeFahrenheit && toUnit == ConvertTemperatureToUnitTypeCelsius:
  114. // °F → °C: (F − 32) × 5/9
  115. result = (temperature - 32) * 5 / 9
  116. case fromUnit == toUnit:
  117. result = temperature
  118. default:
  119. return nil, fmt.Errorf("unsupported conversion: %s to %s", fromUnit, toUnit)
  120. }
  121. // Round to two decimal places
  122. result = math.Round(result*100) / 100
  123. resultText := fmt.Sprintf("%.2f %s = %.2f %s", temperature, fromUnit, result, toUnit)
  124. return &mcp.CallToolResult{
  125. Content: []mcp.CallToolContent{
  126. mcp.TextContent{Text: resultText},
  127. },
  128. }, nil
  129. }
  130. func main() {
  131. handler := NewHandler(&toolHandler{})
  132. ctx, listener, binder := mcp.NewStdioTransport(context.Background(), handler, nil)
  133. srv, err := jsonrpc2.Serve(ctx, listener, binder)
  134. if err != nil {
  135. log.Fatalf("failed to serve: %v", err)
  136. }
  137. srv.Wait()
  138. }
  139. ```
  140. Run the server:
  141. ```bash
  142. go run ./cmd/temperature
  143. ```
  144. ---
  145. ## 🔍 Examples
  146. See complete examples in the [examples directory](https://github.com/ktr0731/go-mcp/tree/main/examples/weather) and the [API documentation](https://pkg.go.dev/github.com/ktr0731/go-mcp).
  147. ---
  148. ## ✅ Supported Features
  149. - Ping
  150. - Tools
  151. - Prompts
  152. - Prompts, Tools, Resources, Resource Templates
  153. - Resource subscription
  154. - Resource update notification
  155. - Logging
  156. - Completion
  157. - Cancellation
  158. 🚧 **Under Development**
  159. - Batching (JSON‑RPC 2.0)
  160. - Streamable HTTP transport
  161. - Progress notification
  162. 🚫 **Not Planned**
  163. - Dynamic prompt and tool changes
  164. Go is not well‑suited for dynamic tool additions. Adding tools dynamically requires constructing tool definitions, JSON Schema, and handlers at runtime. While generated code remains type‑safe, dynamically added components do not, forcing heavy use of `any` and type assertions and harming interface consistency. We delegate these use cases to SDKs in languages better suited for dynamic changes, such as TypeScript.
  165. Most currently implemented MCP servers use static definitions only, and dynamic changes do not seem to be a primary use case yet.
  166. ---
  167. ## 🤝 Contributing
  168. Contributions are welcome! Feel free to submit a pull request.
  169. ---
  170. ## 📄 License
  171. This project is licensed under the MIT License – see the [LICENSE](LICENSE) file for details.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.