offline-mcp 0.4.0

Model Context Protocol server exposing the Offline Protocol registry to AI agents
Documentation
//! The MCP server: newline-delimited JSON-RPC 2.0 over arbitrary
//! reader/writer pairs (stdio in production, strings in tests).

use std::io::{BufRead, Write};

use offline_registry::Registry;
use serde_json::{json, Value};

use crate::mode::DeploymentMode;
use crate::protocol::{
    Request, Response, INVALID_PARAMS, INVALID_REQUEST, METHOD_NOT_FOUND, PARSE_ERROR,
};
use crate::{prompts, resources, tools};

/// Supported protocol versions; echo the client's if known, else latest.
/// Public so the HTTP server can check the `MCP-Protocol-Version` header.
pub const SUPPORTED_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
pub const LATEST_VERSION: &str = "2025-06-18";

const INSTRUCTIONS_LOCAL: &str = "Registry, knowledge base, and planner for the Offline Protocol ecosystem (offline-first mesh networking, messaging, and identity SDKs). Start with `generate_architecture` for new apps, and ALWAYS read the relevant skill via `get_skill` before writing SDK code. The `offline://llms.txt` resource is a one-read ecosystem index. Account tools (`app_status`, `register_native_app`, `set_features`, `apply_project_setup`, …) set up the developer's application without the portal: run `app_status` to see what is missing for sign-in on each platform.";

const INSTRUCTIONS_HOSTED: &str = "Hosted Offline Protocol MCP: registry, planning, and integration knowledge only (no filesystem writes on this server). Start with `generate_architecture`, use `preview_scaffold` to plan greenfield work, and ALWAYS `get_skill` before writing SDK code. To scaffold or integrate packages on disk, run local `offline mcp serve` or the Offline CLI.";

/// Tools that act on the developer's Offline Protocol account (applications,
/// native apps, origins, features). The CLI provides them to the local server;
/// the hosted server has none.
pub trait AccountTools: Send + Sync {
    /// Tool definitions (`name`, `description`, `inputSchema`, `annotations`).
    fn definitions(&self) -> Vec<Value>;
    /// Run a tool; `None` when `name` is not one of these tools.
    fn call(&self, name: &str, args: &Value) -> Option<Result<Value, String>>;
}

pub struct McpServer {
    registry: Registry,
    mode: DeploymentMode,
    account: Option<Box<dyn AccountTools>>,
}

impl McpServer {
    pub fn new(registry: Registry) -> Self {
        Self::with_mode(registry, DeploymentMode::Local)
    }

    pub fn with_mode(registry: Registry, mode: DeploymentMode) -> Self {
        Self {
            registry,
            mode,
            account: None,
        }
    }

    /// Add account tools (local server only; ignored when hosted).
    pub fn with_account_tools(mut self, tools: Box<dyn AccountTools>) -> Self {
        if self.mode == DeploymentMode::Local {
            self.account = Some(tools);
        }
        self
    }

    pub fn mode(&self) -> DeploymentMode {
        self.mode
    }

    /// Serve until EOF. Each line is one JSON-RPC message.
    pub fn run<R: BufRead, W: Write>(&self, reader: R, mut writer: W) -> std::io::Result<()> {
        for line in reader.lines() {
            let line = line?;
            if line.trim().is_empty() {
                continue;
            }
            if let Some(response) = self.handle_message(&line) {
                writer.write_all(response.as_bytes())?;
                writer.write_all(b"\n")?;
                writer.flush()?;
            }
        }
        Ok(())
    }

    /// Handle one raw message; `None` means no response (notification).
    pub fn handle_message(&self, raw: &str) -> Option<String> {
        let request: Request = match serde_json::from_str(raw) {
            Ok(r) => r,
            Err(e) => {
                return Some(
                    Response::error(Value::Null, PARSE_ERROR, format!("parse error: {e}"))
                        .to_json(),
                );
            }
        };

        let id = match &request.id {
            Some(id) => id.clone(),
            None => {
                // JSON-RPC notification: no response.
                return None;
            }
        };

        if !request.jsonrpc.is_empty() && request.jsonrpc != "2.0" {
            return Some(Response::error(id, INVALID_REQUEST, "jsonrpc must be \"2.0\"").to_json());
        }

        let response = self.dispatch(id, &request.method, &request.params);
        Some(response.to_json())
    }

    fn dispatch(&self, id: Value, method: &str, params: &Value) -> Response {
        match method {
            "initialize" => {
                let requested = params
                    .get("protocolVersion")
                    .and_then(Value::as_str)
                    .unwrap_or(LATEST_VERSION);
                let version = if SUPPORTED_VERSIONS.contains(&requested) {
                    requested
                } else {
                    LATEST_VERSION
                };
                Response::success(
                    id,
                    json!({
                        "protocolVersion": version,
                        "capabilities": {
                            "tools": {},
                            "resources": {},
                            "prompts": {}
                        },
                        "serverInfo": {
                            "name": "offline-protocol",
                            "version": env!("CARGO_PKG_VERSION"),
                        },
                        "instructions": match self.mode {
                            DeploymentMode::Local => INSTRUCTIONS_LOCAL,
                            DeploymentMode::Hosted => INSTRUCTIONS_HOSTED,
                        }
                    }),
                )
            }
            "ping" => Response::success(id, json!({})),
            "tools/list" => {
                let mut list = tools::tool_definitions_for(self.mode);
                if let Some(account) = &self.account {
                    list.extend(account.definitions());
                }
                Response::success(id, json!({"tools": list}))
            }
            "tools/call" => {
                let name = match params.get("name").and_then(Value::as_str) {
                    Some(n) => n,
                    None => {
                        return Response::error(id, INVALID_PARAMS, "missing tool `name`");
                    }
                };
                let default_args = json!({});
                let args = params.get("arguments").unwrap_or(&default_args);
                let result = match self.account.as_ref().and_then(|a| a.call(name, args)) {
                    Some(result) => result,
                    None => tools::call_tool_for(&self.registry, name, args, self.mode),
                };
                match result {
                    Ok(result) => Response::success(
                        id,
                        json!({
                            "content": [{
                                "type": "text",
                                "text": serde_json::to_string_pretty(&result)
                                    .expect("tool result serializes"),
                            }],
                            "isError": false
                        }),
                    ),
                    Err(message) => Response::success(
                        id,
                        json!({
                            "content": [{"type": "text", "text": message}],
                            "isError": true
                        }),
                    ),
                }
            }
            "resources/list" => Response::success(
                id,
                json!({"resources": resources::resource_list(&self.registry)}),
            ),
            "resources/read" => {
                let uri = match params.get("uri").and_then(Value::as_str) {
                    Some(u) => u,
                    None => return Response::error(id, INVALID_PARAMS, "missing `uri`"),
                };
                match resources::read_resource(&self.registry, uri) {
                    Ok((mime, text)) => Response::success(
                        id,
                        json!({
                            "contents": [{"uri": uri, "mimeType": mime, "text": text}]
                        }),
                    ),
                    Err(message) => Response::error(id, INVALID_PARAMS, message),
                }
            }
            "prompts/list" => Response::success(id, json!({"prompts": prompts::prompt_list()})),
            "prompts/get" => {
                let name = match params.get("name").and_then(Value::as_str) {
                    Some(n) => n,
                    None => return Response::error(id, INVALID_PARAMS, "missing prompt `name`"),
                };
                let default_args = json!({});
                let args = params.get("arguments").unwrap_or(&default_args);
                match prompts::get_prompt(&self.registry, name, args) {
                    Ok(result) => Response::success(id, result),
                    Err(message) => Response::error(id, INVALID_PARAMS, message),
                }
            }
            other => Response::error(id, METHOD_NOT_FOUND, format!("method `{other}` not found")),
        }
    }
}