Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .claude/skills/devstack/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ takes `profile`, `run` and `yes` (as `--profile`, `--run`, `--yes`) and
`lane_start` takes `profile`, `run` and `timeout_s` too; `logs` takes `file` (one kept log, from its
list); `diagnostics` takes `source: "hub"` for the hub's log. Each tool
describes its parameters.
Tools named `<prefix>__<tool>` are not devstack's: they are the user's MCP
upstreams, which the hub logs in to (the dashboard's *MCP upstreams*). One
that answers it is not logged in needs the user, in the dashboard; tell them,
do not look for another way in.
Register it once (project `.mcp.json` or user configuration; the dashboard
shows *no MCP* in the stack's head while neither has it):

Expand Down
10 changes: 8 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,14 @@ and listed with their assets on the
itself, with OAuth (it finds the authorization server, registers where
the server allows it, PKCE; the browser comes back to the hub) or a
token the user gives it, and keeps the login in the keychain (a file on
a Linux machine without a Secret Service). Their tools in `devstack mcp`
follow.
a Linux machine without a Secret Service). `devstack mcp` offers their
tools in every coding agent as `<prefix>__<tool>`, beside its own, and
calls them through the hub, which starts when it does not run; the token
never leaves the hub. One that is logged out or unreachable keeps the
tools it listed last and answers with the dashboard's page; a change of
the tools is announced (`notifications/tools/list_changed`). Without a
hub (`DEVSTACK_NO_HUB`), upstreams without a login or with a token from
the environment are asked directly.

### Changed

Expand Down
42 changes: 41 additions & 1 deletion crates/devstack-hub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ static UI: Dir<'_> = include_dir!("$OUT_DIR/ui");
mod branches;
mod guests;
mod mcp;
mod mcpclient;
mod notice;
mod notify;
mod open;
Expand All @@ -48,7 +49,7 @@ mod share;
mod shared;
mod summary;
pub mod tray;
mod upstreams;
pub mod upstreams;
mod ws;

pub const VERSION: &str = env!("CARGO_PKG_VERSION");
Expand Down Expand Up @@ -485,6 +486,8 @@ fn router(state: AppState) -> axum::Router {
.route("/auth", get(auth))
.route(upstreams::CALLBACK, get(upstream_callback))
.route("/hub/upstreams", get(upstreams_list).post(upstream_put))
.route("/hub/upstreams/tools", get(upstream_tools))
.route("/hub/upstreams/call", post(upstream_call))
.route("/hub/upstreams/{name}", delete(upstream_remove))
.route("/hub/upstreams/{name}/login", post(upstream_login))
.route("/hub/upstreams/{name}/token", post(upstream_token))
Expand Down Expand Up @@ -2457,6 +2460,43 @@ async fn upstream_put(State(s): State<AppState>, Json(u): Json<upstreams::Upstre
r
}

/// `GET /hub/upstreams/tools`: the upstreams' tools as `devstack mcp` offers
/// them (`<prefix>__<tool>`, allowlists applied); for `devstack mcp`, with
/// the user token (card point 2).
async fn upstream_tools(State(s): State<AppState>) -> Response {
let ups = s.upstreams.clone();
match tokio::task::spawn_blocking(move || ups.tools(&upstreams::http())).await {
Ok(tools) => Json(serde_json::json!({ "tools": tools })).into_response(),
Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
}
}

#[derive(Deserialize)]
struct CallBody {
name: String,
#[serde(default)]
arguments: serde_json::Value,
}

/// `POST /hub/upstreams/call {name, arguments}`: the upstream's answer to a
/// tool call, a `CallToolResult`. The credential stays in the hub.
async fn upstream_call(State(s): State<AppState>, Json(b): Json<CallBody>) -> Response {
let ups = s.upstreams.clone();
let name = b.name.clone();
match tokio::task::spawn_blocking(move || ups.call(&upstreams::calls(), &b.name, b.arguments))
.await
{
Ok(r) => {
diag::info(
"upstream_call",
serde_json::json!({ "tool": name, "error": r["isError"] == true }),
);
Json(r).into_response()
}
Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
}
}

/// `DELETE /hub/upstreams/{name}`: it and its credential go.
async fn upstream_remove(State(s): State<AppState>, Path(name): Path<String>) -> Response {
on_upstreams(&s, move |ups| {
Expand Down
233 changes: 233 additions & 0 deletions crates/devstack-hub/src/mcpclient.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
//! A client of an MCP server over Streamable HTTP, as far as the hub needs
//! one for its upstreams (ADR-0069): `initialize` once per session, then
//! `tools/list` and `tools/call`. A request is a JSON-RPC POST; the answer is
//! JSON, or a server-sent event stream whose event with the request's id is
//! the answer. The session id the server gives comes with every later
//! request; a server that forgot it (`404`) gets a new session once.

use serde_json::{Value, json};

/// The protocol version asked for; the server's answer is used after.
const PROTOCOL: &str = "2025-06-18";

/// A session with one upstream.
#[derive(Debug, Clone, Default)]
pub struct Session {
id: Option<String>,
version: Option<String>,
ready: bool,
}

#[derive(Debug)]
pub enum Error {
/// The upstream refused the credential (`401`, `403`).
Unauthorized,
/// Anything else: not reachable, an HTTP or a JSON-RPC error.
Other(String),
}

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Unauthorized => write!(f, "the upstream refused the login"),
Error::Other(e) => write!(f, "{e}"),
}
}
}

/// `method` with `params` on the upstream at `url`: its `result`. Starts the
/// session first when it has none.
pub fn request(
http: &ureq::Agent,
url: &str,
bearer: Option<&str>,
session: &mut Session,
method: &str,
params: Value,
) -> Result<Value, Error> {
for attempt in 0..2 {
if !session.ready {
start(http, url, bearer, session)?;
}
match post(http, url, bearer, session, method, Some(params.clone()), 2) {
Err(Gone) if attempt == 0 => {
*session = Session::default();
}
Err(Gone) => {
return Err(Error::Other(
"the upstream keeps forgetting its session".into(),
));
}
Ok(r) => return r,
}
}
unreachable!("the loop returns")
}

/// The server forgot the session (`404` with one).
struct Gone;

fn start(
http: &ureq::Agent,
url: &str,
bearer: Option<&str>,
session: &mut Session,
) -> Result<(), Error> {
*session = Session::default();
let params = json!({
"protocolVersion": PROTOCOL,
"capabilities": {},
"clientInfo": { "name": "devstack-hub", "version": env!("CARGO_PKG_VERSION") },
});
let result = match post(http, url, bearer, session, "initialize", Some(params), 1) {
Ok(r) => r?,
Err(Gone) => {
return Err(Error::Other(
"the upstream refused to start a session".into(),
));
}
};
session.version = result["protocolVersion"].as_str().map(str::to_string);
// The notification has no answer to wait for (`202`).
let _ = notify(http, url, bearer, session, "notifications/initialized");
session.ready = true;
Ok(())
}

fn with_headers(
mut req: ureq::RequestBuilder<ureq::typestate::WithBody>,
bearer: Option<&str>,
session: &Session,
) -> ureq::RequestBuilder<ureq::typestate::WithBody> {
req = req
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream");
if let Some(b) = bearer {
req = req.header("Authorization", &format!("Bearer {b}"));
}
if let Some(id) = &session.id {
req = req.header("Mcp-Session-Id", id);
}
if let Some(v) = &session.version {
req = req.header("MCP-Protocol-Version", v);
}
req
}

fn notify(
http: &ureq::Agent,
url: &str,
bearer: Option<&str>,
session: &Session,
method: &str,
) -> Result<(), String> {
let body = json!({ "jsonrpc": "2.0", "method": method });
with_headers(http.post(url), bearer, session)
.send(body.to_string())
.map(|_| ())
.map_err(|e| e.to_string())
}

/// One request: `Err(Gone)` when the server forgot the session; else its
/// result or why not.
fn post(
http: &ureq::Agent,
url: &str,
bearer: Option<&str>,
session: &mut Session,
method: &str,
params: Option<Value>,
id: u64,
) -> Result<Result<Value, Error>, Gone> {
let mut body = json!({ "jsonrpc": "2.0", "id": id, "method": method });
if let Some(p) = params {
body["params"] = p;
}
let mut r = match with_headers(http.post(url), bearer, session).send(body.to_string()) {
Ok(r) => r,
Err(e) => return Ok(Err(Error::Other(format!("{url}: {e}")))),
};
let status = r.status().as_u16();
if status == 404 && session.id.is_some() {
return Err(Gone);
}
if status == 401 || status == 403 {
return Ok(Err(Error::Unauthorized));
}
if let Some(s) = r
.headers()
.get("mcp-session-id")
.and_then(|v| v.to_str().ok())
{
session.id = Some(s.to_string());
}
let sse = r
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.is_some_and(|c| c.starts_with("text/event-stream"));
let text = match r.body_mut().read_to_string() {
Ok(t) => t,
Err(e) => return Ok(Err(Error::Other(format!("{url}: {e}")))),
};
if !(200..300).contains(&status) {
return Ok(Err(Error::Other(format!(
"{url} answered {status}: {}",
text.trim()
))));
}
let answer = if sse {
from_events(&text, id)
} else {
serde_json::from_str(&text).ok()
};
let Some(a) = answer else {
return Ok(Err(Error::Other(format!(
"{url} gave no answer to `{method}`"
))));
};
if let Some(e) = a.get("error") {
return Ok(Err(Error::Other(format!(
"`{method}`: {}",
e["message"].as_str().unwrap_or("an error")
))));
}
Ok(Ok(a.get("result").cloned().unwrap_or(Value::Null)))
}

/// The JSON-RPC answer with `id` in a server-sent event stream.
fn from_events(text: &str, id: u64) -> Option<Value> {
let mut data = String::new();
let mut found = None;
for line in text.lines().chain(std::iter::once("")) {
if let Some(d) = line.strip_prefix("data:") {
if !data.is_empty() {
data.push('\n');
}
data.push_str(d.strip_prefix(' ').unwrap_or(d));
} else if line.is_empty() && !data.is_empty() {
if let Ok(v) = serde_json::from_str::<Value>(&data)
&& v["id"] == json!(id)
{
found = Some(v);
}
data.clear();
}
}
found
}

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

#[test]
fn the_answer_is_found_among_events() {
let text = "event: message\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}\n\n\
data: {\"jsonrpc\":\"2.0\",\"id\":2,\n\
data: \"result\":{\"tools\":[]}}\n\n";
let v = from_events(text, 2).unwrap();
assert_eq!(v["result"]["tools"], json!([]));
assert!(from_events(text, 3).is_none());
}
}
23 changes: 20 additions & 3 deletions crates/devstack-hub/src/secrets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,15 @@ pub struct Secrets {
}

enum Store {
Keychain { service: String },
File { path: PathBuf, lock: Mutex<()> },
Keychain {
service: String,
},
File {
path: PathBuf,
lock: Mutex<()>,
},
/// None: `devstack mcp` without a hub reads no secret (ADR-0069 point 6).
Nothing,
}

impl Secrets {
Expand All @@ -57,9 +64,16 @@ impl Secrets {
}
}

/// A store that holds nothing and takes nothing.
pub fn nothing() -> Self {
Self {
store: Store::Nothing,
}
}

pub fn kind(&self) -> Kind {
match self.store {
Store::Keychain { .. } => Kind::Keychain,
Store::Keychain { .. } | Store::Nothing => Kind::Keychain,
Store::File { .. } => Kind::File,
}
}
Expand All @@ -76,6 +90,7 @@ impl Secrets {
let _held = lock.lock().unwrap();
Ok(read_file(path)?.remove(upstream))
}
Store::Nothing => Ok(None),
}
}

Expand All @@ -90,6 +105,7 @@ impl Secrets {
all.insert(upstream.to_string(), secret.to_string());
write_file(path, &all)
}
Store::Nothing => Err("no secret is kept here".into()),
}
}

Expand All @@ -108,6 +124,7 @@ impl Secrets {
}
Ok(())
}
Store::Nothing => Ok(()),
}
}
}
Expand Down
Loading
Loading