agentcat-sdk 1.0.0

AgentCat analytics SDK for MCP servers built on rmcp
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
//! The settling of the call hooks and the application of their results: each `hooks:*` case of
//! `tests/vectors/queue.json` against the fixture, and the Rust-only paths (the abort after the
//! budget; a panicking hook). Each hook is a task on the test runtime that has finished (`returns`,
//! `throws`) or never finishes (`hangs`), and every wait uses a 50 ms budget; the timeout text
//! keeps the fixed `30000` whatever the budget is.
use std::future::pending;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use serde_json::{Value, json};
use tokio::time::Instant;

use super::{HookResults, apply, settle};
use crate::config::{HookError, UserIdentity};
use crate::handles::{derive_session_id, is_valid_session_id};
use crate::hooks::PendingHooks;
use crate::pipeline::EventObject;
use crate::test_support::json::object;
use crate::test_support::queue::{self, Task, returns, throws};
use crate::test_support::{assert_same_json_text, vectors};
use crate::wire;

/// The hook budget of every test.
const BUDGET: Duration = Duration::from_millis(50);

/// Sets its flag when it is dropped.
struct DropFlag(Arc<AtomicBool>);

impl Drop for DropFlag {
    fn drop(&mut self) {
        self.0.store(true, Ordering::SeqCst);
    }
}

/// A hook task that never finishes and sets `dropped` when its future is dropped.
fn hangs_watched<T: Send + 'static>(dropped: &Arc<AtomicBool>) -> Task<T> {
    let flag = DropFlag(Arc::clone(dropped));
    tokio::spawn(async move {
        let _flag = flag;
        pending::<Result<Option<T>, HookError>>().await
    })
}

/// A tool-call event as `from_call` leaves it, in key order, with the session `session` (`""` in
/// hook mode) and the SDK tags `tags`.
fn call_event(session: &str, tags: Value) -> EventObject {
    let mut event = object(json!({
        "id": "",
        "sessionId": session,
        "projectId": "proj_1",
        "eventType": "mcp:tools/call",
        "timestamp": "2026-10-23T11:59:59.250Z",
        "duration": 750,
        "sdkLanguage": "Rust",
        "serverName": "server",
        "clientName": "client",
        "identifyActorData": {},
        "resourceName": "echo",
        "parameters": {"request": {}, "extra": {}},
        "response": {"content": []},
    }));
    event.insert("tags".to_owned(), tags);
    event
}

/// The keys of `event`, in order.
fn keys(event: &EventObject) -> Vec<&str> {
    event.keys().map(String::as_str).collect()
}

/// The order in which the hooks' results apply: the hook-mode session first, then the identity in
/// its places, then the customer tags under the SDK tags, then the properties.
#[tokio::test]
async fn settled_hooks_apply_in_the_documented_order() {
    let user = UserIdentity::new("user-42")
        .user_name("Ada")
        .user_data(object(json!({"plan": "pro"})));
    let hooks = PendingHooks {
        resolve_session_id: Some(returns(Some("  customer-abc ".to_owned()))),
        identify: Some(returns(Some(user))),
        event_tags: Some(returns(Some(object(
            json!({"env": "test", "agentcat_session_id_source": "customer"}),
        )))),
        event_properties: Some(returns(Some(object(json!({"device": "mobile"}))))),
    };
    let mut log = Vec::new();
    let results = settle(hooks, BUDGET, &mut log).await;
    assert_eq!(log, Vec::<String>::new());

    let mut event = call_event("", json!({"agentcat_session_id_source": "hook"}));
    apply(&mut event, results, true).expect("a derived session needs no minting");
    let expected = json!({
        "id": "",
        "sessionId": derive_session_id("customer-abc", Some("proj_1")),
        "projectId": "proj_1",
        "eventType": "mcp:tools/call",
        "timestamp": "2026-10-23T11:59:59.250Z",
        "duration": 750,
        "sdkLanguage": "Rust",
        "serverName": "server",
        "clientName": "client",
        "identifyActorGivenId": "user-42",
        "identifyActorName": "Ada",
        "identifyActorData": {"plan": "pro"},
        "resourceName": "echo",
        "parameters": {"request": {}, "extra": {}},
        "response": {"content": []},
        "tags": {"env": "test", "agentcat_session_id_source": "hook"},
        "properties": {"device": "mobile"},
    });
    assert_eq!(
        wire::stringify(&Value::Object(event)),
        wire::stringify(&expected)
    );
}

/// A hook that has not settled within the budget is aborted after the timeout line, which names 30
/// 000 ms whatever the budget is, and the event goes on without it.
#[tokio::test]
async fn hanging_hook_is_aborted_after_budget() {
    let dropped = Arc::new(AtomicBool::new(false));
    let mut hooks = PendingHooks::default();
    hooks.identify = Some(hangs_watched(&dropped));
    hooks.event_tags = Some(returns(Some(object(json!({"env": "test"})))));
    let mut log = Vec::new();
    let started = Instant::now();
    let results = settle(hooks, BUDGET, &mut log).await;
    let waited = started.elapsed();
    assert!(waited >= BUDGET, "settled after {waited:?}");
    assert!(waited < Duration::from_secs(2), "settled after {waited:?}");
    assert_eq!(
        log,
        ["Warning: identify hook did not settle within 30000ms; publishing event without it"]
    );
    assert_eq!(results.identity, None);
    assert_eq!(results.tags, Some(object(json!({"env": "test"}))));

    let observed = tokio::time::timeout(Duration::from_secs(1), async {
        while !dropped.load(Ordering::SeqCst) {
            tokio::task::yield_now().await;
        }
    })
    .await;
    assert!(
        observed.is_ok(),
        "the hook's future was not dropped: no abort"
    );
}

/// A hook that panics gives the background-failure line with the panic's message and no value; the
/// other hooks still apply. A panicking `resolve_session_id` (a panic anywhere in the hook's code
/// happens inside its task, since the code runs when the task is first polled) leaves hook mode to
/// mint a session, as a contained failure does. The panic also prints through the process panic
/// hook.
#[tokio::test]
async fn panicking_hook_logs_and_publishes_without_it() {
    let session: Task<String> = tokio::spawn(async { panic!("sync hook boom") });
    let identify: Task<UserIdentity> = tokio::spawn(async { panic!("identify exploded") });
    let mut hooks = PendingHooks::default();
    hooks.resolve_session_id = Some(session);
    hooks.identify = Some(identify);
    hooks.event_properties = Some(returns(Some(object(json!({"device": "mobile"})))));
    let mut log = Vec::new();
    let results = settle(hooks, BUDGET, &mut log).await;
    assert_eq!(
        log,
        [
            "Warning: resolve_session_id hook failed in background - sync hook boom",
            "Warning: identify hook failed in background - identify exploded",
        ]
    );
    assert_eq!(results.session_value, None);
    assert_eq!(results.identity, None);

    let mut event = call_event("", json!({"agentcat_session_id_source": "hook"}));
    apply(&mut event, results, true).expect("minting works");
    let session = event["sessionId"].as_str().expect("a session");
    assert!(is_valid_session_id(session), "{session}");
    assert_eq!(
        event["tags"],
        json!({"agentcat_session_id_source": "minted"})
    );
    assert_eq!(event.get("identifyActorGivenId"), None);
    assert_eq!(event["identifyActorData"], json!({}));
    assert_eq!(event["properties"], json!({"device": "mobile"}));
}

/// A hook that is not set and a hook that gives nothing (`None`) give no result and no log line,
/// and the event keeps what the call gave it: no identity, the SDK tags only, no properties.
#[tokio::test]
async fn unset_and_null_hooks_change_nothing() {
    let mut log = Vec::new();
    let results = settle(PendingHooks::default(), BUDGET, &mut log).await;
    assert!(results.identity.is_none() && results.tags.is_none());
    assert!(results.session_value.is_none() && results.properties.is_none());

    let mut hooks = PendingHooks::default();
    hooks.identify = Some(returns(None));
    hooks.event_tags = Some(returns(None));
    hooks.event_properties = Some(returns(None));
    let results = settle(hooks, BUDGET, &mut log).await;
    assert_eq!(log, Vec::<String>::new());
    let mut event = call_event("ses_1", json!({"agentcat_session_id_source": "supplied"}));
    let before = event.clone();
    apply(&mut event, results, false).expect("no session step");
    assert_eq!(
        wire::stringify(&Value::Object(event)),
        wire::stringify(&Value::Object(before))
    );
}

/// A hook's own error gives the per-hook text followed by the error's `Display`, in the order the
/// hooks settle together.
#[tokio::test]
async fn hook_errors_use_the_pinned_texts() {
    let hooks = PendingHooks {
        resolve_session_id: Some(throws("no session")),
        identify: Some(throws("no identity")),
        event_tags: Some(throws("no tags")),
        event_properties: Some(throws("no properties")),
    };
    let mut log = Vec::new();
    let results = settle(hooks, BUDGET, &mut log).await;
    assert_eq!(
        log,
        [
            "resolve_session_id hook error: no session",
            "Error: identify hook returned an error - no identity",
            "event_tags callback error: no tags",
            "event_properties callback error: no properties",
        ]
    );
    assert_eq!(results.session_value, None);
    assert_eq!(results.identity, None);
    assert_eq!(results.tags, None);
    assert_eq!(results.properties, None);
}

/// The `event_tags` result goes through `validate_tags` when it settles; each dropped tag gives the
/// pinned line, and only the valid tags remain.
#[tokio::test]
async fn invalid_tags_are_dropped_with_the_pinned_logs() {
    let raw = object(json!({"bad/key": "x", "count": 5, "env": "prod"}));
    let mut hooks = PendingHooks::default();
    hooks.event_tags = Some(returns(Some(raw)));
    let mut log = Vec::new();
    let results = settle(hooks, BUDGET, &mut log).await;
    assert_eq!(
        log,
        [
            "Dropping invalid tag: \"bad/key\" \u{2014} key contains invalid characters or is empty",
            "Dropping invalid tag: \"count\" \u{2014} non-string value (got number)",
        ]
    );
    assert_eq!(results.tags, Some(object(json!({"env": "prod"}))));
}

/// Customer tags merge under the SDK tags: an SDK tag keeps its value on a name collision, at the
/// customer's place in the key order.
#[test]
fn sdk_tags_win_collisions() {
    let mut event = call_event("ses_1", json!({"agentcat_session_id_source": "supplied"}));
    let results = HookResults {
        tags: Some(object(
            json!({"agentcat_session_id_source": "customer", "env": "test"}),
        )),
        ..HookResults::default()
    };
    apply(&mut event, results, false).expect("no session step");
    assert_eq!(
        wire::stringify(&event["tags"]),
        r#"{"agentcat_session_id_source":"supplied","env":"test"}"#
    );
}

/// In hook mode a missing hook value mints a session with the `minted` source; outside hook mode
/// the session stays as the call resolved it.
#[test]
fn hook_mode_without_value_mints() {
    let mut event = call_event("", json!({"agentcat_session_id_source": "hook"}));
    apply(&mut event, HookResults::default(), true).expect("minting works");
    let session = event["sessionId"].as_str().expect("a session");
    assert!(is_valid_session_id(session), "{session}");
    assert_eq!(
        event["tags"],
        json!({"agentcat_session_id_source": "minted"})
    );
    assert_eq!(
        keys(&event),
        keys(&call_event("", json!({}))),
        "no key moves"
    );

    let mut untouched = call_event("", json!({"agentcat_session_id_source": "invalid"}));
    apply(&mut untouched, HookResults::default(), false).expect("no session step");
    assert_eq!(untouched["sessionId"], json!(""));
    assert_eq!(
        untouched["tags"],
        json!({"agentcat_session_id_source": "invalid"})
    );
}

// ------------------------------------------------------------------- queue.json hooks:* cases

/// The request fields `apply` decides, each with the event key it comes from.
const APPLIED: [(&str, &str); 6] = [
    ("sessionId", "sessionId"),
    ("identifyActorGivenId", "identifyActorGivenId"),
    ("identifyActorName", "identifyActorName"),
    ("identifyData", "identifyActorData"),
    ("tags", "tags"),
    ("properties", "properties"),
];

/// Runs the `queue.json` case `name`: its hook outcomes settle under [`BUDGET`] and apply to its
/// event. The log lines must be the fixture's, as `queue::expected_logs` gives them, and each field
/// of [`APPLIED`] must be the one of the fixture's first request; a minted session (`<minted>`)
/// must be a valid session ID with the `minted` source. A case without a request checks only the
/// logs.
async fn check_hook_case(name: &str) {
    let case = queue::case(name);
    let hooks = case["hooks"].as_object().expect("hooks");
    let hook_mode = case.get("hook_mode").and_then(Value::as_bool) == Some(true);
    let mut event = object(case["event"].clone());

    let mut log = Vec::new();
    let results = settle(queue::pending_of(name, hooks), BUDGET, &mut log).await;
    assert_eq!(log, queue::expected_logs(&case), "{name}: logs");

    apply(&mut event, results, hook_mode).expect("minting works");
    let Some(request) = case["requests"]
        .as_array()
        .and_then(|requests| requests.first())
    else {
        return;
    };
    for (wire, key) in APPLIED {
        let context = format!("{name}: {wire}");
        match (event.get(key), request.get(wire)) {
            (Some(Value::String(session)), Some(Value::String(minted)))
                if key == "sessionId" && minted == "<minted>" =>
            {
                assert!(is_valid_session_id(session), "{context}: {session}");
                assert_eq!(
                    event["tags"]["agentcat_session_id_source"],
                    json!("minted"),
                    "{context}"
                );
            }
            (Some(Value::String(session)), Some(Value::Null)) if key == "sessionId" => {
                assert_eq!(session, "", "{context}");
            }
            (Some(actual), Some(expected)) => assert_same_json_text(actual, expected, &context),
            (None, None) => {}
            (actual, expected) => {
                panic!("{context}: {actual:?} where the fixture has {expected:?}")
            }
        }
    }
}

/// Generates one test per `queue.json` `hooks:*` case, and [`HOOK_CASES`], their names.
macro_rules! hook_cases {
    ($($test:ident => $case:literal,)*) => {
        $(
            #[tokio::test]
            async fn $test() {
                check_hook_case($case).await;
            }
        )*

        /// The `hooks:*` cases that have a test.
        const HOOK_CASES: &[&str] = &[$($case),*];
    };
}

hook_cases! {
    queue_hooks_identify => "hooks:identify",
    queue_hooks_identify_no_data => "hooks:identify-no-data",
    queue_hooks_identify_null => "hooks:identify-null",
    queue_hooks_identify_throws => "hooks:identify-throws",
    queue_hooks_identify_hangs => "hooks:identify-hangs",
    queue_hooks_tags_invalid_mixed => "hooks:tags-invalid:mixed",
    queue_hooks_tags_invalid_51_valid => "hooks:tags-invalid:51-valid",
    queue_hooks_tags_invalid_none_valid => "hooks:tags-invalid:none-valid",
    queue_hooks_tags_invalid_bang_key => "hooks:tags-invalid:bang-key",
    queue_hooks_tags_collide => "hooks:tags-collide",
    queue_hooks_tags_throws => "hooks:tags-throws",
    queue_hooks_properties => "hooks:properties",
    queue_hooks_properties_empty => "hooks:properties-empty",
    queue_hooks_properties_throws => "hooks:properties-throws",
    queue_hooks_session_hook => "hooks:session-hook",
    queue_hooks_session_hook_telemetry_only => "hooks:session-hook-telemetry-only",
    queue_hooks_session_hook_null => "hooks:session-hook-null",
    queue_hooks_session_hook_throws => "hooks:session-hook-throws",
    queue_hooks_all_hang => "hooks:all-hang",
    queue_hooks_all_settle => "hooks:all-settle",
}

/// Every `hooks:*` case of `queue.json` has its test above.
#[test]
fn every_hook_case_has_a_test() {
    let cases = queue::cases();
    let names: Vec<&str> = cases
        .iter()
        .map(vectors::name)
        .filter(|name| name.starts_with("hooks:"))
        .collect();
    assert_eq!(names, HOOK_CASES);
}