subc-protocol 0.28.0

Shared wire contract for subc <-> modules: the 21-byte envelope, the Frame (header + opaque body), channel-0 control bodies, route.bind/RouteTarget session shapes, and the capability manifest. Single source of truth, depended on by subc-core and AFT.
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
//! The body of a tool-call `REQUEST` frame on a bound route.
//!
//! The daemon splices route frames without reading their bodies, so this
//! shape is a contract between consumers (the MCP gateway, model runners)
//! and provider modules, not something the daemon enforces. Before this
//! type existed every consumer carried its own struct and every provider its
//! own reader, and the fields drifted: the gateway sent `progress_token`,
//! a model runner sent only `name` and `arguments`, and a provider that
//! needed the caller's tool-call id had no field to read it from.
//!
//! Decoding is deliberately tolerant of unknown members: a provider must
//! never refuse a call because a newer consumer added a key it does not
//! know. Omitted optionals decode as `None`; `None` optionals are omitted on
//! the wire, so a body carrying neither optional serializes exactly as the
//! two-field shape older consumers already send — this type is drop-in for
//! them without a wire change.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::Principal;

/// Who really asked for a call that another module relays.
///
/// When a module forwards a tool call on behalf of a different caller, the
/// provider sees the forwarding module as the route's principal and the
/// forwarder's own `call_key`. This records the caller behind it, so the
/// provider can attribute the call in its logs and ledgers.
///
/// It is a claim made by the forwarding module, not something the daemon
/// checks: a provider may record it but must never grant or refuse anything
/// because of it. Authority stays with the route's own principal.
///
/// `#[non_exhaustive]` so a later member is an additive change; build it with
/// [`CallOrigin::new`].
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct CallOrigin {
    /// The original caller, in the same form the daemon stamps on a route.
    pub carrier: Principal,
    /// The original caller's key for the call, with the same bounds as
    /// [`ToolCallRequest::call_key`]; check it with [`validate_call_origin`].
    pub call_key: String,
}

impl CallOrigin {
    /// An origin naming `carrier` as the caller and `call_key` as its key.
    pub fn new(carrier: Principal, call_key: impl Into<String>) -> Self {
        Self {
            carrier,
            call_key: call_key.into(),
        }
    }
}

/// A tool invocation as carried on a route `REQUEST` frame.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct ToolCallRequest {
    /// The provider's bare manifest tool name (no gateway prefix).
    pub name: String,
    /// The arguments exactly as the caller supplied them; consumers never
    /// translate them, and the provider's manifest schema is what accepts
    /// or rejects their shape.
    pub arguments: Value,
    /// The consumer's own identifier for this call, minted by whatever
    /// dispatched it (a model runner's WAL intent id, a gateway request id).
    /// Opaque to the daemon and to subc; unique per call on the consumer's
    /// side, so a provider's at-most-once fence can key on it directly
    /// instead of synthesizing an id from the call's contents.
    ///
    /// `None` is a statement about the PRODUCER, not the call: it means this
    /// consumer did not supply an id, never that the call has no identity.
    /// A reader must not collapse the two — the moment a legacy producer is
    /// on the other end, treating `None` as "no id exists" and synthesizing
    /// one silently reproduces exactly the failure this field exists to end.
    /// A reader that synthesizes a fallback id when this is `None` must
    /// record that the fallback fired (a fallback that never reports firing
    /// is indistinguishable from a working component that is quietly wrong).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    /// An MCP progress token the consumer wants progress notifications
    /// correlated to, when the caller requested progress. Opaque here.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub progress_token: Option<Value>,
    /// A key the consumer chose for this call, which a provider may use to
    /// recognise the same call arriving twice. Opaque to the daemon; a
    /// provider checks only its shape, with [`validate_call_key`], and answers
    /// a malformed one with `invalid_request` naming the field
    /// [`CALL_KEY_FIELD`].
    ///
    /// This struct is deliberately not `#[non_exhaustive]`: a consumer that
    /// builds it field by field must decide what key, if any, to send, so a
    /// new field here is meant to stop its struct literal compiling.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub call_key: Option<String>,
    /// Which version of the tool's schema the consumer built its arguments
    /// against, so a provider can tell a call made against a schema it no
    /// longer serves. Opaque here: the tool-provider role defines what it
    /// holds. A provider checks only its shape, with [`validate_schema_pin`],
    /// and answers a malformed one with `invalid_request` naming the field
    /// [`SCHEMA_PIN_FIELD`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_pin: Option<String>,
    /// The caller behind this call when the consumer is relaying it for
    /// someone else; `None` when the consumer is the caller. For attribution
    /// only, never authority: see [`CallOrigin`]. A provider checks it with
    /// [`validate_call_origin`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<CallOrigin>,
}

impl ToolCallRequest {
    /// A call with no consumer id, no progress token, no call key, no schema
    /// pin and no origin — the shape older two-field consumers send.
    pub fn new(name: impl Into<String>, arguments: Value) -> Self {
        Self {
            name: name.into(),
            arguments,
            tool_call_id: None,
            progress_token: None,
            call_key: None,
            schema_pin: None,
            origin: None,
        }
    }
}

/// The wire name of [`ToolCallRequest::call_key`], for the `field` of the
/// `invalid_request` error a provider returns when the key is malformed.
pub const CALL_KEY_FIELD: &str = "call_key";

/// The wire name of [`ToolCallRequest::schema_pin`], for the `field` of the
/// `invalid_request` error a provider returns when the pin is malformed.
pub const SCHEMA_PIN_FIELD: &str = "schema_pin";

/// The wire path of [`CallOrigin::call_key`] inside a request, for the `field`
/// of the `invalid_request` error a provider returns when it is malformed.
pub const ORIGIN_CALL_KEY_FIELD: &str = "origin.call_key";

/// The longest opaque token field accepted, in bytes (every accepted byte is
/// one ASCII character). Shared by `call_key` and `schema_pin`.
pub const OPAQUE_FIELD_MAX_LEN: usize = 256;

/// The longest `call_key` accepted.
pub const CALL_KEY_MAX_LEN: usize = OPAQUE_FIELD_MAX_LEN;

/// The longest `schema_pin` accepted.
pub const SCHEMA_PIN_MAX_LEN: usize = OPAQUE_FIELD_MAX_LEN;

/// Why an opaque token field (`call_key`, `schema_pin`) was refused. Every
/// variant names the request field it is about, so a provider can put it in
/// its `invalid_request` error without tracking which check ran.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OpaqueFieldError {
    /// The value was the empty string. An absent value is `None`, never `""`.
    Empty { field: &'static str },
    /// The value was longer than [`OPAQUE_FIELD_MAX_LEN`] bytes.
    TooLong { field: &'static str, length: usize },
    /// The byte at `index` is not printable, non-space ASCII.
    InvalidCharacter { field: &'static str, index: usize },
}

/// The error [`validate_call_key`] returns. Kept as a name so code that only
/// formats the error or reads [`OpaqueFieldError::field`] keeps compiling.
pub type CallKeyError = OpaqueFieldError;

impl OpaqueFieldError {
    /// The request field the error is about.
    pub fn field(&self) -> &'static str {
        match self {
            Self::Empty { field }
            | Self::TooLong { field, .. }
            | Self::InvalidCharacter { field, .. } => field,
        }
    }
}

impl std::fmt::Display for OpaqueFieldError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty { field } => write!(f, "{field} must not be empty"),
            Self::TooLong { field, length } => write!(
                f,
                "{field} is {length} bytes; at most {OPAQUE_FIELD_MAX_LEN} are allowed"
            ),
            Self::InvalidCharacter { field, index } => write!(
                f,
                "{field} has a character at byte {index} outside printable ASCII \
                 (0x21 to 0x7E; space is not allowed)"
            ),
        }
    }
}

impl std::error::Error for OpaqueFieldError {}

/// Check an opaque token field: 1 to [`OPAQUE_FIELD_MAX_LEN`] characters, each
/// printable ASCII from 0x21 to 0x7E. `field` is the wire name the error
/// reports.
///
/// Space (0x20) is refused. Providers compare these values byte for byte and
/// write them into logs and ledgers, where a leading or trailing space is
/// invisible: two values that differ only by one would read as the same value
/// and act as different ones. Every other printable character is allowed, so
/// a consumer can use its existing ids (UUIDs, `prefix:id` forms, base64,
/// digests) unchanged.
fn validate_opaque_field(field: &'static str, value: &str) -> Result<(), OpaqueFieldError> {
    if value.is_empty() {
        return Err(OpaqueFieldError::Empty { field });
    }
    if value.len() > OPAQUE_FIELD_MAX_LEN {
        return Err(OpaqueFieldError::TooLong {
            field,
            length: value.len(),
        });
    }
    if let Some(index) = value
        .bytes()
        .position(|byte| !(0x21..=0x7e).contains(&byte))
    {
        return Err(OpaqueFieldError::InvalidCharacter { field, index });
    }
    Ok(())
}

/// Check a `call_key` with the shared opaque-field rule; errors name
/// [`CALL_KEY_FIELD`].
pub fn validate_call_key(key: &str) -> Result<(), CallKeyError> {
    validate_opaque_field(CALL_KEY_FIELD, key)
}

/// Check a `schema_pin` with the shared opaque-field rule; errors name
/// [`SCHEMA_PIN_FIELD`].
pub fn validate_schema_pin(pin: &str) -> Result<(), OpaqueFieldError> {
    validate_opaque_field(SCHEMA_PIN_FIELD, pin)
}

/// Check a [`CallOrigin`]: its `call_key` must pass the shared opaque-field
/// rule, and errors name [`ORIGIN_CALL_KEY_FIELD`]. Every [`Principal`] is
/// accepted as the carrier.
pub fn validate_call_origin(origin: &CallOrigin) -> Result<(), OpaqueFieldError> {
    validate_opaque_field(ORIGIN_CALL_KEY_FIELD, &origin.call_key)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn omitted_optionals_decode_as_none() {
        let request: ToolCallRequest =
            serde_json::from_value(json!({ "name": "grep", "arguments": { "q": "x" } }))
                .expect("two-field body decodes");
        assert_eq!(request.tool_call_id, None);
        assert_eq!(request.progress_token, None);
        assert_eq!(request.call_key, None);
        assert_eq!(request.schema_pin, None);
        assert_eq!(request.origin, None);
    }

    #[test]
    fn call_key_round_trips_as_a_top_level_member() {
        let request = ToolCallRequest {
            name: "grep".to_string(),
            arguments: json!({ "q": "x" }),
            tool_call_id: None,
            progress_token: None,
            call_key: Some("run-7:call-3".to_string()),
            schema_pin: None,
            origin: None,
        };
        let encoded = serde_json::to_value(&request).expect("encode");
        assert_eq!(
            encoded,
            json!({ "name": "grep", "arguments": { "q": "x" }, "call_key": "run-7:call-3" })
        );
        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
        assert_eq!(decoded, request);
    }

    #[test]
    fn a_request_without_a_call_key_omits_the_member_and_round_trips() {
        let request = ToolCallRequest::new("grep", json!({}));
        let encoded = serde_json::to_value(&request).expect("encode");
        assert!(encoded.get("call_key").is_none(), "{encoded}");
        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
        assert_eq!(decoded.call_key, None);
        assert_eq!(decoded, request);
    }

    /// The same bounds for both fields, with each refusal naming its own
    /// field: one validator, two names.
    #[test]
    fn opaque_field_bounds_are_one_to_256_printable_non_space_ascii() {
        type Validate = fn(&str) -> Result<(), OpaqueFieldError>;
        let validators: [(&str, Validate); 2] = [
            (CALL_KEY_FIELD, validate_call_key),
            (SCHEMA_PIN_FIELD, validate_schema_pin),
        ];
        for (field, validate) in validators {
            assert_eq!(validate(""), Err(OpaqueFieldError::Empty { field }));
            assert_eq!(validate("k"), Ok(()));
            assert_eq!(validate(&"k".repeat(256)), Ok(()));
            assert_eq!(
                validate(&"k".repeat(257)),
                Err(OpaqueFieldError::TooLong { field, length: 257 })
            );
            assert_eq!(validate("!~"), Ok(()), "both ends of 0x21..=0x7E");
            for bad in ["ké", "a\tb", "a\u{7f}", "a b"] {
                assert_eq!(
                    validate(bad),
                    Err(OpaqueFieldError::InvalidCharacter { field, index: 1 }),
                    "{field}: {bad:?}"
                );
            }
            let error = validate("").unwrap_err();
            assert_eq!(error.field(), field);
            assert!(error.to_string().starts_with(field), "{error}");
        }
    }

    #[test]
    fn schema_pin_round_trips_as_a_top_level_member() {
        let request = ToolCallRequest {
            schema_pin: Some("sha256:0f1e2d".to_string()),
            ..ToolCallRequest::new("grep", json!({ "q": "x" }))
        };
        let encoded = serde_json::to_value(&request).expect("encode");
        assert_eq!(
            encoded,
            json!({ "name": "grep", "arguments": { "q": "x" }, "schema_pin": "sha256:0f1e2d" })
        );
        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
        assert_eq!(decoded, request);
    }

    #[test]
    fn a_request_without_a_schema_pin_omits_the_member_and_round_trips() {
        let request = ToolCallRequest::new("grep", json!({}));
        let encoded = serde_json::to_value(&request).expect("encode");
        assert!(encoded.get("schema_pin").is_none(), "{encoded}");
        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
        assert_eq!(decoded.schema_pin, None);
        assert_eq!(decoded, request);
    }

    #[test]
    fn none_optionals_are_omitted_so_the_wire_matches_the_two_field_shape() {
        let request = ToolCallRequest::new("grep", json!({ "q": "x" }));
        let encoded = serde_json::to_value(&request).expect("encode");
        assert_eq!(
            encoded,
            json!({ "name": "grep", "arguments": { "q": "x" } })
        );
    }

    #[test]
    fn tool_call_id_round_trips() {
        let request = ToolCallRequest {
            name: "grep".to_string(),
            arguments: json!({ "q": "x" }),
            tool_call_id: Some("wal-intent-42".to_string()),
            progress_token: None,
            call_key: None,
            schema_pin: None,
            origin: None,
        };
        let encoded = serde_json::to_value(&request).expect("encode");
        assert_eq!(encoded["tool_call_id"], json!("wal-intent-42"));
        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
        assert_eq!(decoded, request);
    }

    #[test]
    fn unknown_members_do_not_fail_a_provider_decode() {
        // A newer consumer added a key this provider has never heard of; the
        // call must still decode rather than refuse.
        let request: ToolCallRequest = serde_json::from_value(json!({
            "name": "grep",
            "arguments": {},
            "some_future_key": { "nested": true }
        }))
        .expect("unknown members are tolerated");
        assert_eq!(request.name, "grep");
    }

    fn relayed_origin() -> CallOrigin {
        CallOrigin::new(
            Principal::Reserved {
                module_id: "broca".to_string(),
            },
            "broca:run-7/call-3",
        )
    }

    /// The carrier travels as the tagged `Principal` object the daemon stamps
    /// on a route, never as a bare string.
    #[test]
    fn origin_round_trips_as_a_top_level_member_with_a_tagged_carrier() {
        let request = ToolCallRequest {
            call_key: Some("pf:relay/991".to_string()),
            origin: Some(relayed_origin()),
            ..ToolCallRequest::new("grep", json!({ "q": "x" }))
        };
        let encoded = serde_json::to_value(&request).expect("encode");
        assert_eq!(
            encoded,
            json!({
                "name": "grep",
                "arguments": { "q": "x" },
                "call_key": "pf:relay/991",
                "origin": {
                    "carrier": { "kind": "reserved", "module_id": "broca" },
                    "call_key": "broca:run-7/call-3"
                }
            })
        );
        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
        assert_eq!(decoded, request);
    }

    #[test]
    fn a_request_without_an_origin_omits_the_member_and_decodes_as_none() {
        let request = ToolCallRequest::new("grep", json!({}));
        let encoded = serde_json::to_value(&request).expect("encode");
        assert!(encoded.get("origin").is_none(), "{encoded}");
        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
        assert_eq!(decoded.origin, None);
        assert_eq!(decoded, request);
    }

    #[test]
    fn a_request_with_an_origin_and_an_unknown_member_still_decodes() {
        let request: ToolCallRequest = serde_json::from_value(json!({
            "name": "grep",
            "arguments": {},
            "origin": {
                "carrier": { "kind": "direct" },
                "call_key": "k",
                "some_future_origin_key": 1
            },
            "some_future_key": { "nested": true }
        }))
        .expect("unknown members are tolerated");
        assert_eq!(
            request.origin,
            Some(CallOrigin::new(Principal::Direct, "k"))
        );
    }

    #[test]
    fn call_origin_key_refusals_name_the_origin_call_key_field() {
        let carrier = Principal::Direct;
        let field = ORIGIN_CALL_KEY_FIELD;
        assert_eq!(field, "origin.call_key");
        let cases = [
            (String::new(), OpaqueFieldError::Empty { field }),
            (
                "k".repeat(257),
                OpaqueFieldError::TooLong { field, length: 257 },
            ),
            (
                "pf:relay 991".to_string(),
                OpaqueFieldError::InvalidCharacter { field, index: 8 },
            ),
        ];
        for (key, expected) in cases {
            let error = validate_call_origin(&CallOrigin::new(carrier.clone(), key.clone()))
                .expect_err("malformed origin key is refused");
            assert_eq!(error, expected, "{key:?}");
            assert_eq!(error.field(), "origin.call_key", "{key:?}");
        }
    }

    #[test]
    fn call_origin_accepts_every_carrier_kind() {
        let carriers = [
            Principal::Reserved {
                module_id: "prefrontal-core".to_string(),
            },
            Principal::Direct,
            Principal::Unverified,
        ];
        for carrier in carriers {
            assert_eq!(
                validate_call_origin(&CallOrigin::new(carrier.clone(), "pf:relay/991")),
                Ok(()),
                "{carrier:?}"
            );
        }
    }
}