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
use crate::mcp::era::{correlation_id, CorrelationId};
use crate::mcp::types::*;
use crate::trace::schema::{EpisodeEnd, EpisodeStart, StepEntry, ToolCallEntry, TraceEvent};
use serde_json::json;
use std::collections::HashMap;
/// The correlation key for one event, read from its retained raw JSON.
///
/// `McpEvent::jsonrpc_id` is a public `String` and cannot distinguish a JSON number from a JSON
/// string, so the mapper derives the same typed key the parser uses rather than a second rendering
/// of it. Two readers of one identity is how this drifted apart in the first place.
fn payload_correlation_id(payload: &McpPayload) -> Option<CorrelationId> {
let raw = match payload {
McpPayload::SessionStart { raw }
| McpPayload::ToolsListRequest { raw }
| McpPayload::ToolsListResponse { raw, .. }
| McpPayload::ToolCallRequest { raw, .. }
| McpPayload::ToolCallResponse { raw, .. }
| McpPayload::SessionEnd { raw, .. }
| McpPayload::Other { raw, .. } => raw,
};
correlation_id(raw)
}
/// Map normalized MCP events to Assay V2 trace events (JSONL).
pub fn mcp_events_to_v2_trace(
mut events: Vec<McpEvent>,
episode_id: String,
test_id: Option<String>,
prompt_override: Option<String>,
) -> Vec<TraceEvent> {
// P0.3: Deterministic Sort
// 1. Timestamp (ms)
// 2. Source Line (stable fallback)
// 3. JSON-RPC ID (tie-breaker)
events.sort_by(|a, b| {
let ts_a = a.timestamp_ms.unwrap_or(0);
let ts_b = b.timestamp_ms.unwrap_or(0);
match ts_a.cmp(&ts_b) {
std::cmp::Ordering::Equal => match a.source_line.cmp(&b.source_line) {
std::cmp::Ordering::Equal => {
let id_a = a.jsonrpc_id.as_deref().unwrap_or("");
let id_b = b.jsonrpc_id.as_deref().unwrap_or("");
id_a.cmp(id_b)
}
other => other,
},
other => other,
}
});
let start_ts = events
.iter()
.filter_map(|e| e.timestamp_ms)
.min()
.unwrap_or_else(now_ms);
let mut out = Vec::new();
// P0.1: Prompt Handling
// If not provided, use sentinel to prevent CI failure (E_TRACE_MISS).
let prompt_val = prompt_override.unwrap_or_else(|| "<mcp:session>".to_string());
// EpisodeStart
let mut meta = serde_json::Map::new();
meta.insert("source".into(), json!("mcp_import"));
meta.insert("episode_id".into(), json!(episode_id));
meta.insert(
"mcp".into(),
json!({
"authorization_discovery": summarize_auth_discovery(&events)
}),
);
if let Some(tid) = test_id {
meta.insert("test_id".into(), json!(tid));
}
out.push(TraceEvent::EpisodeStart(EpisodeStart {
episode_id: episode_id.clone(),
timestamp: start_ts,
input: json!({ "prompt": prompt_val }),
meta: serde_json::Value::Object(meta),
}));
// P0.2: Correlation Buffer
// Store pending tool calls: keys = jsonrpc_id
// Values = (index in 'out', step_id, tool_name)
// We emit the 'Step' immediately when Request comes, but we might update it later?
// Actually, Assay V2 separation of Step and ToolCall allows us to emit:
// 1. Step (Request)
// 2. ToolCall (Request + Response combined) -> Wait for Response.
// BUT: To be strictly atomic and clean for the DB ingestion, it's better to emit both Step and ToolCall
// when the *Response* arrives? No, Step usually marks the attempt start.
// Better approach for "Atomic ToolCall" in V2:
// V2 `ToolCallEntry` contains both `args` and `result`.
// So we must wait for the Response to emit the `ToolCallEntry`.
// We can emit the `StepEntry` (invocation) when the Request is seen, or wait.
// Let's emit `StepEntry` on Request, and `ToolCallEntry` on Response.
// The `ToolCallEntry` needs the `args` from the Request.
// Map: id -> (StepId, ToolName, Args, Timestamp)
// The same crate-private typed key the parser correlates on. Keying on the public
// `McpEvent::jsonrpc_id` rendered JSON number `1` and JSON string `"1"` identically, so the
// second request overwrote the first and a numeric response was attached to the string call.
// A number the correlator declines to key does not pair here either, rather than pairing on a
// rendering that cannot tell two ids apart.
let mut pending_calls: HashMap<CorrelationId, (String, String, serde_json::Value, u64)> =
HashMap::new();
let mut idx: i64 = 0;
let mut last_ts = start_ts;
let mut final_output: Option<String> = None;
for e in events {
if let Some(ts) = e.timestamp_ms {
last_ts = last_ts.max(ts);
}
// Read before the match, which consumes the payload.
let correlation = payload_correlation_id(&e.payload);
#[expect(
clippy::wildcard_enum_match_arm,
reason = "only the payload kinds that carry trace-visible steps are mapped; the rest contribute no step, and a new kind that should would have to be named"
)]
match e.payload {
McpPayload::ToolsListRequest { .. } => {
out.push(TraceEvent::Step(StepEntry {
episode_id: episode_id.clone(),
step_id: format!("step_{:03}", idx),
idx: idx as u32,
timestamp: last_ts,
kind: "tool".to_string(),
name: Some("tools/list".to_string()),
content: Some("{}".to_string()),
content_sha256: None,
truncations: vec![],
meta: json!({}),
}));
idx += 1;
}
McpPayload::ToolsListResponse { tools, .. } => {
out.push(TraceEvent::Step(StepEntry {
episode_id: episode_id.clone(),
step_id: format!("step_{:03}", idx),
idx: idx as u32,
timestamp: last_ts,
kind: "tool".to_string(),
name: Some("tools/list.result".to_string()),
content: Some(json!({ "tools": tools }).to_string()),
content_sha256: None,
truncations: vec![],
meta: json!({}),
}));
idx += 1;
}
McpPayload::ToolCallRequest {
name, arguments, ..
} => {
let step_id = format!("step_{:03}", idx);
// Emit the Step (invocation intent)
out.push(TraceEvent::Step(StepEntry {
episode_id: episode_id.clone(),
step_id: step_id.clone(),
idx: idx as u32,
timestamp: last_ts,
kind: "tool".to_string(), // OTel mapping: system="tool"
name: Some(name.clone()),
content: None, // Content is in ToolCall args
content_sha256: None,
truncations: vec![],
meta: json!({ "jsonrpc_id": e.jsonrpc_id }),
}));
// Buffer for correlation if the id can be keyed
if let Some(id) = correlation.clone() {
pending_calls.insert(
id,
(step_id.clone(), name.clone(), arguments.clone(), last_ts),
);
} else {
// Fire and forget / Notification?
// Emit incomplete ToolCall? Or just Step?
// Use Step ID as correlation fallback if needed.
out.push(TraceEvent::ToolCall(ToolCallEntry {
episode_id: episode_id.clone(),
step_id,
timestamp: last_ts,
tool_name: name,
call_index: Some(0),
args: arguments,
args_sha256: None,
result: None, // No response yet/ever
result_sha256: None,
error: None,
truncations: vec![],
}));
}
idx += 1;
}
McpPayload::ToolCallResponse {
result, is_error, ..
} => {
// Try to find matching Request
if let Some(id) = correlation {
if let Some((step_id, name, args, _req_ts)) = pending_calls.remove(&id) {
// Found match! Emit complete ToolCall
out.push(TraceEvent::ToolCall(ToolCallEntry {
episode_id: episode_id.clone(),
step_id,
timestamp: last_ts,
tool_name: name,
call_index: Some(0),
args,
args_sha256: None,
result: Some(if is_error {
json!({"error": result.clone()})
} else {
result.clone()
}),
result_sha256: None,
error: if is_error {
Some("mcp_error".into())
} else {
None
},
truncations: vec![],
}));
} else {
// Orphan response: no matching pending tool call request
eprintln!(
"mcp_events_to_v2_trace: orphan ToolCallResponse with jsonrpc_id {:?} in episode {}",
id,
episode_id
);
}
}
// Heuristic: Last response is final output
final_output = Some(result.to_string());
}
McpPayload::SessionEnd { .. } if final_output.is_none() => {
final_output = Some("mcp_session_end".into());
}
_ => {}
}
}
// Flush pending calls (requests without responses)
for (_id, (step_id, name, args, req_ts)) in pending_calls {
out.push(TraceEvent::ToolCall(ToolCallEntry {
episode_id: episode_id.clone(),
step_id,
timestamp: req_ts,
tool_name: name,
call_index: Some(0),
args,
args_sha256: None,
result: None,
result_sha256: None,
error: Some("timeout/no_response".into()),
truncations: vec![],
}));
}
// Re-sort output by timestamp just in case buffering messed it up?
// Steps are compliant, but late ToolCalls might appear "later" in stream.
// But Trace V2 supports out-of-order ingestion usually.
// However, `assay-cli` replay usually expects roughly ordered stream.
// Let's rely on the DB/Ingester to sort by timestamp if needed, but for local trace file, chronological is nice.
// But `idx` is monotonic.
out.push(TraceEvent::EpisodeEnd(EpisodeEnd {
episode_id,
timestamp: last_ts.max(start_ts),
outcome: None,
final_output,
}));
out
}
fn summarize_auth_discovery(events: &[McpEvent]) -> McpAuthorizationDiscovery {
let mut summary = McpAuthorizationDiscovery::default();
for event in events {
summary.merge_from(&event.auth_discovery);
}
summary
}
fn now_ms() -> u64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}