From 6af3cb62be0b0cd65b4045dd15b12847a92556ce Mon Sep 17 00:00:00 2001 From: htjulia Date: Sun, 29 Nov 2026 19:42:59 +0900 Subject: [PATCH] fix(mcp): bind sessions to their principal and reclaim idle ones MCP session ids came from a sequential counter, sessions were never expired, and POST/GET/DELETE on /platform/mcp only checked that an id existed. Any caller that could reach the endpoint could guess an id and read another session's stream and replay buffer or end it, including the stdio session through the shared HTTP listener. Follow Protean's McpSessionRegistry and McpHttpController: - issue random UUID v4 session ids - bind each session to the principal that initialized it; another principal's POST/GET answers 404 as for an unknown session and its DELETE is a 204 no-op - reclaim sessions idle for 30 minutes (only owner lookups count as activity), closing their streams; embedders can change the timeout with McpSessionStore::set_session_idle_timeout - validate the session before registering the request for cancellation, as Java does before dispatch - end the stdio session as the stdio-local principal at EOF Design doc 17 records the timeout config key non-parity. Closes #113 Tags: #mcp #security #session Co-Authored-By: htjulia --- crates/protrus-host/src/bin/protrus-host.rs | 6 +- crates/protrus-web/src/lib.rs | 343 ++++++++++++++---- .../17-mcp-session-and-extension-contract.md | 25 ++ docs/guide/03-deploying-and-operating.md | 5 +- 4 files changed, 316 insertions(+), 63 deletions(-) diff --git a/crates/protrus-host/src/bin/protrus-host.rs b/crates/protrus-host/src/bin/protrus-host.rs index d730135..250486f 100644 --- a/crates/protrus-host/src/bin/protrus-host.rs +++ b/crates/protrus-host/src/bin/protrus-host.rs @@ -569,9 +569,13 @@ async fn serve_stdio( std::io::stdout().flush()?; } if let Some(session_id) = mcp_session_id { - let request = Request::delete("/platform/mcp") + // The session belongs to the stdio principal, so only that principal can end it. + let mut request = Request::delete("/platform/mcp") .header("Mcp-Session-Id", session_id) .body(Body::empty())?; + request + .extensions_mut() + .insert(AuthenticatedPrincipal("stdio-local".into())); let _ = application.clone().oneshot(request).await; } http_server.abort(); diff --git a/crates/protrus-web/src/lib.rs b/crates/protrus-web/src/lib.rs index 40c9deb..d9197e6 100644 --- a/crates/protrus-web/src/lib.rs +++ b/crates/protrus-web/src/lib.rs @@ -602,12 +602,21 @@ struct McpSession { events: VecDeque<(u64, Value)>, next_event_id: u64, sender: broadcast::Sender<(u64, Value)>, + /// Java's `McpSession.owner`: the principal that initialized the session (`None` when + /// unauthenticated). Only requests from the same principal may use it. + owner: Option, + /// Java's `lastActivityNanos`: reset by every successful owner lookup. + last_activity: std::time::Instant, } +/// Java's `protean.mcp.session.timeout` default (`30m`). +pub const MCP_SESSION_IDLE_TIMEOUT: Duration = Duration::from_secs(30 * 60); +/// Java's `McpSessionRegistry.HEARTBEAT_MS`: the sweep cadence while a stream is open. +const MCP_SESSION_SWEEP_INTERVAL: Duration = Duration::from_secs(15); + /// The MCP server's state: sessions with their replay buffers, and Protean `McpDispatcher`'s /// server-global log threshold, resource subscriptions, and list page size. pub struct McpSessionStore { - next_session_id: AtomicU64, sessions: Mutex>, log_level: std::sync::atomic::AtomicU8, subscriptions: std::sync::Mutex>, @@ -618,12 +627,13 @@ pub struct McpSessionStore { /// Protean's `mcp.session.enabled`: when off there is no session registry, so `initialize` /// issues no `Mcp-Session-Id`, a session id is not checked, and GET has no stream (405). sessions_enabled: bool, + /// Java's idle timeout in milliseconds; 0 disables idle reclaim. + idle_timeout_ms: AtomicU64, } impl Default for McpSessionStore { fn default() -> Self { Self { - next_session_id: AtomicU64::default(), sessions: Mutex::default(), log_level: std::sync::atomic::AtomicU8::new(McpLogLevel::Info as u8), subscriptions: std::sync::Mutex::default(), @@ -632,6 +642,7 @@ impl Default for McpSessionStore { inflight: std::sync::Mutex::default(), strict_schema: std::sync::atomic::AtomicBool::new(false), sessions_enabled: true, + idle_timeout_ms: AtomicU64::new(MCP_SESSION_IDLE_TIMEOUT.as_millis() as u64), } } } @@ -649,51 +660,112 @@ impl McpSessionStore { self.sessions_enabled } - /// Java answers 404 to a session id it does not know, and checks nothing when sessions are off. - async fn rejects_session(&self, id: &str) -> bool { - self.sessions_enabled && !self.contains(id).await + /// Java's `protean.mcp.session.timeout`: sessions with no owner lookup for longer than this + /// are reclaimed. `Duration::ZERO` disables idle reclaim, as a non-positive value does in Java. + pub fn set_session_idle_timeout(&self, timeout: Duration) { + self.idle_timeout_ms.store( + u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX), + Ordering::Relaxed, + ); + } + + pub fn session_idle_timeout(&self) -> Duration { + Duration::from_millis(self.idle_timeout_ms.load(Ordering::Relaxed)) + } + + /// Java answers 404 to a session id it does not know or that another principal owns, and + /// checks nothing when sessions are off. + async fn rejects_session(&self, id: &str, principal: Option<&str>) -> bool { + self.sessions_enabled && !self.lookup(id, principal).await + } + + /// Java's `McpSessionRegistry.get(id, principalName)`: true only when the session exists and + /// belongs to `principal`; another principal's session is indistinguishable from an unknown + /// one. Only a successful lookup counts as activity. + async fn lookup(&self, id: &str, principal: Option<&str>) -> bool { + let mut sessions = self.sessions.lock().await; + self.reclaim_idle(&mut sessions); + match sessions.get_mut(id) { + Some(session) if session.owner.as_deref() == principal => { + session.last_activity = std::time::Instant::now(); + true + } + _ => false, + } + } + + /// Java's `sweep`: removes every session idle longer than the timeout. Dropping a session + /// drops its sender, which ends its open GET stream as Java's `terminate` completes it. + fn reclaim_idle(&self, sessions: &mut BTreeMap) { + let timeout = self.session_idle_timeout(); + if timeout.is_zero() { + return; + } + sessions.retain(|_, session| session.last_activity.elapsed() <= timeout); + } + + async fn sweep(&self) { + let mut sessions = self.sessions.lock().await; + self.reclaim_idle(&mut sessions); } /// Java's `McpSessionRegistry.broadcast`: the notification goes to every session's stream. pub async fn broadcast(&self, payload: Value) { - let ids: Vec = self.sessions.lock().await.keys().cloned().collect(); + let ids: Vec = { + let mut sessions = self.sessions.lock().await; + self.reclaim_idle(&mut sessions); + sessions.keys().cloned().collect() + }; for id in ids { self.publish(&id, payload.clone()).await; } } + /// Java's `create()`: an unowned session, usable by unauthenticated requests only. + #[cfg(test)] async fn create(&self) -> String { - let id = format!( - "mcp-{}", - self.next_session_id.fetch_add(1, Ordering::Relaxed) + 1 - ); + self.create_for(None).await + } + + /// Java's `create(owner)`: a session with a random UUID id, bound to the principal that + /// initialized it. + async fn create_for(&self, owner: Option<&str>) -> String { + let id = uuid::Uuid::new_v4().to_string(); let (sender, _) = broadcast::channel(64); - self.sessions.lock().await.insert( + let mut sessions = self.sessions.lock().await; + self.reclaim_idle(&mut sessions); + sessions.insert( id.clone(), McpSession { events: VecDeque::new(), next_event_id: 0, sender, + owner: owner.map(str::to_owned), + last_activity: std::time::Instant::now(), }, ); id } - async fn contains(&self, id: &str) -> bool { - self.sessions.lock().await.contains_key(id) - } - - async fn remove(&self, id: &str) { - self.sessions.lock().await.remove(id); + /// Java's DELETE: terminates the session only when `principal` owns it. + async fn terminate(&self, id: &str, principal: Option<&str>) { + if self.lookup(id, principal).await { + self.sessions.lock().await.remove(id); + } } async fn open( &self, id: &str, + principal: Option<&str>, after: u64, ) -> Option<(Vec<(u64, Value)>, broadcast::Receiver<(u64, Value)>)> { - let sessions = self.sessions.lock().await; - let session = sessions.get(id)?; + let mut sessions = self.sessions.lock().await; + self.reclaim_idle(&mut sessions); + let session = sessions + .get_mut(id) + .filter(|session| session.owner.as_deref() == principal)?; + session.last_activity = std::time::Instant::now(); let replay = session .events .iter() @@ -1033,20 +1105,23 @@ async fn mcp_post( .filter(|token| !token.is_null()) .cloned(); let streams = token.is_some() && method.as_deref() == Some("tools/call"); - // Java validates the protocol version and the session before it opens a progress stream. - if streams { - if let Some(version) = headers - .get("MCP-Protocol-Version") - .and_then(|value| value.to_str().ok()) - && version != MCP_PROTOCOL_VERSION - { - return mcp_problem(version); - } - if let Some(session_id) = session_id.as_deref() - && state.mcp.rejects_session(session_id).await - { - return mcp_session_problem(session_id, StatusCode::NOT_FOUND).into_response(); - } + // Java validates the protocol version, then the session (which must be known and belong to + // the calling principal), before it dispatches or opens a progress stream. + if let Some(version) = headers + .get("MCP-Protocol-Version") + .and_then(|value| value.to_str().ok()) + && version != MCP_PROTOCOL_VERSION + { + return mcp_problem(version); + } + if let Some(session_id) = session_id.as_deref().filter(|id| !id.trim().is_empty()) + && method.as_deref() != Some("initialize") + && state + .mcp + .rejects_session(session_id, surfaces.principal.as_ref().map(|p| p.0.0.as_str())) + .await + { + return mcp_session_problem(session_id, StatusCode::NOT_FOUND).into_response(); } let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); let progress = Arc::new(mcp_features::McpProgress::new( @@ -1128,12 +1203,6 @@ async fn mcp_respond( let Some(method) = method.as_deref() else { return protocol_error("MALFORMED_REQUEST", "malformed request: missing method"); }; - if let Some(session_id) = session_id.as_deref() - && method != "initialize" - && mcp.rejects_session(session_id).await - { - return mcp_session_problem(session_id, StatusCode::NOT_FOUND).into_response(); - } // Every tool the server lists, in Java's registration order, with registered tools laid over. let tool_list = || { let mut tools = mcp_module_tools(); @@ -1431,7 +1500,9 @@ async fn mcp_respond( } let mut response = Json(json!({"jsonrpc": "2.0", "id": id, "result": result})).into_response(); if method == "initialize" && mcp.sessions_enabled() { - let session_id = mcp.create().await; + let session_id = mcp + .create_for(principal.as_ref().map(|p| p.0.0.as_str())) + .await; response.headers_mut().insert( "Mcp-Session-Id", HeaderValue::from_str(&session_id).expect("generated session id is valid"), @@ -1440,7 +1511,11 @@ async fn mcp_respond( response } -async fn mcp_get(State(WebState { mcp, .. }): State, headers: HeaderMap) -> Response { +async fn mcp_get( + State(WebState { mcp, .. }): State, + principal: Option>, + headers: HeaderMap, +) -> Response { // Java answers GET errors with a bare status: 405 without sessions, then 400 and 404. if !mcp.sessions_enabled() { return StatusCode::METHOD_NOT_ALLOWED.into_response(); @@ -1458,7 +1533,9 @@ async fn mcp_get(State(WebState { mcp, .. }): State, headers: HeaderMa .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse::().ok()) .unwrap_or(0); - let Some((replay, mut receiver)) = mcp.open(&session_id, after).await else { + let principal = principal.map(|p| p.0.0); + let Some((replay, mut receiver)) = mcp.open(&session_id, principal.as_deref(), after).await + else { return StatusCode::NOT_FOUND.into_response(); }; let stream = async_stream::stream! { @@ -1467,15 +1544,22 @@ async fn mcp_get(State(WebState { mcp, .. }): State, headers: HeaderMa yield Ok::(event); } } + // Java's sweeper reclaims idle sessions on its heartbeat; an open stream sweeps on the + // same cadence, and ends once its session is reclaimed or terminated. + let mut sweep = tokio::time::interval(MCP_SESSION_SWEEP_INTERVAL); + sweep.tick().await; loop { - match receiver.recv().await { - Ok((id, payload)) => { - if let Ok(event) = Event::default().id(id.to_string()).json_data(payload) { - yield Ok::(event); + tokio::select! { + received = receiver.recv() => match received { + Ok((id, payload)) => { + if let Ok(event) = Event::default().id(id.to_string()).json_data(payload) { + yield Ok::(event); + } } - } - Err(broadcast::error::RecvError::Lagged(_)) => continue, - Err(broadcast::error::RecvError::Closed) => break, + Err(broadcast::error::RecvError::Lagged(_)) => continue, + Err(broadcast::error::RecvError::Closed) => break, + }, + _ = sweep.tick() => mcp.sweep().await, } } }; @@ -1484,12 +1568,19 @@ async fn mcp_get(State(WebState { mcp, .. }): State, headers: HeaderMa .into_response() } -async fn mcp_delete(State(WebState { mcp, .. }): State, headers: HeaderMap) -> Response { - if let Some(session_id) = headers - .get("Mcp-Session-Id") - .and_then(|value| value.to_str().ok()) +/// Java's DELETE: always 204; only the principal that created the session ends it. +async fn mcp_delete( + State(WebState { mcp, .. }): State, + principal: Option>, + headers: HeaderMap, +) -> Response { + if mcp.sessions_enabled() + && let Some(session_id) = headers + .get("Mcp-Session-Id") + .and_then(|value| value.to_str().ok()) { - mcp.remove(session_id).await; + mcp.terminate(session_id, principal.as_ref().map(|p| p.0.0.as_str())) + .await; } StatusCode::NO_CONTENT.into_response() } @@ -4639,6 +4730,136 @@ mod tests { assert_eq!(unknown.status(), StatusCode::NOT_FOUND); } + /// Sends an MCP request as `principal` (unauthenticated when `None`). + fn mcp_as( + builder: axum::http::request::Builder, + principal: Option<&str>, + session: Option<&str>, + body: Body, + ) -> Request { + let builder = match session { + Some(session) => builder.header("Mcp-Session-Id", session), + None => builder, + }; + let mut request = builder + .header("content-type", "application/json") + .body(body) + .unwrap(); + if let Some(principal) = principal { + request + .extensions_mut() + .insert(AuthenticatedPrincipal(principal.into())); + } + request + } + + async fn mcp_initialize_as(app: &Router, principal: Option<&str>) -> String { + let response = app + .clone() + .oneshot(mcp_as( + Request::post("/platform/mcp"), + principal, + None, + Body::from(r#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#), + )) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + response.headers()["Mcp-Session-Id"].to_str().unwrap().to_owned() + } + + #[tokio::test] + async fn mcp_session_ids_are_random_uuids() { + let app = router_with_mcp(Arc::new(Source), true); + let first = mcp_initialize_as(&app, None).await; + let second = mcp_initialize_as(&app, None).await; + assert_ne!(first, second); + for id in [&first, &second] { + let parsed = uuid::Uuid::parse_str(id).expect("session id is a UUID"); + assert_eq!(parsed.get_version(), Some(uuid::Version::Random), "{id}"); + } + } + + #[tokio::test] + async fn mcp_another_principal_cannot_use_stream_or_end_the_session() { + let store = Arc::new(McpSessionStore::default()); + let app = router_with_mcp(Arc::new(Source), store.clone()); + let session = mcp_initialize_as(&app, Some("alice")).await; + let ping = || Body::from(r#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#); + let status = |request: Request| { + let app = app.clone(); + async move { app.oneshot(request).await.unwrap().status() } + }; + + for principal in [Some("bob"), None] { + let post = status(mcp_as(Request::post("/platform/mcp"), principal, Some(&session), ping())).await; + assert_eq!(post, StatusCode::NOT_FOUND, "{principal:?}"); + let get = status(mcp_as(Request::get("/platform/mcp"), principal, Some(&session), Body::empty())).await; + assert_eq!(get, StatusCode::NOT_FOUND, "{principal:?}"); + let delete = status(mcp_as(Request::delete("/platform/mcp"), principal, Some(&session), Body::empty())).await; + assert_eq!(delete, StatusCode::NO_CONTENT, "{principal:?}"); + } + // Another principal's DELETE does not end the session. + assert!(store.lookup(&session, Some("alice")).await); + let post = status(mcp_as(Request::post("/platform/mcp"), Some("alice"), Some(&session), ping())).await; + assert_eq!(post, StatusCode::OK); + let get = status(mcp_as(Request::get("/platform/mcp"), Some("alice"), Some(&session), Body::empty())).await; + assert_eq!(get, StatusCode::OK); + + // An unauthenticated session is not usable by an authenticated principal either. + let anonymous = mcp_initialize_as(&app, None).await; + let post = status(mcp_as(Request::post("/platform/mcp"), Some("alice"), Some(&anonymous), ping())).await; + assert_eq!(post, StatusCode::NOT_FOUND); + + let delete = status(mcp_as(Request::delete("/platform/mcp"), Some("alice"), Some(&session), Body::empty())).await; + assert_eq!(delete, StatusCode::NO_CONTENT); + assert!(!store.lookup(&session, Some("alice")).await, "the owner ends the session"); + } + + #[tokio::test] + async fn mcp_sessions_are_reclaimed_after_the_idle_timeout() { + let store = Arc::new(McpSessionStore::default()); + assert_eq!(store.session_idle_timeout(), Duration::from_secs(30 * 60)); + let app = router_with_mcp(Arc::new(Source), store.clone()); + store.set_session_idle_timeout(Duration::from_millis(200)); + let session = mcp_initialize_as(&app, None).await; + let (_, mut receiver) = store.open(&session, None, 0).await.unwrap(); + + // Each owner lookup is activity and keeps the session alive. + for _ in 0..3 { + tokio::time::sleep(Duration::from_millis(100)).await; + assert!(store.lookup(&session, None).await); + } + // Another principal's lookup is not activity. + for _ in 0..3 { + tokio::time::sleep(Duration::from_millis(100)).await; + assert!(!store.lookup(&session, Some("bob")).await); + } + store.sweep().await; + assert!(matches!( + receiver.recv().await, + Err(broadcast::error::RecvError::Closed) + ), "reclaim ends the open stream"); + let ping = app + .clone() + .oneshot(mcp_as( + Request::post("/platform/mcp"), + None, + Some(&session), + Body::from(r#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#), + )) + .await + .unwrap(); + assert_eq!(ping.status(), StatusCode::NOT_FOUND); + + // A zero timeout disables idle reclaim. + store.set_session_idle_timeout(Duration::ZERO); + let kept = mcp_initialize_as(&app, None).await; + tokio::time::sleep(Duration::from_millis(250)).await; + store.sweep().await; + assert!(store.lookup(&kept, None).await); + } + #[tokio::test] async fn mcp_without_sessions_issues_none_checks_none_and_has_no_stream() { let app = router_with_mcp( @@ -7153,7 +7374,7 @@ mod tests { let store = Arc::new(McpSessionStore::default()); let app = || router_with_mcp_session_store(Arc::new(Source), store.clone(), Arc::new(PermissiveControlAuthorizer)); let session = store.create().await; - let delivered = || async { store.open(&session, 0).await.unwrap().0 }; + let delivered = || async { store.open(&session, None, 0).await.unwrap().0 }; assert_eq!(store.log_level(), McpLogLevel::Info); store.emit_log(McpLogLevel::Debug, Some("test"), json!({"m": "debug"})).await; store.emit_log(McpLogLevel::Warning, Some("test"), json!({"m": "warn"})).await; @@ -7184,7 +7405,7 @@ mod tests { let app = || router_with_mcp_session_store(Arc::new(Source), store.clone(), Arc::new(PermissiveControlAuthorizer)); let (first, second) = (store.create().await, store.create().await); store.notify_resource_updated("protean://modules").await; - assert!(store.open(&first, 0).await.unwrap().0.is_empty(), "nothing before subscribing"); + assert!(store.open(&first, None, 0).await.unwrap().0.is_empty(), "nothing before subscribing"); let (_, subscribed) = send(app(), rpc("resources/subscribe", json!({"uri": "protean://modules"}))).await; assert_eq!(subscribed["result"], json!({})); @@ -7192,7 +7413,7 @@ mod tests { store.notify_resource_updated("protean://modules/other/versions").await; // Subscriptions are server-global: every session receives the update. for session in [&first, &second] { - let events = store.open(session, 0).await.unwrap().0; + let events = store.open(session, None, 0).await.unwrap().0; assert_eq!(events.len(), 1); assert_eq!( events[0].1, @@ -7201,7 +7422,7 @@ mod tests { } send(app(), rpc("resources/unsubscribe", json!({"uri": "protean://modules"}))).await; store.notify_resource_updated("protean://modules").await; - assert_eq!(store.open(&first, 0).await.unwrap().0.len(), 1, "nothing after unsubscribing"); + assert_eq!(store.open(&first, None, 0).await.unwrap().0.len(), 1, "nothing after unsubscribing"); for method in ["resources/subscribe", "resources/unsubscribe"] { let (_, missing) = send(app(), rpc(method, json!({"uri": null}))).await; assert_eq!(missing["error"]["message"], format!("[INVALID_ARGUMENT] {method}: uri required")); @@ -7251,7 +7472,7 @@ mod tests { let (_, before) = send(app(), rpc("tools/list", json!({}))).await; store.register_tool(Arc::new(Echo("consumer.echo"))).await; - let events = store.open(&session, 0).await.unwrap().0; + let events = store.open(&session, None, 0).await.unwrap().0; assert_eq!(events.len(), 1); assert_eq!(events[0].1, json!({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"})); let (_, listed) = send(app(), rpc("tools/list", json!({}))).await; @@ -7293,7 +7514,7 @@ mod tests { store.unregister_tool("consumer.echo").await; store.unregister_tool("protean.get_module").await; store.unregister_tool("consumer.echo").await; - assert_eq!(store.open(&session, 0).await.unwrap().0.len(), 4, "an absent name announces nothing"); + assert_eq!(store.open(&session, None, 0).await.unwrap().0.len(), 4, "an absent name announces nothing"); let (_, after) = send(app(), rpc("tools/list", json!({}))).await; assert_eq!(names(&after), names(&before)); let (_, gone) = send(app(), mcp_call("consumer.echo", json!({}))).await; @@ -7942,7 +8163,7 @@ mod tests { bridge("other"); let mut events = Vec::new(); for _ in 0..100 { - events = store.open(&session, 0).await.unwrap().0; + events = store.open(&session, None, 0).await.unwrap().0; if events.len() == 3 { break; } diff --git a/docs/design/17-mcp-session-and-extension-contract.md b/docs/design/17-mcp-session-and-extension-contract.md index a3e1d4f..229f641 100644 --- a/docs/design/17-mcp-session-and-extension-contract.md +++ b/docs/design/17-mcp-session-and-extension-contract.md @@ -41,6 +41,31 @@ error는 Java `ErrorCode` 표의 JSON-RPC code·title을 쓰고 `error.data`에 6. 15초 heartbeat comment와 idle timeout sweep은 proxy liveness/session reclaim을 위한 것이며 tool progress event를 대체하지 않는다. +### 2.1 session id·소유자·유휴 회수 (issue #113, 2026-11-29) + +Java 근거: `McpSessionRegistry.create(owner)`(`UUID.randomUUID()`, 89행), `get(id, principalName)`(98–105행, +소유자가 다르면 없는 session과 같이 null, 성공한 조회만 activity), `sweep()`(296–304행, 유휴 회수는 +`terminate`로 stream까지 닫는다), `McpHttpController`(POST 107–113행 404 problem, GET 165–168행 본문 없는 404, +DELETE 174–182행 다른 principal이면 아무것도 하지 않고 204), `McpConfiguration`의 `protean.mcp.session.timeout:30m`. +테스트는 `McpSessionOwnershipHttpTest`. + +- session id는 UUID v4(CSPRNG)다. 순번 id(`mcp-`)는 쓰지 않는다. +- `initialize`한 요청의 principal(`AuthenticatedPrincipal`, 없으면 미인증)이 소유자다. 그 뒤 POST·GET·DELETE는 + 같은 principal이어야 한다. 미인증 session은 미인증 요청만 쓴다. 다른 principal의 POST는 `UNKNOWN_SESSION` + 404 problem, GET은 본문 없는 404, DELETE는 204지만 session은 남는다 — 모르는 session과 구별되지 않는다. +- 소유자가 맞는 조회만 activity로 센다. 30분 넘게 조회가 없으면 session을 지우고 열린 GET stream을 닫는다. + 회수는 요청이 올 때와 열린 stream마다 15초(Java heartbeat 주기)에 한 번 돈다. +- stdio transport의 session은 `stdio-local` principal 소유이므로 같은 store를 쓰는 HTTP listener에서는 보이지 + 않는다. EOF 때 같은 principal로 DELETE해 닫는다. Java stdio는 session을 만들지 않는다. +- session 수 상한은 두지 않는다 — Java에도 없다(parity). 유휴 회수가 수명을 제한한다. + +**non-parity — 유휴 시한 설정 키.** Java는 Spring property `protean.mcp.session.timeout`(기본 30m, 0 이하면 회수 +끔)으로 바꾼다. 이 키는 Java `ConfigRegistry`에 없으므로 Protrus 설정 레지스트리에도 넣지 않는다. 사유: 레지스트리는 +Java `ConfigRegistry` 목록을 따르고(설계 30), Spring property 층은 Protrus host 부트스트랩에 대응이 없다. +사용자 영향: 단독 host는 30분 고정이다. embedder는 `McpSessionStore::set_session_idle_timeout`(`Duration::ZERO`면 +회수 끔)으로 바꾼다. migration note: Java에서 `protean.mcp.session.timeout`을 바꿔 쓰던 배포는 host에서는 +기본값을 받는다. 검증: `mcp_sessions_are_reclaimed_after_the_idle_timeout`. + session stream attach, replay, live delivery는 한 session lock에서 순서 보장한다. send failure는 stream만 detach하고 buffer/session은 남겨 reconnect replay를 허용한다. terminate/shutdown은 stream과 pending server-request future를 모두 complete한다. diff --git a/docs/guide/03-deploying-and-operating.md b/docs/guide/03-deploying-and-operating.md index c469dc7..732b8e3 100644 --- a/docs/guide/03-deploying-and-operating.md +++ b/docs/guide/03-deploying-and-operating.md @@ -312,13 +312,16 @@ curl -s -i http://127.0.0.1:8088/platform/mcp -H 'content-type: application/json ``` ```text -mcp-session-id: mcp-1 +mcp-session-id: 3f6c2a9e-8d41-4b7a-9c35-0e2f7d1b6a84 {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{"listChanged":true},"resources":{"subscribe":true},"prompts":{},"logging":{},"completions":{}},"serverInfo":{"name":"protean","version":"0.1.0"}}} ``` Send `Mcp-Session-Id` on later requests if you want session features (notifications, cancellation); plain `tools/call` requests work without it. The bearer token works exactly as on REST. +A session belongs to the identity that initialized it: requests from any other identity (or +without a token, for a token-initialized session) get `404` as for an unknown session. Sessions +idle for 30 minutes are reclaimed; initialize again after a `404`. `protean.deploy_module` and `protean.update_module` take the deploy envelope itself as `arguments`: