pidl

package module
v0.1.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
  • 📚 Built-in examples: OAuth 2.0, PKCE, OIDC, MCP, A2A
  • ⌨️ CLI tool for validation and diagram generation
  • 📦 Go library for programmatic use

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
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"}
  ],
  "flows": [
    {"from": "client", "to": "server", "action": "request", "label": "Request", "mode": "request", "phase": "main"},
    {"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

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 (default "plantuml")
  -o string   Output file (default: stdout)
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 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 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"`
}

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.

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"`
}

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) 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) PhaseIDs

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

PhaseIDs returns a slice of all phase IDs.

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