---
description: Define domain protocol specification (SDS - Spec-Driven Specification)
---

## User Input

```text
$ARGUMENTS
```

You **MUST** consider the user input before proceeding (if not empty).

## Outline

The text the user typed after `/metaspec.sds.specify` is the **protocol specification description**. 

**PURPOSE: Protocol Specification (SDS)** 🎯

This command is for defining **domain protocols, rules, and standards**:
- Focus: WHAT the protocol is
- Output: `specs/protocol/001-{name}/spec.md`
- Independent of any implementation
- Pure protocol definition

**NOT for toolkit implementation** - Use `/metaspec.sdd.specify` for that.

Follow this execution flow:

### 1. Determine Protocol and Load Existing Specification

**Step 1a: Generate Protocol Name**

Based on user input, generate:
- Short name: `{domain}-{component}-protocol`
- Example: "mcp-core-protocol", "graphql-schema", "oauth2-flow"
- Check existing `specs/protocol/` directory structure

**Step 1b: Find Next Available Number**

```bash
# List existing protocol specs
ls specs/protocol/ | grep -E '^[0-9]{3}-' | sort -n
# Find next number (e.g., if 001, 002 exist, use 003)
```

**Step 1c: Load Existing or Create New**

- Check for `specs/protocol/{number}-{name}/spec.md`
- If exists, load for updating
- If new, create new directory structure

### 2. Gather Protocol Specification Content

**Focus**: Define the domain protocol, entities, schemas, and validation rules.

**Critical Questions**:

1. **Protocol Name**: What is this protocol called?
   - Example: "MCP (Model Context Protocol)"
   
2. **Protocol Purpose**: What problem does this protocol solve?
   - Example: "Enable AI models to interact with external tools and resources"
   
3. **Core Entities**: What are the main entities in this protocol?
   - Example: Server, Tool, Resource, Prompt
   
4. **Entity Schemas**: What fields/properties does each entity have?
   - Example: Tool has `name`, `description`, `inputSchema`
   
5. **Validation Rules**: What are the constraints and requirements?
   - Example: "Tool name must be unique", "inputSchema must be valid JSON Schema"

6. **Protocol Operations**: What operations/interfaces does the protocol define?
   - Example: `initialize`, `tools/list`, `tools/call`

**Important Notes**:
- This is SDS (Spec-Driven Specification) - focus on protocol definition only
- Do NOT include implementation details (Parser, Validator, CLI)
- For toolkit development, use `/metaspec.sdd.specify` instead

**If user input is vague**, make informed guesses based on domain standards and document assumptions.

### 3. Generate Protocol Specification Content

Generate **Domain Protocol Specification** with these sections:

#### **Protocol Overview**
- Protocol name and version
- Problem it solves
- Core capabilities
- Example: "MCP (Model Context Protocol) v1.0 enables standardized communication between AI models and external tools/resources."

#### **Glossary** (Optional but Recommended)

Define key terms used in the protocol to help all audiences understand:

**Template**:
```markdown
## Glossary

- **{Term 1}**: {Clear, concise definition}
  - Example: "Tool: A callable function exposed by the server that can be invoked by AI agents"
  
- **{Term 2}**: {Clear, concise definition}
  - Example: "Resource: A data source or file that can be accessed through the protocol"
  
- **{Term 3}**: {Clear, concise definition}
```

**When to include**:
- Protocol contains domain-specific terminology
- Audience includes non-technical stakeholders
- Terms might be ambiguous or have multiple meanings

**Best practices**:
- Keep definitions concise (1-2 sentences)
- Provide examples where helpful
- Focus on protocol-specific meanings
- Avoid overly technical jargon in definitions

#### **Use Cases** (Optional but Recommended)

Describe real-world scenarios where this protocol applies:

**Template**:
```markdown
## Use Cases

### Use Case 1: {Scenario Name}

**Scenario**: {Brief description of the situation}

**Actors**: {Who/what is involved}
- Actor 1: {Role}
- Actor 2: {Role}

**Flow**:
1. {Step 1}
2. {Step 2}
3. {Step 3}

**Protocol Elements Used**:
- {Entity or Operation 1}
- {Entity or Operation 2}

**Outcome**: {Expected result}

### Use Case 2: {Another Scenario}
...
```

**When to include**:
- Protocol purpose might not be immediately clear
- Need to demonstrate practical value
- Want to guide implementation priorities

**Best practices**:
- Provide 2-4 concrete use cases
- Cover common scenarios
- Show how entities and operations work together
- Keep scenarios realistic and relatable

#### **Core Entities**

Define protocol entities (NOT toolkit entities):

**Template**:
```markdown
### Entity: {EntityName}

**Purpose**: {What this entity represents in the protocol}

**Schema**:
```yaml
entity_name:
  field1:
    type: string
    required: true
    description: {field description}
  field2:
    type: number
    required: false
    description: {field description}
```

**Validation Rules**:
- {Rule 1}
- {Rule 2}

**Example**:
```json
{
  "field1": "example value",
  "field2": 42
}
```
\```

**Repeat for each entity**.

#### **Workflow** (Optional but Recommended for Stateful Protocols)

Define state machines and transition rules for entities with lifecycle:

**When to include**:
- Protocol involves state management (e.g., Order, Session, Device)
- Entities have lifecycle or status changes
- Operations have sequential dependencies
- Need to define allowed/forbidden transitions

**Template**:
```markdown
## Workflow

### State Machine: {Entity Name}

**States**:
- `{state_1}`: {State description}
  - Example: `pending`: Order received, awaiting confirmation
- `{state_2}`: {State description}
  - Example: `confirmed`: Order confirmed, preparing for shipment
- `{state_3}`: {State description}

**Initial State**: `{initial_state}`
**Final States**: `{final_state_1}`, `{final_state_2}`

**Allowed Transitions**:

#### `{state_1}` → `{state_2}`
- **Trigger**: {What causes this transition}
- **Precondition**: {What must be true before transition}
- **Action**: {What happens during transition}
- **Postcondition**: {What must be true after transition}

Example:
#### `pending` → `confirmed`
- **Trigger**: Admin confirms order
- **Precondition**: Payment verified, inventory available
- **Action**: Reserve inventory, send confirmation email
- **Postcondition**: Order status is `confirmed`, inventory reserved

**Forbidden Transitions**:
- ❌ `{state_x}` → `{state_y}`: {Reason why this is forbidden}
  - Example: `confirmed` → `pending`: Cannot un-confirm an order
- ❌ `{state_z}` → `{state_w}`: {Reason}

**Validation Rules**:
1. All transitions must follow allowed paths
2. Preconditions must be satisfied before transition
3. State must be explicitly set (no implicit transitions)
4. {Additional validation rules}

**State Diagram** (Optional):
```mermaid
stateDiagram-v2
    [*] --> state_1
    state_1 --> state_2
    state_2 --> state_3
    state_1 --> cancelled
    state_3 --> [*]
```
\```

**Note**: 
- Multiple entities can have their own state machines
- Define one state machine per entity that has lifecycle
- Focus on protocol-level states (WHAT), not implementation details (HOW)
\```

**Best practices**:
- Keep states minimal (3-7 states is typical)
- Clearly define preconditions and postconditions
- Document why certain transitions are forbidden
- Use clear, business-meaningful state names
- Consider using state diagrams for complex workflows

#### **Protocol Operations**

Define operations/interfaces:

**Template**:
```markdown
### Operation: {operation_name}

**Purpose**: {What this operation does}

**Request Schema**:
```yaml
operation_name_request:
  param1:
    type: string
    required: true
  param2:
    type: object
    required: false
```

**Response Schema**:
```yaml
operation_name_response:
  result:
    type: string
  error:
    type: string
    required: false
```

**Validation Rules**:
- {Rule 1}
- {Rule 2}
\```

#### **Validation Rules Summary**

Comprehensive list of all protocol constraints:

```markdown
## Validation Rules

### Entity Validation
1. {Entity 1}: {validation rules}
2. {Entity 2}: {validation rules}

### Operation Validation
1. {Operation 1}: {validation rules}
2. {Operation 2}: {validation rules}

### Cross-Entity Validation
1. {Rule 1}
2. {Rule 2}
```

#### **Error Handling**

Define protocol-level error handling:

```markdown
## Error Handling

### Error Codes
- `E001`: {Error description}
- `E002`: {Error description}

### Error Response Format
```yaml
error_response:
  code: string
  message: string
  details: object (optional)
```
\```

#### **Examples**

Provide complete protocol examples:

```markdown
## Protocol Examples

### Example 1: {Scenario Name}

**Request**:
```json
{protocol request example}
```

**Response**:
```json
{protocol response example}
```

**Validation**: All rules pass ✅
\```

### 4. Write Specification File

**Location**: `specs/protocol/{number}-{name}/spec.md`

**Use template**: `meta/templates/protocol-spec-template.md.j2`

Populate the template with the following variables:

- `metadata`
  - `name`: Protocol name (e.g., "MCP Core Protocol")
  - `version`: Semantic version (start with `1.0.0`)
  - `status`: Draft | Stable | Deprecated
  - `created`: ISO date (`{{ today }}`)
  - `summary`: 3-5 sentence overview (from Step 3)
- `glossary`: List of `{ term, definition, example }` (optional)
- `use_cases`: List of use case dictionaries (name, scenario, actors, flow, elements, outcome)
- `entities`: For each protocol entity collected in Step 3:
  - `name`, `purpose`
  - `fields`: `[{ name, type, required, description, constraints }]`
  - `schema_example`: YAML snippet (optional)
  - `validation`: Bullet list of entity-specific rules
  - `examples`: JSON examples (optional)
- `workflows`: State machines (if applicable) with `states`, `transitions`, `forbidden`, `validation`
- `operations`: Protocol operations/interfaces with request/response schemas
- `validation_rules`: Flat list of cross-cutting rules (`id`, `description`, `type`, `target`, `scope`, `details`)
- `error_handling`: `{ codes: [...], format: yaml_snippet }` (optional)
- `examples`: End-to-end examples (request/response pairs)
- `references`: External resources or related protocols

The template automatically renders:
- YAML frontmatter (`protocol`, `entities`, `operations`, `validation_rules`, etc.) for machine-readable specs
- Markdown body (Overview, Entities, Workflow, Operations, Validation, Examples) for human-readable docs

✅ Ensure all required sections are populated. Optional sections (Glossary, Use Cases, Workflow, Error Handling) can be omitted if not applicable—the template handles empty lists gracefully.

### 5. Create README.md (Optional)

If this is a new protocol spec, create `specs/protocol/{number}-{name}/README.md`:

```markdown
# {Protocol Name}

Brief overview of the protocol.

## Files

- `spec.md` - Complete protocol specification
- `schema.{format}` - Schema files (if applicable)

## Status

**Current Status**: {Draft | Stable | Deprecated}

## Quick Start

{How to read and use this protocol specification}
```

### 6. Update Dependencies (If needed)

If this protocol depends on other protocols, document in spec.md:

```markdown
## Dependencies

- **protocol/001-base-protocol** - Core protocol definitions
- **protocol/002-auth-protocol** - Authentication mechanisms
```

### 7. Success Output

```
✅ Protocol specification created/updated:

📁 Location:
   specs/protocol/{number}-{name}/spec.md

📋 Protocol: {Protocol Name} v{version}

🧾 YAML Frontmatter: protocol metadata, entities, operations, validation_rules captured

📖 Glossary: {count} terms defined (if included)
   - {Term 1}
   - {Term 2}
   ...

🎯 Use Cases: {count} scenarios described (if included)
   - {Use Case 1}
   - {Use Case 2}
   ...

🎯 Core Entities: {count} entities defined
   - {Entity 1}
   - {Entity 2}
   ...

🔄 Workflow: {count} state machines defined (if included)
   - {Entity 1} State Machine: {state_count} states, {transition_count} transitions
   - {Entity 2} State Machine: {state_count} states, {transition_count} transitions
   ...

🔄 Operations: {count} operations defined
   - {Operation 1}
   - {Operation 2}
   ...

✓ Validation Rules: {count} rules specified

🔄 Next steps:
1. Review protocol specification
2. Run /metaspec.sds.analyze to check consistency
3. Create toolkit with /metaspec.sdd.specify
```

## Best Practices

### Protocol Specification Focus

✅ **DO**:
- Define WHAT the protocol is
- Specify entities, schemas, validation rules
- Define operations and interfaces
- Keep implementation-agnostic
- Use standard data formats (JSON Schema, YAML)

❌ **DON'T**:
- Include implementation code
- Specify Parser/Validator details
- Define CLI commands
- Mix protocol and toolkit concerns

### Naming Conventions

- **Protocol names**: `{domain}-{component}-protocol`
- **Entity names**: PascalCase (e.g., `ServerInfo`, `ToolDefinition`)
- **Operations**: snake_case (e.g., `tools/list`, `initialize`)
- **Fields**: camelCase (e.g., `userName`, `isActive`)

### Version Control

- Start with v1.0 for new protocols
- Use semantic versioning
- Document breaking changes
- Mark deprecated fields clearly

### Documentation

- Provide clear examples
- Explain validation rules rationale
- Link to related standards
- Include common pitfalls

## Constitution Check

Before finalizing, verify against `memory/constitution.md`:

```bash
# Check protocol spec against constitution
grep -A 5 "Entity Clarity" memory/constitution.md
grep -A 5 "Minimal Viable Abstraction" memory/constitution.md
```

**Ensure**:
- Protocol entities are minimal and clear
- No over-engineering
- Progressive enhancement is possible
- Domain specificity is maintained

## Troubleshooting

**If protocol seems too complex**:
→ Break into multiple protocol specs (e.g., core + extensions)

**If overlapping with toolkit**:
→ Move implementation concerns to `specs/toolkit/` using `/metaspec.sdd.specify`

**If unclear validation rules**:
→ Use `/metaspec.sds.clarify` to resolve ambiguities

**If protocol dependencies are complex**:
→ Document in `Dependencies` section and consider using `/metaspec.sds.analyze`
