mcp

package module
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 10 Imported by: 4

README

mcp-go

Go Reference Go Report Card CI Coverage

A Go framework for building Model Context Protocol (MCP) servers — like Gin, but for MCP.

mcp-go is an opinionated, production-ready framework for building MCP servers in Go with typed handlers, automatic schema generation, middleware, and multiple transports.

If the MCP SDK gives you protocol correctness, and mark3labs/mcp-go gives you SDK convenience, mcp-go gives you application structure and production defaults.


Why mcp-go?

Building an MCP server directly on top of SDKs means repeatedly solving the same problems:

  • input decoding & validation
  • schema generation
  • error handling
  • middleware (auth, timeouts, logging)
  • transport wiring (stdio vs HTTP)

mcp-go solves these once — idiomatically, safely, and with great DX.


Quickstart (5 minutes)

package main

import (
    "context"
    "log"

    "github.com/felixgeelhaar/mcp-go"
)

func main() {
    srv := mcp.NewServer(mcp.ServerInfo{
        Name:    "example",
        Version: "0.1.0",
    })

    srv.Tool("hello").
        Description("Say hello").
        Handler(func(ctx context.Context, in struct{ Name string `json:"name"` }) (string, error) {
            return "Hello " + in.Name, nil
        })

    log.Fatal(mcp.ServeStdio(context.Background(), srv))
}

That's it:

  • Typed input
  • Automatic JSON Schema
  • MCP-compliant responses
  • No manual routing or validation

Core Features

Typed MCP tools

Define tools using strongly-typed Go structs. Invalid input never reaches your business logic.

type SearchInput struct {
    Query string `json:"query" jsonschema:"required"`
    Limit int    `json:"limit"`
}

srv.Tool("search").
    Description("Search for items").
    Handler(func(ctx context.Context, input SearchInput) ([]string, error) {
        // Your search logic here
        return []string{"result1", "result2"}, nil
    })
Automatic JSON Schema

Schemas are derived from Go structs and:

  • validated automatically
  • exposed via MCP introspection
  • kept in sync with code

No manual schema maintenance.


Gin-style middleware

Apply cross-cutting concerns consistently:

srv.Use(
    middleware.Recover(),
    middleware.Timeout(5*time.Second),
    middleware.RequestID(),
    middleware.Logging(logger),
)

Use cases:

  • auth / principals
  • rate limiting
  • tracing
  • metrics
  • panic recovery

Multiple transports

Run the same server over:

  • stdio (CLI / agent use)
  • HTTP + SSE (service deployments)
  • WebSocket (bidirectional communication)
  • gRPC (high-performance service-to-service)
// Stdio for CLI tools
mcp.ServeStdio(ctx, srv)

// HTTP + SSE for web services
mcp.ServeHTTP(ctx, srv, ":8080")

// WebSocket for bidirectional communication
mcp.ServeWebSocket(ctx, srv, ":8081")

// gRPC for high-performance service-to-service
mcp.ServeGRPC(ctx, srv, ":9090")
MCP Apps Support

Build tools with interactive UIs using the MCP Apps extension. Tools declare a ui:// resource URI via UIResource(), and the linked HTML resource is rendered as a sandboxed iframe in supported hosts like Claude Desktop.

srv.Tool("visualize").
    Description("Visualize data interactively").
    UIResource("ui://my-app/visualizer").
    Handler(func(input VisualizeInput) (any, error) {
        return getData(input.ID), nil
    })

// Serve the UI as a resource with the MCP Apps MIME type
srv.Resource("ui://my-app/visualizer").
    Name("Visualizer").
    MimeType("text/html;profile=mcp-app").
    Handler(func(ctx context.Context, uri string, params map[string]string) (*mcp.ResourceContent, error) {
        return &mcp.ResourceContent{
            URI:      uri,
            MimeType: "text/html;profile=mcp-app",
            Text:     visualizerHTML,
        }, nil
    })

UIResource() sets _meta.ui.resourceUri on both tools/list and tools/call responses, telling MCP hosts to render the linked resource as an interactive app alongside tool results.

Building the HTML resource

The HTML resource must be a single self-contained file (inline CSS, JS, no external requests). The recommended stack:

  • @modelcontextprotocol/ext-apps — Client SDK for the MCP Apps postMessage protocol (handles ui/initialize handshake, receives tool results)
  • Vite + vite-plugin-singlefile — Bundles everything into one HTML file
  • Go embed.FS — Embeds the built HTML files into the Go binary
Common pitfalls

Vue/React string templates and the runtime compiler. If you use Vue's defineComponent with a template string (instead of .vue SFCs), Vite's default Vue build is runtime-only and cannot compile templates at runtime. The iframe will render empty with no error. Fix this by aliasing Vue to the full build in vite.config.ts:

// vite.config.ts
export default defineConfig({
  resolve: {
    alias: {
      vue: "vue/dist/vue.esm-bundler.js",
    },
  },
});

No TypeScript in runtime-compiled templates. Vue's runtime template compiler only understands JavaScript. TypeScript syntax like as any or : string in template expressions will throw SyntaxError: Unexpected identifier. Move type assertions to setup() or use computed properties.

Resource MIME type. Use text/html;profile=mcp-app (not plain text/html) so hosts recognize the resource as an MCP App.

Working example

Roady ships 14 MCP Apps (D3.js charts, task boards, interactive dashboards) built with mcp-go. See app/ for the Vue + Vite + singlefile setup and internal/infrastructure/mcp/ for the Go resource registration.


Production-ready defaults
  • strict JSON decoding
  • safe error mapping
  • graceful shutdown
  • context propagation everywhere

You can opt out — but safety is the default.


How this fits into the MCP ecosystem

Project What it is
MCP Go SDK Low-level protocol implementation
mark3labs/mcp-go Community SDK / helpers
mcp-go Full Go framework for MCP servers

Think:

  • MCP SDK → net/http
  • mcp-go → Gin

We build on top of the MCP spec — not instead of it.


When should you use mcp-go?

Use mcp-go if you:

  • are building real MCP services, not just experiments
  • want typed APIs and validation
  • need auth, limits, observability
  • deploy MCP servers in production

If you want raw protocol access only, an SDK may be a better fit.


Used by

  • Roady — Planning-first system of record with 14 interactive MCP Apps (D3.js visualizations, task boards, dashboards)
  • Obvia — Incident automation & AIOps tooling
  • Internal MCP services and experiments

Want to add your project? Open a PR!


Installation

go get github.com/felixgeelhaar/mcp-go

Requires Go 1.25 or later.


Documentation


Examples

Tools

Tools are functions that can be called by the AI model:

type CalculateInput struct {
    Operation string  `json:"operation" jsonschema:"required"`
    A         float64 `json:"a" jsonschema:"required"`
    B         float64 `json:"b" jsonschema:"required"`
}

srv.Tool("calculate").
    Description("Perform arithmetic operations").
    Handler(func(input CalculateInput) (float64, error) {
        switch input.Operation {
        case "add":
            return input.A + input.B, nil
        case "multiply":
            return input.A * input.B, nil
        default:
            return 0, fmt.Errorf("unknown operation: %s", input.Operation)
        }
    })
Return Type Flexibility

Tool handlers can return any JSON-serializable type. The framework automatically handles serialization:

// String returns are used as-is
srv.Tool("greet").
    Handler(func(input GreetInput) (string, error) {
        return "Hello, " + input.Name, nil
    })

// Structs are automatically JSON-serialized
type StatusResult struct {
    Status  string `json:"status"`
    Count   int    `json:"count"`
    Healthy bool   `json:"healthy"`
}

srv.Tool("status").
    Handler(func(input StatusInput) (StatusResult, error) {
        return StatusResult{
            Status:  "ok",
            Count:   42,
            Healthy: true,
        }, nil
    })
// Response text: {"status":"ok","count":42,"healthy":true}

// Maps and slices work too
srv.Tool("list").
    Handler(func(input ListInput) (map[string]any, error) {
        return map[string]any{
            "items": []string{"a", "b", "c"},
            "total": 3,
        }, nil
    })

This ensures compliance with the MCP specification which requires the text field to always be a string.

Structured Content

Tools can return typed structured data alongside text content blocks using OutputSchema and StructuredResult:

type TableOutput struct {
    Headers []string   `json:"headers"`
    Rows    [][]string `json:"rows"`
}

srv.Tool("extract_table").
    Description("Extract table data from a page").
    OutputSchema(TableOutput{}).
    Handler(func(ctx context.Context, input ExtractInput) (mcp.StructuredResult, error) {
        return mcp.StructuredResult{
            Content:           []mcp.Content{mcp.NewTextContent("Found 3 rows")},
            StructuredContent: map[string]any{"headers": []string{"name", "age"}, "rows": [][]string{{"Alice", "30"}}},
        }, nil
    })

The response includes both content (text blocks for display) and structuredContent (typed data matching the output schema). Clients that understand structuredContent can render it natively (tables, trees, etc.).

Dynamic Tool Registration

Add and remove tools at runtime, then notify connected clients:

// Add a tool dynamically
srv.Tool("fill_form").Handler(fillFormHandler)

// Notify clients that the tool list changed
session := mcp.SessionFromContext(ctx)
session.NotifyToolListChanged()

// Remove a tool when it's no longer relevant
srv.RemoveTool("fill_form")
session.NotifyToolListChanged()

// Same pattern works for resources and prompts
srv.RemoveResource("config://temp")
session.NotifyResourceListChanged()

srv.RemovePrompt("onboarding")
session.NotifyPromptListChanged()
Resources

Resources expose data via URI templates:

srv.Resource("file://{path}").
    Name("File").
    Description("Read file content").
    MimeType("text/plain").
    Handler(func(ctx context.Context, uri string, params map[string]string) (*mcp.ResourceContent, error) {
        content, err := os.ReadFile(params["path"])
        if err != nil {
            return nil, err
        }
        return &mcp.ResourceContent{
            URI:      uri,
            MimeType: "text/plain",
            Text:     string(content),
        }, nil
    })
Prompts

Prompts are parameterized message templates:

srv.Prompt("code-review").
    Description("Generate a code review prompt").
    Argument("language", "Programming language", true).
    Handler(func(ctx context.Context, args map[string]string) (*mcp.PromptResult, error) {
        return &mcp.PromptResult{
            Messages: []mcp.PromptMessage{
                {
                    Role:    "user",
                    Content: mcp.TextContent{Type: "text", Text: fmt.Sprintf("Review this %s code:", args["language"])},
                },
            },
        }, nil
    })
Tool Metadata

Attach arbitrary metadata to tools via _meta, or use the UIResource shorthand for MCP Apps:

// Arbitrary metadata
srv.Tool("my-tool").
    Meta(map[string]any{"custom": "data"}).
    Handler(myHandler)

// MCP Apps shorthand — sets _meta.ui.resourceUri
srv.Tool("visualize").
    UIResource("ui://my-app/dashboard").
    Handler(vizHandler)

The _meta field is included in both tools/list and tools/call JSON-RPC responses.

Middleware

Add cross-cutting concerns with middleware:

// Use default production middleware stack
middleware := mcp.DefaultMiddlewareWithTimeout(logger, 30*time.Second)

mcp.ServeStdio(ctx, srv, mcp.WithMiddleware(middleware...))

Built-in middleware:

  • Recover() - Catch panics and convert to errors
  • RequestID() - Inject unique request IDs
  • Timeout(d) - Enforce request deadlines
  • Logging(logger) - Structured request logging
  • Auth() - API key and Bearer token authentication
  • RateLimit() - Request throttling
  • SizeLimit() - Request size limits
  • OTel() - OpenTelemetry tracing and metrics
  • Audit() - Request/response audit logging
  • Tracing() - Correlation and trace ID propagation
  • OAuth2() - JWT-based OAuth 2.0 authentication
Enterprise Features
Horizontal Scaling with SessionStore

Persist sessions across server restarts for load-balanced deployments:

// Redis-backed session store
store := redis.NewSessionStore(redisClient, 24*time.Hour)

mcp.ServeHTTP(ctx, srv, ":8080",
    mcp.WithSessionStore(store),
)

// In-memory store for single-instance deployments
mcp.ServeHTTP(ctx, srv, ":8080",
    mcp.WithSessionStore(mcp.NewInMemorySessionStore()),
)
Server Discovery

Clients can discover MCP servers via /.well-known/mcp:

mcp.ServeHTTP(ctx, srv, ":8080",
    mcp.WithDiscovery(mcp.ServerDiscovery{
        Name:        "my-server",
        Description: "My MCP server",
    }),
)
Tasks for Long-Running Operations

Register async tasks that can be created, monitored, and canceled:

srv.RegisterTask("long-task", "A long running task", func(ctx context.Context, input map[string]any) (*mcp.TaskResult, error) {
    // Task runs asynchronously
    return &mcp.TaskResult{Data: "completed"}, nil
})

// Create a task
task, _ := srv.Tasks().CreateTask(ctx, mcp.CreateTaskRequest{
    Name:   "long-task",
    Params: map[string]any{"key": "value"},
})

// List and cancel tasks
tasks, _ := srv.Tasks().ListTasks(10, "")
srv.Tasks().CancelTask(task.ID)
Tool Annotations

Mark tools with behavioral hints for clients:

srv.Tool("read-config").
    Description("Read configuration").
    ReadOnly().
    Handler(readHandler)

srv.Tool("delete-user").
    Description("Delete a user account").
    Destructive().
    Handler(deleteHandler)

srv.Tool("update-setting").
    Description("Update a setting").
    Idempotent().
    Handler(updateHandler)
Completion Support

Provide autocomplete suggestions for prompt arguments and resource URIs:

srv.PromptCompletion("code-review").
    Argument("language", func(ctx context.Context, value string) (*mcp.CompletionResult, error) {
        return &mcp.CompletionResult{
            Values: []string{"go", "python", "typescript"},
        }, nil
    })
Bidirectional Communication

Servers can make requests back to clients via sessions:

// Request LLM completion from client (sampling)
session := mcp.SessionFromContext(ctx)
result, _ := session.CreateMessage(ctx, mcp.CreateMessageRequest{
    Messages: []mcp.SamplingMessage{{Role: mcp.User, Content: mcp.Content{Type: "text", Text: "Summarize this"}}},
})

// Query client workspace roots
roots, _ := session.ListRoots(ctx)

// Send log messages to client
session.LogMessage(ctx, mcp.LoggingMessage{Level: mcp.Info, Data: "Processing complete"})

// Notify clients of resource changes
session.NotifyResourceUpdated(ctx, "config://app")

// Elicitation — ask the user for structured input mid-task
elicitor := mcp.ElicitFromContext(ctx)
if elicitor != nil {
    result, _ := elicitor.Elicit(ctx, &mcp.ElicitRequest{
        Message: "Multiple fields match 'Name'. Which one?",
        RequestedSchema: map[string]any{
            "type": "object",
            "properties": map[string]any{
                "field": map[string]any{"type": "string", "enum": []string{"First Name", "Last Name"}},
            },
        },
    })
    if result.Action == "accept" {
        selectedField := result.Content["field"]
        // Use selectedField...
    }
}

// Channels — push messages proactively into the AI session
channel := mcp.ChannelFromContext(ctx)
if channel != nil {
    channel.SendText("navigation", "Page navigated to /dashboard")
    channel.Send(&mcp.ChannelMessage{
        Channel:  "network",
        Content:  mcp.NewTextContent("API response received"),
        Data:     map[string]any{"status": 200, "url": "/api/users"},
        Priority: "high",
    })
}
HTTP Transport

Serve over HTTP with Server-Sent Events:

mcp.ServeHTTP(ctx, srv, ":8080",
    mcp.WithReadTimeout(30*time.Second),
    mcp.WithWriteTimeout(30*time.Second),
)
WebSocket Transport

Serve over WebSocket for full-duplex communication:

mcp.ServeWebSocket(ctx, srv, ":8081",
    mcp.WithWebSocketReadTimeout(30*time.Second),
    mcp.WithWebSocketWriteTimeout(30*time.Second),
)
gRPC Transport

Serve over gRPC with Protocol Buffers for high-performance service-to-service communication:

mcp.ServeGRPC(ctx, srv, ":9090",
    mcp.WithGRPCShutdownTimeout(10*time.Second),
)
Client SDK

Consume MCP servers programmatically:

transport, _ := client.NewStdioTransport("./my-server")
c := client.New(transport, client.WithTimeout(10*time.Second))

info, _ := c.Initialize(ctx)
tools, _ := c.ListTools(ctx)
result, _ := c.CallTool(ctx, "search", SearchInput{Query: "hello"})
Testing

Test MCP servers without transport overhead:

func TestMyServer(t *testing.T) {
    srv := mcp.NewServer(mcp.ServerInfo{Name: "test", Version: "1.0.0"})
    srv.Tool("greet").Handler(greetHandler)

    tc := testutil.NewTestClient(t, srv)
    defer tc.Close()

    result, err := tc.CallTool("greet", map[string]any{"name": "World"})
    if err != nil {
        t.Fatal(err)
    }
    // result == "Hello, World!"
}

JSON Schema Tags

Use struct tags to define JSON Schema for tool inputs:

type SearchInput struct {
    Query    string   `json:"query" jsonschema:"required,description=Search query"`
    Limit    int      `json:"limit" jsonschema:"description=Max results,default=10"`
    Tags     []string `json:"tags" jsonschema:"description=Filter by tags"`
    MinScore float64  `json:"minScore" jsonschema:"minimum=0,maximum=1"`
}

Supported tags:

  • required - Field is required
  • description=... - Field description
  • default=... - Default value
  • minimum=N / maximum=N - Numeric bounds
  • minLength=N / maxLength=N - String length bounds
  • enum=a|b|c - Allowed values

Philosophy

  • Typed > dynamic
  • Safe defaults > flexibility
  • Frameworks create ecosystems

mcp-go aims to be the default Go framework for MCP — boring, predictable, and a joy to use.


Contributing

Contributions are welcome! Please read our Contributing Guide.

License

MIT License - see LICENSE for details.

Documentation

Overview

Package mcp provides a framework for building MCP (Model Context Protocol) servers.

mcp-go aims to be the "Gin framework" for MCP servers, providing typed handlers with automatic JSON Schema generation, Gin-style middleware chains, pluggable transports (stdio, HTTP+SSE, WebSocket), and production-ready defaults.

Handler Signatures

Tool handlers: func(input T) (R, error) or func(ctx, input T) (R, error)

Resource handlers receive URI and template params (e.g., "users://{id}"):

func(ctx, uri string, params map[string]string) (*ResourceContent, error)

Prompt handlers: func(ctx, args map[string]string) (*PromptResult, error)

Progress Reporting

Use ProgressFromContext in long-running handlers. Report is thread-safe. Errors are non-fatal and typically ignored.

Error Handling

Return errors from handlers. Use protocol.NewInvalidParams, protocol.NewNotFound, etc. for specific MCP error codes.

See examples/basic for a complete working example with tools, resources, and prompts.

Example

ExampleNewServer demonstrates creating an MCP server with tools, resources, and prompts.

// Create server with capabilities and instructions
srv := mcp.NewServer(mcp.ServerInfo{
	Name:    "example-server",
	Version: "1.0.0",
	Capabilities: mcp.Capabilities{
		Tools:     true,
		Resources: true,
		Prompts:   true,
	},
}, mcp.WithInstructions("Use search to find documents."))

// Register a typed tool
type SearchInput struct {
	Query string `json:"query" jsonschema:"required"`
	Limit int    `json:"limit" jsonschema:"maximum=100"`
}

srv.Tool("search").
	Description("Search for documents").
	Handler(func(ctx context.Context, input SearchInput) ([]string, error) {
		return []string{"result1", "result2"}, nil
	})

// Register a resource with URI template
srv.Resource("users://{id}").
	Name("User").
	MimeType("application/json").
	Handler(func(ctx context.Context, uri string, params map[string]string) (*mcp.ResourceContent, error) {
		id := params["id"] // extracted from template
		return &mcp.ResourceContent{
			URI:      uri,
			MimeType: "application/json",
			Text:     fmt.Sprintf(`{"id": "%s"}`, id),
		}, nil
	})

// Register a prompt
srv.Prompt("greet").
	Description("Generate a greeting").
	Argument("name", "Name to greet", true).
	Handler(func(ctx context.Context, args map[string]string) (*mcp.PromptResult, error) {
		return &mcp.PromptResult{
			Messages: []mcp.PromptMessage{
				{
					Role:    "user",
					Content: mcp.TextContent{Type: "text", Text: "Hello, " + args["name"]},
				},
			},
		}, nil
	})

fmt.Println("Server created with tools, resources, and prompts")
Output:
Server created with tools, resources, and prompts

Index

Examples

Constants

View Source
const (
	RoleUser      = server.RoleUser
	RoleAssistant = server.RoleAssistant
)

Role constants

View Source
const (
	LogLevelDebug     = server.LogLevelDebug
	LogLevelInfo      = server.LogLevelInfo
	LogLevelNotice    = server.LogLevelNotice
	LogLevelWarning   = server.LogLevelWarning
	LogLevelError     = server.LogLevelError
	LogLevelCritical  = server.LogLevelCritical
	LogLevelAlert     = server.LogLevelAlert
	LogLevelEmergency = server.LogLevelEmergency
)

LogLevel constants

View Source
const (
	KB = middleware.KB
	MB = middleware.MB
)

Size limit presets.

Variables

View Source
var (
	Bool  = server.Bool
	Float = server.Float
)

Helper functions for annotation values

View Source
var (
	NewTextContent  = server.NewTextContent
	NewImageContent = server.NewImageContent
)

Content constructors

View Source
var (
	ContextWithCancellationManager = server.ContextWithCancellationManager
	CancellationManagerFromContext = server.CancellationManagerFromContext
)

Context utilities for cancellation

View Source
var (
	NewElicitor       = server.NewElicitor
	ElicitFromContext = server.ElicitFromContext
)
View Source
var (
	NewChannelSender   = server.NewChannelSender
	ChannelFromContext = server.ChannelFromContext
)
View Source
var (
	NewSession              = server.NewSession
	WithClientCapabilities  = server.WithClientCapabilities
	WithRootsChangeCallback = server.WithRootsChangeCallback
	ContextWithSession      = server.ContextWithSession
	SessionFromContext      = server.SessionFromContext
)
View Source
var (
	RateLimit            = middleware.RateLimit
	RateLimitByMethod    = middleware.RateLimitByMethod
	RateLimitByClient    = middleware.RateLimitByClient
	WithRateLimitKeyFunc = middleware.WithRateLimitKeyFunc
	WithRateLimitLogger  = middleware.WithRateLimitLogger
)

RateLimit re-exports for convenience.

View Source
var (
	SizeLimit           = middleware.SizeLimit
	WithSizeLimitLogger = middleware.WithSizeLimitLogger
)
View Source
var (
	Auth                     = middleware.Auth
	WithAuthLogger           = middleware.WithAuthLogger
	WithAuthSkipMethods      = middleware.WithAuthSkipMethods
	WithAuthRealm            = middleware.WithAuthRealm
	WithAuthErrorMessage     = middleware.WithAuthErrorMessage
	APIKeyAuthenticator      = middleware.APIKeyAuthenticator
	BearerTokenAuthenticator = middleware.BearerTokenAuthenticator
	StaticAPIKeys            = middleware.StaticAPIKeys
	StaticTokens             = middleware.StaticTokens
	ChainAuthenticators      = middleware.ChainAuthenticators
	IdentityFromContext      = middleware.IdentityFromContext
	ContextWithIdentity      = middleware.ContextWithIdentity
)
View Source
var (
	DefaultCORSConfig = transport.DefaultCORSConfig
	WithCORS          = transport.WithCORS
	WithDefaultCORS   = transport.WithDefaultCORS
)
View Source
var (
	DefaultShutdownConfig  = transport.DefaultShutdownConfig
	NewShutdownManager     = transport.NewShutdownManager
	WithShutdownTimeout    = transport.WithShutdownTimeout
	WithShutdownDrainDelay = transport.WithShutdownDrainDelay
)
View Source
var (
	// WithTitle sets a human-readable display name for the server.
	WithTitle = server.WithTitle
	// WithDescription sets a description of what the server does.
	WithDescription = server.WithDescription
	// WithWebsiteURL sets the server's documentation or homepage URL.
	WithWebsiteURL = server.WithWebsiteURL
	// WithIcons sets the icons for UI display.
	WithIcons = server.WithIcons
	// WithBuildInfo sets build metadata for debugging and version verification.
	WithBuildInfo = server.WithBuildInfo
)

ServerInfo option functions

View Source
var (
	OTel                = middleware.OTel
	WithTracerProvider  = middleware.WithTracerProvider
	WithMeterProvider   = middleware.WithMeterProvider
	WithOTelServiceName = middleware.WithOTelServiceName
	WithOTelSkipMethods = middleware.WithOTelSkipMethods
	SpanFromContext     = middleware.SpanFromContext
	AddSpanEvent        = middleware.AddSpanEvent
	SetSpanAttribute    = middleware.SetSpanAttribute
)
View Source
var NewCancellationManager = server.NewCancellationManager
View Source
var NewSubscriptionManager = server.NewSubscriptionManager
View Source
var ProgressFromContext = server.ProgressFromContext

ProgressFromContext returns the progress reporter from context. Use this in tool handlers to report progress for long-running operations.

Example:

srv.Tool("process").Handler(func(ctx context.Context, input ProcessInput) (string, error) {
    progress := mcp.ProgressFromContext(ctx)
    total := 100.0
    for i := 0; i < 100; i++ {
        progress.Report(float64(i), &total)
        // do work...
    }
    return "done", nil
})
View Source
var ShouldLog = server.ShouldLog

ShouldLog returns true if a message at the given level should be logged

View Source
var WithInstructions = server.WithInstructions

WithInstructions sets the server instructions that provide context to AI models about how to use this server effectively.

Functions

func ExtractParams added in v1.2.0

func ExtractParams[T any](params map[string]string) (T, error)

ExtractParams extracts URI template parameters into a typed struct. Use this in resource handlers for type-safe parameter extraction.

Example:

type UserParams struct {
    ID   string `uri:"id"`
    Page int    `uri:"page"`
}

srv.Resource("users://{id}/page/{page}").Handler(func(ctx context.Context, uri string, params map[string]string) (*mcp.ResourceContent, error) {
    p, err := mcp.ExtractParams[UserParams](params)
    if err != nil {
        return nil, err
    }
    // Use p.ID (string) and p.Page (int)
})

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request ID from the context, or empty string if not set.

func ServeGRPC added in v1.2.1

func ServeGRPC(ctx context.Context, srv *Server, addr string, opts ...GRPCOption) error

ServeGRPC runs the server using gRPC transport with bidirectional streaming. This enables MCP communication over gRPC, providing benefits like binary encoding, built-in flow control, and native support for enterprise infrastructure. This blocks until the context is canceled or an error occurs.

func ServeGRPCWithMiddleware added in v1.2.1

func ServeGRPCWithMiddleware(ctx context.Context, srv *Server, addr string, grpcOpts []GRPCOption, serveOpts ...ServeOption) error

ServeGRPCWithMiddleware runs the server using gRPC transport with middleware support.

func ServeHTTP

func ServeHTTP(ctx context.Context, srv *Server, addr string, opts ...HTTPOption) error

ServeHTTP runs the server using HTTP transport with SSE support. This blocks until the context is canceled or an error occurs.

func ServeHTTPWithMiddleware

func ServeHTTPWithMiddleware(ctx context.Context, srv *Server, addr string, httpOpts []HTTPOption, serveOpts ...ServeOption) error

ServeHTTPWithMiddleware runs the server using HTTP transport with middleware support.

func ServeStdio

func ServeStdio(ctx context.Context, srv *Server, opts ...ServeOption) error

ServeStdio runs the server using stdio transport. This blocks until the context is canceled or an error occurs.

func ServeWebSocket

func ServeWebSocket(ctx context.Context, srv *Server, addr string, opts ...WebSocketOption) error

ServeWebSocket runs the server using WebSocket transport. This blocks until the context is canceled or an error occurs.

func ServeWebSocketWithMiddleware

func ServeWebSocketWithMiddleware(ctx context.Context, srv *Server, addr string, wsOpts []WebSocketOption, serveOpts ...ServeOption) error

ServeWebSocketWithMiddleware runs the server using WebSocket transport with middleware support.

Types

type AuthOption

type AuthOption = middleware.AuthOption

type Authenticator

type Authenticator = middleware.Authenticator

type BuildInfo added in v1.2.1

type BuildInfo = server.BuildInfo

type CORSConfig

type CORSConfig = transport.CORSConfig

CORS configuration for HTTP transports.

type CancellationManager added in v1.1.0

type CancellationManager = server.CancellationManager

type CancelledNotification added in v1.1.0

type CancelledNotification = server.CancelledNotification

Cancellation types

type Capabilities

type Capabilities = server.Capabilities

Capabilities declares what features the server supports.

type ChannelMessage added in v1.9.0

type ChannelMessage = server.ChannelMessage

Channel types for server-initiated push messages

type ChannelSender added in v1.9.0

type ChannelSender = server.ChannelSender

type ClientCapabilities added in v1.1.0

type ClientCapabilities = server.ClientCapabilities

type CompletionArgument added in v1.2.0

type CompletionArgument = server.CompletionArgument

type CompletionHandler added in v1.2.0

type CompletionHandler = server.CompletionHandler

type CompletionRef added in v1.2.0

type CompletionRef = server.CompletionRef

Completion types for autocomplete support

type CompletionResult added in v1.2.0

type CompletionResult = server.CompletionResult

type Content added in v1.1.0

type Content = server.Content

type CreateMessageRequest added in v1.1.0

type CreateMessageRequest = server.CreateMessageRequest

type CreateMessageResult added in v1.1.0

type CreateMessageResult = server.CreateMessageResult

type ElicitRequest added in v1.9.0

type ElicitRequest = server.ElicitRequest

Elicitation types for interactive user prompts

type ElicitResult added in v1.9.0

type ElicitResult = server.ElicitResult

type Elicitor added in v1.9.0

type Elicitor = server.Elicitor

type GRPCOption added in v1.2.1

type GRPCOption = grpctransport.Option

GRPCOption configures the gRPC transport.

func WithGRPCDrainDelay added in v1.2.1

func WithGRPCDrainDelay(d time.Duration) GRPCOption

WithGRPCDrainDelay sets the delay before starting connection draining. This allows load balancers to remove the server from rotation.

func WithGRPCShutdownTimeout added in v1.2.1

func WithGRPCShutdownTimeout(d time.Duration) GRPCOption

WithGRPCShutdownTimeout sets the maximum time to wait for graceful shutdown.

type HTTPOption

type HTTPOption = transport.HTTPOption

HTTPOption configures the HTTP transport.

func WithDiscovery added in v1.8.0

func WithDiscovery(discovery *transport.ServerDiscovery) HTTPOption

WithDiscovery sets the server discovery metadata for the /.well-known/mcp endpoint.

func WithReadTimeout

func WithReadTimeout(d time.Duration) HTTPOption

WithReadTimeout sets the read timeout for HTTP requests.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) HTTPOption

WithWriteTimeout sets the write timeout for HTTP responses.

type Icon added in v1.2.1

type Icon = server.Icon

ServerInfo metadata types

type Identity

type Identity = middleware.Identity

Auth re-exports for convenience.

type ImageContent

type ImageContent = server.ImageContent

type ListRootsResult added in v1.1.0

type ListRootsResult = server.ListRootsResult

type LogField

type LogField = middleware.Field

func LogF

func LogF(key string, value any) LogField

LogF creates a new log field with the given key and value.

type LogLevel added in v1.1.0

type LogLevel = server.LogLevel

Logging types for MCP log messages

type Logger

type Logger = middleware.Logger

type LoggingMessage added in v1.1.0

type LoggingMessage = server.LoggingMessage

type Middleware

type Middleware = middleware.Middleware

Middleware types

func Chain

func Chain(middlewares ...Middleware) Middleware

Chain composes multiple middleware into a single middleware.

func DefaultMiddleware

func DefaultMiddleware(logger Logger) []Middleware

DefaultMiddleware returns the recommended production middleware stack.

func DefaultMiddlewareWithTimeout

func DefaultMiddlewareWithTimeout(logger Logger, timeout time.Duration) []Middleware

DefaultMiddlewareWithTimeout returns the default stack with a timeout middleware.

Example

ExampleDefaultMiddlewareWithTimeout shows using the production middleware stack.

srv := mcp.NewServer(mcp.ServerInfo{Name: "server", Version: "1.0.0"})

// Create a logger (implement mcp.Logger interface)
var logger mcp.Logger // = yourLogger

// Use default production middleware: recover, request ID, timeout, logging
_ = logger
_ = srv
// mcp.ServeStdio(ctx, srv, mcp.WithMiddleware(
//     mcp.DefaultMiddlewareWithTimeout(logger, 30*time.Second)...,
// ))

fmt.Println("Server configured with default middleware")
Output:
Server configured with default middleware

func Logging

func Logging(logger Logger) Middleware

Logging returns middleware that logs request details.

func Recover

func Recover() Middleware

Recover returns middleware that catches panics and converts them to internal errors.

func RecoverWithHandler

func RecoverWithHandler(handler func(ctx context.Context, req *protocol.Request, panicVal any) (*protocol.Response, error)) Middleware

RecoverWithHandler returns middleware that catches panics and calls the provided handler.

func RequestID

func RequestID() Middleware

RequestID returns middleware that injects a unique request ID into the context.

func Timeout

func Timeout(d time.Duration) Middleware

Timeout returns middleware that enforces a request deadline.

type MiddlewareHandlerFunc

type MiddlewareHandlerFunc = middleware.HandlerFunc

type ModelHint added in v1.1.0

type ModelHint = server.ModelHint

type ModelPreferences added in v1.1.0

type ModelPreferences = server.ModelPreferences

type NotificationSender added in v1.1.0

type NotificationSender = server.NotificationSender

type OTelOption added in v1.2.0

type OTelOption = middleware.OTelOption

OpenTelemetry re-exports for convenience.

type Option

type Option = server.Option

Option configures a Server.

type Progress

type Progress = server.Progress

type ProgressReporter

type ProgressReporter = server.ProgressReporter

type ProgressToken

type ProgressToken = server.ProgressToken

Progress types for streaming tool responses

type PromptAnnotations

type PromptAnnotations = server.PromptAnnotations

type PromptArgument

type PromptArgument = server.PromptArgument

type PromptInfo

type PromptInfo = server.PromptInfo

type PromptMessage

type PromptMessage = server.PromptMessage

type PromptResult

type PromptResult = server.PromptResult

Prompt types

type RateLimitOption

type RateLimitOption = middleware.RateLimitOption

type RequestSender added in v1.1.0

type RequestSender = server.RequestSender

type ResourceAnnotations

type ResourceAnnotations = server.ResourceAnnotations

type ResourceContent

type ResourceContent = server.ResourceContent

Resource types

type ResourceInfo

type ResourceInfo = server.ResourceInfo

type ResourceTemplateInfo added in v1.2.0

type ResourceTemplateInfo = server.ResourceTemplateInfo

Resource template types

type ResourceUpdatedNotification added in v1.1.0

type ResourceUpdatedNotification = server.ResourceUpdatedNotification

type Role added in v1.1.0

type Role = server.Role

type Root added in v1.1.0

type Root = server.Root

Roots types for workspace awareness

type RootsCapability added in v1.1.0

type RootsCapability = server.RootsCapability

type SamplingMessage added in v1.1.0

type SamplingMessage = server.SamplingMessage

Sampling types for server-initiated LLM completions

type ServeOption

type ServeOption func(*serveOptions)

ServeOption configures how the server is run.

func WithLogger

func WithLogger(l Logger) ServeOption

WithLogger sets the logger for the default middleware stack.

func WithMiddleware

func WithMiddleware(m ...Middleware) ServeOption

WithMiddleware adds middleware to the request handling chain.

type Server

type Server = server.Server

Server is the MCP server instance.

func NewServer

func NewServer(info ServerInfo, opts ...Option) *Server

NewServer creates a new MCP server with the given info and options.

type ServerInfo

type ServerInfo = server.Info

ServerInfo contains server metadata exposed to clients.

type Session added in v1.1.0

type Session = server.Session

Session types for bidirectional MCP communication

type SessionOption added in v1.1.0

type SessionOption = server.SessionOption

type SetLevelRequest added in v1.1.0

type SetLevelRequest = server.SetLevelRequest

type ShutdownConfig

type ShutdownConfig = transport.ShutdownConfig

Shutdown configuration for HTTP transports.

type ShutdownManager

type ShutdownManager = transport.ShutdownManager

type SizeLimitOption

type SizeLimitOption = middleware.SizeLimitOption

SizeLimit re-exports for convenience.

type StructuredResult added in v1.9.0

type StructuredResult = server.StructuredResult

Structured result types for tool responses

type SubscribeRequest added in v1.1.0

type SubscribeRequest = server.SubscribeRequest

Subscription types for resource change notifications

type SubscriptionManager added in v1.1.0

type SubscriptionManager = server.SubscriptionManager

type TextContent

type TextContent = server.TextContent

type ToolAnnotations

type ToolAnnotations = server.ToolAnnotations

Annotation types for tools, resources, and prompts

type UnsubscribeRequest added in v1.1.0

type UnsubscribeRequest = server.UnsubscribeRequest

type WebSocketOption

type WebSocketOption = transport.WebSocketOption

WebSocketOption configures the WebSocket transport.

func WithWebSocketReadTimeout

func WithWebSocketReadTimeout(d time.Duration) WebSocketOption

WithWebSocketReadTimeout sets the read timeout for WebSocket messages.

func WithWebSocketWriteTimeout

func WithWebSocketWriteTimeout(d time.Duration) WebSocketOption

WithWebSocketWriteTimeout sets the write timeout for WebSocket messages.

Directories

Path Synopsis
Package client provides an MCP client for connecting to MCP servers.
Package client provides an MCP client for connecting to MCP servers.
examples
basic command
Package main provides a basic example of an MCP server.
Package main provides a basic example of an MCP server.
grpc command
Package main provides an example of an MCP server using gRPC transport.
Package main provides an example of an MCP server using gRPC transport.
http command
Package main demonstrates HTTP transport usage in an MCP server.
Package main demonstrates HTTP transport usage in an MCP server.
middleware command
Package main demonstrates middleware usage in an MCP server.
Package main demonstrates middleware usage in an MCP server.
minimal command
Package main provides a minimal MCP server example.
Package main provides a minimal MCP server example.
prompts command
Package main demonstrates prompt usage in an MCP server.
Package main demonstrates prompt usage in an MCP server.
resources command
Package main demonstrates resource usage in an MCP server.
Package main demonstrates resource usage in an MCP server.
session command
Package main demonstrates v1.1 session features: sampling, roots, and logging.
Package main demonstrates v1.1 session features: sampling, roots, and logging.
Package middleware provides middleware utilities for MCP request handling.
Package middleware provides middleware utilities for MCP request handling.
Package protocol defines the MCP JSON-RPC 2.0 message types and error codes.
Package protocol defines the MCP JSON-RPC 2.0 message types and error codes.
Package schema provides JSON Schema generation from Go types.
Package schema provides JSON Schema generation from Go types.
Package server provides the core MCP server implementation.
Package server provides the core MCP server implementation.
Package testutil provides testing utilities for MCP servers.
Package testutil provides testing utilities for MCP servers.
Package transport provides MCP transport implementations.
Package transport provides MCP transport implementations.
grpc
Package grpc provides MCP transport over gRPC.
Package grpc provides MCP transport over gRPC.

Jump to

Keyboard shortcuts

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