robloxstudio-worktree 0.1.0

Own an isolated Rojo, Roblox Studio, and MCP runtime for each Git worktree
Documentation
use std::fs;
use std::path::PathBuf;
use std::time::Duration;

use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use url::Url;

pub const DEFAULT_MCP_URL: &str = "http://127.0.0.1:58741";

#[derive(Clone, Debug)]
pub struct McpClient {
    base_url: String,
    auth_token: Option<String>,
}

impl McpClient {
    pub fn new(base_url: &str) -> Result<Self> {
        Ok(Self {
            base_url: normalize_mcp_url(base_url)?,
            auth_token: load_auth_token(),
        })
    }

    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    pub fn tool(&self, name: &str, payload: Value, timeout: Duration) -> Result<Value> {
        let url = format!("{}/mcp/{name}", self.base_url.trim_end_matches('/'));
        let agent = ureq::AgentBuilder::new().timeout(timeout).build();
        let mut request = agent.post(&url).set("Accept", "application/json");
        if let Some(token) = &self.auth_token {
            request = request.set("X-MCP-Auth", token);
        }
        let response = match request.send_json(payload) {
            Ok(response) => response,
            Err(ureq::Error::Status(code, response)) => {
                let detail = response.into_string().unwrap_or_default();
                bail!("MCP /mcp/{name} failed with HTTP {code}: {detail}");
            }
            Err(error) => {
                bail!(
                    "Could not connect to Roblox Studio MCP at {}: {error}. Start the MCP server first.",
                    self.base_url
                );
            }
        };
        let envelope: Value = response
            .into_json()
            .with_context(|| format!("MCP tool {name} returned invalid JSON"))?;
        let content = envelope
            .get("content")
            .and_then(Value::as_array)
            .filter(|value| !value.is_empty())
            .with_context(|| format!("MCP tool {name} returned no content"))?;
        let first = content.first().expect("non-empty content");
        if first.get("type").and_then(Value::as_str) != Some("text") {
            bail!("MCP tool {name} returned unsupported content: {content:?}");
        }
        let text = first
            .get("text")
            .and_then(Value::as_str)
            .with_context(|| format!("MCP tool {name} returned non-text payload"))?;
        let decoded: Value = serde_json::from_str(text)
            .with_context(|| format!("MCP tool {name} returned invalid JSON text"))?;
        if decoded.get("success").and_then(Value::as_bool) == Some(false) {
            let message = decoded
                .get("message")
                .or_else(|| decoded.get("error"))
                .cloned()
                .unwrap_or_else(|| decoded.clone());
            bail!("MCP tool {name} failed: {message}");
        }
        if let Some(error) = decoded.get("error").filter(|value| !value.is_null()) {
            bail!("MCP tool {name} failed: {error}");
        }
        if !decoded.is_object() {
            bail!("MCP tool {name} returned unexpected payload: {decoded}");
        }
        Ok(decoded)
    }

    pub fn manage_status(&self, instance_id: &str) -> Result<Value> {
        self.tool(
            "manage_instance",
            json!({"action": "status", "instance_id": instance_id}),
            Duration::from_secs(60),
        )
    }
}

pub fn normalize_mcp_url(raw: &str) -> Result<String> {
    let mut url = Url::parse(raw).with_context(|| format!("Invalid MCP URL: {raw}"))?;
    if matches!(url.host_str(), Some("localhost" | "0.0.0.0")) {
        url.set_host(Some("127.0.0.1"))
            .map_err(|_| anyhow::anyhow!("Could not normalize MCP URL {raw}"))?;
    }
    Ok(url.to_string().trim_end_matches('/').to_owned())
}

fn load_auth_token() -> Option<String> {
    if let Ok(token) = std::env::var("ROBLOX_STUDIO_MCP_AUTH_TOKEN") {
        let token = token.trim().to_owned();
        if !token.is_empty() {
            return Some(token);
        }
    }
    let path = std::env::var_os("ROBLOX_STUDIO_MCP_AUTH_TOKEN_FILE")
        .map(PathBuf::from)
        .or_else(|| {
            std::env::var_os("HOME")
                .map(PathBuf::from)
                .map(|home| home.join(".robloxstudio-mcp/auth-token"))
        })?;
    fs::read_to_string(path)
        .ok()
        .map(|token| token.trim().to_owned())
        .filter(|token| !token.is_empty())
}