crtx-mcp 0.1.2

MCP stdio JSON-RPC 2.0 server for Cortex — tool dispatch, ToolHandler trait, gate wiring (ADR 0045).
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
//! `cortex_memory_accept` MCP tool handler.
//!
//! Promotes a candidate memory to active after verifying the operator's
//! server-side confirmation token (ADR 0047 §3). The old caller-supplied
//! `confirmed: true` pattern (RT1-F4) is replaced with a `confirmation_token`
//! parameter that must match the token generated at server startup — the same
//! mechanism used by `CortexSessionCommitTool`.
//!
//! After token validation the handler composes the full ADR 0026 policy
//! envelope (proof-closure, contradiction, semantic-trust,
//! operator-temporal-use) and delegates to [`cortex_memory::accept`], exactly
//! as `cortex memory accept` does in the CLI.
//!
//! Gates: [`GateId::CommitWrite`].

use std::sync::{Arc, Mutex, RwLock};

use chrono::Utc;
use cortex_core::{
    compose_policy_outcomes, AuditRecordId, MemoryId, PolicyContribution, PolicyOutcome,
};
use cortex_memory::accept as memory_accept;
use cortex_store::{
    repo::{
        memories::{
            accept_open_contradiction_contribution, accept_proof_closure_contribution,
            ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID, ACCEPT_SEMANTIC_TRUST_RULE_ID,
        },
        ContradictionRepo, MemoryAcceptanceAudit, MemoryRepo,
    },
    verify_memory_proof_closure, Pool,
};
use serde_json::{json, Value};
use tracing::warn;

use crate::tool_handler::{GateId, ToolError, ToolHandler};

/// Stable invariant emitted when `memory_accept` bypasses the ADR 0047 §3
/// token check via auto-commit mode.
pub const MEMORY_ACCEPT_AUTO_COMMIT_INVARIANT: &str = "memory.accept.auto_commit_mode";

/// The `Warn`-floor invariant for the operator temporal-use contributor when
/// no operator attestation is bound on this surface (honest no-attestation
/// floor, not a BreakGlass substitution).
const ACCEPT_OPERATOR_TEMPORAL_AUTHORITY_WARN_NO_ATTESTATION_INVARIANT: &str =
    "memory.accept.operator_temporal_authority.warn_no_attestation";

/// MCP tool: `cortex_memory_accept`.
///
/// Schema:
/// ```text
/// cortex_memory_accept(
///   memory_id:          string,
///   confirmation_token: string,
/// ) ->
///   { accepted: bool, memory_id: string }
/// ```
#[derive(Debug)]
pub struct CortexMemoryAcceptTool {
    pool: Arc<Mutex<Pool>>,
    /// The confirmation token generated at server startup (ADR 0047 §3).
    ///
    /// Shared with `CortexSessionCommitTool` via the same
    /// `Arc<RwLock<Option<String>>>` written once by `serve.rs` before the
    /// stdio loop starts.
    pub session_token: Arc<RwLock<Option<String>>>,
    /// When `true`, the ADR 0047 §3 token check is bypassed.
    ///
    /// Set by `serve.rs` when `CORTEX_MCP_AUTO_COMMIT=1` is present in the
    /// environment. MUST only be used in operator-controlled CI contexts.
    pub auto_commit: bool,
}

impl CortexMemoryAcceptTool {
    /// Construct the tool over a shared, mutex-guarded store connection and
    /// the server-side confirmation token.
    #[must_use]
    pub fn new(
        pool: Arc<Mutex<Pool>>,
        session_token: Arc<RwLock<Option<String>>>,
        auto_commit: bool,
    ) -> Self {
        Self {
            pool,
            session_token,
            auto_commit,
        }
    }
}

impl ToolHandler for CortexMemoryAcceptTool {
    fn name(&self) -> &'static str {
        "cortex_memory_accept"
    }

    fn gate_set(&self) -> &'static [GateId] {
        &[GateId::CommitWrite]
    }

    fn call(&self, params: Value) -> Result<Value, ToolError> {
        // ── 1. Extract memory_id ──────────────────────────────────────────
        let memory_id_str = params["memory_id"]
            .as_str()
            .filter(|s| !s.is_empty())
            .ok_or_else(|| ToolError::InvalidParams("memory_id is required".into()))?;

        // ── 2. Extract confirmation_token ─────────────────────────────────
        let confirmation_token = params
            .get("confirmation_token")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                ToolError::InvalidParams(
                    "required parameter `confirmation_token` is missing or not a string".into(),
                )
            })?
            .to_owned();

        // ── 3. Verify the token (or bypass when auto_commit is active) ────
        if self.auto_commit {
            warn!(
                invariant = MEMORY_ACCEPT_AUTO_COMMIT_INVARIANT,
                "cortex_memory_accept: auto-commit mode — token check bypassed \
                 (CORTEX_MCP_AUTO_COMMIT=1) [{}]",
                MEMORY_ACCEPT_AUTO_COMMIT_INVARIANT,
            );
        } else {
            if confirmation_token.is_empty() {
                return Err(ToolError::InvalidParams(
                    "confirmation_token must not be empty".into(),
                ));
            }

            let stored_token = self
                .session_token
                .read()
                .map_err(|_| ToolError::Internal("session token lock poisoned".into()))?
                .clone();

            match stored_token {
                None => {
                    warn!("cortex_memory_accept: session token not initialised — rejecting");
                    return Err(ToolError::Internal(
                        "server session token not initialised".into(),
                    ));
                }
                Some(ref server_token) => {
                    if !tokens_equal(&confirmation_token, server_token) {
                        return Err(ToolError::PolicyRejected(
                            "invalid confirmation token".into(),
                        ));
                    }
                }
            }
        }

        // ── 4. Parse and validate the memory ID ──────────────────────────
        let memory_id: MemoryId = memory_id_str.parse().map_err(|err| {
            ToolError::InvalidParams(format!("memory_id `{memory_id_str}` is invalid: {err}"))
        })?;

        tracing::info!("cortex_memory_accept via MCP: memory_id={}", memory_id);

        // ── 5. Compose the ADR 0026 policy envelope ───────────────────────
        let pool_guard = self
            .pool
            .lock()
            .map_err(|err| ToolError::Internal(format!("pool lock poisoned: {err}")))?;

        let proof_report =
            verify_memory_proof_closure(&pool_guard, &memory_id).map_err(|err| {
                ToolError::Internal(format!(
                    "proof closure preflight failed for {memory_id}: {err}"
                ))
            })?;
        let proof_contribution = accept_proof_closure_contribution(&proof_report);

        let candidate_ref = memory_id.to_string();
        let contradictions = ContradictionRepo::new(&pool_guard)
            .list_open()
            .map_err(|err| {
                ToolError::Internal(format!(
                    "contradiction preflight failed for {memory_id}: {err}"
                ))
            })?;
        let open_contradictions = contradictions
            .iter()
            .filter(|row| row.left_ref == candidate_ref || row.right_ref == candidate_ref)
            .count();
        let contradiction_contribution = accept_open_contradiction_contribution(open_contradictions);

        let semantic_trust_contribution = PolicyContribution::new(
            ACCEPT_SEMANTIC_TRUST_RULE_ID,
            PolicyOutcome::Allow,
            "mcp operator confirmation token validated: \
             candidate passed lineage validation upstream",
        )
        .expect("static semantic trust contribution shape is valid");

        let operator_temporal_use_contribution = PolicyContribution::new(
            ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID,
            PolicyOutcome::Warn,
            format!(
                "{ACCEPT_OPERATOR_TEMPORAL_AUTHORITY_WARN_NO_ATTESTATION_INVARIANT}: \
                 no operator attestation bound on this MCP surface; accepting at the honest floor",
            ),
        )
        .expect("static operator temporal use contribution shape is valid");

        let policy = compose_policy_outcomes(
            vec![
                proof_contribution,
                contradiction_contribution,
                semantic_trust_contribution,
                operator_temporal_use_contribution,
            ],
            None,
        );

        // ── 6. Execute the accept via the cortex_memory lifecycle layer ───
        let repo = MemoryRepo::new(&pool_guard);
        let audit = MemoryAcceptanceAudit {
            id: AuditRecordId::new(),
            actor_json: json!({"kind": "mcp", "tool": "cortex_memory_accept"}),
            reason: "operator accepted candidate memory via MCP confirmation token".to_string(),
            source_refs_json: json!([memory_id.to_string()]),
            created_at: Utc::now(),
        };

        let accepted_id =
            memory_accept(&repo, &memory_id, Utc::now(), &audit, &policy, &proof_report)
                .map_err(|err| ToolError::PolicyRejected(err.to_string()))?;

        Ok(json!({
            "accepted": true,
            "memory_id": accepted_id.to_string(),
        }))
    }
}

/// Constant-time byte comparison to prevent timing oracle attacks on the
/// confirmation token (ADR 0047 §3).
///
/// Returns `true` only when both strings are identical. The comparison
/// always iterates over every byte of the shorter string even when lengths
/// differ, so it does not short-circuit on length mismatch in a way that
/// leaks information via timing.
fn tokens_equal(a: &str, b: &str) -> bool {
    if a.len() != b.len() {
        return false;
    }
    a.bytes()
        .zip(b.bytes())
        .fold(0u8, |acc, (x, y)| acc | (x ^ y))
        == 0
}

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

    fn make_tool(token: Option<&str>) -> CortexMemoryAcceptTool {
        make_tool_with_auto_commit(token, false)
    }

    fn make_tool_with_auto_commit(
        token: Option<&str>,
        auto_commit: bool,
    ) -> CortexMemoryAcceptTool {
        let pool = Arc::new(Mutex::new(
            cortex_store::Pool::open_in_memory().expect("in-memory sqlite"),
        ));
        let session_token = Arc::new(RwLock::new(token.map(str::to_owned)));
        CortexMemoryAcceptTool::new(pool, session_token, auto_commit)
    }

    /// Missing `confirmation_token` must be rejected with InvalidParams.
    #[test]
    fn missing_confirmation_token_returns_invalid_params() {
        let tool = make_tool(Some("correct-token"));
        let err = tool
            .call(serde_json::json!({"memory_id": "01JSVFAKEAAAAAAAAAAAAAAAAA"}))
            .expect_err("must reject missing token");
        assert!(
            matches!(err, ToolError::InvalidParams(_)),
            "expected InvalidParams, got: {err:?}"
        );
    }

    /// Empty `confirmation_token` must be rejected with InvalidParams.
    #[test]
    fn empty_confirmation_token_returns_invalid_params() {
        let tool = make_tool(Some("correct-token"));
        let err = tool
            .call(serde_json::json!({
                "memory_id": "01JSVFAKEAAAAAAAAAAAAAAAAA",
                "confirmation_token": ""
            }))
            .expect_err("must reject empty token");
        assert!(
            matches!(err, ToolError::InvalidParams(_)),
            "expected InvalidParams, got: {err:?}"
        );
    }

    /// Wrong token must return PolicyRejected.
    #[test]
    fn wrong_token_returns_policy_rejected() {
        let tool = make_tool(Some("correct-token"));
        let err = tool
            .call(serde_json::json!({
                "memory_id": "01JSVFAKEAAAAAAAAAAAAAAAAA",
                "confirmation_token": "wrong-token"
            }))
            .expect_err("must reject wrong token");
        assert!(
            matches!(err, ToolError::PolicyRejected(_)),
            "expected PolicyRejected, got: {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("invalid confirmation token"),
            "error must cite ADR 0047 §3 message: {msg}"
        );
    }

    /// Uninitialised server token must fail with Internal, not PolicyRejected.
    #[test]
    fn uninitialised_server_token_returns_internal() {
        let tool = make_tool(None);
        let err = tool
            .call(serde_json::json!({
                "memory_id": "01JSVFAKEAAAAAAAAAAAAAAAAA",
                "confirmation_token": "anything"
            }))
            .expect_err("must fail when server token is uninitialised");
        assert!(
            matches!(err, ToolError::Internal(_)),
            "expected Internal, got: {err:?}"
        );
    }

    /// Missing `memory_id` must be rejected with InvalidParams.
    #[test]
    fn missing_memory_id_returns_invalid_params() {
        let tool = make_tool(Some("tok"));
        let err = tool
            .call(serde_json::json!({"confirmation_token": "tok"}))
            .expect_err("must reject missing memory_id");
        assert!(
            matches!(err, ToolError::InvalidParams(_)),
            "expected InvalidParams, got: {err:?}"
        );
    }

    /// gate_set must declare CommitWrite.
    #[test]
    fn gate_set_declares_commit_write() {
        let tool = make_tool(Some("tok"));
        assert!(
            tool.gate_set().contains(&GateId::CommitWrite),
            "gate_set must include CommitWrite"
        );
    }

    /// gate_set must NOT declare SessionWrite (that was the old, incorrect wiring).
    #[test]
    fn gate_set_does_not_declare_session_write() {
        let tool = make_tool(Some("tok"));
        assert!(
            !tool.gate_set().contains(&GateId::SessionWrite),
            "gate_set must not include SessionWrite"
        );
    }

    /// Tool name matches the MCP schema contract.
    #[test]
    fn tool_name_matches_schema_contract() {
        let tool = make_tool(Some("tok"));
        assert_eq!(tool.name(), "cortex_memory_accept");
    }

    /// In auto-commit mode a missing `confirmation_token` is still InvalidParams.
    #[test]
    fn auto_commit_rejects_missing_token_param() {
        let tool = make_tool_with_auto_commit(Some("server-tok"), true);
        let err = tool
            .call(serde_json::json!({"memory_id": "01JSVFAKEAAAAAAAAAAAAAAAAA"}))
            .expect_err("missing param must still be rejected in auto_commit mode");
        assert!(
            matches!(err, ToolError::InvalidParams(_)),
            "expected InvalidParams, got: {err:?}"
        );
    }

    /// The auto-commit invariant constant has the expected value.
    #[test]
    fn auto_commit_invariant_constant_value() {
        assert_eq!(
            MEMORY_ACCEPT_AUTO_COMMIT_INVARIANT,
            "memory.accept.auto_commit_mode"
        );
    }

    /// Regression guard for RT1-F4: a caller-supplied `confirmed: true` must
    /// NOT bypass the token check.
    ///
    /// Passing `confirmed: true` without a valid `confirmation_token` must
    /// fail with InvalidParams (missing required param), not succeed.
    #[test]
    fn confirmed_bool_true_does_not_bypass_token_check() {
        let tool = make_tool(Some("correct-token"));
        // Pass the old vulnerable parameter — no `confirmation_token`.
        let err = tool
            .call(serde_json::json!({
                "memory_id": "01JSVFAKEAAAAAAAAAAAAAAAAA",
                "confirmed": true
            }))
            .expect_err("confirmed:true without token must be rejected");
        assert!(
            matches!(err, ToolError::InvalidParams(_)),
            "expected InvalidParams (missing confirmation_token), got: {err:?}"
        );
    }
}