use std::sync::Arc;
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use crate::jsonrpc::{ConnectionContext, Router, RpcError};
use super::registry::SessionRegistry;
pub fn register(router: &mut Router, registry: Arc<SessionRegistry>) {
let r = registry.clone();
router.register(
"session.create",
move |params: Value, ctx: ConnectionContext| {
let r = r.clone();
async move { create(&r, params, ctx).await }
},
);
let r = registry.clone();
router.register(
"session.list",
move |params: Value, ctx: ConnectionContext| {
let r = r.clone();
async move { list(&r, params, ctx).await }
},
);
let r = registry.clone();
router.register(
"session.status",
move |params: Value, ctx: ConnectionContext| {
let r = r.clone();
async move { status(&r, params, ctx).await }
},
);
let r = registry.clone();
router.register(
"session.send",
move |params: Value, ctx: ConnectionContext| {
let r = r.clone();
async move { send(&r, params, ctx).await }
},
);
let r = registry.clone();
router.register(
"session.attach",
move |params: Value, ctx: ConnectionContext| {
let r = r.clone();
async move { attach(&r, params, ctx).await }
},
);
let r = registry.clone();
router.register(
"session.detach",
move |params: Value, ctx: ConnectionContext| {
let r = r.clone();
async move { detach(&r, params, ctx).await }
},
);
let r = registry.clone();
router.register(
"session.cancel",
move |params: Value, ctx: ConnectionContext| {
let r = r.clone();
async move { cancel(&r, params, ctx).await }
},
);
let r = registry.clone();
router.register(
"session.get_transcript",
move |params: Value, ctx: ConnectionContext| {
let r = r.clone();
async move { get_transcript(&r, params, ctx).await }
},
);
}
#[derive(Deserialize)]
struct SessionIdParams {
session_id: String,
}
#[derive(Deserialize)]
struct CreateParams {
task: String,
#[serde(default)]
agent: Option<String>,
#[serde(default)]
project: Option<String>,
}
#[derive(Deserialize)]
struct SendParams {
session_id: String,
input: String,
}
fn parse<T: DeserializeOwned>(params: Value, method: &str) -> Result<T, RpcError> {
serde_json::from_value(params).map_err(|e| RpcError::invalid_params(format!("{method}: {e}")))
}
async fn create(
registry: &SessionRegistry,
params: Value,
_ctx: ConnectionContext,
) -> Result<Value, RpcError> {
let p: CreateParams = parse(params, "session.create")?;
if p.task.trim().is_empty() {
return Err(RpcError::invalid_argument("task must not be empty"));
}
let session = registry.create(p.task, p.agent, p.project);
Ok(json!(session))
}
async fn list(
registry: &SessionRegistry,
_params: Value,
_ctx: ConnectionContext,
) -> Result<Value, RpcError> {
Ok(json!({ "sessions": registry.list() }))
}
async fn status(
registry: &SessionRegistry,
params: Value,
_ctx: ConnectionContext,
) -> Result<Value, RpcError> {
let p: SessionIdParams = parse(params, "session.status")?;
Ok(json!(registry.status(&p.session_id)?))
}
async fn send(
registry: &SessionRegistry,
params: Value,
_ctx: ConnectionContext,
) -> Result<Value, RpcError> {
let p: SendParams = parse(params, "session.send")?;
registry.send(&p.session_id, &p.input)?;
Ok(json!({ "acknowledged": true }))
}
async fn attach(
registry: &SessionRegistry,
params: Value,
ctx: ConnectionContext,
) -> Result<Value, RpcError> {
let p: SessionIdParams = parse(params, "session.attach")?;
let events = registry.attach(&p.session_id, ctx.connection_id, ctx.notify.clone())?;
Ok(json!({
"session_id": p.session_id,
"events": events,
"stream_url": format!("/sessions/{}/events", p.session_id),
}))
}
async fn detach(
registry: &SessionRegistry,
params: Value,
ctx: ConnectionContext,
) -> Result<Value, RpcError> {
let p: SessionIdParams = parse(params, "session.detach")?;
registry.detach(&p.session_id, ctx.connection_id)?;
Ok(json!({}))
}
async fn cancel(
registry: &SessionRegistry,
params: Value,
_ctx: ConnectionContext,
) -> Result<Value, RpcError> {
let p: SessionIdParams = parse(params, "session.cancel")?;
if registry.is_executing(&p.session_id) {
registry.request_cancel(&p.session_id)?;
Ok(json!(registry.status(&p.session_id)?))
} else {
Ok(json!(registry.cancel(&p.session_id)?))
}
}
async fn get_transcript(
registry: &SessionRegistry,
params: Value,
_ctx: ConnectionContext,
) -> Result<Value, RpcError> {
let p: SessionIdParams = parse(params, "session.get_transcript")?;
Ok(json!(registry.get_transcript(&p.session_id)?))
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::sync::mpsc;
use trusty_common::mcp::Request;
fn test_ctx() -> ConnectionContext {
let (tx, _rx) = mpsc::unbounded_channel();
ConnectionContext::new(tx)
}
#[tokio::test]
async fn register_wires_every_session_method() {
let registry = Arc::new(SessionRegistry::new());
let mut router = Router::new();
register(&mut router, registry.clone());
let session = registry.create("t".to_string(), None, None);
let cases: &[(&str, Value)] = &[
("session.list", json!({})),
("session.status", json!({"session_id": session.id})),
(
"session.send",
json!({"session_id": session.id, "input": "hi"}),
),
("session.attach", json!({"session_id": session.id})),
("session.detach", json!({"session_id": session.id})),
("session.get_transcript", json!({"session_id": session.id})),
];
for (method, params) in cases {
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: method.to_string(),
params: Some(params.clone()),
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"{method} should succeed, got {:?}",
resp.error
);
}
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "session.cancel".to_string(),
params: Some(json!({"session_id": session.id})),
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"session.cancel should succeed, got {:?}",
resp.error
);
}
#[tokio::test]
async fn create_rejects_empty_task() {
let registry = SessionRegistry::new();
let err = create(®istry, json!({"task": " "}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32003);
}
#[tokio::test]
async fn create_returns_running_session() {
let registry = SessionRegistry::new();
let result = create(®istry, json!({"task": "do it"}), test_ctx())
.await
.unwrap();
assert_eq!(result["status"], "running");
assert_eq!(result["task"], "do it");
}
#[tokio::test]
async fn list_returns_sessions_key() {
let registry = SessionRegistry::new();
registry.create("a".to_string(), None, None);
let result = list(®istry, Value::Null, test_ctx()).await.unwrap();
assert_eq!(result["sessions"].as_array().unwrap().len(), 1);
}
#[tokio::test]
async fn status_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = status(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn get_transcript_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = get_transcript(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn get_transcript_on_never_run_session_is_empty() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let result = get_transcript(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap();
assert_eq!(result["session_id"], session.id);
assert_eq!(result["turns"].as_array().unwrap().len(), 0);
assert_eq!(result["cost_usd"], Value::Null);
}
#[tokio::test]
async fn send_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = send(
®istry,
json!({"session_id": "nope", "input": "hi"}),
test_ctx(),
)
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn attach_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = attach(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn detach_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = detach(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn cancel_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = cancel(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn cancel_executing_session_requests_cooperative_cancel() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, None);
let flag = registry.begin_execution(&session.id).unwrap();
let result = cancel(®istry, json!({"session_id": &session.id}), test_ctx())
.await
.unwrap();
assert_eq!(
result["status"], "running",
"status must NOT be transitioned immediately for an executing session"
);
assert!(
flag.load(std::sync::atomic::Ordering::Relaxed),
"the shared cancel flag must have been set"
);
}
}