gomcp

package module
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 6, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

README ΒΆ

GoMCP

Go Version License Release gomcp MCP server

The fast, idiomatic way to build MCP servers in Go.

δΈ­ζ–‡ζ–‡ζ‘£



🎯 What is GoMCP?

GoMCP is a framework for building Model Context Protocol (MCP) servers β€” not just an SDK. Think of it as "Gin for MCP".

MCP is the open protocol that lets AI applications (Claude Desktop, Cursor, Kiro, VS Code Copilot) call external tools, read data sources, and use prompt templates. GoMCP makes building those servers trivial.

Why GoMCP?
mcp-go (mark3labs) Official Go SDK GoMCP
Level SDK SDK Framework
Schema generation Manual jsonschema tag mcp tag + auto validation
Middleware Basic hooks None Full chain (Logger, Auth, RateLimit, OTel…)
Tool groups No No Yes (user.get, admin.delete)
Import Gin routes No No βœ… One line
Import OpenAPI/Swagger No No βœ… One line
Import gRPC services No No βœ…
Built-in auth No No Bearer / API Key / Basic + RBAC (Bearer = your token/JWT validator)
Inspector UI No No βœ…
Test utilities Basic No mcptest package

πŸ› οΈ Tech Stack

Environment Requirements
Requirement Version
Go β‰₯ 1.25
MCP Protocol 2024-11-05 (backward compatible with 2025-11-25)
Core Dependencies
Technology Description
Go standard library Framework routing, JSON-RPC, transports β€” no forced DB/ORM deps
Gin Adapter only β€” import existing Gin routes
gRPC Adapter only β€” import gRPC services
OpenTelemetry Optional β€” distributed tracing
YAML v3 Provider only β€” hot-reload tool definitions

🌟 Core Features

πŸ”§ Tool Development
  • Struct-tag auto schema β€” define parameters with Go structs and mcp tags, JSON Schema generated automatically
  • Typed handlers β€” func(*Context, Input) (Output, error) β€” no manual parameter parsing
  • Parameter validation β€” required, min/max, enum, pattern β€” checked before your handler runs
  • Component versioning β€” register multiple versions, clients call name@version
  • Async tasks β€” long-running tools return task ID, with polling and cancellation
πŸ”Œ Adapters (Core Differentiator)
  • Gin adapter β€” import existing Gin routes as MCP tools with one line
  • OpenAPI adapter β€” generate tools from Swagger/OpenAPI 3.x docs
  • gRPC adapter β€” import gRPC service methods as MCP tools
πŸ” Security
  • BearerAuth β€” Bearer token check via your validator (JWT parsing is up to you; this library does not decode JWTs)
  • APIKeyAuth β€” API key validation via header
  • BasicAuth β€” HTTP Basic authentication
  • RequireRole / RequirePermission β€” RBAC authorization on tool groups
🧩 Framework Features
  • Middleware chain β€” Logger, Recovery, RequestID, Timeout, RateLimit, OpenTelemetry
  • Tool groups β€” organize tools with prefixes and group-level middleware
  • Resource & Prompt β€” full MCP support including URI templates and parameterized prompts
  • Auto-completions β€” suggest values for prompt/resource arguments
πŸš€ Production Ready
  • Multiple transports β€” stdio (Claude Desktop, Cursor, Kiro) and Streamable HTTP with SSE
  • MCP Inspector β€” built-in web debug UI for browsing and testing tools
  • Hot-reload β€” load tool definitions from YAML files with file watching
  • mcptest package β€” in-memory client for unit testing with snapshot support
  • Lifecycle β€” Close(), session idle eviction, async concurrency β€” see Server lifecycle, sessions & async tasks.

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        User Code                             β”‚
β”‚   s.Tool() / s.ToolFunc() / s.Resource() / s.Prompt()        β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                     Framework Core                           β”‚
β”‚   Router β†’ Middleware Chain β†’ Validation β†’ Handler β†’ Result   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚   Schema   β”‚  Validator  β”‚   Adapters    β”‚  Observability    β”‚
β”‚  Generator β”‚   Engine    β”‚ Gin/OpenAPI/  β”‚  OTel / Logger    β”‚
β”‚ (mcp tags) β”‚ (auto)      β”‚ gRPC          β”‚  / Inspector      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                     Protocol Layer                           β”‚
β”‚          JSON-RPC 2.0 / MCP / Capability Negotiation         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                     Transport Layer                          β”‚
β”‚              stdio  /  Streamable HTTP + SSE                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Project Structure
gomcp/
β”œβ”€β”€ server.go              # Server core, tool/resource/prompt registration
β”œβ”€β”€ context.go             # Request context with typed accessors
β”œβ”€β”€ group.go               # Tool groups with prefix naming
β”œβ”€β”€ middleware.go           # Middleware chain helpers (SkipAuthForMCPMethods, handshake skips)
β”œβ”€β”€ middleware_builtin.go   # Logger, Recovery, RequestID, Timeout, RateLimit
β”œβ”€β”€ middleware_auth.go      # Bearer/API key/Basic auth, RBAC, SSE auth helpers
β”œβ”€β”€ middleware_otel.go      # OpenTelemetry tracing
β”œβ”€β”€ schema/                # struct tag β†’ JSON Schema generator + validator
β”œβ”€β”€ transport/             # stdio + Streamable HTTP + optional CORS helper
β”œβ”€β”€ adapter/               # Gin, OpenAPI, gRPC adapters
β”œβ”€β”€ mcptest/               # Testing utilities
β”œβ”€β”€ task.go                # Async task support
β”œβ”€β”€ completion.go          # Auto-completions
β”œβ”€β”€ inspector.go           # Web debug UI
β”œβ”€β”€ provider.go            # Hot-reload from YAML
└── examples/              # Working examples

πŸ“¦ Installation

go get github.com/zhangpanda/gomcp

⚑ Quick Start

5 lines to a working MCP server
package main

import (
    "fmt"
    "github.com/zhangpanda/gomcp"
)

type SearchInput struct {
    Query string `json:"query" mcp:"required,desc=Search keyword"`
    Limit int    `json:"limit" mcp:"default=10,min=1,max=100"`
}

type SearchResult struct {
    Items []string `json:"items"`
    Total int      `json:"total"`
}

func main() {
    s := gomcp.New("my-server", "1.0.0")

    s.ToolFunc("search", "Search documents by keyword", func(ctx *gomcp.Context, in SearchInput) (SearchResult, error) {
        items := []string{fmt.Sprintf("Result for %q", in.Query)}
        return SearchResult{Items: items, Total: len(items)}, nil
    })

    s.Stdio()
}

The SearchInput struct automatically generates this JSON Schema:

{
  "type": "object",
  "properties": {
    "query": { "type": "string", "description": "Search keyword" },
    "limit": { "type": "integer", "default": 10, "minimum": 1, "maximum": 100 }
  },
  "required": ["query"]
}

Invalid parameters are rejected before your handler runs:

validation failed: query: required; limit: must be <= 100

πŸ“– Usage Guide

Struct Tag Reference
Tag Type Description Example
required flag Field must be provided mcp:"required"
desc string Human-readable description mcp:"desc=Search keyword"
default any Default value mcp:"default=10"
min number Minimum value (inclusive) mcp:"min=0"
max number Maximum value (inclusive) mcp:"max=100"
enum string Pipe-separated allowed values mcp:"enum=asc|desc"
pattern string Regex validation mcp:"pattern=^[a-z]+$"

Combine: mcp:"required,desc=User email,pattern=^[^@]+@[^@]+$"

Supported types: string, int, float64, bool, []T, nested structs.

Tools

Simple handler:

s.Tool("hello", "Say hello", func(ctx *gomcp.Context) (*gomcp.CallToolResult, error) {
    return ctx.Text("Hello, " + ctx.String("name")), nil
})

Typed handler (recommended):

type Input struct {
    Name  string `json:"name"  mcp:"required,desc=User name"`
    Email string `json:"email" mcp:"required,pattern=^[^@]+@[^@]+$"`
}

s.ToolFunc("create_user", "Create user", func(ctx *gomcp.Context, in Input) (User, error) {
    return db.CreateUser(in.Name, in.Email)
})
Resources
// Static
s.Resource("config://app", "App config", func(ctx *gomcp.Context) (any, error) {
    return map[string]any{"version": "1.0"}, nil
})

// Dynamic URI template
s.ResourceTemplate("db://{table}/{id}", "DB record", func(ctx *gomcp.Context) (any, error) {
    return db.Find(ctx.String("table"), ctx.String("id")), nil
})
Prompts
s.Prompt("code_review", "Code review",
    []gomcp.PromptArgument{gomcp.PromptArg("language", "Language", true)},
    func(ctx *gomcp.Context) ([]gomcp.PromptMessage, error) {
        return []gomcp.PromptMessage{
            gomcp.UserMsg(fmt.Sprintf("Review this %s code for bugs.", ctx.String("language"))),
        }, nil
    },
)
Middleware
s.Use(gomcp.Logger())                              // Log MCP method + duration
s.Use(gomcp.Recovery())                            // Recover from panics
s.Use(gomcp.RequestID())                           // Unique request ID
s.Use(gomcp.Timeout(10 * time.Second))             // Deadline enforcement
s.Use(gomcp.RateLimit(100))                        // 100 calls/minute
s.Use(gomcp.OpenTelemetry())                       // Distributed tracing
// Pick one: BearerAuth (token required on initialize too) or BearerAuthSkipHandshake (initialize/ping anonymous).
s.Use(gomcp.BearerAuthSkipHandshake(tokenValidator))
s.Use(gomcp.APIKeyAuthSkipHandshake("X-API-Key", keyValidator))

Custom middleware:

func AuditLog() gomcp.Middleware {
    return func(ctx *gomcp.Context, next func() error) error {
        start := time.Now()
        err := next()
        log.Printf("tool=%s duration=%s err=%v", ctx.String("_tool_name"), time.Since(start), err)
        return err
    }
}
Tool Groups
user := s.Group("user", authMiddleware)
user.Tool("get", "Get user", getUser)              // β†’ user.get
user.Tool("update", "Update user", updateUser)      // β†’ user.update

admin := user.Group("admin", gomcp.RequireRole("admin"))
admin.Tool("delete", "Delete user", deleteUser)     // β†’ user.admin.delete
Adapters

Gin β€” one line to import your existing API:

adapter.ImportGin(s, ginRouter, adapter.ImportOptions{
    IncludePaths: []string{"/api/v1/"},
})
// GET /api/v1/users/:id β†’ Tool get_api_v1_users_by_id (id = required param)

OpenAPI β€” generate from Swagger docs:

adapter.ImportOpenAPI(s, "./swagger.yaml", adapter.OpenAPIOptions{
    TagFilter: []string{"pets"},
    ServerURL: "https://api.example.com",
})

gRPC:

adapter.ImportGRPC(s, grpcConn, adapter.GRPCOptions{
    Services: []string{"user.UserService"},
})
Component Versioning
s.ToolFunc("search", "v1", searchV1, gomcp.Version("1.0"))
s.ToolFunc("search", "v2 with embeddings", searchV2, gomcp.Version("2.0"))
// "search" β†’ latest, "search@1.0" β†’ exact version
Async Tasks
s.AsyncTool("report", "Generate report", func(ctx *gomcp.Context) (*gomcp.CallToolResult, error) {
    // long-running work
    return ctx.Text("done"), nil
})
// Client gets taskId immediately, polls tasks/get, can tasks/cancel
Hot-Reload
s.LoadDir("./tools/", gomcp.DirOptions{Watch: true})

Server lifecycle, sessions & async tasks
  • Server.Close() β€” When your process or test tears down a server that uses LoadDir(..., Watch: true) or long-lived HTTP, call Close() once. It stops the YAML watch loop, the session eviction background goroutine, and the async task manager eviction loop. The call is idempotent.
  • Sessions β€” Session state is in-memory only. Identifiers come from the client Mcp-Session-Id header (see Streamable HTTP). Sessions idle for 30 minutes (no access via that ID) are removed; the next request with the same ID gets a new empty session. Do not rely on Session storage across long idle periods unless the client keeps traffic or you refresh state yourself.
  • SetMaxConcurrentTasks(n) β€” Set this before the first AsyncTool / AsyncToolFunc. After the internal task manager is created, later calls are a no-op (avoids races with in-flight work).
  • Shutdown vs async work β€” Close() does not wait for async tool handlers that are still running; add your own timeout / wait if you need hard guarantees before exit.
MCP Inspector
s.Dev(":9090") // http://localhost:9090 β€” browse and test all tools
Testing
func TestSearch(t *testing.T) {
    c := mcptest.NewClient(t, setupServer())
    c.Initialize()

    result := c.CallTool("search", map[string]any{"query": "golang"})
    result.AssertNoError(t)
    result.AssertContains(t, "golang")

    mcptest.MatchSnapshot(t, "search_result", result)
}
Transports
s.Stdio()          // Claude Desktop, Cursor, Kiro
s.HTTP(":8080")    // Remote deployment with SSE
s.Handler()        // Embed in existing HTTP server
// Browser clients: wrap the handler with transport.WrapCORS(h, []string{"https://your.app"}) when needed
Use with AI Clients
{
  "mcpServers": {
    "my-server": {
      "command": "/path/to/your/binary"
    }
  }
}

Works with Claude Desktop, Cursor, Kiro, Windsurf, VS Code Copilot, and any MCP-compatible client.


πŸ“‹ Roadmap

  • Core: Tool, Resource, Prompt with full MCP protocol support
  • Struct-tag auto schema generation + parameter validation
  • Middleware chain (Logger, Recovery, RateLimit, Timeout, RequestID)
  • Auth middleware (Bearer / API Key / Basic) + RBAC authorization
  • Tool groups with prefix naming and nested groups
  • stdio + Streamable HTTP transports with SSE notifications
  • Gin adapter β€” import existing Gin routes as MCP tools
  • OpenAPI adapter β€” generate tools from Swagger/OpenAPI docs
  • gRPC adapter β€” import gRPC services as MCP tools
  • OpenTelemetry integration
  • mcptest package with snapshot testing
  • Component versioning + deprecation
  • Async tasks with polling and cancellation
  • MCP Inspector web debug UI
  • Hot-reload provider from YAML
  • Auto-completions for prompt/resource arguments

🀝 Feedback & Support

πŸ’‘ Recommended reading: How To Ask Questions The Smart Way


πŸ”’ Security

HTTP transport and authentication
  • Use middleware runs for every JSON-RPC method (except the notification notifications/initialized, which has no response): initialize, tools/list, tools/call, resources/read, prompts/get, tasks/*, completion/complete, etc. Use BearerAuth / APIKeyAuth / BasicAuth when exposing POST /mcp. For APIKeyAuth, api_key (and other merged params) come from tools/call arguments, prompts/get arguments, or resources/read params JSON when no header is sentβ€”prefer headers for production.
  • BearerAuthSkipHandshake / APIKeyAuthSkipHandshake / BasicAuthSkipHandshake (or SkipAuthForMCPMethods) let initialize and ping run without credentials while keeping other methods protectedβ€”typical for MCP HTTP clients that negotiate before sending tokens.
  • Request context propagates into tool, resource, and prompt handlers (deadlines, Authorization, and injected headers from Streamable HTTP).
  • SSE (GET /mcp) does not execute MCP middleware. Use WithSSEAuth with SSEBearerAuth, SSEAPIKeyAuth, SSEBasicAuth, or your own gate. Without WithSSEAuth, any client that can open GET receives broadcast notifications.
  • Browser fetch: wrap your /mcp handler with transport.WrapCORS(h, allowedOrigins) from github.com/zhangpanda/gomcp/transport; never use * with credentialsβ€”only list trusted origins.

When deploying Streamable HTTP in production, combine TLS, authentication middleware on POST, and WithSSEAuth when notifications must not be public.

To report security vulnerabilities, see SECURITY.md.


Copyright Β© 2026 GoMCP Contributors

Licensed under the Apache License 2.0.

Important Notes
  1. This project is open source and free for both personal and commercial use under the Apache 2.0 license.
  2. You must retain the copyright notice, license text, and any attribution notices in all copies or substantial portions of the software.
  3. The Apache 2.0 license includes an express grant of patent rights from contributors to users.
  4. Contributions to this project are licensed under the same Apache 2.0 license.
  5. Unauthorized removal of copyright notices may result in legal action.
Patent Notice

Certain features of this framework (struct-tag schema generation, HTTP-to-MCP automatic adapter, OpenAPI-to-MCP automatic adapter) are the subject of pending patent applications. The Apache 2.0 license grants you a perpetual, worldwide, royalty-free patent license to use these features as part of this software.


⭐ Star History

If you find GoMCP useful, please consider giving it a star! It helps others discover the project.

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	TaskRunning   = "running"
	TaskCompleted = "completed"
	TaskFailed    = "failed"
	TaskCancelled = "cancelled"
)

Task states

Variables ΒΆ

This section is empty.

Functions ΒΆ

func HandshakeAuthSkipMethods ΒΆ added in v1.4.0

func HandshakeAuthSkipMethods() []string

HandshakeAuthSkipMethods returns MCP JSON-RPC methods that commonly omit credentials on Streamable HTTP before authenticated calls. Pass the result to SkipAuthForMCPMethods or use helpers such as BearerAuthSkipHandshake.

func PrometheusMetrics ΒΆ

func PrometheusMetrics() (Middleware, *Metrics)

PrometheusMetrics returns a middleware that records tool call metrics. Access metrics via s.MetricsHandler() for the /metrics endpoint.

func SSEAPIKeyAuth ΒΆ added in v1.4.0

func SSEAPIKeyAuth(headerName string, validate KeyValidator) func(*http.Request) error

SSEAPIKeyAuth returns an HTTP gate like APIKeyAuth but reads only the named header (no tool-argument fallback).

func SSEBasicAuth ΒΆ added in v1.4.0

func SSEBasicAuth(validate func(username, password string) (map[string]any, error)) func(*http.Request) error

SSEBasicAuth returns an HTTP gate enforcing the same Basic rules as BasicAuth.

func SSEBearerAuth ΒΆ added in v1.4.0

func SSEBearerAuth(validate TokenValidator) func(*http.Request) error

SSEBearerAuth returns an HTTP gate suitable for WithSSEAuth, enforcing the same Bearer rules as BearerAuth.

func WithAuthHeader ΒΆ

func WithAuthHeader(ctx context.Context, value string) context.Context

WithAuthHeader injects an Authorization header value into a context. Used by transport layers to pass HTTP auth info to middleware.

func WithHeaders ΒΆ

func WithHeaders(ctx context.Context, headers map[string]string) context.Context

WithHeaders injects HTTP headers into a context.

func WithMIMEType ΒΆ

func WithMIMEType(mime string) func(*ResourceInfo)

WithMIMEType sets the MIME type for a resource.

func WithResourceDescription ΒΆ

func WithResourceDescription(desc string) func(*ResourceInfo)

WithResourceDescription sets the description for a resource.

func WithTemplateDescription ΒΆ

func WithTemplateDescription(desc string) func(*ResourceTemplateInfo)

WithTemplateDescription sets the description for a resource template.

func WithTemplateMIMEType ΒΆ

func WithTemplateMIMEType(mime string) func(*ResourceTemplateInfo)

WithTemplateMIMEType sets the MIME type for a resource template.

Types ΒΆ

type CallToolParams ΒΆ

type CallToolParams struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
}

CallToolParams is the request parameters for tools/call.

type CallToolResult ΒΆ

type CallToolResult struct {
	Content []ContentBlock `json:"content"`
	IsError bool           `json:"isError,omitempty"`
}

CallToolResult is the response from a tool invocation.

func ErrorResult ΒΆ

func ErrorResult(msg string) *CallToolResult

ErrorResult creates an error result with isError set to true.

func TextResult ΒΆ

func TextResult(s string) *CallToolResult

TextResult creates a successful text result.

type CompletionHandler ΒΆ

type CompletionHandler func(partial string) []string

CompletionHandler returns completion suggestions for a partial input.

type ContentBlock ΒΆ

type ContentBlock struct {
	Type     string `json:"type"`
	Text     string `json:"text"`
	Data     string `json:"data,omitempty"`
	MIMEType string `json:"mimeType,omitempty"`
}

ContentBlock represents a single content item in a tool result.

type Context ΒΆ

type Context struct {
	// contains filtered or unexported fields
}

Context carries request-scoped data through the handler chain.

func (*Context) Args ΒΆ

func (c *Context) Args() map[string]any

Args returns the raw arguments map.

func (*Context) Bind ΒΆ

func (c *Context) Bind(v any) error

Bind unmarshals the raw arguments into the given struct.

func (*Context) Bool ΒΆ

func (c *Context) Bool(key string) bool

Bool returns a boolean argument.

func (*Context) Context ΒΆ

func (c *Context) Context() context.Context

Context returns the underlying context.Context.

func (*Context) Error ΒΆ

func (c *Context) Error(msg string) *CallToolResult

Error builds an error result.

func (*Context) Float ΒΆ

func (c *Context) Float(key string) float64

Float returns a float64 argument.

func (*Context) Get ΒΆ

func (c *Context) Get(key string) (any, bool)

Get retrieves a value from the context store.

func (*Context) Int ΒΆ

func (c *Context) Int(key string) int

Int returns an integer argument.

func (*Context) JSON ΒΆ

func (c *Context) JSON(v any) *CallToolResult

JSON builds a JSON text result.

func (*Context) Logger ΒΆ

func (c *Context) Logger() *slog.Logger

Logger returns a contextual logger.

func (*Context) Session ΒΆ

func (c *Context) Session() *Session

Session returns the session associated with this request (nil for stdio without session).

func (*Context) Set ΒΆ

func (c *Context) Set(key string, val any)

Set stores a key-value pair in the context.

func (*Context) String ΒΆ

func (c *Context) String(key string) string

String returns a string argument.

func (*Context) Text ΒΆ

func (c *Context) Text(s string) *CallToolResult

Text builds a text result.

type DirOptions ΒΆ

type DirOptions struct {
	Watch    bool          // watch for file changes
	Interval time.Duration // poll interval (default 2s)
	Pattern  string        // glob pattern (default "*.tool.yaml")
	OnReload func()        // callback after reload
}

DirOptions configures directory-based tool loading.

type GetPromptParams ΒΆ

type GetPromptParams struct {
	Name      string            `json:"name"`
	Arguments map[string]string `json:"arguments,omitempty"`
}

GetPromptParams is the request parameters for prompts/get.

type GetPromptResult ΒΆ

type GetPromptResult struct {
	Description string          `json:"description,omitempty"`
	Messages    []PromptMessage `json:"messages"`
}

GetPromptResult is the response to prompts/get.

type Group ΒΆ

type Group struct {
	// contains filtered or unexported fields
}

Group allows organizing tools under a common prefix with shared middleware.

func (*Group) Group ΒΆ

func (g *Group) Group(prefix string, mws ...Middleware) *Group

Group creates a nested sub-group.

func (*Group) Tool ΒΆ

func (g *Group) Tool(name, description string, handler HandlerFunc, opts ...ToolOption)

Tool registers a tool under this group. The tool name becomes "prefix.name".

func (*Group) ToolFunc ΒΆ

func (g *Group) ToolFunc(name, description string, fn any, opts ...ToolOption)

ToolFunc registers a typed tool under this group.

func (*Group) Use ΒΆ

func (g *Group) Use(mw ...Middleware)

Use adds middleware to this group.

type HandlerFunc ΒΆ

type HandlerFunc func(ctx *Context) (*CallToolResult, error)

HandlerFunc is the simplest tool handler signature.

type InitializeResult ΒΆ

type InitializeResult struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ServerCapabilities `json:"capabilities"`
	ServerInfo      ServerInfo         `json:"serverInfo"`
}

InitializeResult is the response to an initialize request.

type JSONSchema ΒΆ

type JSONSchema struct {
	Type       string                `json:"type"`
	Properties map[string]JSONSchema `json:"properties,omitempty"`
	Required   []string              `json:"required,omitempty"`
	// field constraints
	Description string      `json:"description,omitempty"`
	Default     any         `json:"default,omitempty"`
	Enum        []any       `json:"enum,omitempty"`
	Minimum     *float64    `json:"minimum,omitempty"`
	Maximum     *float64    `json:"maximum,omitempty"`
	Pattern     string      `json:"pattern,omitempty"`
	Items       *JSONSchema `json:"items,omitempty"`
}

JSONSchema represents a JSON Schema definition for tool parameters.

type KeyValidator ΒΆ

type KeyValidator func(key string) (meta map[string]any, err error)

KeyValidator validates an API key and returns metadata (stored in context as "_auth_claims").

type Metrics ΒΆ

type Metrics struct {
	// contains filtered or unexported fields
}

Metrics holds Prometheus-compatible metrics for tool calls.

func (*Metrics) Handler ΒΆ

func (m *Metrics) Handler() http.Handler

Handler returns an http.Handler that serves /metrics in Prometheus text format.

type Middleware ΒΆ

type Middleware func(ctx *Context, next func() error) error

Middleware processes a request and calls next to continue the chain.

func APIKeyAuth ΒΆ

func APIKeyAuth(headerName string, validate KeyValidator) Middleware

APIKeyAuth returns a middleware that validates API keys. It checks the header specified by headerName (e.g. "X-API-Key"), falling back to the "api_key" argument merged from tools/call arguments, prompts/get arguments, or resources/read params (see mergedArgsForMiddleware).

func APIKeyAuthSkipHandshake ΒΆ added in v1.4.0

func APIKeyAuthSkipHandshake(headerName string, validate KeyValidator) Middleware

APIKeyAuthSkipHandshake wraps APIKeyAuth so methods from HandshakeAuthSkipMethods do not require an API key.

func BasicAuth ΒΆ

func BasicAuth(validate func(username, password string) (map[string]any, error)) Middleware

BasicAuth returns a middleware that validates HTTP Basic Authentication.

func BasicAuthSkipHandshake ΒΆ added in v1.4.0

func BasicAuthSkipHandshake(validate func(username, password string) (map[string]any, error)) Middleware

BasicAuthSkipHandshake wraps BasicAuth so methods from HandshakeAuthSkipMethods do not require Basic credentials.

func BearerAuth ΒΆ

func BearerAuth(validate TokenValidator) Middleware

BearerAuth returns a middleware that validates Bearer tokens.

func BearerAuthSkipHandshake ΒΆ added in v1.4.0

func BearerAuthSkipHandshake(validate TokenValidator) Middleware

BearerAuthSkipHandshake wraps BearerAuth so methods from HandshakeAuthSkipMethods do not require a Bearer token.

func Logger ΒΆ

func Logger() Middleware

Logger returns a middleware that logs each MCP request with duration.

func OpenTelemetry ΒΆ

func OpenTelemetry() Middleware

OpenTelemetry returns a middleware that creates a span for each tool call. It uses the globally registered TracerProvider by default. Pass a custom TracerProvider via OpenTelemetryWithProvider().

func OpenTelemetryWithProvider ΒΆ

func OpenTelemetryWithProvider(tp trace.TracerProvider) Middleware

OpenTelemetryWithProvider returns an OTel middleware using the given provider.

func RateLimit ΒΆ

func RateLimit(perMinute int) Middleware

RateLimit returns a middleware that limits calls to n per minute using a token bucket.

func Recovery ΒΆ

func Recovery() Middleware

Recovery returns a middleware that recovers from panics.

func RequestID ΒΆ

func RequestID() Middleware

RequestID injects a unique request ID into the context.

func RequirePermission ΒΆ

func RequirePermission(perm string) Middleware

RequirePermission returns a middleware that checks if the user has the required permission.

func RequireRole ΒΆ

func RequireRole(role string) Middleware

RequireRole returns a middleware that checks if the authenticated user has the required role. Roles are read from ctx store key "_auth_roles" (set by auth middleware).

func SkipAuthForMCPMethods ΒΆ added in v1.4.0

func SkipAuthForMCPMethods(skip []string, mw Middleware) Middleware

SkipAuthForMCPMethods runs mw unless the current MCP method on ctx (store key "_mcp_method") is in skip. Place auth middleware inside this wrapper so handshake calls can omit credentials without weakening other methods.

func Timeout ΒΆ

func Timeout(d time.Duration) Middleware

Timeout returns a middleware that enforces a deadline on the entire MCP request (including dispatch to tools/resources/prompts). The request context is replaced with a timeout context; handlers should use Context.Context and check context.Context.Done to cancel work so long calls return promptly when the deadline hits.

type Option ΒΆ

type Option func(*Server)

Option configures the Server.

func WithDescription ΒΆ

func WithDescription(desc string) Option

WithDescription sets the server description.

func WithLogger ΒΆ

func WithLogger(l *slog.Logger) Option

WithLogger sets a custom logger for the server.

func WithMaxRequestSize ΒΆ

func WithMaxRequestSize(n int64) Option

WithMaxRequestSize sets the maximum request body size in bytes (default 10MB).

func WithSSEAuth ΒΆ added in v1.4.0

func WithSSEAuth(fn func(*http.Request) error) Option

WithSSEAuth sets an optional handler invoked before accepting an SSE connection on Streamable HTTP GET. Return a non-nil error to reject the connection (typically 401). Use SSEBearerAuth, SSEAPIKeyAuth, or SSEBasicAuth, or supply your own check.

type PromptArgument ΒΆ

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

PromptArgument describes a prompt parameter.

func PromptArg ΒΆ

func PromptArg(name, desc string, required bool) PromptArgument

type PromptCapability ΒΆ

type PromptCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

PromptCapability describes prompt-related capabilities.

type PromptContent ΒΆ

type PromptContent struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

PromptContent holds the content of a prompt message.

type PromptHandler ΒΆ

type PromptHandler func(ctx *Context) ([]PromptMessage, error)

PromptHandler returns messages for a prompt.

type PromptInfo ΒΆ

type PromptInfo struct {
	Name        string           `json:"name"`
	Description string           `json:"description,omitempty"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

PromptInfo describes a registered prompt template.

type PromptListResult ΒΆ

type PromptListResult struct {
	Prompts []PromptInfo `json:"prompts"`
}

PromptListResult is the response to prompts/list.

type PromptMessage ΒΆ

type PromptMessage struct {
	Role    string        `json:"role"`
	Content PromptContent `json:"content"`
}

PromptMessage is a single message in a prompt response.

func AssistantMsg ΒΆ

func AssistantMsg(text string) PromptMessage

AssistantMsg creates an assistant-role prompt message.

func UserMsg ΒΆ

func UserMsg(text string) PromptMessage

UserMsg creates a user-role prompt message.

type ReadResourceParams ΒΆ

type ReadResourceParams struct {
	URI string `json:"uri"`
}

ReadResourceParams is the request parameters for resources/read.

type ReadResourceResult ΒΆ

type ReadResourceResult struct {
	Contents []ResourceContents `json:"contents"`
}

ReadResourceResult is the response to resources/read.

type ResourceCapability ΒΆ

type ResourceCapability struct {
	Subscribe   bool `json:"subscribe,omitempty"`
	ListChanged bool `json:"listChanged,omitempty"`
}

ResourceCapability describes resource-related capabilities.

type ResourceContents ΒΆ

type ResourceContents struct {
	URI      string `json:"uri"`
	MIMEType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"`
}

ResourceContents holds the content returned by a resource read.

type ResourceHandler ΒΆ

type ResourceHandler func(ctx *Context) (any, error)

ResourceHandler returns content for a resource.

type ResourceInfo ΒΆ

type ResourceInfo struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	MIMEType    string `json:"mimeType,omitempty"`
}

ResourceInfo describes a static resource.

type ResourceListResult ΒΆ

type ResourceListResult struct {
	Resources []ResourceInfo `json:"resources"`
}

ResourceListResult is the response to resources/list.

type ResourceTemplateInfo ΒΆ

type ResourceTemplateInfo struct {
	URITemplate string `json:"uriTemplate"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	MIMEType    string `json:"mimeType,omitempty"`
}

ResourceTemplateInfo describes a dynamic resource with a URI template.

type ResourceTemplateListResult ΒΆ

type ResourceTemplateListResult struct {
	ResourceTemplates []ResourceTemplateInfo `json:"resourceTemplates"`
}

ResourceTemplateListResult is the response to resources/templates/list.

type Server ΒΆ

type Server struct {
	// contains filtered or unexported fields
}

Server is the core MCP server.

func New ΒΆ

func New(name, version string, opts ...Option) *Server

New creates a new MCP Server.

func (*Server) AsyncTool ΒΆ

func (s *Server) AsyncTool(name, description string, handler HandlerFunc, opts ...ToolOption)

AsyncTool registers an async tool that returns a task ID immediately.

func (*Server) AsyncToolFunc ΒΆ

func (s *Server) AsyncToolFunc(name, description string, fn any, opts ...ToolOption)

AsyncToolFunc registers an async typed tool.

func (*Server) Close ΒΆ added in v1.4.0

func (s *Server) Close()

Close stops background work tied to the server: the session manager eviction loop, the signal used by LoadDir(Watch: true), and the async task manager eviction loop. It is idempotent. It does not wait for in-flight AsyncTool handlers to finish.

func (*Server) Completion ΒΆ

func (s *Server) Completion(refType, refName, argName string, handler CompletionHandler)

Completion registers an auto-complete handler for a prompt or resource argument. refType is "prompt" or "resource", refName is the prompt/resource name, argName is the argument.

func (*Server) Dev ΒΆ

func (s *Server) Dev(addr string) error

Dev starts the server in development mode with Inspector UI on the given address.

func (*Server) Group ΒΆ

func (s *Server) Group(prefix string, mws ...Middleware) *Group

Group creates a new tool group with a name prefix.

func (*Server) HTTP ΒΆ

func (s *Server) HTTP(addr string) error

HTTP starts the server over Streamable HTTP on the given address. For browser clients using a custom mux, wrap the MCP handler with transport.WrapCORS from package transport.

func (*Server) HandleRaw ΒΆ

func (s *Server) HandleRaw(ctx context.Context, raw json.RawMessage) json.RawMessage

HandleRaw processes a raw JSON-RPC message. Used by mcptest and custom transports.

func (*Server) Handler ΒΆ

func (s *Server) Handler() http.Handler

Handler returns an http.Handler for embedding in existing HTTP servers. When browsers call POST /mcp cross-origin, wrap this handler with transport.WrapCORS from package transport.

func (*Server) LoadDir ΒΆ

func (s *Server) LoadDir(dir string, opts DirOptions) error

LoadDir loads tool definitions from YAML files in a directory.

func (*Server) Prompt ΒΆ

func (s *Server) Prompt(name, description string, args []PromptArgument, handler PromptHandler)

Prompt registers a prompt template.

func (*Server) RegisterToolRaw ΒΆ

func (s *Server) RegisterToolRaw(name, description string, inputSchema JSONSchema, handler HandlerFunc, opts ...ToolOption)

RegisterToolRaw registers a tool with a pre-built schema (used by adapters).

func (*Server) Resource ΒΆ

func (s *Server) Resource(uri, name string, handler ResourceHandler, opts ...func(*ResourceInfo))

Resource registers a static resource.

func (*Server) ResourceTemplate ΒΆ

func (s *Server) ResourceTemplate(uriTemplate, name string, handler ResourceHandler, opts ...func(*ResourceTemplateInfo))

ResourceTemplate registers a dynamic resource with URI template (e.g. "db://{table}/{id}").

func (*Server) Sessions ΒΆ

func (s *Server) Sessions() *SessionManager

Sessions returns the session manager for inspecting active sessions.

func (*Server) SetMaxConcurrentTasks ΒΆ

func (s *Server) SetMaxConcurrentTasks(n int)

SetMaxConcurrentTasks sets the max concurrent async tasks. Must be called before the first Server.AsyncTool or Server.AsyncToolFunc. If a task manager already exists, this is a no-op to avoid race conditions with in-flight tasks.

func (*Server) Stdio ΒΆ

func (s *Server) Stdio() error

Stdio starts the server over stdin/stdout.

func (*Server) Tool ΒΆ

func (s *Server) Tool(name, description string, handler HandlerFunc, opts ...ToolOption)

Tool registers a tool with a simple HandlerFunc.

func (*Server) ToolFunc ΒΆ

func (s *Server) ToolFunc(name, description string, fn any, opts ...ToolOption)

ToolFunc registers a tool using a typed function. Signature: func(*Context, InputStruct) (OutputType, error)

func (*Server) Use ΒΆ

func (s *Server) Use(mw ...Middleware)

Use adds global middleware to the server.

type ServerCapabilities ΒΆ

type ServerCapabilities struct {
	Tools     *ToolCapability     `json:"tools,omitempty"`
	Resources *ResourceCapability `json:"resources,omitempty"`
	Prompts   *PromptCapability   `json:"prompts,omitempty"`
}

ServerCapabilities declares the server's supported features.

type ServerInfo ΒΆ

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ServerInfo describes the MCP server name and version.

type Session ΒΆ

type Session struct {
	ID        string
	CreatedAt time.Time
	// contains filtered or unexported fields
}

Session represents a client connection session.

func (*Session) Get ΒΆ

func (s *Session) Get(key string) (any, bool)

Get retrieves a value from the session.

func (*Session) Set ΒΆ

func (s *Session) Set(key string, val any)

Set stores a value in the session.

type SessionManager ΒΆ

type SessionManager struct {
	// contains filtered or unexported fields
}

SessionManager tracks active sessions.

func (*SessionManager) Count ΒΆ

func (sm *SessionManager) Count() int

Count returns the number of active sessions.

func (*SessionManager) Get ΒΆ

func (sm *SessionManager) Get(id string) *Session

Get returns an existing session or creates a new one for the given ID.

func (*SessionManager) GetOrCreate ΒΆ

func (sm *SessionManager) GetOrCreate(id string) *Session

GetOrCreate returns an existing session or creates one with a new ID.

func (*SessionManager) Remove ΒΆ

func (sm *SessionManager) Remove(id string)

Remove deletes a session.

type TokenValidator ΒΆ

type TokenValidator func(token string) (claims map[string]any, err error)

TokenValidator validates a bearer token and returns claims (stored in context as "_auth_claims"). Implement JWT or opaque-token checks yourself inside validate; this package does not parse JWTs.

type ToolCapability ΒΆ

type ToolCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

ToolCapability describes tool-related capabilities.

type ToolInfo ΒΆ

type ToolInfo struct {
	Name        string            `json:"name"`
	Description string            `json:"description,omitempty"`
	InputSchema JSONSchema        `json:"inputSchema"`
	Annotations map[string]string `json:"annotations,omitempty"`
}

ToolInfo describes a registered tool and its input schema.

type ToolListResult ΒΆ

type ToolListResult struct {
	Tools []ToolInfo `json:"tools"`
}

ToolListResult is the response to tools/list.

type ToolOption ΒΆ

type ToolOption func(*toolEntry)

ToolOption configures a tool registration.

func Deprecated ΒΆ

func Deprecated(msg string) ToolOption

Deprecated marks a tool as deprecated.

func Version ΒΆ

func Version(v string) ToolOption

Version sets the version for a tool. Versioned tools are registered as "name@version".

Directories ΒΆ

Path Synopsis
examples
basic command
filesystem command
Package main implements a real-world MCP server for filesystem operations.
Package main implements a real-world MCP server for filesystem operations.
gin-adapter command
openapi-adapter command
Package inspector provides a development UI for GoMCP servers.
Package inspector provides a development UI for GoMCP servers.
internal
uid
Package mcptest provides testing utilities for GoMCP servers.
Package mcptest provides testing utilities for GoMCP servers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL