To implement an MCP (Model Context Protocol) server in Kratos, use the github.com/go-kratos/kratos/contrib/transport/mcp/v3 module. This allows you to define tools using mcp-go and register them with a Kratos server.
Key steps:
- Initialize a new MCP server using
tm.NewServer with a name, version, address, and optional middleware. - Define an MCP tool using
mcp.NewTool with descriptions and argument schemas. - Register a handler function for the tool using
srv.AddTool(tool, handler). - Wrap the server in a Kratos application using
kratos.New and kratos.Server(srv). - Run the application with
app.Run().
import(
tm "github.com/go-kratos/kratos/contrib/transport/mcp/v3"
mcp "github.com/mark3labs/mcp-go/mcp"
)
func helloHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
name, ok := request.Params.Arguments["name"].(string)
if !ok {
return nil, errors.New("name must be a string")
}
return mcp.NewToolResultText(fmt.Sprintf("Hello, %s!", name)), nil
}
func main() {
// 1. Create the MCP server
srv := tm.NewServer("kratos-mcp", "v1.0.0", tm.Address(":8000"), tm.Middleware(Health))
// 2. Define the tool
tool := mcp.NewTool("hello_world",
mcp.WithDescription("Say hello to someone"),
mcp.WithString("name",
mcp.Required(),
mcp.Description("Name of the person to greet"),
),
)
// 3. Add tool handler
srv.AddTool(tool, helloHandler)
// 4. Create Kratos application
app := kratos.New(
kratos.Name("kratos-app"),
kratos.Server(srv),
)
// 5. Run
if err := app.Run(); err != nil {
panic(err)
}
}