pmat 3.17.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# 🤖 PMAT Agent Scaffolding - Comprehensive Guide

## Table of Contents
1. [Overview]#overview
2. [Agent Types]#agent-types
3. [Scaffolding Workflows]#scaffolding-workflows
4. [Template System]#template-system
5. [Quality Standards]#quality-standards
6. [MCP Integration]#mcp-integration
7. [CI/CD Pipeline]#cicd-pipeline
8. [Best Practices]#best-practices

## Overview

PMAT's agent scaffolding system provides deterministic, high-quality code generation for creating MCP (Model Context Protocol) agents, state machines, and hybrid AI systems. Every generated agent follows extreme quality standards with built-in testing, documentation, and monitoring.

### Key Features
- **🎯 Deterministic Generation**: Reproducible agent creation with seed-based generation
- **🏗️ Multiple Templates**: MCP servers, state machines, hybrid agents, calculators
- **📊 Quality Enforcement**: TDD, 80% coverage, complexity ≤10 enforced
- **🔄 State Management**: Built-in state machine patterns for complex workflows
- **🔌 MCP Native**: First-class Model Context Protocol support
- **📈 Monitoring Built-in**: Telemetry, metrics, and observability from day one

## Agent Types

### 1. MCP Server Agent
**Purpose**: Standard MCP-compliant server for tool integration

```bash
pmat scaffold agent \
  --name my-tools \
  --template mcp-server \
  --features "file-ops,network,database" \
  --quality extreme
```

**Generated Structure:**
```
my-tools/
├── src/
│   ├── main.rs           # MCP server entry point
│   ├── tools/            # Tool implementations
│   │   ├── file_ops.rs   # File operation tools
│   │   ├── network.rs    # Network tools
│   │   └── database.rs   # Database tools
│   ├── handlers/         # Request handlers
│   ├── validation/       # Input validation
│   └── tests/           # Comprehensive tests
├── Cargo.toml           # Dependencies
├── mcp.json            # MCP manifest
└── README.md           # Documentation
```

### 2. State Machine Agent
**Purpose**: Complex workflow automation with deterministic states

```bash
pmat scaffold agent \
  --name workflow-engine \
  --template state-machine \
  --features "approval,retry,rollback" \
  --quality strict
```

**State Machine Features:**
- Deterministic state transitions
- Event-driven architecture
- Rollback capability
- Audit logging
- Visual state diagram generation

### 3. Hybrid Agent (Deterministic + Probabilistic)
**Purpose**: Combines deterministic core with AI capabilities

```bash
pmat scaffold agent \
  --name smart-analyzer \
  --template hybrid \
  --deterministic-core "ast-parser,rules-engine" \
  --probabilistic-wrapper "llm-interface,embedding-search" \
  --quality extreme
```

**Architecture:**
```
┌─────────────────────────────────────┐
│     Probabilistic Wrapper (AI)      │
│  • LLM Integration                  │
│  • Semantic Search                  │
│  • Pattern Learning                 │
├─────────────────────────────────────┤
│      Deterministic Core             │
│  • AST Parsing                      │
│  • Rules Engine                     │
│  • State Management                 │
└─────────────────────────────────────┘
```

### 4. Calculator Agent
**Purpose**: Mathematical and computational operations

```bash
pmat scaffold agent \
  --name math-engine \
  --template calculator \
  --features "statistics,linear-algebra,optimization" \
  --quality standard
```

### 5. Custom Agent
**Purpose**: User-defined template

```bash
pmat scaffold agent \
  --name custom-agent \
  --template custom:./templates/my-agent.yaml \
  --quality extreme
```

## Scaffolding Workflows

### Interactive Mode

```bash
# Guided agent creation with prompts
pmat scaffold agent --interactive

# Interactive prompts:
# 1. Agent name: my-agent
# 2. Template type: [mcp-server/state-machine/hybrid/calculator/custom]
# 3. Features to include: file-ops, network
# 4. Quality level: [standard/strict/extreme]
# 5. Output directory: ./agents/my-agent
# 6. Overwrite if exists? [y/n]
```

### Batch Generation

```bash
# Generate multiple agents from specification
cat > agents.yaml << EOF
agents:
  - name: file-manager
    template: mcp-server
    features: [file-ops, compression]
  - name: data-processor
    template: state-machine
    features: [validation, transformation]
  - name: ai-assistant
    template: hybrid
    deterministic: [parser]
    probabilistic: [llm]
EOF

pmat scaffold agent --batch agents.yaml
```

### Dry Run Mode

```bash
# Preview what will be generated without creating files
pmat scaffold agent \
  --name test-agent \
  --template mcp-server \
  --dry-run

# Output:
# Would create:
#   ./test-agent/src/main.rs (2.3 KB)
#   ./test-agent/src/tools/mod.rs (1.1 KB)
#   ./test-agent/Cargo.toml (0.8 KB)
#   ./test-agent/mcp.json (0.5 KB)
#   ./test-agent/tests/integration.rs (3.2 KB)
#   ./test-agent/README.md (4.5 KB)
# Total: 6 files, 12.4 KB
```

## Template System

### Built-in Templates

#### MCP Server Template
```yaml
# templates/mcp-server.yaml
name: mcp-server
version: 1.0.0
description: Standard MCP server implementation

structure:
  - path: src/main.rs
    template: mcp_server_main.rs.hbs
  - path: src/tools/mod.rs
    template: tools_module.rs.hbs
  - path: mcp.json
    template: mcp_manifest.json.hbs

features:
  file-ops:
    files:
      - src/tools/file_ops.rs
    dependencies:
      - tokio-fs = "1.0"
  network:
    files:
      - src/tools/network.rs
    dependencies:
      - reqwest = "0.11"

quality:
  standard:
    max_complexity: 20
    min_coverage: 60
  strict:
    max_complexity: 15
    min_coverage: 70
  extreme:
    max_complexity: 10
    min_coverage: 80
```

### Custom Templates

```yaml
# my-custom-template.yaml
name: custom-service
version: 1.0.0

structure:
  - path: src/main.rs
    content: |
      fn main() {
          println!("{{agent_name}} starting...");
      }

variables:
  - name: agent_name
    required: true
    default: "MyAgent"
  - name: port
    required: false
    default: 3000

validation:
  - rule: agent_name_valid
    pattern: "^[a-z][a-z0-9-]*$"
    message: "Agent name must be lowercase with hyphens"
```

### Template Validation

```bash
# Validate a custom template
pmat scaffold validate-template ./my-template.yaml

# Output:
# ✅ Template structure valid
# ✅ Variables defined correctly
# ✅ File paths valid
# ⚠️ Warning: No tests defined
# 
# Template can be used with:
# pmat scaffold agent --template custom:./my-template.yaml
```

## Quality Standards

### Enforced Standards

Every generated agent enforces:

1. **Complexity Limits**
   - Cyclomatic: ≤10 (extreme), ≤15 (strict), ≤20 (standard)
   - Cognitive: ≤10 (extreme), ≤15 (strict), ≤20 (standard)

2. **Test Coverage**
   - ≥80% (extreme), ≥70% (strict), ≥60% (standard)
   - Unit tests for all public functions
   - Integration tests for all tools
   - Property tests for state machines

3. **Documentation**
   - README with usage examples
   - Inline documentation for all public APIs
   - Architecture diagrams for complex agents

4. **Code Quality**
   - Zero SATD comments
   - No clippy warnings
   - Formatted with rustfmt

### Quality Verification

```bash
# Generated agents include quality checks
cd my-agent/

# Run quality gate
make quality-gate

# Run tests with coverage
make test-coverage

# Check complexity
pmat analyze complexity src/
```

## MCP Integration

### Generated MCP Manifest

```json
{
  "name": "my-agent",
  "version": "1.0.0",
  "description": "Generated MCP agent",
  "tools": [
    {
      "name": "read_file",
      "description": "Read file contents",
      "inputSchema": {
        "type": "object",
        "properties": {
          "path": {
            "type": "string",
            "description": "File path to read"
          }
        },
        "required": ["path"]
      }
    }
  ],
  "configuration": {
    "max_file_size": {
      "type": "integer",
      "default": 10485760,
      "description": "Maximum file size in bytes"
    }
  }
}
```

### MCP Tool Implementation

```rust
// Generated tool implementation
#[derive(Debug, Deserialize)]
struct ReadFileArgs {
    path: String,
}

async fn handle_read_file(args: ReadFileArgs) -> Result<String> {
    // Validation
    validate_path(&args.path)?;
    
    // Implementation with error handling
    let content = tokio::fs::read_to_string(&args.path)
        .await
        .context("Failed to read file")?;
    
    // Return with proper formatting
    Ok(content)
}

// Automatic test generation
#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    async fn test_read_file_success() {
        let args = ReadFileArgs {
            path: "test.txt".to_string(),
        };
        let result = handle_read_file(args).await;
        assert!(result.is_ok());
    }
    
    #[tokio::test]
    async fn test_read_file_not_found() {
        let args = ReadFileArgs {
            path: "nonexistent.txt".to_string(),
        };
        let result = handle_read_file(args).await;
        assert!(result.is_err());
    }
}
```

## CI/CD Pipeline

### Generated GitHub Actions

```yaml
# .github/workflows/agent-ci.yml (generated)
name: Agent CI
on: [push, pull_request]

jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Install PMAT
        run: cargo install pmat --locked
      
      - name: Quality Gate
        run: pmat quality-gate --file src/
      
      - name: Complexity Check
        run: |
          pmat analyze complexity src/
          # Fail if complexity > 10
          pmat analyze complexity src/ --max 10
      
      - name: Test Coverage
        run: |
          cargo llvm-cov --html
          # Fail if coverage < 80%
          cargo llvm-cov --fail-under 80
      
      - name: MCP Validation
        run: pmat validate mcp.json
```

### Docker Support

```dockerfile
# Generated Dockerfile
FROM rust:1.75 as builder

WORKDIR /app
COPY . .
RUN cargo build --release

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

COPY --from=builder /app/target/release/my-agent /usr/local/bin/
COPY --from=builder /app/mcp.json /etc/my-agent/

EXPOSE 3000
CMD ["my-agent", "--config", "/etc/my-agent/mcp.json"]
```

## Best Practices

### 1. Start with Templates

```bash
# List available templates
pmat scaffold list-templates

# Show template details
pmat scaffold agent --template mcp-server --show-template

# Always start with a template
pmat scaffold agent \
  --name my-agent \
  --template mcp-server \
  --features "file-ops"
```

### 2. Use Interactive Mode for Learning

```bash
# Interactive mode provides guidance
pmat scaffold agent --interactive

# It will:
# - Explain each option
# - Suggest best practices
# - Validate inputs
# - Show preview before generation
```

### 3. Enforce Quality from Start

```bash
# Always use strict or extreme quality
pmat scaffold agent \
  --name production-agent \
  --template state-machine \
  --quality extreme

# This ensures:
# - Lower technical debt
# - Better maintainability
# - Easier debugging
# - Higher reliability
```

### 4. Version Control Integration

```bash
# Generate with git initialization
pmat scaffold agent \
  --name my-agent \
  --template mcp-server \
  --git-init

# Creates:
# - .gitignore with Rust patterns
# - Initial commit
# - Pre-commit hooks for quality
```

### 5. Testing Strategy

```bash
# Generated agents include test commands
cd my-agent/

# Unit tests
cargo test --lib

# Integration tests
cargo test --test integration

# Property tests (if state machine)
cargo test --features proptest

# Coverage report
cargo llvm-cov --html
```

## Advanced Features

### State Machine Visualization

```bash
# Generate state diagram for state machine agents
pmat scaffold agent \
  --name workflow \
  --template state-machine \
  --visualize

# Creates workflow.dot and workflow.svg
# Shows all states and transitions visually
```

### Multi-Agent Systems

```bash
# Generate coordinated agent system
cat > multi-agent.yaml << EOF
system:
  name: distributed-processor
  agents:
    - name: coordinator
      template: state-machine
      role: orchestrator
    - name: worker-1
      template: mcp-server
      role: processor
    - name: worker-2
      template: mcp-server
      role: processor
  communication:
    protocol: grpc
    service_discovery: consul
EOF

pmat scaffold agent --system multi-agent.yaml
```

### Agent Migration

```bash
# Migrate existing code to agent structure
pmat scaffold agent \
  --name migrated-agent \
  --template mcp-server \
  --migrate-from ./legacy-code/
```

## Integration with PMAT Ecosystem

### Quality Gate Integration

```toml
# Generated pmat.toml
[agent.quality]
complexity_limit = 10
coverage_minimum = 80
satd_tolerance = 0

[agent.monitoring]
telemetry = true
metrics = true
tracing = true
```

### MCP Tool Testing

```javascript
// Test generated MCP tools
const agent = await mcp.connect('localhost:3000');

// List available tools
const tools = await agent.listTools();
console.log(`Agent provides ${tools.length} tools`);

// Test each tool
for (const tool of tools) {
  const result = await agent.callTool(tool.name, tool.testData);
  assert(result.success, `Tool ${tool.name} failed`);
}
```

---

**Version**: 2.71.0 | **Last Updated**: 2025-09-09 | **Status**: Production Ready