Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(mcp): propagate actor identity + skip-list to admission ctx

Djalma Júniorb77beb52efda
diff --git a/crates/ai-memory-mcp/src/actor.rs b/crates/ai-memory-mcp/src/actor.rs
new file mode 100644
index 00000000..a27ba9fd
--- /dev/null
+++ b/crates/ai-memory-mcp/src/actor.rs
@@ -0,0 +1,168 @@
+//! Per-request actor context — pure helper mapping `X-Memory-Actor-*`
+//! HTTP headers to a typed [`ActorContext`].
+//!
+//! ## Why this exists
+//!
+//! `mcp-auth` (Go sidecar) validates the Keycloak JWT and injects 5
+//! request headers derived from claims. The `memory_write_page` tool
+//! method receives the raw HTTP `Parts` via rmcp's `Extension<Parts>`
+//! extractor (rmcp 1.7+) and calls [`actor_from_headers`] to build the
+//! [`ActorContext`] that feeds into the admission webhook chain.
+//!
+//! ## Why not `tokio::task_local`
+//!
+//! We tried that first. `rmcp::transport::streamable_http_server::tower`
+//! dispatches each tool handler via `tokio::spawn` (see
+//! `tower.rs:569+619+1183`), which **does not** inherit task-locals from
+//! the outer axum middleware. The Extension extractor is the official
+//! supported path — see
+//! <https://docs.rs/rmcp/1.7/rmcp/transport/streamable_http_server/struct.StreamableHttpService.html#accessing-http-request-data-from-tool-handlers>.
+//!
+//! ## Wire contract
+//!
+//! Headers expected (set by `mcp-auth` from validated JWT claims):
+//!
+//! | Header | JWT claim source |
+//! |---|---|
+//! | `X-Memory-Actor-Agent` | DCR `client_name` (fallback `azp`) |
+//! | `X-Memory-Actor-User` | `preferred_username` |
+//! | `X-Memory-Actor-Sub` | `sub` |
+//! | `X-Memory-Actor-Client` | `azp` (authorized party / DCR client UUID) |
+//! | `X-Memory-Actor-Session-Id` | optional |
+//!
+//! All headers are optional — missing ones fall back to `None`. Use
+//! [`ActorContext::has_any`] to skip building an admission context when
+//! the actor is completely anonymous (the chain still runs with a
+//! default context — webhooks decide what to do with an empty actor).
+
+use ai_memory_wiki::ActorContext;
+use axum::http::HeaderMap;
+
+fn header_str(headers: &HeaderMap, name: &str) -> Option<String> {
+ headers
+ .get(name)
+ .and_then(|v| v.to_str().ok())
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+}
+
+/// Build an [`ActorContext`] from `X-Memory-Actor-*` headers.
+///
+/// Header names are matched case-insensitively (per HTTP spec).
+#[must_use]
+pub fn actor_from_headers(headers: &HeaderMap) -> ActorContext {
+ ActorContext {
+ agent: header_str(headers, "x-memory-actor-agent"),
+ user: header_str(headers, "x-memory-actor-user"),
+ sub: header_str(headers, "x-memory-actor-sub"),
+ client: header_str(headers, "x-memory-actor-client"),
+ session_id: header_str(headers, "x-memory-actor-session-id"),
+ }
+}
+
+/// Parse the admission-chain loop-prevention skip list from the
+/// `X-Memory-Skip-Admission-Chain` request header (comma-separated
+/// webhook names). A webhook that writes back into the engine (e.g. via
+/// `memory_write_page`) sets this so the chain doesn't re-invoke it on
+/// the recursive write — see [`ai_memory_wiki::AdmissionContext::skip_webhooks`].
+///
+/// Returns an empty `Vec` when the header is absent. Entries are trimmed
+/// and empty tokens dropped, so `"a, ,b,"` → `["a", "b"]`.
+#[must_use]
+pub fn skip_webhooks_from_headers(headers: &HeaderMap) -> Vec<String> {
+ headers
+ .get("x-memory-skip-admission-chain")
+ .and_then(|v| v.to_str().ok())
+ .map(|s| {
+ s.split(',')
+ .map(str::trim)
+ .filter(|t| !t.is_empty())
+ .map(str::to_string)
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::http::HeaderValue;
+
+ #[test]
+ fn full_header_set_maps_correctly() {
+ let mut h = HeaderMap::new();
+ h.insert(
+ "x-memory-actor-agent",
+ HeaderValue::from_static("claude-code"),
+ );
+ h.insert("x-memory-actor-user", HeaderValue::from_static("djalmajr"));
+ h.insert("x-memory-actor-sub", HeaderValue::from_static("8f3a-uuid"));
+ h.insert(
+ "x-memory-actor-client",
+ HeaderValue::from_static("72836f52-uuid"),
+ );
+ h.insert(
+ "x-memory-actor-session-id",
+ HeaderValue::from_static("019e6d-session"),
+ );
+ let ctx = actor_from_headers(&h);
+ assert_eq!(ctx.agent.as_deref(), Some("claude-code"));
+ assert_eq!(ctx.user.as_deref(), Some("djalmajr"));
+ assert_eq!(ctx.sub.as_deref(), Some("8f3a-uuid"));
+ assert_eq!(ctx.client.as_deref(), Some("72836f52-uuid"));
+ assert_eq!(ctx.session_id.as_deref(), Some("019e6d-session"));
+ assert!(ctx.has_any());
+ }
+
+ #[test]
+ fn missing_headers_leave_none() {
+ let h = HeaderMap::new();
+ let ctx = actor_from_headers(&h);
+ assert!(ctx.agent.is_none());
+ assert!(ctx.user.is_none());
+ assert!(ctx.sub.is_none());
+ assert!(ctx.client.is_none());
+ assert!(ctx.session_id.is_none());
+ assert!(!ctx.has_any());
+ }
+
+ #[test]
+ fn empty_or_whitespace_header_treated_as_none() {
+ let mut h = HeaderMap::new();
+ h.insert("x-memory-actor-agent", HeaderValue::from_static(" "));
+ h.insert("x-memory-actor-user", HeaderValue::from_static(""));
+ let ctx = actor_from_headers(&h);
+ assert!(ctx.agent.is_none(), "whitespace must trim to None");
+ assert!(ctx.user.is_none(), "empty must be None");
+ assert!(!ctx.has_any());
+ }
+
+ #[test]
+ fn case_insensitive_header_lookup() {
+ // HeaderMap normalises names to lowercase on insert; this verifies
+ // that the canonical `X-Memory-Actor-Agent` form also resolves.
+ let mut h = HeaderMap::new();
+ h.insert("X-Memory-Actor-Agent", HeaderValue::from_static("codex"));
+ let ctx = actor_from_headers(&h);
+ assert_eq!(ctx.agent.as_deref(), Some("codex"));
+ }
+
+ #[test]
+ fn skip_webhooks_parses_csv_trims_and_drops_empties() {
+ let mut h = HeaderMap::new();
+ h.insert(
+ "x-memory-skip-admission-chain",
+ HeaderValue::from_static("contributors, ,git-mirror,"),
+ );
+ assert_eq!(
+ skip_webhooks_from_headers(&h),
+ vec!["contributors".to_string(), "git-mirror".to_string()]
+ );
+ }
+
+ #[test]
+ fn skip_webhooks_absent_header_is_empty() {
+ let h = HeaderMap::new();
+ assert!(skip_webhooks_from_headers(&h).is_empty());
+ }
+}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 02db1737..f8151394 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1613,6 +1613,7 @@ async fn handle_write_page(
tier,
pinned: req.pinned,
title: req.title,
+ admission_ctx: None,
})
.await
.map_err(|e| internal_err(e.to_string()))?;
diff --git a/crates/ai-memory-mcp/src/lib.rs b/crates/ai-memory-mcp/src/lib.rs
index 5b9db9c2..ac178164 100644
--- a/crates/ai-memory-mcp/src/lib.rs
+++ b/crates/ai-memory-mcp/src/lib.rs
@@ -8,8 +8,10 @@
//! agentmemory #510 / #553 "negotiated-down to a version the client
//! discards tools for" failure mode.
+pub mod actor;
pub mod admin;
mod server;
+pub use actor::actor_from_headers;
pub use admin::{AdminState, admin_router};
pub use server::{AiMemoryServer, MEMORY_INSTRUCTIONS};
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index d93a9bf8..f3bcd2fd 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -12,6 +12,7 @@ use ai_memory_llm::{Embedder, LlmProvider};
use ai_memory_store::{DecayParams, PageHit, ReaderPool, WriterHandle};
use ai_memory_wiki::{Wiki, WritePageRequest};
use rmcp::handler::server::router::tool::ToolRouter;
+use rmcp::handler::server::tool::Extension;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
CallToolResult, Content, Implementation, ProtocolVersion, ServerCapabilities, ServerInfo,
@@ -814,6 +815,7 @@ impl AiMemoryServer {
async fn memory_write_page(
&self,
Parameters(args): Parameters<WritePageArgs>,
+ Extension(parts): Extension<axum::http::request::Parts>,
) -> Result<CallToolResult, McpError> {
let Some(wiki) = self.wiki.as_ref() else {
return Err(McpError::internal_error(
@@ -854,6 +856,29 @@ impl AiMemoryServer {
serde_json::Value::Object(fm)
};
+ // Populate the admission context from the request's `X-Memory-Actor-*`
+ // headers (set by the `mcp-auth` sidecar after JWT validation). rmcp 1.7
+ // exposes the original HTTP `Parts` via the `Extension<Parts>` extractor —
+ // task-locals can't be used because StreamableHttpService dispatches the
+ // tool handler in a `tokio::spawn`-ed task that doesn't inherit them.
+ // See `crate::actor::actor_from_headers` for the JWT-claim → header map.
+ let actor = crate::actor::actor_from_headers(&parts.headers);
+ // Loop prevention: a webhook that writes back into the engine sets
+ // `X-Memory-Skip-Admission-Chain` so the chain doesn't re-invoke it
+ // on the recursive write. Build the ctx when either the actor OR the
+ // skip list is present (a skip-only write still needs to carry it).
+ let skip_webhooks = crate::actor::skip_webhooks_from_headers(&parts.headers);
+ let admission_ctx = if actor.has_any() || !skip_webhooks.is_empty() {
+ Some(ai_memory_wiki::AdmissionContext {
+ actor,
+ op: ai_memory_wiki::AdmissionOp::WritePage,
+ skip_webhooks,
+ ..ai_memory_wiki::AdmissionContext::default()
+ })
+ } else {
+ None
+ };
+
let page_id = wiki
.write_page(WritePageRequest {
workspace_id: ws,
@@ -864,6 +889,7 @@ impl AiMemoryServer {
tier,
pinned: args.pinned,
title: args.title,
+ admission_ctx,
})
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
@@ -1851,16 +1877,29 @@ mod tests {
let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
.with_wiki(wiki);
+ // Build a synthetic `Parts` so the new `Extension<Parts>` extractor
+ // can be satisfied — no actor headers, so the admission chain
+ // gets a default (anonymous) context, same as a stdio caller.
+ let parts = axum::http::Request::builder()
+ .uri("/mcp")
+ .method("POST")
+ .body(())
+ .unwrap()
+ .into_parts()
+ .0;
let result = server
- .memory_write_page(Parameters(WritePageArgs {
- path: "notes/santander-2025.md".into(),
- body: "# Santander 2025\n\nDurable tax annotation.".into(),
- title: Some("Santander 2025".into()),
- tier: Some("semantic".into()),
- tags: vec!["finance".into()],
- pinned: true,
- project: None,
- }))
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ path: "notes/santander-2025.md".into(),
+ body: "# Santander 2025\n\nDurable tax annotation.".into(),
+ title: Some("Santander 2025".into()),
+ tier: Some("semantic".into()),
+ tags: vec!["finance".into()],
+ pinned: true,
+ project: None,
+ }),
+ rmcp::handler::server::tool::Extension(parts),
+ )
.await
.unwrap();
let text = result
diff --git a/crates/ai-memory-mcp/tests/admin_backup.rs b/crates/ai-memory-mcp/tests/admin_backup.rs
index 787ac431..7a16ade5 100644
--- a/crates/ai-memory-mcp/tests/admin_backup.rs
+++ b/crates/ai-memory-mcp/tests/admin_backup.rs
@@ -64,6 +64,7 @@ async fn seed_page(state: &AdminState, store: &Store, path: &str, body: &str) {
tier: Tier::Semantic,
pinned: false,
title: Some("Test".into()),
+ admission_ctx: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rs
index 0cf1a250..a17f9775 100644
--- a/crates/ai-memory-mcp/tests/admin_phase3.rs
+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs
@@ -360,6 +360,7 @@ async fn embed_all_projects_rebuilds_workspace_projects() {
tier: Tier::Semantic,
pinned: false,
title: Some("A".into()),
+ admission_ctx: None,
})
.await
.unwrap();
@@ -374,6 +375,7 @@ async fn embed_all_projects_rebuilds_workspace_projects() {
tier: Tier::Semantic,
pinned: false,
title: Some("B".into()),
+ admission_ctx: None,
})
.await
.unwrap();
@@ -463,6 +465,7 @@ async fn commit_with_new_page_returns_committed_true_and_40char_oid() {
tier: Tier::Semantic,
pinned: false,
title: Some("Commit test".into()),
+ admission_ctx: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/tests/admin_purge.rs b/crates/ai-memory-mcp/tests/admin_purge.rs
index c84f7e38..7fd9f0ef 100644
--- a/crates/ai-memory-mcp/tests/admin_purge.rs
+++ b/crates/ai-memory-mcp/tests/admin_purge.rs
@@ -89,6 +89,7 @@ async fn seed_two_projects(store: &Store, wiki: &Wiki) -> (WorkspaceId, ProjectI
tier: Tier::Semantic,
pinned: false,
title: Some("Keep page".into()),
+ admission_ctx: None,
})
.await
.unwrap();
@@ -102,6 +103,7 @@ async fn seed_two_projects(store: &Store, wiki: &Wiki) -> (WorkspaceId, ProjectI
tier: Tier::Semantic,
pinned: false,
title: Some("Doomed page".into()),
+ admission_ctx: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/tests/admin_rename.rs b/crates/ai-memory-mcp/tests/admin_rename.rs
index 6d5d01fb..f6953711 100644
--- a/crates/ai-memory-mcp/tests/admin_rename.rs
+++ b/crates/ai-memory-mcp/tests/admin_rename.rs
@@ -78,6 +78,7 @@ async fn seed_page(store: &Store, wiki: &Wiki, project: &str) -> String {
tier: Tier::Semantic,
pinned: false,
title: Some(project.into()),
+ admission_ctx: None,
})
.await
.unwrap();