mcp

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2026 License: MIT Imports: 6 Imported by: 1

README

Model Context Protocol (MCP) Implementation

Overview

This package provides a go-zero integration for the Model Context Protocol (MCP) using the official go-sdk. It wraps the official MCP SDK to provide a seamless integration with go-zero's REST server framework.

Features

  • Official SDK Integration: Built on top of the official Model Context Protocol Go SDK
  • No SDK Import Required: Use mcp.AddTool() directly without importing the official SDK
  • go-zero Integration: Seamlessly integrates with go-zero's REST server and configuration system
  • Dual Transport Support:
    • SSE (Server-Sent Events) transport for 2024-11-05 MCP spec
    • Streamable HTTP transport for 2025-03-26 MCP spec
  • CORS Support: Configurable CORS settings for cross-origin requests
  • Type-Safe Tool Handlers: Generic tool handlers with automatic JSON schema generation
  • Prompts and Resources: Full support for MCP prompts and resources

Quick Start

1. Installation
go get github.com/zeromicro/go-zero

Note: The official MCP SDK is a transitive dependency and will be installed automatically. You don't need to import it directly in your code.

2. Configuration

Create a configuration file config.yaml:

name: my-mcp-server
host: localhost
port: 8080
mcp:
  name: my-mcp-server
  version: 1.0.0
  useStreamable: false  # Use SSE transport (default), set to true for Streamable HTTP
  sseEndpoint: /sse
  messageEndpoint: /message
  sseTimeout: 24h
  messageTimeout: 30s
  cors:
    - http://localhost:3000
3. Create Your Server
package main

import (
	"context"
	"log"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/mcp"
)

type GreetArgs struct {
	Name string `json:"name" jsonschema:"description=Name of the person to greet"`
}

func main() {
	// Load configuration
	var c mcp.McpConf
	conf.MustLoad("config.yaml", &c)

	// Create MCP server
	server := mcp.NewMcpServer(c)

	// Register a tool with automatic schema generation using the SDK directly
	tool := &mcp.Tool{
		Name:        "greet",
		Description: "Greet someone by name",
	}

	handler := func(ctx context.Context, req *mcp.CallToolRequest, args GreetArgs) (*mcp.CallToolResult, any, error) {
		return &mcp.CallToolResult{
			Content: []mcp.Content{
				&mcp.TextContent{Text: "Hello, " + args.Name + "!"},
			},
		}, nil, nil
	}

	// Register tool with type-safe generics - no need to import official SDK
	mcp.AddTool(server, tool, handler)

	// Start server
	defer server.Stop()
	server.Start()
}

Adding Tools

Tools are functions that the MCP client can call. The SDK automatically generates JSON schemas from your struct tags. Use sdkmcp.AddTool with the server's underlying SDK server:

type CalculateArgs struct {
	Operation string  `json:"operation" jsonschema:"enum=add,enum=subtract,enum=multiply,enum=divide"`
	A         float64 `json:"a" jsonschema:"description=First number"`
	B         float64 `json:"b" jsonschema:"description=Second number"`
}

tool := &mcp.Tool{
	Name:        "calculate",
	Description: "Perform arithmetic operations",
}

handler := func(ctx context.Context, req *mcp.CallToolRequest, args CalculateArgs) (*mcp.CallToolResult, any, error) {
	var result float64
	switch args.Operation {
	case "add":
		result = args.A + args.B
	case "subtract":
		result = args.A - args.B
	case "multiply":
		result = args.A * args.B
	case "divide":
		if args.B == 0 {
			return &mcp.CallToolResult{IsError: true}, nil, fmt.Errorf("division by zero")
		}
		result = args.A / args.B
	}

	return &mcp.CallToolResult{
		Content: []mcp.Content{
			&mcp.TextContent{Text: fmt.Sprintf("Result: %v", result)},
		},
	}, result, nil
}

// Register tool
mcp.AddTool(server, tool, handler)

Adding Prompts

Prompts provide reusable message templates:

prompt := &mcp.Prompt{
	Name:        "code-review",
	Description: "Review code for best practices",
}

handler := func(ctx context.Context, req *sdkmcp.GetPromptRequest, args map[string]string) (*mcp.GetPromptResult, error) {
	code := args["code"]
	language := args["language"]

	return &mcp.GetPromptResult{
		Messages: []mcp.PromptMessage{
			{
				Role: "user",
				Content: &mcp.TextContent{
					Text: fmt.Sprintf("Please review this %s code:\n\n%s", language, code),
				},
			},
		},
	}, nil
}

server.AddPrompt(prompt, handler)

Adding Resources

Resources provide access to data that the model can read:

resource := &mcp.Resource{
	URI:         "file:///docs/readme.md",
	Name:        "README",
	Description: "Project documentation",
	MimeType:    "text/markdown",
}

handler := func(ctx context.Context, req *sdkmcp.ReadResourceRequest, uri string) (*mcp.ReadResourceResult, error) {
	content, err := os.ReadFile("README.md")
	if err != nil {
		return nil, err
	}

	return &mcp.ReadResourceResult{
		Contents: []mcp.ResourceContents{
			{
				URI:      uri,
				MimeType: "text/markdown",
				Text:     string(content),
			},
		},
	}, nil
}

server.AddResource(resource, handler)

Transport Options

SSE Transport (Default)

The SSE (Server-Sent Events) transport is the original MCP transport from the 2024-11-05 specification:

mcp:
  useStreamable: false
  sseEndpoint: /sse
Streamable HTTP Transport

The newer Streamable HTTP transport from the 2025-03-26 specification provides better connection management:

mcp:
  useStreamable: true
  messageEndpoint: /message

Configuration Options

Field Type Default Description
name string Server name (required, from RestConf)
host string Server host (required, from RestConf)
port int Server port (required, from RestConf)
mcp.name string MCP server name (defaults to name)
mcp.version string 1.0.0 Server version
mcp.useStreamable bool false Use Streamable HTTP transport instead of SSE
mcp.sseEndpoint string /sse SSE endpoint path
mcp.messageEndpoint string /message Message endpoint path
mcp.sseTimeout duration 24h SSE connection timeout
mcp.messageTimeout duration 30s Message processing timeout
mcp.cors []string Allowed CORS origins

Examples

See the adhoc/mcp directory for a complete working example.

Official SDK Documentation

For more details on the underlying MCP SDK, see:

License

This implementation follows the go-zero project license (MIT).

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddTool added in v1.10.0

func AddTool[In, Out any](server McpServer, tool *Tool, handler func(context.Context, *CallToolRequest, In) (*CallToolResult, Out, error))

AddTool registers a tool with the MCP server using type-safe generics. The SDK automatically generates JSON schema from the Args struct tags.

Example:

type GreetArgs struct {
    Name string `json:"name" jsonschema:"description=Name to greet"`
}

tool := &mcp.Tool{
    Name: "greet",
    Description: "Greet someone",
}

handler := func(ctx context.Context, req *mcp.CallToolRequest, args GreetArgs) (*mcp.CallToolResult, any, error) {
    return &mcp.CallToolResult{
        Content: []mcp.Content{&mcp.TextContent{Text: "Hello " + args.Name}},
    }, nil, nil
}

mcp.AddTool(server, tool, handler)

Types

type AudioContent

type AudioContent = sdkmcp.AudioContent

Re-export commonly used SDK types for convenience

type CallToolParams added in v1.10.0

type CallToolParams = sdkmcp.CallToolParams

Re-export commonly used SDK types for convenience

type CallToolRequest added in v1.10.0

type CallToolRequest = sdkmcp.CallToolRequest

Re-export commonly used SDK types for convenience

type CallToolResult

type CallToolResult = sdkmcp.CallToolResult

Re-export commonly used SDK types for convenience

type Content added in v1.10.0

type Content = sdkmcp.Content

Content types

type GetPromptParams added in v1.10.0

type GetPromptParams = sdkmcp.GetPromptParams

Re-export commonly used SDK types for convenience

type GetPromptResult added in v1.10.0

type GetPromptResult = sdkmcp.GetPromptResult

Re-export commonly used SDK types for convenience

type ImageContent

type ImageContent = sdkmcp.ImageContent

Re-export commonly used SDK types for convenience

type Implementation added in v1.10.0

type Implementation = sdkmcp.Implementation

Re-export commonly used SDK types for convenience

type McpConf

type McpConf struct {
	rest.RestConf
	Mcp struct {
		// Name is the server name reported in initialize responses
		Name string `json:",optional"`

		// Version is the server version reported in initialize responses
		Version string `json:",default=1.0.0"`

		// UseStreamable when true uses Streamable HTTP transport (2025-03-26 spec),
		// otherwise uses SSE transport (2024-11-05 spec)
		UseStreamable bool `json:",default=false"`

		// SseEndpoint is the path for Server-Sent Events connections
		// Used for SSE transport mode
		SseEndpoint string `json:",default=/sse"`

		// MessageEndpoint is the path for JSON-RPC requests
		// Used for Streamable HTTP transport mode
		MessageEndpoint string `json:",default=/message"`

		// Cors contains allowed CORS origins
		Cors []string `json:",optional"`

		// SseTimeout is the maximum time allowed for SSE connections
		SseTimeout time.Duration `json:",default=24h"`

		// MessageTimeout is the maximum time allowed for request execution
		MessageTimeout time.Duration `json:",default=30s"`
	}
}

McpConf defines the configuration for an MCP server. It embeds rest.RestConf for HTTP server settings and adds MCP-specific configuration options.

type McpServer

type McpServer interface {
	// Start starts the HTTP server
	Start()
	// Stop stops the HTTP server
	Stop()
}

McpServer defines the interface for Model Context Protocol servers using the official SDK

func NewMcpServer

func NewMcpServer(c McpConf) McpServer

NewMcpServer creates a new MCP server using the official SDK

type Prompt

type Prompt = sdkmcp.Prompt

Prompt types

type PromptHandler

type PromptHandler func(
	ctx context.Context,
	req *sdkmcp.GetPromptRequest,
	args map[string]string,
) (*GetPromptResult, error)

PromptHandler is a function signature for prompt handlers.

type PromptMessage

type PromptMessage = sdkmcp.PromptMessage

Re-export commonly used SDK types for convenience

type ReadResourceParams added in v1.10.0

type ReadResourceParams = sdkmcp.ReadResourceParams

Re-export commonly used SDK types for convenience

type ReadResourceResult added in v1.10.0

type ReadResourceResult = sdkmcp.ReadResourceResult

Re-export commonly used SDK types for convenience

type Resource

type Resource = sdkmcp.Resource

Resource types

type ResourceContents added in v1.10.0

type ResourceContents = sdkmcp.ResourceContents

Re-export commonly used SDK types for convenience

type ResourceHandler

type ResourceHandler func(
	ctx context.Context,
	req *sdkmcp.ReadResourceRequest,
	uri string,
) (*ReadResourceResult, error)

ResourceHandler is a function signature for resource handlers.

type SSEHandler added in v1.10.0

type SSEHandler = sdkmcp.SSEHandler

Transport types

type Server added in v1.10.0

type Server = sdkmcp.Server

Session and server types

type ServerOptions added in v1.10.0

type ServerOptions = sdkmcp.ServerOptions

Re-export commonly used SDK types for convenience

type ServerSession added in v1.10.0

type ServerSession = sdkmcp.ServerSession

Re-export commonly used SDK types for convenience

type StreamableHTTPHandler added in v1.10.0

type StreamableHTTPHandler = sdkmcp.StreamableHTTPHandler

Re-export commonly used SDK types for convenience

type TextContent

type TextContent = sdkmcp.TextContent

Re-export commonly used SDK types for convenience

type Tool

type Tool = sdkmcp.Tool

Tool types

type ToolHandler deprecated

type ToolHandler[Args any, Meta any] func(
	ctx context.Context,
	req *CallToolRequest,
	args Args,
) (*CallToolResult, Meta, error)

ToolHandler is a generic function signature for tool handlers. Handlers should accept context, request, and typed arguments, and return a result, metadata, and error.

Deprecated: Use ToolHandlerFor directly from the SDK types.

Jump to

Keyboard shortcuts

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