pidl

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 7 Imported by: 0

README

PIDL

Go CI Go Lint Go SAST Go Report Card Docs Visualization License

Protocol Interaction Description Language - A JSON-based DSL for describing protocol choreography that compiles to diagrams.

PIDL models protocols as directed interaction graphs between entities, enabling generation of sequence diagrams, data flow diagrams, and other visualizations. It's designed for protocols where the primary concern is "who talks to whom, in what order" rather than message schemas or transport details.

Features

  • 📋 JSON-based DSL for describing protocol flows
  • 🎨 Multiple output formats: PlantUML, Mermaid, Graphviz DOT, D2
  • 📚 Built-in examples: OAuth 2.0, PKCE, OIDC, MCP, A2A
  • ⌨️ CLI tool for validation and diagram generation
  • 📦 Go library for programmatic use
  • 🔀 Conditional flows with condition field for when clauses
  • 🔄 Alternative paths with alternatives for error handling and branching
  • 📝 Annotations with typed notes (security, performance, deprecated, etc.)
  • 📊 Nested phases with parent hierarchy support

Installation

go install github.com/grokify/pidl/cmd/pidl@latest

Or clone and build:

git clone https://github.com/grokify/pidl.git
cd pidl
go build -o pidl ./cmd/pidl

Quick Start

List available examples
pidl examples
Generate a diagram from an example
# PlantUML sequence diagram
pidl generate oauth2_authorization_code

# Mermaid sequence diagram
pidl generate -f mermaid oauth2_pkce

# Graphviz DOT data flow diagram
pidl generate -f dot mcp_tool_invocation

# D2 sequence diagram
pidl generate -f d2 oauth2_pkce

# D2 data flow diagram
pidl generate -f d2-flow oauth2_pkce

# D2 architecture diagram
pidl generate -f d2-arch oauth2_pkce
Create a new protocol file
# Create from scratch
pidl init my-protocol.json

# Copy from an example
pidl init -from oauth2_authorization_code my-oauth.json
Validate protocol files
pidl validate my-protocol.json
pidl validate *.json

PIDL Format

A PIDL document is a JSON file with three main sections:

{
  "protocol": {
    "id": "my-protocol",
    "name": "My Protocol",
    "version": "1.0",
    "description": "A sample protocol",
    "category": "auth"
  },
  "entities": [
    {"id": "client", "name": "Client", "type": "client"},
    {"id": "server", "name": "Server", "type": "server"}
  ],
  "phases": [
    {"id": "main", "name": "Main Flow"},
    {"id": "error_handling", "name": "Error Handling", "parent": "main"}
  ],
  "flows": [
    {
      "from": "client",
      "to": "server",
      "action": "request",
      "label": "Request",
      "mode": "request",
      "phase": "main",
      "condition": "token_valid",
      "note": "Requires valid token",
      "annotations": [
        {"type": "security", "text": "Validate token signature"}
      ],
      "alternatives": [
        {
          "condition": "token_expired",
          "flows": [
            {"from": "server", "to": "client", "action": "refresh_required", "mode": "response"}
          ]
        }
      ]
    },
    {"from": "server", "to": "client", "action": "response", "label": "Response", "mode": "response", "phase": "main"}
  ]
}
Entity Types
Type Description
client Application or service initiating requests
authorization_server Issues tokens and handles authentication
resource_server Hosts protected resources
user Human actor
browser User agent / web browser
agent AI/LLM agent
tool_server Exposes tools via protocol (MCP)
delegated_agent Agent receiving delegated tasks (A2A)
Flow Modes
Mode Description Arrow Style
request Synchronous request Solid ->
response Synchronous response Dashed -->
redirect HTTP redirect Solid with annotation
callback Callback/webhook Solid with annotation
interactive Human interaction Solid
event Asynchronous event Dashed
tool_call Tool invocation (MCP) Solid with annotation
tool_result Tool result (MCP) Dashed with annotation
Flow Extensions
Field Description
condition Conditional execution clause (renders as opt block)
note Visible note displayed on diagram
annotations Array of typed annotations for tooling
alternatives Alternative paths (renders as alt/else blocks)
Annotation Types
Type Description
security Security-related notes
performance Performance considerations
deprecated Deprecated functionality
info General information
warning Warning messages
error Error conditions
Nested Phases

Phases support hierarchical nesting via the parent field:

{
  "phases": [
    {"id": "auth", "name": "Authentication"},
    {"id": "mfa", "name": "Multi-Factor Auth", "parent": "auth"},
    {"id": "token", "name": "Token Exchange", "parent": "auth"}
  ]
}

CLI Reference

pidl <command> [options] [arguments]

Commands:
  validate   Validate PIDL JSON files
  generate   Generate diagrams from PIDL files
  examples   List or show built-in examples
  init       Create a new PIDL file from template
  version    Print version information
  help       Show help message
validate
pidl validate [options] <file> [file...]

Options:
  -q    Quiet mode (only show errors)
generate
pidl generate [options] <file>

Options:
  -f string   Output format: plantuml, mermaid, dot, d2, d2-flow, d2-arch (default "plantuml")
  -o string   Output file (default: stdout)

D2 formats:

  • d2 - Sequence diagram
  • d2-flow - Data flow diagram with entity shapes
  • d2-arch - Architecture diagram with entities grouped by type
examples
pidl examples [options] [name]

Options:
  -json   Show example JSON content
init
pidl init [options] <filename>

Options:
  -name string   Protocol name
  -from string   Initialize from example

Go Library

import (
    "github.com/grokify/pidl"
    "github.com/grokify/pidl/render"
    "github.com/grokify/pidl/examples"
)

// Parse a PIDL file
p, err := pidl.ParseFile("protocol.json")

// Validate
if errs := p.Validate(); errs.HasErrors() {
    log.Fatal(errs)
}

// Generate PlantUML
diagram, err := render.RenderString(render.FormatPlantUML, p)

// Use built-in examples
names := examples.List()
oauth, err := examples.GetProtocol("oauth2_authorization_code")

// Create a new protocol
p := pidl.NewMinimalProtocol("my-protocol", "My Protocol")
pidl.WriteProtocolFile("output.json", p)

Built-in Examples

Example Protocol
oauth2_authorization_code OAuth 2.0 Authorization Code Flow
oauth2_pkce OAuth 2.0 with PKCE
oidc_authentication OpenID Connect Authentication
mcp_tool_invocation MCP Tool Invocation
a2a_agent_delegation A2A Agent Delegation

Target Protocols

PIDL is designed for describing:

  • Authentication/Authorization: OAuth 2.0, OpenID Connect, SAML
  • Agent Protocols: MCP (Model Context Protocol), A2A (Agent-to-Agent)
  • API Flows: Multi-party API choreography

Documentation

License

MIT License - see LICENSE for details.

Documentation

Overview

Package pidl provides types and utilities for the Protocol Interaction Description Language. PIDL is a JSON-based DSL for describing protocol choreography that compiles to diagrams.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsValidAnnotationType added in v0.2.0

func IsValidAnnotationType(t AnnotationType) bool

IsValidAnnotationType checks if the annotation type is valid.

func SanitizeID

func SanitizeID(s string) string

SanitizeID converts a string to a valid PIDL ID (lowercase, alphanumeric, underscores/hyphens).

func TitleCase

func TitleCase(s string) string

TitleCase converts a string to title case (first letter of each word capitalized).

func ValidateFile

func ValidateFile(filename string) (*Protocol, ValidationErrors, error)

ValidateFile parses and validates a PIDL file, returning any validation errors.

func WriteProtocolFile

func WriteProtocolFile(filename string, p *Protocol) error

WriteProtocolFile writes a protocol to a file as formatted JSON.

Types

type Alternative added in v0.2.0

type Alternative struct {
	// Condition describes when this alternative is taken.
	Condition string `json:"condition"`

	// Flows are the steps in this alternative path.
	Flows []Flow `json:"flows"`

	// Description provides additional context.
	Description string `json:"description,omitempty"`
}

Alternative represents an alternative path in the flow.

type Annotation added in v0.2.0

type Annotation struct {
	// Type categorizes the annotation.
	Type AnnotationType `json:"type"`

	// Text is the annotation message.
	Text string `json:"text"`

	// Details provides additional context.
	Details string `json:"details,omitempty"`
}

Annotation represents a typed annotation on a flow.

type AnnotationType added in v0.2.0

type AnnotationType string

AnnotationType represents the type of annotation.

const (
	AnnotationTypeSecurity    AnnotationType = "security"
	AnnotationTypePerformance AnnotationType = "performance"
	AnnotationTypeDeprecated  AnnotationType = "deprecated"
	AnnotationTypeInfo        AnnotationType = "info"
	AnnotationTypeWarning     AnnotationType = "warning"
	AnnotationTypeError       AnnotationType = "error"
)

type Category

type Category string

Category represents the protocol category.

const (
	CategoryAuth         Category = "auth"
	CategoryAgent        Category = "agent"
	CategoryMessaging    Category = "messaging"
	CategoryProvisioning Category = "provisioning"
	CategoryOther        Category = "other"
)

type Entity

type Entity struct {
	// ID is the unique identifier used in flow references.
	ID string `json:"id"`

	// Name is the human-readable display name.
	Name string `json:"name"`

	// Type classifies the entity.
	Type EntityType `json:"type"`

	// Description of the entity's role.
	Description string `json:"description,omitempty"`
}

Entity represents a participant in the protocol.

type EntityType

type EntityType string

EntityType represents the type of an entity.

const (
	EntityTypeClient              EntityType = "client"
	EntityTypeAuthorizationServer EntityType = "authorization_server"
	EntityTypeResourceServer      EntityType = "resource_server"
	EntityTypeUser                EntityType = "user"
	EntityTypeBrowser             EntityType = "browser"
	EntityTypeAgent               EntityType = "agent"
	EntityTypeToolServer          EntityType = "tool_server"
	EntityTypeTool                EntityType = "tool"
	EntityTypeDelegatedAgent      EntityType = "delegated_agent"
	EntityTypeIdentityProvider    EntityType = "identity_provider"
	EntityTypeServiceProvider     EntityType = "service_provider"
	EntityTypeServer              EntityType = "server"
	EntityTypeOther               EntityType = "other"
)

type FileValidationResult

type FileValidationResult struct {
	Filename string
	Protocol *Protocol
	Errors   ValidationErrors
	ParseErr error
}

FileValidationResult contains the result of validating a single file.

func ValidateFiles

func ValidateFiles(filenames []string) []FileValidationResult

ValidateFiles validates multiple PIDL files, returning results for each.

func (FileValidationResult) IsValid

func (r FileValidationResult) IsValid() bool

IsValid returns true if the file parsed and validated successfully.

type Flow

type Flow struct {
	// From is the source entity ID.
	From string `json:"from"`

	// To is the target entity ID.
	To string `json:"to"`

	// Action identifies the action being performed.
	Action string `json:"action"`

	// Label is the display label (defaults to Action).
	Label string `json:"label,omitempty"`

	// Mode is the interaction mode.
	Mode FlowMode `json:"mode,omitempty"`

	// Phase is the phase ID this flow belongs to.
	Phase string `json:"phase,omitempty"`

	// Description provides additional details.
	Description string `json:"description,omitempty"`

	// Sequence provides explicit ordering.
	Sequence int `json:"sequence,omitempty"`

	// Condition specifies when this flow is executed (e.g., "token_valid", "error").
	Condition string `json:"condition,omitempty"`

	// Note is a visible annotation displayed on the diagram.
	Note string `json:"note,omitempty"`

	// Annotations are typed annotations for tooling and documentation.
	Annotations []Annotation `json:"annotations,omitempty"`

	// Alternatives are alternative paths from this flow point.
	Alternatives []Alternative `json:"alternatives,omitempty"`
}

Flow represents an interaction between two entities.

func (Flow) DisplayLabel

func (f Flow) DisplayLabel() string

DisplayLabel returns the label for display, falling back to Action if Label is empty.

func (Flow) EffectiveMode

func (f Flow) EffectiveMode() FlowMode

EffectiveMode returns the flow mode, defaulting to FlowModeRequest if empty.

func (Flow) HasAlternatives added in v0.2.0

func (f Flow) HasAlternatives() bool

HasAlternatives returns true if the flow has alternative paths.

func (Flow) HasAnnotations added in v0.2.0

func (f Flow) HasAnnotations() bool

HasAnnotations returns true if the flow has annotations.

func (Flow) HasCondition added in v0.2.0

func (f Flow) HasCondition() bool

HasCondition returns true if the flow has a condition.

func (Flow) HasNote added in v0.2.0

func (f Flow) HasNote() bool

HasNote returns true if the flow has a note.

type FlowMode

type FlowMode string

FlowMode represents the type of interaction.

const (
	FlowModeRequest     FlowMode = "request"
	FlowModeResponse    FlowMode = "response"
	FlowModeRedirect    FlowMode = "redirect"
	FlowModeCallback    FlowMode = "callback"
	FlowModeInteractive FlowMode = "interactive"
	FlowModeEvent       FlowMode = "event"
	FlowModeToolCall    FlowMode = "tool_call"
	FlowModeToolResult  FlowMode = "tool_result"
)

type Phase

type Phase struct {
	// ID is the unique identifier.
	ID string `json:"id"`

	// Name is the human-readable name.
	Name string `json:"name"`

	// Description of the phase.
	Description string `json:"description,omitempty"`

	// Parent is the ID of the parent phase for nested phases.
	Parent string `json:"parent,omitempty"`
}

Phase represents a logical grouping of flows.

type Protocol

type Protocol struct {
	// ProtocolMeta contains metadata about the protocol.
	ProtocolMeta ProtocolMeta `json:"protocol"`

	// Entities are the participants in the protocol (systems, actors, services).
	Entities []Entity `json:"entities"`

	// Phases provide optional logical grouping of flows.
	Phases []Phase `json:"phases,omitempty"`

	// Flows are the interactions between entities.
	Flows []Flow `json:"flows"`
}

Protocol represents a complete PIDL document describing a protocol's choreography.

func MustParse

func MustParse(data []byte) *Protocol

MustParse parses PIDL JSON data and panics on error. Use only in tests or initialization code.

func MustParseFile

func MustParseFile(filename string) *Protocol

MustParseFile reads and parses a PIDL JSON file, panicking on error. Use only in tests or initialization code.

func NewMinimalProtocol

func NewMinimalProtocol(id, name string) *Protocol

NewMinimalProtocol creates a minimal valid protocol scaffold.

func NewProtocol

func NewProtocol(id, name string) *Protocol

NewProtocol creates a new Protocol with the given ID and name.

func Parse

func Parse(data []byte) (*Protocol, error)

Parse parses PIDL JSON data into a Protocol.

func ParseFile

func ParseFile(filename string) (*Protocol, error)

ParseFile reads and parses a PIDL JSON file.

func ParseReader

func ParseReader(r io.Reader) (*Protocol, error)

ParseReader parses PIDL JSON from an io.Reader.

func (*Protocol) ChildPhases added in v0.2.0

func (p *Protocol) ChildPhases(parentID string) []Phase

ChildPhases returns phases that have the given parent ID.

func (*Protocol) EntityByID

func (p *Protocol) EntityByID(id string) *Entity

EntityByID returns the entity with the given ID, or nil if not found.

func (*Protocol) EntityIDs

func (p *Protocol) EntityIDs() []string

EntityIDs returns a slice of all entity IDs.

func (*Protocol) FlowsByPhase

func (p *Protocol) FlowsByPhase(phaseID string) []Flow

FlowsByPhase returns all flows belonging to the given phase.

func (*Protocol) IsValid

func (p *Protocol) IsValid() bool

IsValid returns true if the Protocol passes validation.

func (*Protocol) PhaseByID

func (p *Protocol) PhaseByID(id string) *Phase

PhaseByID returns the phase with the given ID, or nil if not found.

func (*Protocol) PhaseDepth added in v0.2.0

func (p *Protocol) PhaseDepth(phaseID string) int

PhaseDepth returns the nesting depth of a phase (0 for root phases).

func (*Protocol) PhaseIDs

func (p *Protocol) PhaseIDs() []string

PhaseIDs returns a slice of all phase IDs.

func (*Protocol) RootPhases added in v0.2.0

func (p *Protocol) RootPhases() []Phase

RootPhases returns phases that have no parent (top-level phases).

func (*Protocol) ToJSON

func (p *Protocol) ToJSON() ([]byte, error)

ToJSON serializes a Protocol to JSON with indentation.

func (*Protocol) ToJSONCompact

func (p *Protocol) ToJSONCompact() ([]byte, error)

ToJSONCompact serializes a Protocol to compact JSON.

func (*Protocol) Validate

func (p *Protocol) Validate() ValidationErrors

Validate checks the Protocol for errors and returns all found issues.

func (*Protocol) WriteFile

func (p *Protocol) WriteFile(filename string) error

WriteFile writes the Protocol to a file as JSON.

type ProtocolMeta

type ProtocolMeta struct {
	// ID is the unique identifier for the protocol.
	ID string `json:"id"`

	// Name is the human-readable name.
	Name string `json:"name"`

	// Version of this protocol description.
	Version string `json:"version,omitempty"`

	// Description provides a brief summary.
	Description string `json:"description,omitempty"`

	// Category classifies the protocol type.
	Category Category `json:"category,omitempty"`

	// References links to relevant specifications.
	References []Reference `json:"references,omitempty"`
}

ProtocolMeta contains metadata about a protocol.

type Reference

type Reference struct {
	// Name of the reference (e.g., "RFC 6749").
	Name string `json:"name"`

	// URL to the reference.
	URL string `json:"url"`
}

Reference links to external documentation.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a validation error with context.

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors is a collection of validation errors.

func (ValidationErrors) Error

func (e ValidationErrors) Error() string

func (ValidationErrors) HasErrors

func (e ValidationErrors) HasErrors() bool

HasErrors returns true if there are any validation errors.

Directories

Path Synopsis
cmd
pidl command
Command pidl is the CLI tool for the Protocol Interaction Description Language.
Command pidl is the CLI tool for the Protocol Interaction Description Language.
Package examples provides embedded PIDL example protocols.
Package examples provides embedded PIDL example protocols.
Package render provides diagram renderers for PIDL protocols.
Package render provides diagram renderers for PIDL protocols.
Package schema provides the embedded PIDL JSON Schema.
Package schema provides the embedded PIDL JSON Schema.

Jump to

Keyboard shortcuts

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