unistructgen 0.2.2

A powerful Rust code generator
Documentation
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
# UniStructGen

**Rust toolkit for type-safe code generation, AI tool calling, structured LLM outputs, and compiler-driven agents.**

Parse JSON, OpenAPI, SQL, GraphQL, Markdown, or .env schemas into a language-agnostic intermediate representation (IR), then generate idiomatic Rust structs, JSON Schema for LLM structured outputs, or wire up AI tool calling -- all with compile-time safety.

**Author**: Maxim Bogovic (more info at [https://bogovick.com](https://bogovick.com))
**Version**: 0.1.0
**License**: MIT / Apache-2.0
**Rust**: 1.70+

[![Crates.io](https://img.shields.io/crates/v/unistructgen.svg)](https://crates.io/crates/unistructgen)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)]()
[![Rust](https://img.shields.io/badge/rust-1.70%2B-orange.svg)]()

---

**Why developers use UniStructGen**
- **Ship types fast** — generate Rust structs from real JSON and schemas at compile time.
- **Keep LLM tools correct** — auto‑generate JSON Schemas and tool definitions from Rust functions.
- **Reduce boilerplate** — one source of truth for types, validation, and docs.

Try the killer example:
```bash
cargo run -p killer-example
```

---

## What Problem Does This Solve

You have data schemas -- JSON payloads, database DDL, OpenAPI specs, GraphQL types, environment variables. You need Rust structs that match. You also need JSON Schema to tell an LLM exactly what shape of response you expect. And you need to turn plain Rust functions into tools the LLM can call.

UniStructGen gives you one pipeline for all of this:

```
Schema (JSON/SQL/OpenAPI/GraphQL/.env/Markdown)
    |
    v
  Parser  -->  IR (Intermediate Representation)  -->  Generator
    |                                                      |
    v                                                      v
  Rust structs         or         JSON Schema (Draft 2020-12)
```

Instead of hand-writing struct definitions, JSON Schema, serde attributes, and tool boilerplate, you describe the shape once and generate everything.

---

## Project Status

**Stable core:** `core/`, `codegen/`, `parsers/*`, `proc-macro/`, `cli/` are the primary developer-facing surface and should remain backward compatible within minor versions.

**Experimental/optional:** `llm/`, `mcp/`, `agent/`, and `schema-registry/` are evolving and may change more frequently.

**Compile-time fetch controls:** set `UNISTRUCTGEN_FETCH_OFFLINE=1` to disable network, `UNISTRUCTGEN_FETCH_CACHE=0` to disable caching, `UNISTRUCTGEN_FETCH_CACHE_DIR=/path` to override cache location, and `UNISTRUCTGEN_FETCH_TIMEOUT_MS=...` to override timeouts.

---

## Table of Contents

- [Quick Start]#quick-start
- [Killer Example (60 Seconds)]#killer-example-60-seconds
- [Core Feature: `#[ai_tool]` Macro]#core-feature-ai_tool-macro
- [Core Feature: JSON Schema for Structured LLM Outputs]#core-feature-json-schema-for-structured-llm-outputs
- [Core Feature: AI Validation Loop]#core-feature-ai-validation-loop
- [Core Feature: Compiler Diagnostics for AI Agents]#core-feature-compiler-diagnostics-for-ai-agents
- [Core Feature: Compile-Time API Fetching]#core-feature-compile-time-api-fetching
- [Core Feature: LLM Client Abstraction]#core-feature-llm-client-abstraction
- [All 6 Parsers]#all-6-parsers
- [Builder API]#builder-api
- [Pipeline API]#pipeline-api
- [CLI]#cli
- [Architecture]#architecture
- [Crate Map]#crate-map
- [Type Mapping Reference]#type-mapping-reference
- [Examples]#examples
- [Blog]#blog
- [License]#license

---

## Quick Start

Add the crates you need to `Cargo.toml`:

```toml
[dependencies]
# The main crate with all features enabled (core, parsers, codegen, etc.)
unistructgen = { version = "0.2.1", features = ["full"] }

# Or pick specific features:
# unistructgen = { version = "0.2.1", features = ["json", "llm", "agent", "mcp"] }

# Proc macros must be a separate crate:
unistructgen-macro = "0.2"

# External dependencies used in examples
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
```

Minimal example -- generate a Rust struct from JSON at compile time:

```rust
use unistructgen_macro::generate_struct_from_json;

generate_struct_from_json! {
    name = "User",
    json = r#"{"id": 1, "name": "Alice", "tags": ["admin"]}"#,
    serde = true
}

// Now `User` struct exists with fields: id (i64), name (String), tags (Vec<String>)
// Derives: Debug, Clone, PartialEq, Serialize, Deserialize
```

---

## Killer Example (60 Seconds)

One small program that shows the core value: **types + tool schemas + safe execution**.

```bash
cargo run -p killer-example
```

What it demonstrates:
- Compile-time Rust types from JSON
- LLM tool schema generation from functions
- Safe, structured tool execution

See: `examples/killer-example/README.md`

---

## Core Feature: `#[ai_tool]` Macro

Turn any Rust function into an LLM-callable tool with a single attribute. The macro generates a JSON Schema from the function signature, creates a tool struct implementing `AiTool`, and handles JSON argument deserialization.

```rust
use unistructgen_macro::ai_tool;
use unistructgen::core::{ToolRegistry, Context};

/// Calculate shipping cost based on weight and destination
#[ai_tool]
fn calculate_shipping(weight_kg: f64, destination: String) -> f64 {
    weight_kg * 2.5 + if destination == "international" { 15.0 } else { 5.0 }
}

// The macro generates `CalculateShippingTool` struct implementing `AiTool`

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut registry = ToolRegistry::new();
    registry.register(CalculateShippingTool);

    let context = Context::new();

    // Export OpenAI-compatible tool definitions for any LLM
    let definitions = registry.get_definitions();
    // Returns Vec<Value> in OpenAI function calling format:
    // [{"type": "function", "function": {"name": "calculate_shipping", ...}}]

    // Execute a tool call from LLM response
    let result = registry.execute(
        "calculate_shipping",
        r#"{"weight_kg": 3.0, "destination": "domestic"}"#,
        &context,
    ).await?;

    Ok(())
}
```

### What `#[ai_tool]` generates

Given a function `fn calculate_shipping(weight_kg: f64, destination: String) -> f64`:

1. **JSON Schema** (Draft 2020-12) derived from the Rust types via the IR type system
2. **`CalculateShippingTool` struct** implementing the `AiTool` trait
3. **Argument deserialization struct** with `serde::Deserialize`
4. **Description** extracted from the function's `///` doc comment

### Dependency injection with `#[context]`

Tools can access shared resources (database pools, API clients) via the `Context` container:

```rust
#[derive(Clone)]
struct DbPool { url: String }

/// Get user balance from database
#[ai_tool]
async fn get_user_balance(#[context] db: DbPool, user_id: i32) -> Result<f64, String> {
    // `db` is extracted from Context automatically
    Ok(1250.50)
}

// Setup
let mut context = Context::new();
context.insert(DbPool { url: "postgres://localhost/mydb".into() });

let mut registry = ToolRegistry::new();
registry.register(GetUserBalanceTool);

// Execute -- Context provides the DbPool, LLM provides user_id
let result = registry.execute("get_user_balance", r#"{"user_id": 42}"#, &context).await?;
```

### Parallel batch execution

```rust
use unistructgen_core::tools::ToolCall;

let calls = vec![
    ToolCall { name: "get_user_balance".into(), arguments: r#"{"user_id": 1}"#.into() },
    ToolCall { name: "calculate_shipping".into(), arguments: r#"{"weight_kg": 5.0, "destination": "domestic"}"#.into() },
];

let results = registry.execute_batch(calls, &context).await;
// Returns Vec<(String, ToolResult)> -- all executed concurrently
```

### Supported argument types

| Rust Type | JSON Schema Type | Notes |
|---|---|---|
| `String`, `&str` | `"string"` | |
| `i8`, `i16`, `i32` | `"integer"` | |
| `i64`, `isize` | `"integer"` | |
| `f32`, `f64` | `"number"` | |
| `bool` | `"boolean"` | |
| `Vec<T>` | `"array"` | Recursive |
| `Option<T>` | nullable | Recursive |

---

## Core Feature: JSON Schema for Structured LLM Outputs

Generate Draft 2020-12 JSON Schema from any IR module. Use it as a contract for OpenAI `response_format.json_schema` or inject into system prompts for Ollama.

```rust
use unistructgen::core::{StructGen, FieldType, CodeGenerator};
use unistructgen::codegen::JsonSchemaRenderer;

// Define the response structure
let module = StructGen::new()
    .name("AgentResponse")
    .field("answer", FieldType::String)
    .field("confidence", FieldType::F64)
    .field("sources", FieldType::vec(FieldType::String))
    .field("requires_action", FieldType::Bool)
    .build_ir_module();

// Generate JSON Schema
let renderer = JsonSchemaRenderer::new().fragment();
let schema = renderer.generate(&module)?;
```

Output:

```json
{
  "$defs": {
    "AgentResponse": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "answer": { "type": "string" },
        "confidence": { "type": "number" },
        "sources": { "type": "array", "items": { "type": "string" } },
        "requires_action": { "type": "boolean" }
      },
      "required": ["answer", "confidence", "sources", "requires_action"]
    }
  },
  "$ref": "#/$defs/AgentResponse"
}
```

### Using with OpenAI

```rust
use unistructgen_llm::{LlmClient, CompletionRequest, Message};
use unistructgen_llm::openai::OpenAiClient;

// Reads OPENAI_API_KEY from environment
let client = OpenAiClient::new("gpt-4o")?;

let schema_value: serde_json::Value = serde_json::from_str(&schema)?;

let response = client.complete(CompletionRequest {
    messages: vec![Message::user("Analyze this codebase")],
    response_schema: Some(schema_value), // strict: true is set automatically
    ..Default::default()
}).await?;
// Response is guaranteed to match the AgentResponse schema
```

### Schema features

- `$defs` with `$ref` for nested types and cross-references
- Recursive type support
- Strict mode (`additionalProperties: false`) for OpenAI compatibility
- Fragment mode (`.fragment()`) omits `$schema` for embedding in larger payloads
- All IR types mapped: primitives, `Option<T>`, `Vec<T>`, `HashMap<K,V>`, named references, enums as string unions

---

## Core Feature: Reverse IR (Rust -> IR -> Schema)

Define your types in Rust and generate the IR/Schema from them. This is the reverse of the standard flow, allowing you to use Rust as the Source of Truth.

```rust
use unistructgen::core::IntoIR;
use unistructgen::codegen::JsonSchemaRenderer;

#[derive(IntoIR)]
struct User {
    #[field(min_value = 1, doc = "Unique ID")]
    id: i64,
    
    #[field(max_length = 100)]
    name: String,
    
    #[field(format = "email", optional)]
    email: Option<String>,
}

// Get the IR definition at runtime
let definition = User::ir_definition().unwrap();

// Wrap in a module
let mut module = unistructgen::core::ir::IRModule::new("UserModule".to_string());
module.add_type(definition);

// Generate JSON Schema
let schema = JsonSchemaRenderer::new().generate(&module)?;
```

Supported `#[field]` attributes:
- `doc = "..."`: Overrides/adds documentation
- `min_length`, `max_length`: String/array length constraints
- `min_value`, `max_value`: Numeric range constraints
- `pattern = "..."`: Regex pattern
- `format = "..."`: Format string (e.g., "email", "date-time")
- `optional`: Force optionality in IR

---

## Core Feature: AI Validation Loop

LLMs produce malformed JSON. UniStructGen provides structured validation errors and auto-generated correction prompts to send back to the LLM for self-healing.

```rust
use unistructgen::core::{ValidationReport, AiValidationError, map_serde_error};

let mut response_json = llm_client.complete(request).await?;

for attempt in 0..3 {
    match serde_json::from_str::<AgentResponse>(&response_json) {
        Ok(valid) => break,
        Err(e) => {
            // Convert serde error to AI-friendly structured format
            let ai_error = map_serde_error(&e);
            // ai_error.path = "confidence"
            // ai_error.message = "invalid type: string \"high\", expected f64"

            let mut report = ValidationReport::new();
            report.add_error(ai_error);

            // Generate correction prompt for the LLM
            let correction = report.to_correction_prompt();
            // "The generated JSON response was invalid. Please fix the following errors:
            //  1. Field `confidence`: invalid type: string "high", expected f64
            //     Hint: Ensure the field name and type matches the schema exactly.
            //  Return the corrected JSON only."

            response_json = llm_client.complete(CompletionRequest {
                messages: vec![Message::user(&correction)],
                response_schema: Some(schema.clone()),
                ..Default::default()
            }).await?;
        }
    }
}
```

### Validation types

| Type | Purpose |
|---|---|
| `AiValidationError` | Structured error with `path`, `message`, `invalid_value`, `correction_hint` |
| `ValidationReport` | Aggregates errors; generates correction prompts via `to_correction_prompt()` |
| `map_serde_error()` | Converts `serde_json::Error` to `AiValidationError` with field path extraction |
| `AiValidatable` trait | For types that can self-validate: `fn validate_ai(&self) -> ValidationReport` |

---

## Core Feature: Compiler Diagnostics for AI Agents

Build AI agents that write Rust code and iterate on compiler errors. The `diagnostics` module parses structured output from `cargo check --message-format=json`.

```rust
use unistructgen::core::diagnostics::CargoDiagnostics;
use std::path::Path;

// Run cargo check on a project directory
let errors = CargoDiagnostics::check(Path::new("./sandbox_project"))?;

for error in &errors {
    println!("Error: {}", error.message);
    println!("Rendered: {}", error.rendered);
    if let Some(span) = &error.primary_span {
        println!("At {}:{}:{}", span.file_name, span.line_start, span.column_start);
    }
}

// Feed errors back to AI for correction
if !errors.is_empty() {
    let feedback = errors.iter()
        .map(|e| e.rendered.clone())
        .collect::<Vec<_>>()
        .join("\n");
    // Send feedback to LLM for code correction
}
```

### Code patching from LLM output

The `patch` module provides `CodeFix` and `Hunk` structs for applying LLM-generated code fixes:

```rust
use unistructgen::core::patch::CodeFix;

// LLM can output structured fixes as JSON
let fix: CodeFix = serde_json::from_str(llm_response)?;
// fix.file_path, fix.explanation, fix.changes (Vec<Hunk>)

let fixed_code = fix.apply(&original_source)?;
```

---

## Core Feature: Compile-Time API Fetching

Fetch a JSON API at compile time and generate type-safe structs. No manual type definitions. No codegen scripts.

```rust
use unistructgen_macro::struct_from_external_api;

struct_from_external_api! {
    struct_name = "GithubRepo",
    url_api = "https://api.github.com/repos/rust-lang/rust",
    method = "GET",
    auth_bearer = "ghp_your_token",
    serde = true,
    optional = true,
    max_depth = 3,
    max_entity_count = 10
}

// GithubRepo struct is now available with all fields from the API response
```

### Authentication methods

| Parameter | Format | Protocol |
|---|---|---|
| `auth_bearer = "token"` | Bearer token | OAuth2, JWT |
| `auth_api_key = "X-API-Key:value"` | Custom header | API key |
| `auth_basic = "user:password"` | HTTP Basic Auth | Basic |

### Parameters

| Parameter | Type | Default | Description |
|---|---|---|---|
| `struct_name` | string | `"ApiResponse"` | Name of the generated struct |
| `url_api` / `url` | string | required | API endpoint URL |
| `method` | string | `"GET"` | HTTP method (GET, POST, PUT, DELETE) |
| `serde` | bool | `true` | Add Serialize/Deserialize derives |
| `default` | bool | `false` | Add Default derive |
| `optional` | bool | `false` | Make all fields Optional |
| `max_depth` | int | unlimited | Limit nested object depth |
| `max_entity_count` | int | unlimited | Limit array items used for inference |
| `timeout` | int | `30000` | Request timeout in ms |

---

## Core Feature: LLM Client Abstraction

Unified async trait for OpenAI and Ollama with built-in structured output support.

```rust
use unistructgen::llm::{LlmClient, CompletionRequest, Message};

// OpenAI (reads OPENAI_API_KEY from env)
use unistructgen::llm::openai::OpenAiClient;
let openai = OpenAiClient::new("gpt-4o")?;

// Ollama (local, defaults to http://localhost:11434)
use unistructgen::llm::ollama::OllamaClient;
let ollama = OllamaClient::new("llama3");

// Factory with auto-detection
use unistructgen::llm::{LlmClientFactory, Provider};
let client = LlmClientFactory::new()
    .with_provider(Provider::Auto) // OpenAI if key exists, else Ollama
    .with_model("gpt-4o")
    .build()?;
```

### `LlmClient` trait

```rust
#[async_trait]
pub trait LlmClient: Send + Sync {
    async fn complete(&self, request: CompletionRequest) -> Result<String>;
    async fn complete_stream(&self, request: CompletionRequest) -> Result<LlmStream>;
    fn model(&self) -> &str;
}
```

### `CompletionRequest` fields

| Field | Type | Description |
|---|---|---|
| `messages` | `Vec<Message>` | Conversation messages (system, user, assistant) |
| `temperature` | `Option<f32>` | Sampling temperature |
| `max_tokens` | `Option<u32>` | Max response tokens |
| `response_schema` | `Option<Value>` | JSON Schema for structured output |

### Structured output per provider

- **OpenAI**: Uses `response_format.json_schema` with `strict: true` (native API support)
// Ollama: Enables `format: "json"` and injects the schema into the system prompt

---

## Core Feature: MCP Server (Model Context Protocol)

Turn your Rust functions into an MCP Server compatible with Claude Desktop, Cursor, and Windsurf in one line.

```rust
use unistructgen_macro::ai_tool;
use unistructgen::core::{ToolRegistry, Context};
use unistructgen::mcp::serve_stdio;
use std::sync::Arc;

#[ai_tool]
fn query_database(sql: String) -> String { 
    // ... execute sql ...
    "Query result".to_string()
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut registry = ToolRegistry::new();
    registry.register(QueryDatabaseTool); // generated by macro

    // Run MCP server on stdio
    serve_stdio(Arc::new(registry), Context::new()).await?;
    Ok(())
}
```

This automatically implements the Model Context Protocol:
- `tools/list`: Exports your tools with full JSON Schema definitions
- `tools/call`: Executes your Rust functions with arguments provided by the LLM
- `initialize`: Handles handshake and capabilities

Supported transports:
- `serve_stdio`: For local agents (Claude Desktop, IDEs)
- `serve_sse`: For remote/web agents (requires `sse` feature)

---

## Core Feature: Agent Runtime & Orchestration

Build autonomous agents and pipelines directly in Rust. The runtime handles the ReAct loop (Reasoning + Acting), tool execution, and context management.

```rust
use unistructgen::agent::{Agent, AgentPipeline};
use unistructgen::core::ToolRegistry;
use unistructgen_macro::ai_tool;
use std::sync::Arc;

// 1. Define Tools
#[ai_tool]
fn search_web(query: String) -> String { /* ... */ }

// 2. Build Agent
let researcher = Agent::builder()
    .name("Researcher")
    .client(llm_client)
    .tools(Arc::new(registry))
    .system_prompt("You are a researcher. Use tools to find info.")
    .build()?;

// 3. Run (Auto-loop: Thought -> Action -> Observation -> Thought)
let answer = researcher.run("What is the latest Rust version?").await?;
```

### Multi-Agent DAG Pipeline

Chain agents together to solve complex tasks.

```rust
let pipeline = AgentPipeline::builder()
    .agent("planner", planner_agent)
    .agent("coder", coder_agent)
    .agent("reviewer", reviewer_agent)
    .start("planner")
    .transition("planner", "coder")
    .transition("coder", "reviewer")
    .build()?;

let result = pipeline.run("Create a snake game").await?;
```

---

## All 6 Parsers

UniStructGen includes parsers for 6 input formats. Each implements the `Parser` trait and produces `IRModule`.

### 1. JSON

```rust
// Proc macro (compile-time)
generate_struct_from_json! {
    name = "User",
    json = r#"{"id": 1, "name": "Alice", "tags": ["admin"]}"#,
    serde = true
}

// Runtime pipeline
use unistructgen::parsers::json::{JsonParser, ParserOptions};
let mut parser = JsonParser::new(ParserOptions {
    struct_name: "User".into(),
    derive_serde: true,
    ..Default::default()
});
let ir = parser.parse(json_str)?;
```

Smart type inference detects: DateTime, UUID, Email, URL patterns in string values.

### 2. OpenAPI / Swagger

```rust
// Proc macro
openapi_to_rust! {
    file = "api/openapi.yaml",
    generate_client = true,
    generate_validation = true
}

// Also supports: spec = "inline yaml...", url = "https://..."
```

Client generation is a typed scaffold (best-effort) and may require manual adjustments for edge cases.

### 3. SQL DDL

```rust
generate_struct_from_sql! {
    sql = r#"CREATE TABLE users (
        id SERIAL PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        email VARCHAR(255) UNIQUE,
        created_at TIMESTAMP DEFAULT NOW()
    );"#,
    serde = true
}
```

### 4. GraphQL Schema

```rust
generate_struct_from_graphql! {
    schema = r#"
        type User { id: ID!, name: String!, email: String, posts: [Post!]! }
        type Post { id: ID!, title: String!, body: String! }
    "#,
    serde = true
}
```

### 5. .env Files

```rust
generate_struct_from_env! {
    name = "AppConfig",
    env = r#"
        DATABASE_URL=postgres://localhost/mydb
        PORT=8080
        DEBUG=true
    "#
}
// Generates: AppConfig { database_url: String, port: i64, debug: bool }
```

### 6. Markdown Tables

```rust
// Runtime via MarkdownParser or CLI:
// unistructgen generate --input schema.md --name Config
```

The markdown parser also includes a **semantic chunker** for RAG pipelines:

```rust
use unistructgen::parsers::markdown::chunker::SemanticChunker;

let markdown = std::fs::read_to_string("docs/README.md")?;
let chunks = SemanticChunker::chunk(&markdown);
// Each chunk preserves heading hierarchy and semantic boundaries
```

---

## Builder API

Build IR structs and enums programmatically with a fluent API, then generate Rust code or JSON Schema.

```rust
use unistructgen::core::{StructGen, EnumGen, ModuleGen, FieldType, FieldBuilder};

// Struct
let code = StructGen::new()
    .name("User")
    .doc("Represents a user in the system")
    .field("id", FieldType::I64)
    .field("name", FieldType::String)
    .field_optional("email", FieldType::String)
    .field_with(|f| f.doc("User's age").range(0.0, 150.0), "age", FieldType::I32)
    .with_serde()
    .with_default()
    .generate()?;

// Enum
let code = EnumGen::new()
    .name("OrderStatus")
    .variant("Pending")
    .variant_with_rename("InTransit", "in_transit")
    .variant("Delivered")
    .with_serde()
    .generate()?;

// Module with multiple types
let code = ModuleGen::new("models")
    .add_struct(StructGen::new().name("User").field("id", FieldType::I64))
    .add_enum(EnumGen::new().name("Status").variant("Active"))
    .generate()?;
```

### Field constraints

Constraints generate `#[validate(...)]` attributes on the rendered Rust struct:

```rust
FieldBuilder::new("email", FieldType::String)
    .optional()
    .doc("User email")
    .rename("user_email")       // #[serde(rename = "user_email")]
    .length(5, 255)             // #[validate(length(min = 5, max = 255))]
    .pattern(r"^[\w@.]+$")     // #[validate(regex = "...")]
    .format("email")           // #[validate(email)]
    .build();
```

### Quick JSON parsing

```rust
use unistructgen::core::from_json;

let code = from_json(r#"{"id": 1, "name": "Alice"}"#)
    .struct_name("User")
    .with_serde()
    .generate()?;
```

---

## Pipeline API

Chain a parser, transformers, and generator into a processing pipeline:

```rust
use unistructgen::core::{Pipeline, transformer::FieldOptionalizer};
use unistructgen::parsers::json::{JsonParser, ParserOptions};
use unistructgen::codegen::{RustRenderer, RenderOptions};

let mut pipeline = Pipeline::new(
    JsonParser::new(ParserOptions {
        struct_name: "User".into(),
        derive_serde: true,
        ..Default::default()
    }),
    RustRenderer::new(RenderOptions::default()),
)
.add_transformer(Box::new(FieldOptionalizer::new()));

let rust_code = pipeline.execute(r#"{"id": 1, "name": "Alice"}"#)?;
```

### Built-in transformers

| Transformer | Effect |
|---|---|
| `FieldOptionalizer` | Wraps all fields in `Option<T>` |
| `DocCommentAdder` | Adds doc comments to structs/fields |
| `TypeDeduplicator` | Deduplicates identical nested struct definitions |
| `FieldRenamer` | Renames fields (e.g. snake_case conversion) |

### Plugin system

Plugins hook into the pipeline at parse and generate stages:

```rust
use unistructgen::core::{PluginRegistry, plugin::LoggingPlugin};

let mut plugins = PluginRegistry::new();
plugins.register(Box::new(LoggingPlugin::new(true)))?;

let input = plugins.before_parse(input)?;
let module = plugins.after_parse(module)?;
let code = plugins.after_generate(code)?;
```

---

## CLI

```bash
cargo install unistructgen-cli

# Generate Rust structs from JSON
unistructgen generate --input data.json --name MyStruct --serde

# Generate from Markdown table
unistructgen generate --input schema.md --name Config

# Generate HTTP client scaffold from OpenAPI spec
unistructgen client --spec api.yaml --name GitHub --output ./generated

# AI-powered error fixing (experimental)
unistructgen fix
```

---

## Architecture

```
                    +--------------------------------------------------------------+
                    |                        UniStructGen                           |
                    |                                                               |
  +----------+     |  +--------+    +----+    +-------------+    +----------+      |
  |  JSON    |--+  |  |        |    |    |    |             |    |  Rust    |      |
  |  OpenAPI |--+  |  |        |    |    |    |             |    |  Code    |      |
  |  SQL     |--+  |  | Parser |--->| IR |--->| Transformer |--->|  JSON    |      |
  |  GraphQL |--+->|  |        |    |    |    |             |    |  Schema  |      |
  |  .env    |--+  |  |        |    |    |    |             |    |          |      |
  |  Markdown|--+  |  +--------+    +----+    +-------------+    +----------+      |
  +----------+     |  [Plugins]                [Plugins]                            |
                   +--------------------------------------------------------------+
                                        |
                            +-----------+-----------+
                            v           v           v
                     +------------+ +--------+ +----------+ +--------+
                     | #[ai_tool] | |  LLM   | |Validation| |  MCP   |
                     | ToolRegist | | Client | |  Loop    | | Server |
                     | JSON Schema| |OpenAI  | | Reports  | | stdio/ |
                     +------------+ |Ollama  | | Prompts  | |  sse   |
                                    +--------+ +----------+ +--------+
```

### Core traits

| Trait | Module | Purpose | Implementations |
|---|---|---|---|
| `Parser` | `core::parser` | Input format to IR | `JsonParser`, `OpenApiParser`, `MarkdownParser`, `SqlParser`, `GraphqlParser`, `EnvParser` |
| `CodeGenerator` | `core::codegen` | IR to output code | `RustRenderer`, `JsonSchemaRenderer` |
| `IRTransformer` | `core::transformer` | Transform IR in-flight | `FieldOptionalizer`, `DocCommentAdder`, `TypeDeduplicator`, `FieldRenamer` |
| `Plugin` | `core::plugin` | Pipeline hooks | `LoggingPlugin`, `HeaderPlugin`, custom |
| `AiTool` | `core::tools` | LLM tool interface | Auto-generated by `#[ai_tool]` |
| `LlmClient` | `llm` | LLM provider abstraction | `OpenAiClient`, `OllamaClient` |
| `AiValidatable` | `core::validation` | Self-validation for AI | Custom types |
| `IRVisitor` | `core::visitor` | IR traversal/analysis | `StructNameCollector`, `FieldCounter`, `IRValidator` |

### IR type system

```rust
// core::ir -- the shared representation all parsers emit and all generators consume

IRModule { name: String, types: Vec<IRType> }
IRType::Struct(IRStruct) | IRType::Enum(IREnum)

IRStruct { name, fields: Vec<IRField>, derives, doc, attributes }
IRField  { name, source_name, ty: IRTypeRef, optional, default, constraints, attributes, doc }

IRTypeRef::Primitive(PrimitiveKind)  // String, I32, I64, F64, Bool, DateTime, Uuid, etc.
IRTypeRef::Option(Box<IRTypeRef>)    // Option<T>
IRTypeRef::Vec(Box<IRTypeRef>)       // Vec<T>
IRTypeRef::Named(String)             // Reference to another struct/enum
IRTypeRef::Map(Box, Box)             // HashMap<K, V>

FieldConstraints { min_length, max_length, min_value, max_value, pattern, format }
```

---

## Crate Map

```
unistructgen/                # Main crate (monolith)
├── src/
│   ├── lib.rs               # Exports core, codegen, parsers, etc.
│   ├── core/                # unistructgen::core
│   │   ├── ir.rs            # IRModule, IRStruct, IRField
│   │   ├── api.rs           # StructGen, EnumGen
│   │   ├── parser.rs        # Parser trait
│   │   ├── codegen.rs       # CodeGenerator trait
│   │   ├── transformer.rs   # IRTransformer trait
│   │   ├── tools.rs         # AiTool trait
│   │   └── ...
│   ├── codegen/             # unistructgen::codegen
│   │   ├── lib.rs           # RustRenderer
│   │   └── json_schema.rs   # JsonSchemaRenderer
│   ├── parsers/             # unistructgen::parsers
│   │   ├── json/            # unistructgen::parsers::json
│   │   ├── openapi/         # unistructgen::parsers::openapi
│   │   ├── markdown/        # unistructgen::parsers::markdown
│   │   ├── sql/             # unistructgen::parsers::sql
│   │   ├── graphql/         # unistructgen::parsers::graphql
│   │   └── env/             # unistructgen::parsers::env
│   ├── llm/                 # unistructgen::llm (feature="llm")
│   ├── mcp/                 # unistructgen::mcp (feature="mcp")
│   └── agent/               # unistructgen::agent (feature="agent")
│
unistructgen-macro/          # Proc-macro crate (separate)
│   └── src/lib.rs           # generate_struct_from_json!, #[ai_tool], etc.
│
unistructgen-cli/            # CLI crate (separate)
│   └── src/main.rs          # `unistructgen` binary
```

---

## Type Mapping Reference

How IR types map across parsers and generators:

| IR Type | Rust Output | JSON Schema Output | Source: JSON | Source: SQL | Source: GraphQL |
|---|---|---|---|---|---|
| `String` | `String` | `"string"` | string values | `VARCHAR`, `TEXT` | `String`, `ID` |
| `I32` | `i32` | `"integer"` | small ints | `INT`, `INTEGER` | `Int` |
| `I64` | `i64` | `"integer"` | large ints | `BIGINT`, `SERIAL` | -- |
| `F64` | `f64` | `"number"` | floats | `DOUBLE`, `REAL` | `Float` |
| `Bool` | `bool` | `"boolean"` | booleans | `BOOLEAN` | `Boolean` |
| `DateTime` | `chrono::DateTime<Utc>` | `"string" format:"date-time"` | ISO 8601 strings | `TIMESTAMP` | -- |
| `Uuid` | `uuid::Uuid` | `"string" format:"uuid"` | UUID strings | `UUID` | -- |
| `Decimal` | `rust_decimal::Decimal` | `"number"` | -- | `DECIMAL`, `NUMERIC` | -- |
| `Option(T)` | `Option<T>` | omitted from `required` | -- | nullable columns | nullable fields |
| `Vec(T)` | `Vec<T>` | `"array"` | arrays | -- | `[Type]` |
| `Map(K,V)` | `HashMap<K,V>` | `"object" + additionalProperties` | dynamic objects | -- | -- |
| `Named(S)` | `S` | `"$ref": "#/$defs/S"` | nested objects | -- | type references |

---

## Examples

| Example | What It Demonstrates |
|---|---|
| `tools-agent` | Register functions as AI tools, batch execution, dependency injection via Context, LlmClientFactory |
| `docu-agent` | RAG ingestion with SemanticChunker, JSON Schema contract, AI validation loop with auto-correction |
| `code-agent` | Compiler-driven development: AI writes code, CargoDiagnostics checks, errors fed back, AI fixes iteratively |
| `github-client` | GitHub API client scaffold generated from OpenAPI spec |
| `blog-api` | Blog API types from OpenAPI |
| `api-example` | Struct generation from live API responses with `struct_from_external_api!` |
| `proc-macro-example` | All proc macros: JSON, OpenAPI, SQL, GraphQL, .env |
| `killer-example` | Types + LLM tool schema + safe execution in one file |

## Blog

- `docs/blog/announcing-unistructgen.md`

---

## Development

```bash
# Check all workspace crates
cargo check --all

# Run all tests
cargo test --all

# Run tests for a specific crate
cargo test -p unistructgen-core

# Build release
cargo build --release

# Run CLI in dev
cargo run -p unistructgen -- generate --input data.json --name MyStruct
```

---

## License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT License ([LICENSE-MIT]LICENSE-MIT or <http://opensource.org/licenses/MIT>)

at your option.