systemprompt-models 0.2.1

Foundation data models for systemprompt.io AI governance infrastructure. Shared DTOs, config, and domain types consumed by every layer of the MCP governance pipeline.
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
<div align="center">
  <a href="https://systemprompt.io">
    <img src="https://systemprompt.io/logo.svg" alt="systemprompt.io" width="150" />
  </a>
  <p><strong>Production infrastructure for AI agents</strong></p>
  <p><a href="https://systemprompt.io">systemprompt.io</a><a href="https://systemprompt.io/documentation">Documentation</a><a href="https://github.com/systempromptio/systemprompt-core">Core</a><a href="https://github.com/systempromptio/systemprompt-template">Template</a></p>
</div>

---


# systemprompt-models

Shared data models and types for systemprompt.io OS.

[![Crates.io](https://img.shields.io/crates/v/systemprompt-models.svg)](https://crates.io/crates/systemprompt-models)
[![Documentation](https://docs.rs/systemprompt-models/badge.svg)](https://docs.rs/systemprompt-models)
[![License: BUSL-1.1](https://img.shields.io/badge/License-BUSL--1.1-blue.svg)](https://github.com/systempromptio/systemprompt-core/blob/main/LICENSE)

## Overview

**Part of the Shared layer in the systemprompt.io architecture.**
**Infrastructure** · [Self-Hosted Deployment](https://systemprompt.io/features/self-hosted-ai-platform)

This crate provides common data models, error types, and repository patterns used throughout systemprompt.io. It includes API models, authentication types, configuration, database models, and service-layer error handling.

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
systemprompt-models = "0.0.1"
```

## Feature Flags

| Feature | Default | Description |
|---------|---------|-------------|
| `web` | No | Axum `IntoResponse` implementations |

## Modules

### `api` - API Response Models

Standard JSON API response structures:

```rust
use systemprompt_models::{ApiResponse, ApiError, ErrorCode};

let response = ApiResponse::success(data);
let error = ApiError::not_found("User not found");
```

### `auth` - Authentication Models

```rust
use systemprompt_models::{AuthenticatedUser, BaseRole, AuthError};

let user = AuthenticatedUser {
    id: "user-123".to_string(),
    username: "alice".to_string(),
    roles: vec![BaseRole::Admin],
    scopes: vec!["admin".to_string()],
};
```

### `config` - Configuration Models

```rust
use systemprompt_models::Config;
use systemprompt_traits::ConfigProvider;

let config = Config::from_env()?;
let db_url = config.database_url(); // ConfigProvider trait
```

### `errors` - Error Handling

**`RepositoryError`** - Database/repository layer errors:
```rust
use systemprompt_models::RepositoryError;

let err = RepositoryError::NotFound("user-123".to_string());
// Automatically converts to ApiError
let api_err: ApiError = err.into();
```

**`ServiceError`** - Business logic layer errors:
```rust
use systemprompt_models::ServiceError;

let err = ServiceError::Validation("Invalid email".to_string());
let api_err: ApiError = err.into(); // Converts to HTTP 400
```

**Error Conversion Flow:**
```
RepositoryError → ServiceError → ApiError → HTTP Response
```

### `repository` - Repository Patterns

**Service Lifecycle Trait:**
```rust
use systemprompt_models::ServiceLifecycle;

#[async_trait]
impl ServiceLifecycle for MyServiceRepository {
    async fn get_running_services(&self) -> Result<Vec<ServiceRecord>, RepositoryError> { ... }
    async fn mark_crashed(&self, service_id: &str) -> Result<(), RepositoryError> { ... }
    async fn update_status(&self, service_id: &str, status: &str) -> Result<(), RepositoryError> { ... }
}
```

**Query Builder:**
```rust
use systemprompt_models::WhereClause;

let (clause, params) = WhereClause::new()
    .eq("status", "active")
    .is_not_null("pid")
    .build();

let query = format!("SELECT * FROM services {}", clause);
```

**Repository Macros:**
```rust
use systemprompt_models::impl_repository_base;

impl_repository_base!(MyRepository, DbPool, db_pool);

// Expands to:
// impl Repository for MyRepository {
//     type Pool = DbPool;
//     type Error = RepositoryError;
//     fn pool(&self) -> &Self::Pool { &self.db_pool }
// }
```

### `execution` - Execution Context

```rust
use systemprompt_core_system::RequestContext;

let req_ctx = RequestContext {
    session_id: "session-123".into(),
    trace_id: "trace-456".into(),
    user_id: "user-789".into(),
    context_id: "ctx-000".into(),
    task_id: None,
    ai_tool_call_id: None,
    client_id: None,
    auth_token: None,
    user: None,
    start_time: std::time::Instant::now(),
    user_type: UserType::AdminUser,
};
```

## Error Handling Pattern

systemprompt.io uses a layered error handling approach:

### Layer 1: Repository (Database)

```rust
use systemprompt_traits::RepositoryError;

async fn get_user(&self, id: &str) -> Result<User, RepositoryError> {
    sqlx::query_as(...)
        .fetch_optional(self.pool().pool())
        .await?
        .ok_or_else(|| RepositoryError::NotFound(format!("User {}", id)))
}
```

### Layer 2: Service (Business Logic)

```rust
use systemprompt_models::ServiceError;

async fn create_user(&self, data: CreateUser) -> Result<User, ServiceError> {
    if data.email.is_empty() {
        return Err(ServiceError::Validation("Email required".into()));
    }

    self.repo.create_user(data)
        .await
        .map_err(|e| e.into()) // RepositoryError → ServiceError
}
```

### Layer 3: API (HTTP)

```rust
use systemprompt_models::ApiError;

async fn create_user_handler(
    State(service): State<UserService>,
    Json(data): Json<CreateUser>,
) -> Result<Json<User>, ApiError> {
    let user = service.create_user(data)
        .await
        .map_err(|e| e.into())?; // ServiceError → ApiError

    Ok(Json(user))
}
```

## Repository Pattern

All repositories should implement the `Repository` trait from `systemprompt-traits`:

```rust
use systemprompt_traits::{Repository, RepositoryError};
use systemprompt_core_database::DbPool;

pub struct UserRepository {
    db_pool: DbPool,
}

impl Repository for UserRepository {
    type Pool = DbPool;
    type Error = RepositoryError;

    fn pool(&self) -> &Self::Pool {
        &self.db_pool
    }
}

impl UserRepository {
    pub fn new(db_pool: DbPool) -> Self {
        Self { db_pool }
    }

    pub async fn get_user(&self, id: &str) -> Result<Option<User>, RepositoryError> {
        sqlx::query_as::<_, User>(GET_USER_QUERY)
            .bind(id)
            .fetch_optional(self.pool().pool())
            .await
            .map_err(|e| e.into())
    }
}

const GET_USER_QUERY: &str = "SELECT * FROM users WHERE id = ?";
```

## Query Helpers

### WhereClause Builder

```rust
use systemprompt_models::WhereClause;

let (clause, params) = WhereClause::new()
    .eq("status", "active")
    .is_not_null("deleted_at")
    .like("name", "%john%")
    .in_list("role", vec!["admin".into(), "user".into()])
    .build();

// clause = "WHERE status = ? AND deleted_at IS NOT NULL AND name LIKE ? AND role IN (?, ?)"
// params = vec!["active", "%john%", "admin", "user"]
```

### Repository Macros

```rust
// Base trait implementation
impl_repository_base!(UserRepository, DbPool, db_pool);

// Query execution
let users = repository_query!(
    self.pool(),
    "SELECT * FROM users WHERE status = ?",
    "active"
)?;

// Execute statement
repository_execute!(
    self.pool(),
    "UPDATE users SET status = ? WHERE id = ?",
    "inactive",
    user_id
)?;
```

## Module Models

```rust
use systemprompt_models::{Module, ModuleType, ServiceCategory};

let module = Module {
    id: "mod-123".to_string(),
    name: "my-module".to_string(),
    version: "1.0.0".to_string(),
    display_name: "My Module".to_string(),
    category: ServiceCategory::Core,
    module_type: ModuleType::Regular,
    enabled: true,
    config: HashMap::new(),
    ..Default::default()
};
```

## Dependencies

- `serde` / `serde_json` - Serialization
- `sqlx` - Database types
- `anyhow` / `thiserror` - Error handling
- `chrono` / `uuid` - Common types
- `axum` - Request types for analytics
- `async-trait` - Async traits
- `systemprompt-traits` - Core trait definitions
- `systemprompt-core-logging` - Logging context

## Best Practices

### 1. Use Shared Error Types

```rust
// ✅ Good
async fn my_repo_method(&self) -> Result<Data, RepositoryError> { ... }

// ❌ Bad
async fn my_repo_method(&self) -> Result<Data, anyhow::Error> { ... }
```

### 2. Layer Your Errors

```rust
// Repository layer
Result<T, RepositoryError>

// Service layer
Result<T, ServiceError>

// API layer
Result<T, ApiError>
```

### 3. Use Query Builders

```rust
// ✅ Good
let (clause, params) = WhereClause::new().eq("status", status).build();

// ❌ Bad
let clause = format!("WHERE status = '{}'", status); // SQL injection risk!
```

### 4. Implement Repository Trait

```rust
// ✅ Good - Consistent pattern
impl Repository for MyRepository { ... }

// ❌ Bad - No trait, inconsistent
impl MyRepository {
    pub fn get_pool(&self) -> &DbPool { ... } // Different name
}
```

## Testing

Mock repositories using traits:

```rust
#[cfg(test)]
mod tests {
    use super::*;

    struct MockUserRepository {
        users: Vec<User>,
    }

    impl Repository for MockUserRepository {
        type Pool = ();
        type Error = RepositoryError;
        fn pool(&self) -> &Self::Pool { &() }
    }

    #[tokio::test]
    async fn test_user_service() {
        let repo = MockUserRepository { users: vec![] };
        let service = UserService::new(repo);
        // Test service logic
    }
}
```

## Usage

```rust
use systemprompt_models::config::AgentConfig;

fn main() -> anyhow::Result<()> {
    let yaml = r#"
        id: developer_agent
        name: Developer
        description: Writes and reviews code
    "#;
    let agent: AgentConfig = serde_yaml::from_str(yaml)?;
    println!("loaded agent: {}", agent.id);
    Ok(())
}
```

## License

Business Source License 1.1 - See [LICENSE](https://github.com/systempromptio/systemprompt-core/blob/main/LICENSE) for details.