Protocol Buffers has been able to evolve and support so many languages largely because of its plugin system. Plugins can be written in any language and can output pretty much anything you want, from code and documentation to other schema formats.
How plugins work is still a bit arcane because the details are scattered across the comments of google/protobuf/compiler/plugin.proto and the descriptor reference. Most people end up copying an existing plugin and hacking on it until it does what they want. This post covers how the plugin protocol works and walks through building a simple Protobuf plugin from scratch.
The protocol
When you run buf generate, the Buf CLI executes the plugins listed in buf.gen.yaml. local: names a plugin binary on your PATH (or a local file path). Plugin binaries are conventionally named protoc-gen-<name> because protoc looks for protoc-gen-summary when you pass --summary_out:
version: v2
plugins:
- local: protoc-gen-summary
out: genThat entry needs a protoc-gen-summary binary on your PATH. local: also accepts a command with arguments, and the example project uses that to run every plugin in this post with go run.
The Buf CLI writes a CodeGeneratorRequest message to the plugin’s standard input and reads a CodeGeneratorResponse from standard output, while standard error goes straight to the terminal, which makes it useful for logging and debugging. If a plugin writes anything else to stdout, the plugin run is broken and the Buf CLI or protoc will show an error.
By default, buf generate invokes a local plugin once per directory so it can run jobs in parallel, and each run’s file_to_generate lists only the files in that directory. That works well for plugins that write one output file per input file, which is the most typical case. If your plugin needs all input files in a single invocation (for example, to write one combined documentation file), set strategy: all on the plugin entry in buf.gen.yaml.
The messages used for plugin input and output, specified in plugin.proto, are pretty simple. Here they are without the comments, the Version message, or the Feature enum:
message CodeGeneratorRequest {
repeated string file_to_generate = 1;
optional string parameter = 2;
repeated FileDescriptorProto proto_file = 15;
repeated FileDescriptorProto source_file_descriptors = 17;
optional Version compiler_version = 3;
}
message CodeGeneratorResponse {
optional string error = 1;
optional uint64 supported_features = 2;
optional int32 minimum_edition = 3;
optional int32 maximum_edition = 4;
message File {
optional string name = 1;
optional string insertion_point = 2;
optional string content = 15;
optional GeneratedCodeInfo generated_code_info = 16;
}
repeated File file = 15;
}Both messages use Protobuf’s binary wire format. In the request, file_to_generate is the list of .proto files the plugin should generate code for, and proto_file has a FileDescriptorProto for each of those files plus everything they import.
A plugin’s output files all go back in the response. Each one is a CodeGeneratorResponse.File with a path (relative to out: in buf.gen.yaml) and the contents, and it’s the Buf CLI or protoc that writes them to disk.
Plugins don’t get command-line flags. Plugin options come in through CodeGeneratorRequest.parameter. In buf.gen.yaml, you set them with the opt key (here with two of protoc-gen-go’s options):
version: v2
plugins:
- local: protoc-gen-go
out: gen
opt:
- paths=source_relative
- default_api_level=API_OPAQUEbuf generate joins those entries with commas into a single string ("paths=source_relative,default_api_level=API_OPAQUE") and puts it in CodeGeneratorRequest.parameter.
The comments in plugin.proto describe every field in full, including the ones we didn’t detail above.
From scratch in Go
For our first example, we’ll build protoc-gen-summary, which writes a .summary.md file for each proto file with a Markdown table for every top-level message and a row per field. For message fields, we also print the path of the file that defined the message. Since that message might come from an import, we pass all of proto_file to the descriptor loader, then loop only over file_to_generate when writing Markdown. The example project at the end of this post has a pet.proto that imports owner.proto. For pet.proto, the plugin writes:
# acme/pet/v1/pet.proto
## Pet
| # | Field | Type | Defined in |
| --- | --- | --- | --- |
| 1 | name | string | |
| 2 | age | int32 | |
| 3 | owner | acme.pet.v1.Owner | acme/pet/v1/owner.proto |Here is the plugin’s main.go, up to the end of run(). It only depends on google.golang.org/protobuf and the whole thing fits in under 100 lines. It needs Go 1.26 or newer for new with a value, like new("text"), which the examples use to set optional fields:
package main
import (
"fmt"
"io"
"os"
"strings"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/pluginpb"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "protoc-gen-summary:", err)
os.Exit(1)
}
}
func run() error {
input, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
request := &pluginpb.CodeGeneratorRequest{}
if err := proto.Unmarshal(input, request); err != nil {
return err
}
files, err := protodesc.NewFiles(&descriptorpb.FileDescriptorSet{
File: request.GetProtoFile(),
})
if err != nil {
return err
}
response := &pluginpb.CodeGeneratorResponse{
SupportedFeatures: new(uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL |
pluginpb.CodeGeneratorResponse_FEATURE_SUPPORTS_EDITIONS)),
MinimumEdition: new(int32(descriptorpb.Edition_EDITION_PROTO2)),
MaximumEdition: new(int32(descriptorpb.Edition_EDITION_2024)),
}
for _, name := range request.GetFileToGenerate() {
file, err := files.FindFileByPath(name)
if err != nil {
return err
}
response.File = append(response.File, &pluginpb.CodeGeneratorResponse_File{
Name: new(strings.TrimSuffix(file.Path(), ".proto") + ".summary.md"),
Content: new(renderFile(file)),
})
}
output, err := proto.Marshal(response)
if err != nil {
return err
}
_, err = os.Stdout.Write(output)
return err
}Show renderFile
func renderFile(file protoreflect.FileDescriptor) string {
var builder strings.Builder
fmt.Fprintf(&builder, "# %s\n\n", file.Path())
messages := file.Messages()
for i := range messages.Len() {
message := messages.Get(i)
fmt.Fprintf(&builder, "## %s\n\n", message.Name())
builder.WriteString("| # | Field | Type | Defined in |\n")
builder.WriteString("| --- | --- | --- | --- |\n")
fields := message.Fields()
for j := range fields.Len() {
field := fields.Get(j)
typeName := field.Kind().String()
definedIn := ""
if fieldMessage := field.Message(); fieldMessage != nil {
typeName = string(fieldMessage.FullName())
definedIn = fieldMessage.ParentFile().Path()
} else if fieldEnum := field.Enum(); fieldEnum != nil {
typeName = string(fieldEnum.FullName())
}
fmt.Fprintf(&builder, "| %d | %s | %s | %s |\n", field.Number(), field.Name(), typeName, definedIn)
}
builder.WriteString("\n")
}
return builder.String()
}Most of run() is required ceremony for stdin and stdout, so we won’t cover that in depth. Instead, we’ll look at how the plugin uses descriptors, handles options, returns errors, and declares edition support.
protoreflect descriptors
You could inspect the raw FileDescriptorProto messages directly, and there are plugins created this way, but it becomes an issue once you have references to types in another file. You would have to index every file and resolve type names yourself, so there is typically a function for converting FileDescriptorProto into usable descriptor data structures that handle all of the type resolution for you. In Go, that function is protodesc.NewFiles:
files, err := protodesc.NewFiles(&descriptorpb.FileDescriptorSet{
File: request.GetProtoFile(),
})protodesc.NewFiles resolves the imports and gives back a tree of protoreflect descriptors:
FileDescriptor (acme/pet/v1/pet.proto)
├── Messages() ──> MessageDescriptor (Pet)
│ ├── Fields() ──> FieldDescriptor (owner)
│ │ └── Message() ──> MessageDescriptor (Owner)
│ │ └── ParentFile() ──> FileDescriptor (acme/pet/v1/owner.proto)
│ ├── Oneofs() ──> OneofDescriptor
│ ├── Messages() ──> MessageDescriptor (nested)
│ └── Enums() ──> EnumDescriptor (nested)
├── Enums() ──> EnumDescriptor
│ └── Values() ──> EnumValueDescriptor
└── Services() ──> ServiceDescriptor
└── Methods() ──> MethodDescriptorInside renderFile, calling field.Message() returns the descriptor for that message type, and ParentFile().Path() gives us the path of the file that defined it:
if fieldMessage := field.Message(); fieldMessage != nil {
typeName = string(fieldMessage.FullName())
definedIn = fieldMessage.ParentFile().Path()
}To stay short, renderFile doesn’t special-case repeated or map fields. There’s a quirk with map fields: field.Message() returns the hidden entry message that Protobuf generates for the map. A pets map prints as PetsEntry. In a real plugin, check field.IsMap() and field.IsList() first.
Plugin options
protoc-gen-summary doesn’t have any options, so it just ignores request.GetParameter(). When you do need to read opt values from buf.gen.yaml without a plugin framework, you split that comma-separated string and handle each key=value pair yourself:
for param := range strings.SplitSeq(request.GetParameter(), ",") {
if param == "" {
continue
}
key, value, _ := strings.Cut(param, "=")
// handle key and value
}Returning errors
In protoc-gen-summary, any error from run() gets printed to stderr and exits with status 1. That makes sense if the plugin can’t process the request, like if it fails to unmarshal stdin. If the user gives your plugin bad input, though, like an invalid option or a .proto file that’s missing an annotation you need, you should populate the Error field on CodeGeneratorResponse and exit 0 instead:
response := &pluginpb.CodeGeneratorResponse{
Error: new("acme/pet/v1/pet.proto: missing required option"),
}When you return an error in the response message, buf generate knows the plugin ran properly and formats the error message for the user instead of reporting a plugin crash.
Supporting Protobuf Editions
protoc-gen-summary also sets three feature and edition fields on CodeGeneratorResponse:
response := &pluginpb.CodeGeneratorResponse{
SupportedFeatures: new(uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL |
pluginpb.CodeGeneratorResponse_FEATURE_SUPPORTS_EDITIONS)),
MinimumEdition: new(int32(descriptorpb.Edition_EDITION_PROTO2)),
MaximumEdition: new(int32(descriptorpb.Edition_EDITION_2024)),
}buf generate checks these fields to verify that your plugin supports the files in the project. FEATURE_PROTO3_OPTIONAL declares support for proto3 optional fields, and FEATURE_SUPPORTS_EDITIONS declares support for Editions. If you leave FEATURE_PROTO3_OPTIONAL out, buf generate only prints a warning when a file has proto3 optional fields. If you leave FEATURE_SUPPORTS_EDITIONS out, generation fails as soon as it sees a file with an edition statement, with one error per file:
Failure: plugin "go run ./go/cmd/protoc-gen-summary" does not support feature "supports editions" which is required by "acme/pet/v1/owner.proto"
plugin "go run ./go/cmd/protoc-gen-summary" does not support feature "supports editions" which is required by "acme/pet/v1/pet.proto"It does the same check against MinimumEdition and MaximumEdition. If you lower MaximumEdition to EDITION_2023 and run protoc-gen-summary against the edition 2024 files in the example project, generation fails with a similar error:
Failure: plugin "go run ./go/cmd/protoc-gen-summary" does not support edition "2024" which is required by "acme/pet/v1/owner.proto"
plugin "go run ./go/cmd/protoc-gen-summary" does not support edition "2024" which is required by "acme/pet/v1/pet.proto"When a file uses Editions, its syntax field is "editions" instead of "proto2" or "proto3", and behaviors like field presence are stored as feature flags on the descriptor. In Go, you don’t have to read those flags yourself. protoreflect resolves features for you, and field.HasPresence() works the same on proto2, proto3, and Editions files. Both Go libraries below hand you protoreflect descriptors, so that holds for them too.
Again with protoplugin
github.com/bufbuild/protoplugin handles stdin and stdout, builds the protoreflect descriptors, and validates generated file paths so you don’t have to write that glue code yourself. Here is the same protoc-gen-summary plugin using it:
Show the protoplugin version
package main
import (
"context"
"fmt"
"strings"
"github.com/bufbuild/protoplugin"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/descriptorpb"
)
func main() {
protoplugin.Main(protoplugin.HandlerFunc(handle))
}
func handle(
_ context.Context,
_ protoplugin.PluginEnv,
responseWriter protoplugin.ResponseWriter,
request protoplugin.Request,
) error {
responseWriter.SetFeatureProto3Optional()
responseWriter.SetFeatureSupportsEditions(descriptorpb.Edition_EDITION_PROTO2, descriptorpb.Edition_EDITION_2024)
files, err := request.FileDescriptorsToGenerate()
if err != nil {
return err
}
for _, file := range files {
responseWriter.AddFile(
strings.TrimSuffix(file.Path(), ".proto")+".summary.md",
renderFile(file),
)
}
return nil
}
// renderFile is the same function as in the from-scratch plugin.renderFile is the same function as before, and it’s left out of the listing. In handle, request.FileDescriptorsToGenerate() replaces protodesc.NewFiles and the path lookup loop. SetFeatureSupportsEditions sets the feature flag plus the minimum and maximum editions in one call. Plugin options are still exposed as the raw comma-separated string through request.Parameter(). One difference from protogen below is that protoplugin isn’t tied to Go code generation, so the input .proto files don’t need Go import paths.
Generating Go with protogen
Plugins that generate Go code alongside protoc-gen-go usually use google.golang.org/protobuf/compiler/protogen, which is the same library protoc-gen-go is built on. It handles Go type names, imports, and the standard Go plugin options for you.
Here is protoc-gen-fieldnames, which writes a _fieldnames.pb.go file for each proto file with the field names of every top-level message. For pet.proto:
// Code generated by protoc-gen-fieldnames. DO NOT EDIT.
// source: acme/pet/v1/pet.proto
package petv1
// PetFieldNames lists the fields of acme.pet.v1.Pet.
var PetFieldNames = []string{
"name",
"age",
"owner",
}Show the protogen version
package main
import (
"strconv"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/pluginpb"
)
func main() {
protogen.Options{}.Run(func(plugin *protogen.Plugin) error {
plugin.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL |
pluginpb.CodeGeneratorResponse_FEATURE_SUPPORTS_EDITIONS)
plugin.SupportedEditionsMinimum = descriptorpb.Edition_EDITION_PROTO2
plugin.SupportedEditionsMaximum = descriptorpb.Edition_EDITION_2024
for _, file := range plugin.Files {
if !file.Generate {
continue
}
out := plugin.NewGeneratedFile(file.GeneratedFilenamePrefix+"_fieldnames.pb.go", file.GoImportPath)
out.P("// Code generated by protoc-gen-fieldnames. DO NOT EDIT.")
out.P("// source: ", file.Desc.Path())
out.P()
out.P("package ", file.GoPackageName)
for _, message := range file.Messages {
name := message.GoIdent.GoName + "FieldNames"
out.P()
out.P("// ", name, " lists the fields of ", message.Desc.FullName(), ".")
out.P("var ", name, " = []string{")
for _, field := range message.Fields {
out.P(strconv.Quote(string(field.Desc.Name())), ",")
}
out.P("}")
}
}
return nil
})
}message.GoIdent.GoName is the struct name protoc-gen-go uses for the message (including parent prefixes for nested messages), and file.GoPackageName is the Go package it belongs to, so our generated slice lands in the same package as the generated struct.
There’s one gotcha with protogen. Every file in the request needs a Go import path, including imports you aren’t generating code for. If one is missing, the plugin fails with unable to determine Go import path. The buf.gen.yaml in Running the examples uses managed mode to set go_package on every file. It also passes paths=source_relative, which puts the output next to the .proto path.
To support custom options alongside the built-in Go flags, pass a ParamFunc in protogen.Options. Its signature matches flag.FlagSet.Set from the standard library:
var flags flag.FlagSet
includeUnexported := flags.Bool("include_unexported", false, "")
protogen.Options{
ParamFunc: flags.Set,
}.Run(func(plugin *protogen.Plugin) error {
// *includeUnexported is populated before this callback runs
return nil
})Without a ParamFunc, unknown options are ignored.
Libraries for other languages
Other Protobuf runtimes have plugin libraries too, each built for generating code in its own language:
@bufbuild/protopluginfor TypeScript and JavaScript.protoc-gen-esis built on itscreateEcmaScriptPlugin, which manages imports and can emit.ts,.js, and.d.tsfrom one generator through thetargetoption. The Protobuf-ES guide to writing plugins walks through building one.google/protobuf/compiler/plugin.hfor C++, which is part oflibprotoc. You implementCodeGenerator, the same interfaceprotoc’s built-in generators implement, pass it toPluginMaininmain(), and link againstlibprotoc.SwiftProtobufPluginLibraryfor Swift, a library target in swift-protobuf.protoc-gen-swiftand grpc-swift’sprotoc-gen-grpc-swift-2are built on it. The library’s docs are pretty short. Those two plugins are the best place to see how it’s used.- The
protobuf.pluginmodule in protobuf-py for Python.protobuf.plugin.runreads the request fromstdinand passes linked descriptors and a typed options dataclass to your generator function, with helper methods on each generated file for tracking Python imports.
Running the examples
The local option in buf.gen.yaml can also be a command with arguments in place of a binary name or path. This is useful for fast iteration and prototyping with Go, using go run instead of needing to build a binary, adjust the path, and so on. One buf.gen.yaml runs all three plugins straight from source:
version: v2
managed:
enabled: true
override:
# protoc-gen-fieldnames writes Go, so every file needs a Go import path.
- file_option: go_package_prefix
value: example.com/gen/go
plugins:
- local: ["go", "run", "./go/cmd/protoc-gen-summary"]
out: gen/raw
- local: ["go", "run", "./go/cmd/protoc-gen-summary-protoplugin"]
out: gen/protoplugin
- local: ["go", "run", "./go/cmd/protoc-gen-fieldnames"]
out: gen/go
opt: paths=source_relativeShow the rest of the example project
Each plugin is a main.go under go/cmd/<plugin name>/, all in one Go module in the go directory. The go.work at the root is what lets go run find that module from the root.
edition = "2024";
package acme.pet.v1;
// A person who owns one or more pets.
message Owner {
string name = 1;
string email = 2;
}edition = "2024";
package acme.pet.v1;
import "acme/pet/v1/owner.proto";
// A pet in the store.
message Pet {
string name = 1;
int32 age = 2;
Owner owner = 3;
}version: v2
modules:
- path: protogo 1.26.0
use ./gomodule example.com/plugins101
go 1.26.0
require google.golang.org/protobuf v1.36.12
require github.com/bufbuild/protoplugin v0.0.0-20260414125817-25d1d281b46bbuf generate from the root fills gen/raw, gen/protoplugin, and gen/go.
Next steps
For a real Go plugin, skip the stdin and stdout handling and start with protoplugin (or protogen if you’re generating Go). And if your organization has a private BSR instance (Pro or above), you can publish the plugin as a custom remote plugin and swap local: for remote: in buf.gen.yaml.