mcpr_integrations/store/event.rs
1//! Event types sent from the proxy hot path to the background storage writer.
2//!
3//! These are the "write side" of the storage engine. The proxy constructs events
4//! from MCP request/response data and sends them through an mpsc channel —
5//! never blocking the hot path.
6//!
7//! # Separation from McprEvent
8//!
9//! `mcpr-integrations` has its own `McprEvent` for cloud/stdout emission.
10//! `StoreEvent` is intentionally independent — different schema, different
11//! lifecycle, no coupling between crates. The conversion happens at the
12//! call site in `mcp_handler.rs` where both are built from the same locals.
13
14/// Top-level event enum sent through the storage channel.
15///
16/// The background writer dispatches on this to decide which table to write to
17/// and whether to INSERT, UPDATE, or close a session.
18#[derive(Debug)]
19pub enum StoreEvent {
20 /// A completed MCP request — one row in the `requests` table.
21 Request(RequestEvent),
22
23 /// A new MCP session from an `initialize` handshake — one row in `sessions`.
24 Session(SessionEvent),
25
26 /// A session was cleanly closed (transport disconnect).
27 /// Updates `ended_at` on the existing session row.
28 SessionClosed {
29 session_id: String,
30 /// Unix milliseconds (UTC) when the close was detected.
31 ended_at: i64,
32 },
33
34 /// A new `SchemaVersion` was created by the proxy's SchemaManager.
35 /// Writer UPSERTs `server_schema` and appends change rows.
36 SchemaVersion(SchemaVersionEvent),
37}
38
39/// One completed MCP request, ready to be written to the `requests` table.
40///
41/// Built from the same data the proxy already computes for logging and cloud
42/// emission (method, tool name, latency, status, sizes). No extra parsing needed.
43#[derive(Debug)]
44pub struct RequestEvent {
45 /// UUIDv7 generated by mcpr — time-ordered, globally unique.
46 /// Used for cloud emitter correlation and as the primary lookup key.
47 pub request_id: String,
48
49 /// Unix milliseconds (UTC) when the request was received.
50 /// Millisecond resolution is sufficient for latency tracking and avoids
51 /// i64 overflow concerns that nanosecond timestamps would introduce.
52 pub ts: i64,
53
54 /// Proxy name from config (e.g., "api-server").
55 /// Tags every row so a shared database can hold data from multiple proxies.
56 pub proxy: String,
57
58 /// MCP session ID from the `mcp-session-id` header.
59 /// Nullable: pre-handshake probes or malformed clients may not have one.
60 /// Soft foreign key to `sessions.session_id` (no hard FK constraint —
61 /// avoids ordering edge cases in the async writer).
62 pub session_id: Option<String>,
63
64 /// MCP JSON-RPC method (e.g., "tools/call", "resources/read", "initialize").
65 /// Stored as-is from the protocol layer — no normalization.
66 pub method: String,
67
68 /// Tool name for `tools/call` requests, None for other methods.
69 /// Extracted from the JSON-RPC params by the proxy's MCP parser.
70 pub tool: Option<String>,
71
72 /// Wall-clock time from proxy receiving the request to getting the upstream response.
73 /// Includes network round-trip to upstream — this is what the AI client experiences.
74 /// Stored in microseconds for sub-millisecond precision.
75 pub latency_us: i64,
76
77 /// Whether the request succeeded, failed, or timed out.
78 pub status: RequestStatus,
79
80 /// MCP error code if `status` is `Error` (e.g., "-32600", "-32601").
81 /// None for successful requests.
82 pub error_code: Option<String>,
83
84 /// Human-readable error message, truncated to 512 chars at the call site.
85 /// None for successful requests.
86 pub error_msg: Option<String>,
87
88 /// Request payload size in bytes. None if not measured.
89 pub bytes_in: Option<i64>,
90
91 /// Response payload size in bytes. None if not measured.
92 pub bytes_out: Option<i64>,
93}
94
95/// Emitted once per MCP session, when the proxy intercepts the `initialize` handshake.
96///
97/// The `clientInfo` field in the MCP `initialize` request is the authoritative source
98/// of client identity — we don't guess from headers or user-agent strings.
99#[derive(Debug)]
100pub struct SessionEvent {
101 /// MCP session ID — primary key in the `sessions` table.
102 pub session_id: String,
103
104 /// Which proxy this session connected through.
105 pub proxy: String,
106
107 /// Unix milliseconds (UTC) of the `initialize` request.
108 pub started_at: i64,
109
110 /// Client name from `clientInfo.name` (e.g., "claude-desktop", "cursor").
111 /// None if the client omits `clientInfo` (non-compliant but possible).
112 pub client_name: Option<String>,
113
114 /// Client version from `clientInfo.version` (e.g., "1.2.0").
115 pub client_version: Option<String>,
116
117 /// Normalized platform identifier derived from client_name.
118 /// Values: "claude", "chatgpt", "vscode", "cursor", "unknown".
119 /// Normalization happens at write time via a static lookup table.
120 pub client_platform: Option<String>,
121}
122
123/// A new `SchemaVersion` produced by the proxy's `SchemaManager`.
124///
125/// The writer trusts the event: `SchemaManager` guarantees the payload
126/// differs from the previous version (unchanged ingests return `None`
127/// and produce no event). The writer only diffs against the prior row
128/// to populate `schema_changes`.
129#[derive(Debug)]
130pub struct SchemaVersionEvent {
131 pub ts: i64,
132 /// Proxy name from config (upstream identity).
133 pub proxy: String,
134 pub upstream_url: String,
135 pub method: String,
136 /// Merged `result` payload as JSON string.
137 pub payload: String,
138 /// SHA-256 hex digest of the canonical payload.
139 pub content_hash: String,
140}
141
142/// Outcome of a single MCP request.
143///
144/// Maps to the `status` CHECK constraint in the `requests` table:
145/// `CHECK (status IN ('ok', 'error', 'timeout'))`.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum RequestStatus {
148 /// Upstream returned a valid MCP response (may still contain application-level errors).
149 Ok,
150 /// Upstream returned an MCP error response (JSON-RPC error object).
151 Error,
152 /// The request timed out before the upstream responded.
153 Timeout,
154}
155
156impl RequestStatus {
157 /// SQL-safe string representation, matching the CHECK constraint values.
158 pub fn as_str(&self) -> &'static str {
159 match self {
160 RequestStatus::Ok => "ok",
161 RequestStatus::Error => "error",
162 RequestStatus::Timeout => "timeout",
163 }
164 }
165}