use std::sync::Arc;
use http_body_util::{BodyExt, Full};
use hyper::body::Bytes;
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use rmcp::model::{
CallToolRequestParams, CallToolResponse, CallToolResult, GetPromptRequestParams,
GetPromptResponse, Implementation, InitializeRequestParams, InitializeResult,
ListPromptsResult, ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig,
Tool,
};
use rmcp::service::RequestContext;
use rmcp::{ErrorData, RoleServer, ServerHandler, ServiceExt};
use serde_json::{json, Value as Json};
use tokio::sync::Mutex;
use crate::persist::Endpoint;
const PROTOCOL_VERSION: &str = "2025-06-18";
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
#[derive(Debug, Clone, thiserror::Error)]
pub enum UpstreamError {
#[error("cannot reach the MemFork daemon at {url}: {reason}")]
Unreachable {
url: String,
reason: String,
},
#[error("the MemFork daemon answered unexpectedly: {0}")]
Unusable(String),
#[error("the MemFork daemon has forgotten this session")]
SessionGone,
#[error("{message}")]
Rpc {
code: i64,
message: String,
},
}
impl UpstreamError {
pub fn is_disconnect(&self) -> bool {
matches!(
self,
UpstreamError::Unreachable { .. } | UpstreamError::SessionGone
)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Hello {
pub namespace: String,
pub client: Option<String>,
pub session: Option<String>,
}
impl Hello {
fn capabilities(&self) -> Json {
let mut session = serde_json::Map::new();
session.insert("namespace".to_owned(), json!(self.namespace));
if let Some(client) = &self.client {
session.insert("client".to_owned(), json!(client));
}
if let Some(id) = &self.session {
session.insert("session".to_owned(), json!(id));
}
json!({ "experimental": { crate::mcp::SESSION_CAPABILITY: session } })
}
}
#[derive(Debug)]
pub struct Upstream {
url: String,
token: String,
http: Client<hyper_util::client::legacy::connect::HttpConnector, Full<Bytes>>,
session: Mutex<Option<String>>,
next_id: std::sync::atomic::AtomicI64,
}
impl Upstream {
pub async fn connect(endpoint: &Endpoint, hello: &Hello) -> Result<Self, UpstreamError> {
let port = endpoint
.port
.ok_or_else(|| UpstreamError::Unusable("the endpoint file names no port".to_owned()))?;
let token = endpoint.token.clone().ok_or_else(|| {
UpstreamError::Unusable("the endpoint file carries no token".to_owned())
})?;
let upstream = Upstream {
url: format!("http://127.0.0.1:{port}{}", crate::serve::MCP_PATH),
token,
http: Client::builder(TokioExecutor::new()).build_http(),
session: Mutex::new(None),
next_id: std::sync::atomic::AtomicI64::new(1),
};
upstream.initialize(hello).await?;
Ok(upstream)
}
async fn initialize(&self, hello: &Hello) -> Result<(), UpstreamError> {
let result = self
.request(
"initialize",
json!({
"protocolVersion": PROTOCOL_VERSION,
"capabilities": hello.capabilities(),
"clientInfo": { "name": "memfork-proxy", "version": crate::VERSION },
}),
)
.await?;
let _ = result;
self.notify("notifications/initialized", json!({})).await
}
pub async fn list_tools(&self) -> Result<Vec<Tool>, UpstreamError> {
let result = self.request("tools/list", json!({})).await?;
let tools = result
.get("tools")
.cloned()
.ok_or_else(|| UpstreamError::Unusable("no tools in the answer".to_owned()))?;
serde_json::from_value(tools)
.map_err(|e| UpstreamError::Unusable(format!("the tool list did not parse: {e}")))
}
pub async fn close(&self) {
let Some(session) = self.session.lock().await.clone() else {
return;
};
let Ok(request) = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(&self.url)
.header(
hyper::header::AUTHORIZATION,
format!("Bearer {}", self.token),
)
.header("Mcp-Session-Id", session)
.header("MCP-Protocol-Version", PROTOCOL_VERSION)
.body(Full::new(Bytes::new()))
else {
return;
};
let _ = tokio::time::timeout(
std::time::Duration::from_secs(2),
self.http.request(request),
)
.await;
}
pub async fn report(&self, body: &Json) {
let url = self
.url
.replace(crate::serve::MCP_PATH, crate::serve::REPORT_PATH);
let Ok(request) = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url)
.header(hyper::header::CONTENT_TYPE, "application/json")
.header(
hyper::header::AUTHORIZATION,
format!("Bearer {}", self.token),
)
.body(Full::new(Bytes::from(body.to_string())))
else {
return;
};
let _ = tokio::time::timeout(
std::time::Duration::from_secs(2),
self.http.request(request),
)
.await;
}
pub async fn autopilot(&self, body: &Json) -> Result<Json, UpstreamError> {
let url = self
.url
.replace(crate::serve::MCP_PATH, crate::serve::AUTOPILOT_PATH);
let unreachable = |reason: String| UpstreamError::Unreachable {
url: url.clone(),
reason,
};
let request = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(&url)
.header(hyper::header::CONTENT_TYPE, "application/json")
.header(
hyper::header::AUTHORIZATION,
format!("Bearer {}", self.token),
)
.body(Full::new(Bytes::from(body.to_string())))
.map_err(|e| unreachable(format!("cannot build the request: {e}")))?;
let response = tokio::time::timeout(
std::time::Duration::from_secs(5),
self.http.request(request),
)
.await
.map_err(|_| unreachable("it did not answer in time".to_owned()))?
.map_err(|e| unreachable(e.to_string()))?;
let status = response.status();
let collected = response
.into_body()
.collect()
.await
.map_err(|e| unreachable(format!("the answer could not be read: {e}")))?;
let text = String::from_utf8_lossy(&collected.to_bytes()).into_owned();
if !status.is_success() {
return Err(UpstreamError::Unusable(format!("HTTP {status}: {text}")));
}
serde_json::from_str(&text)
.map_err(|e| UpstreamError::Unusable(format!("the answer did not parse: {e}")))
}
pub async fn call_tool(&self, params: &CallToolRequestParams) -> Result<Json, UpstreamError> {
let payload = serde_json::to_value(params)
.map_err(|e| UpstreamError::Unusable(format!("cannot encode the call: {e}")))?;
self.request("tools/call", payload).await
}
async fn notify(&self, method: &str, params: Json) -> Result<(), UpstreamError> {
let body = json!({ "jsonrpc": "2.0", "method": method, "params": params });
self.post(&body).await.map(|_| ())
}
async fn request(&self, method: &str, params: Json) -> Result<Json, UpstreamError> {
let id = self
.next_id
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let body = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
let text = self.post(&body).await?;
let message = parse_message(&text)?;
if let Some(error) = message.get("error") {
return Err(UpstreamError::Rpc {
code: error.get("code").and_then(Json::as_i64).unwrap_or(0),
message: error
.get("message")
.and_then(Json::as_str)
.unwrap_or("the daemon reported an error")
.to_owned(),
});
}
message
.get("result")
.cloned()
.ok_or_else(|| UpstreamError::Unusable(format!("no result in {text}")))
}
async fn post(&self, body: &Json) -> Result<String, UpstreamError> {
let unreachable = |reason: String| UpstreamError::Unreachable {
url: self.url.clone(),
reason,
};
let mut builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(&self.url)
.header(hyper::header::CONTENT_TYPE, "application/json")
.header(hyper::header::ACCEPT, "application/json, text/event-stream")
.header(
hyper::header::AUTHORIZATION,
format!("Bearer {}", self.token),
)
.header("MCP-Protocol-Version", PROTOCOL_VERSION);
if let Some(session) = self.session.lock().await.as_ref() {
builder = builder.header("Mcp-Session-Id", session);
}
let request = builder
.body(Full::new(Bytes::from(body.to_string())))
.map_err(|e| unreachable(format!("cannot build the request: {e}")))?;
let response = tokio::time::timeout(REQUEST_TIMEOUT, self.http.request(request))
.await
.map_err(|_| unreachable("it did not answer in time".to_owned()))?
.map_err(|e| unreachable(e.to_string()))?;
if let Some(session) = response
.headers()
.get("Mcp-Session-Id")
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
{
*self.session.lock().await = Some(session);
}
let status = response.status();
let collected = response
.into_body()
.collect()
.await
.map_err(|e| unreachable(format!("the answer could not be read: {e}")))?;
let text = String::from_utf8_lossy(&collected.to_bytes()).into_owned();
if status == hyper::StatusCode::NOT_FOUND && self.session.lock().await.is_some() {
return Err(UpstreamError::SessionGone);
}
if status == hyper::StatusCode::UNAUTHORIZED {
return Err(UpstreamError::Unusable(
"the daemon rejected our token; it may have been restarted".to_owned(),
));
}
if !status.is_success() {
return Err(UpstreamError::Unusable(format!("HTTP {status}: {text}")));
}
Ok(text)
}
}
fn parse_message(text: &str) -> Result<Json, UpstreamError> {
let trimmed = text.trim_start();
if trimmed.starts_with('{') {
return serde_json::from_str(trimmed)
.map_err(|e| UpstreamError::Unusable(format!("the answer did not parse: {e}")));
}
for line in text.lines() {
if let Some(payload) = line.strip_prefix("data:") {
let payload = payload.trim();
if payload.is_empty() {
continue;
}
return serde_json::from_str(payload).map_err(|e| {
UpstreamError::Unusable(format!("an event-stream payload did not parse: {e}"))
});
}
}
Err(UpstreamError::Unusable(format!(
"the answer was neither JSON nor an event stream: {}",
text.chars().take(200).collect::<String>()
)))
}
pub type Reconnect = Arc<
dyn Fn(Hello) -> futures::future::BoxFuture<'static, Result<Upstream, String>> + Send + Sync,
>;
#[derive(Clone)]
pub struct Proxy {
upstream: Arc<tokio::sync::RwLock<Option<Arc<Upstream>>>>,
connect: Reconnect,
namespace: String,
client: Arc<std::sync::Mutex<Option<String>>>,
session: String,
root: std::path::PathBuf,
hasher: Arc<crate::facts::Hasher>,
kept: Arc<std::sync::Mutex<std::collections::BTreeSet<String>>>,
follower: Arc<std::sync::Mutex<Option<crate::autopilot::follow::Follower>>>,
}
impl std::fmt::Debug for Proxy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Proxy").finish_non_exhaustive()
}
}
impl Proxy {
pub fn new(connect: Reconnect, namespace: String) -> Self {
let cwd = std::env::current_dir().unwrap_or_default();
let root = crate::facts::project_root(&cwd);
Proxy {
upstream: Arc::new(tokio::sync::RwLock::new(None)),
connect,
namespace,
client: Arc::new(std::sync::Mutex::new(None)),
session: crate::tools::dispatch::new_session_id(),
follower: Arc::new(std::sync::Mutex::new(
crate::autopilot::follow::Follower::open(&root),
)),
root,
hasher: Arc::new(crate::facts::Hasher::default()),
kept: Arc::new(std::sync::Mutex::new(std::collections::BTreeSet::new())),
}
}
async fn follow(&self) {
if !crate::policy::allows(crate::policy::Feature::Autopilot) {
return;
}
let follows = crate::autopilot::config::read(&self.root)
.config()
.is_some_and(crate::autopilot::config::Config::follows);
fn lock(
proxy: &Proxy,
) -> std::sync::MutexGuard<'_, Option<crate::autopilot::follow::Follower>> {
proxy.follower.lock().unwrap_or_else(|e| e.into_inner())
}
if !follows {
if let Some(f) = lock(self).as_mut() {
if f.started() {
f.reset();
}
}
return;
}
let needs_cursor = match lock(self).as_ref() {
Some(f) => !f.started(),
None => return,
};
let Ok(up) = self.current().await else {
return;
};
if needs_cursor {
let worktree = match lock(self).as_ref() {
Some(f) => f.repo().worktree_key(),
None => return,
};
let remembered = up
.autopilot(&json!({ "action": "cursor", "worktree": worktree }))
.await
.ok()
.and_then(|a| a["cursor"].as_u64());
if let Some(f) = lock(self).as_mut() {
f.start(remembered);
}
}
let request = {
let mut guard = lock(self);
let Some(f) = guard.as_mut() else {
return;
};
f.observe()
.map(|o| o.to_request(&self.session, &self.namespace, f.repo()))
};
let Some(request) = request else {
return;
};
if up.autopilot(&request).await.is_err() {
if let Some(f) = lock(self).as_mut() {
f.reset();
}
}
}
fn keep_alive(&self, key: String, id: String, namespace: Option<String>, lease: u64) {
{
let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
if !kept.insert(key.clone()) {
return;
}
}
let proxy = self.clone();
let every = std::time::Duration::from_millis((lease * 1000 / 2).max(250));
tokio::spawn(async move {
loop {
tokio::time::sleep(every).await;
let mut args = serde_json::Map::new();
args.insert("action".to_owned(), json!("renew"));
args.insert("id".to_owned(), json!(id));
if let Some(ns) = &namespace {
args.insert("namespace".to_owned(), json!(ns));
}
let params =
CallToolRequestParams::new("memfork_task".to_owned()).with_arguments(args);
let renewed = proxy
.with_retry(move |up| {
let params = params.clone();
Box::pin(async move { up.call_tool(¶ms).await })
})
.await
.ok()
.and_then(|raw| raw.get("structuredContent").cloned())
.is_some_and(|c| c.get("renewed") == Some(&json!(true)));
if !renewed {
break;
}
}
proxy
.kept
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&key);
});
}
fn hello(&self) -> Hello {
Hello {
namespace: self.namespace.clone(),
client: self
.client
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone(),
session: Some(self.session.clone()),
}
}
async fn current(&self) -> Result<Arc<Upstream>, String> {
if let Some(existing) = self.upstream.read().await.clone() {
return Ok(existing);
}
let mut slot = self.upstream.write().await;
if let Some(existing) = slot.clone() {
return Ok(existing);
}
let fresh = Arc::new((self.connect)(self.hello()).await?);
*slot = Some(Arc::clone(&fresh));
Ok(fresh)
}
async fn reconnect(&self) -> Result<Arc<Upstream>, String> {
let mut slot = self.upstream.write().await;
let fresh = Arc::new((self.connect)(self.hello()).await?);
*slot = Some(Arc::clone(&fresh));
Ok(fresh)
}
async fn prepare_acceptance(
&self,
args: &mut rmcp::model::JsonObject,
) -> Result<(), ErrorData> {
if args.get("action") != Some(&json!("done")) || args.contains_key("acceptance") {
return Ok(());
}
let Some(id) = args.get("id").and_then(Json::as_str).map(str::to_owned) else {
return Ok(());
};
let ns = args
.get("namespace")
.and_then(Json::as_str)
.unwrap_or(&self.namespace)
.to_owned();
let mut get = serde_json::Map::new();
get.insert("key".to_owned(), json!(crate::board::task_key(&ns, &id)));
if let Some(branch) = args.get("branch") {
get.insert("branch".to_owned(), branch.clone());
}
let params = CallToolRequestParams::new("memfork_get").with_arguments(get);
let raw = self
.with_retry(move |up| {
let params = params.clone();
Box::pin(async move { up.call_tool(¶ms).await })
})
.await?;
let found = serde_json::from_value::<CallToolResult>(raw)
.ok()
.and_then(|r| r.structured_content);
let Some(task) = found
.as_ref()
.and_then(|c| c["value"].as_str())
.and_then(|v| serde_json::from_str::<Json>(v).ok())
else {
return Ok(());
};
let root = self.root.clone();
let prepared =
tokio::task::spawn_blocking(move || crate::plans::prepare_done(&root, &id, &task))
.await
.map_err(|e| {
ErrorData::internal_error(format!("the acceptance run failed: {e}"), None)
})?;
match prepared {
Ok(Some(ran)) => {
args.insert("acceptance".to_owned(), json!(ran));
Ok(())
}
Ok(None) => Ok(()),
Err(why) => Err(ErrorData::invalid_params(why, None)),
}
}
async fn with_retry<T, F>(&self, operation: F) -> Result<T, ErrorData>
where
F: for<'a> Fn(&'a Upstream) -> futures::future::BoxFuture<'a, Result<T, UpstreamError>>,
{
let first = self.current().await.map_err(|why| {
ErrorData::internal_error(
format!(
"the MemFork daemon could not be started: {why}. \
Run `memfork doctor` to see the state of the data directory."
),
None,
)
})?;
match operation(&first).await {
Ok(value) => return Ok(value),
Err(e) if !e.is_disconnect() => return Err(as_mcp_error(&e)),
Err(_) => {}
}
let fresh = self.reconnect().await.map_err(|why| {
ErrorData::internal_error(
format!(
"the MemFork daemon stopped and could not be restarted: {why}. \
Run `memfork doctor` to see the state of the data directory."
),
None,
)
})?;
operation(&fresh).await.map_err(|e| {
ErrorData::internal_error(
format!(
"the MemFork daemon stopped, was restarted, and still could not \
be reached: {e}"
),
None,
)
})
}
}
fn as_mcp_error(e: &UpstreamError) -> ErrorData {
match e {
UpstreamError::Rpc { code, message } => {
ErrorData::new(rmcp::model::ErrorCode(*code as i32), message.clone(), None)
}
other => ErrorData::internal_error(other.to_string(), None),
}
}
impl ServerHandler for Proxy {
async fn list_prompts(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListPromptsResult, ErrorData> {
Ok(ListPromptsResult::with_all_items(crate::prompts::list()))
}
async fn get_prompt(
&self,
request: GetPromptRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<GetPromptResponse, ErrorData> {
crate::prompts::get(&request.name, request.arguments.as_ref(), &self.namespace)
.map(Into::into)
.map_err(|why| ErrorData::invalid_params(why, None))
}
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_tools()
.enable_prompts()
.build(),
)
.with_server_info(
Implementation::new("memfork", crate::VERSION)
.with_title("MemFork — branchable agent memory"),
)
.with_instructions(crate::mcp::instructions(&self.namespace))
}
async fn initialize(
&self,
request: InitializeRequestParams,
context: RequestContext<RoleServer>,
) -> Result<InitializeResult, ErrorData> {
let name = request.client_info.name.trim();
if !name.is_empty() {
*self.client.lock().unwrap_or_else(|e| e.into_inner()) = Some(name.to_owned());
}
context.peer.set_peer_info(request.clone());
self.negotiate_initialize(&request)
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
Ok(ListToolsResult::with_all_items(crate::mcp::tool_list()))
}
async fn call_tool(
&self,
request: CallToolRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
let mut params = request.clone();
self.follow().await;
if params.name == "memfork_put" {
if let Some(args) = params.arguments.as_mut() {
let sources: Option<Vec<String>> = args
.get("sources")
.and_then(|s| serde_json::from_value(s.clone()).ok());
if let Some(Ok(sources)) = sources.map(|s| crate::facts::normalise(&s)) {
let hashes = self.hasher.record(&self.root, &sources);
args.insert("source_hashes".to_owned(), json!(hashes));
}
}
}
if params.name == "memfork_task" {
if let Some(args) = params.arguments.as_mut() {
if let Err(refused) = self.prepare_acceptance(args).await {
return Ok(CallToolResult::structured_error(json!({
"error": refused.message,
"tool": "memfork_task",
}))
.into());
}
}
}
let forwarded = params.clone();
let raw = self
.with_retry(move |up| {
let params = forwarded.clone();
Box::pin(async move { up.call_tool(¶ms).await })
})
.await?;
let mut result = match serde_json::from_value::<CallToolResult>(raw.clone()) {
Ok(result) => result,
Err(_) => return Ok(CallToolResult::structured(raw).into()),
};
if params.name == "memfork_task" {
if let (Some(args), Some(content)) = (¶ms.arguments, &result.structured_content) {
if args.get("action") == Some(&json!("claim")) && content["claimed"] == true {
if let (Some(key), Some(id)) = (
content["key"].as_str(),
args.get("id").and_then(Json::as_str),
) {
let lease = content["lease_seconds"]
.as_u64()
.unwrap_or(crate::board::DEFAULT_LEASE_SECONDS);
let ns = args
.get("namespace")
.and_then(Json::as_str)
.map(str::to_owned);
self.keep_alive(key.to_owned(), id.to_owned(), ns, lease);
}
}
}
}
if result.is_error != Some(true) {
if let Some(mut content) = result.structured_content.take() {
let checked = crate::facts::check(&mut content, &self.root, &self.hasher);
if !checked.is_empty() {
let client = self
.hello()
.client
.unwrap_or_else(|| "unknown client".to_owned());
let body = json!({
"client": client,
"namespace": self.namespace,
"facts": checked.facts.iter().map(|(k, s)| json!([k, s])).collect::<Vec<_>>(),
});
if let Ok(up) = self.current().await {
up.report(&body).await;
}
result = CallToolResult::structured(content);
} else {
result.structured_content = Some(content);
}
}
}
Ok(result.into())
}
}
pub async fn serve_stdio(proxy: Proxy) -> Result<(), String> {
let upstream = Arc::clone(&proxy.upstream);
let service = proxy
.serve(rmcp::transport::stdio())
.await
.map_err(|e| format!("cannot start the MCP proxy: {e}"))?;
let waited = service
.waiting()
.await
.map_err(|e| format!("the MCP proxy stopped with an error: {e}"));
let connected = upstream.read().await.clone();
if let Some(connected) = connected {
connected.close().await;
}
waited.map(|_| ())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_hello_carries_the_project_and_the_client() {
let hello = Hello {
namespace: "shop".to_owned(),
client: Some("real-client".to_owned()),
session: Some("s1".to_owned()),
};
let caps = hello.capabilities();
let session = &caps["experimental"][crate::mcp::SESSION_CAPABILITY];
assert_eq!(session["namespace"], "shop");
assert_eq!(session["client"], "real-client");
let early = Hello {
namespace: "shop".to_owned(),
client: None,
session: None,
};
assert!(
early.capabilities()["experimental"][crate::mcp::SESSION_CAPABILITY]
.get("client")
.is_none()
);
}
#[test]
fn a_plain_json_answer_parses() {
let message =
parse_message(r#"{"jsonrpc":"2.0","id":1,"result":{"ok":true}}"#).expect("parsed");
assert_eq!(message["result"]["ok"], true);
}
#[test]
fn an_event_stream_answer_parses() {
let body =
"event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"ok\":true}}\n\n";
let message = parse_message(body).expect("parsed");
assert_eq!(message["result"]["ok"], true);
}
#[test]
fn something_that_is_neither_is_reported_rather_than_guessed_at() {
let err = parse_message("<html>not this</html>").expect_err("refused");
assert!(err.to_string().contains("neither JSON nor an event stream"));
}
#[test]
fn only_a_transport_failure_counts_as_the_daemon_going_away() {
assert!(UpstreamError::Unreachable {
url: "http://127.0.0.1:1/mcp".to_owned(),
reason: "refused".to_owned(),
}
.is_disconnect());
assert!(!UpstreamError::Rpc {
code: -32602,
message: "bad arguments".to_owned(),
}
.is_disconnect());
assert!(!UpstreamError::Unusable("odd".to_owned()).is_disconnect());
assert!(UpstreamError::SessionGone.is_disconnect());
}
}