Skip to content

Instantly share code, notes, and snippets.

@HauptJ
Created February 22, 2026 23:10
Show Gist options
  • Select an option

  • Save HauptJ/6784fe287a8e318a76d33ca59ad3784c to your computer and use it in GitHub Desktop.

Select an option

Save HauptJ/6784fe287a8e318a76d33ca59ad3784c to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
func main() {
// Create a new MCP server
s := server.NewMCPServer(
"Calculator Demo",
"1.0.0",
server.WithToolCapabilities(false),
server.WithRecovery(),
)
// Add Hello World tool
helloTool := mcp.NewTool("hello_world",
mcp.WithDescription("Say hello to someone"),
mcp.WithString("name",
mcp.Required(),
mcp.Description("The name of the person to say hello to"),
),
)
// Add Hello World tool handler
s.AddTool(helloTool, helloHandler)
// Add a calculator tool
calculatorTool := mcp.NewTool("calculate",
mcp.WithDescription("Perform basic arithmetic operations"),
mcp.WithString("operation",
mcp.Required(),
mcp.Description("The operation to perform (add, subtract, multiply, divide)"),
mcp.Enum("add", "subtract", "multiply", "divide"),
),
mcp.WithNumber("x",
mcp.Required(),
mcp.Description("First number"),
),
mcp.WithNumber("y",
mcp.Required(),
mcp.Description("Second number"),
),
)
// Add the calculator handler
s.AddTool(calculatorTool, calculatorHandler)
// Start the server
if err := server.ServeStdio(s); err != nil {
fmt.Printf("Server error: %s\n", err)
}
}
func helloHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
name, err := request.RequireString("name")
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
return mcp.NewToolResultText(fmt.Sprintf("Hello %s!", name)), nil
}
func calculatorHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
// Using helper function for type-safe argument access
op, err := request.RequireString("operation")
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
x, err := request.RequireFloat("x")
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
y, err := request.RequireFloat("y")
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
var result float64
switch op {
case "add":
result = x + y
case "subtract":
result = x - y
case "multiply":
result = x * y
case "divide":
if y == 0 {
return mcp.NewToolResultError("Cannot divide by zero"), nil
}
result = x / y
default:
return mcp.NewToolResultError("Invalid operation"), nil
}
return mcp.NewToolResultText(fmt.Sprintf("%f", result)), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment