use std::{
borrow::Cow,
collections::HashSet,
future::Future,
pin::Pin,
sync::{Arc, mpsc as std_mpsc},
};
mod discovery;
mod file_dialogs;
mod held_input;
mod logs;
mod profiling;
mod registry;
mod server;
mod sessions;
mod shared;
mod tools;
pub(crate) use file_dialogs::ServingBroker;
pub use file_dialogs::{
FileDialogBroker, FileDialogError, FileDialogFuture, FileDialogOperation, FileDialogRequest, FileDialogSelection,
};
pub use logs::{McpLogLayer, log_layer};
use registry::{ToolKind, ToolRegistry};
pub use rmcp;
pub use rmcp::schemars;
pub use server::McpService;
use shared::McpShared;
pub use shared::{McpToolOutput, McpToolResult};
use crate::app::{App, Tree};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Scope {
Observe,
Interact,
Navigate,
Custom(Cow<'static, str>),
}
impl Scope {
pub fn custom(name: impl Into<Cow<'static, str>>) -> Self {
Self::Custom(name.into())
}
}
pub struct McpToolCtx<'a> {
pub tree: &'a mut Tree,
pub app: &'a mut App,
}
type CustomSyncHandler = Arc<registry::SyncToolHandler>;
type CustomAsyncHandler = Arc<registry::AsyncToolHandler>;
enum CustomToolKind {
Sync(CustomSyncHandler),
Async(CustomAsyncHandler),
}
pub struct McpTool {
name: String,
description: String,
scope: Scope,
read_only: bool,
input_schema: serde_json::Value,
kind: Option<CustomToolKind>,
}
impl McpTool {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
description: String::new(),
scope: Scope::custom("app"),
read_only: false,
input_schema: serde_json::json!({ "type": "object", "properties": {} }),
kind: None,
}
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = description.into();
self
}
pub fn scope(mut self, scope: impl Into<Scope>) -> Self {
self.scope = scope.into();
self
}
pub fn read_only(mut self) -> Self {
self.read_only = true;
self
}
pub fn input_schema(mut self, schema: serde_json::Value) -> Self {
self.input_schema = schema;
self
}
pub fn handler<F>(mut self, handler: F) -> Self
where
F: Fn(&mut McpToolCtx<'_>, serde_json::Value) -> Result<serde_json::Value, String> + Send + Sync + 'static,
{
self.kind = Some(CustomToolKind::Sync(Arc::new(handler)));
self
}
pub fn async_handler<F, Fut>(mut self, handler: F) -> Self
where
F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<serde_json::Value, String>> + Send + 'static,
{
self.kind = Some(CustomToolKind::Async(Arc::new(move |args| {
Box::pin(handler(args)) as Pin<Box<dyn Future<Output = Result<serde_json::Value, String>> + Send>>
})));
self
}
}
impl From<&'static str> for Scope {
fn from(name: &'static str) -> Self {
Scope::custom(name)
}
}
pub struct McpConfig {
scopes: HashSet<Scope>,
denied_tools: HashSet<String>,
port: Option<u16>,
app_name: Option<String>,
include_devtools: bool,
instructions: Option<String>,
tools: Vec<McpTool>,
file_dialogs: Option<FileDialogBroker>,
hosted: bool,
#[cfg(feature = "router")]
navigator: Option<crate::router::Navigator>,
}
impl Default for McpConfig {
fn default() -> Self {
Self::new()
}
}
impl McpConfig {
pub fn new() -> Self {
Self {
scopes: HashSet::from([Scope::Observe, Scope::Interact]),
denied_tools: HashSet::new(),
port: None,
app_name: None,
include_devtools: false,
instructions: None,
tools: Vec::new(),
file_dialogs: None,
hosted: false,
#[cfg(feature = "router")]
navigator: None,
}
}
pub fn hosted(mut self) -> Self {
self.hosted = true;
self
}
pub fn scopes(mut self, scopes: impl IntoIterator<Item = Scope>) -> Self {
self.scopes = scopes.into_iter().collect();
self
}
pub fn scope(mut self, scope: Scope) -> Self {
self.scopes.insert(scope);
self
}
pub fn deny_tool(mut self, name: impl Into<String>) -> Self {
self.denied_tools.insert(name.into());
self
}
pub fn port(mut self, port: u16) -> Self {
self.port = Some(port);
self
}
pub fn app_name(mut self, name: impl Into<String>) -> Self {
self.app_name = Some(name.into());
self
}
pub fn include_devtools(mut self, include: bool) -> Self {
self.include_devtools = include;
self
}
pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
self.instructions = Some(instructions.into());
self
}
pub fn tool(mut self, tool: McpTool) -> Self {
self.tools.push(tool);
self
}
pub fn file_dialogs(mut self, broker: FileDialogBroker) -> Self {
self.file_dialogs = Some(broker);
self
}
#[cfg(feature = "router")]
pub fn navigator(mut self, navigator: crate::router::Navigator) -> Self {
self.navigator = Some(navigator);
self
}
}
#[derive(Clone)]
pub struct McpHandle {
shared: Arc<McpShared>,
registry: Arc<ToolRegistry>,
sender: std_mpsc::Sender<shared::McpRequest>,
port: u16,
}
impl McpHandle {
pub fn port(&self) -> u16 {
self.port
}
pub fn service(&self) -> McpService {
McpService::new(self.shared.clone(), self.registry.clone(), self.sender.clone())
}
pub fn token(&self) -> &str {
&self.shared.token
}
pub fn is_enabled(&self) -> bool {
self.shared.is_enabled()
}
pub fn set_enabled(&self, enabled: bool) {
self.shared.set_enabled(enabled);
}
pub fn set_scopes(&self, scopes: impl IntoIterator<Item = Scope>) {
self.shared.set_scopes(scopes.into_iter().collect());
}
pub fn add_scope(&self, scope: Scope) {
self.shared.add_scope(scope);
}
pub fn remove_scope(&self, scope: &Scope) {
self.shared.remove_scope(scope);
}
pub fn deny_tool(&self, name: impl Into<String>) {
self.shared.deny_tool(name);
}
pub fn allow_tool(&self, name: &str) {
self.shared.allow_tool(name);
}
#[cfg(feature = "router")]
pub fn set_navigator(&self, navigator: crate::router::Navigator) {
*self.shared.navigator.write().unwrap() = Some(navigator);
}
}
pub(crate) struct McpWaitEntry {
pub(crate) mode: McpWaitMode,
pub(crate) reply: Option<shared::McpReply>,
}
pub(crate) enum McpWaitMode {
Frames(u32),
Idle,
}
pub struct McpState {
pub(crate) shared: Arc<McpShared>,
pub(crate) registry: Arc<ToolRegistry>,
pub(crate) receiver: std_mpsc::Receiver<shared::McpRequest>,
pub(crate) include_devtools: bool,
pub(crate) held: parking_lot::Mutex<held_input::HeldInput>,
server: Option<server::ServerRuntime>,
discovery_path: Option<std::path::PathBuf>,
}
fn default_app_name() -> String {
std::env::current_exe()
.ok()
.and_then(|path| path.file_stem().map(|stem| stem.to_string_lossy().into_owned()))
.unwrap_or_else(|| "lurq-app".to_owned())
}
fn build_registry(tools: Vec<McpTool>) -> ToolRegistry {
let mut registry = ToolRegistry {
tools: registry::builtin_tools(cfg!(feature = "router")),
};
registry.tools.extend(profiling::registered_tools());
for tool in tools {
assert!(
!tool.name.starts_with("lurq_"),
"custom MCP tool {:?} uses the reserved lurq_ prefix",
tool.name
);
assert!(
registry.find(&tool.name).is_none(),
"custom MCP tool {:?} is registered twice",
tool.name
);
let kind = match tool.kind {
Some(CustomToolKind::Sync(handler)) => ToolKind::Sync(handler),
Some(CustomToolKind::Async(handler)) => ToolKind::Async(handler),
None => panic!("custom MCP tool {:?} has no handler", tool.name),
};
registry.tools.push(registry::RegisteredTool {
name: tool.name,
description: tool.description,
scope: tool.scope,
read_only: tool.read_only,
input_schema: tool.input_schema,
kind,
});
}
registry
}
impl Tree {
pub fn enable_mcp(&mut self, config: McpConfig) -> McpHandle {
assert!(self.mcp.is_none(), "enable_mcp called twice on this tree");
let mut registry = build_registry(config.tools);
if config.file_dialogs.is_some() {
registry.tools.extend(tools::file_dialogs::registered_tools());
}
let registry = Arc::new(registry);
let app_name = config.app_name.unwrap_or_else(default_app_name);
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
let shared = Arc::new(McpShared::new(
config.scopes,
config.denied_tools,
token,
app_name,
config.instructions,
));
*shared.profiling.write().unwrap() = self.profiling_handle();
shared
.include_profile_devtools
.store(config.include_devtools, std::sync::atomic::Ordering::Relaxed);
if let Some(broker) = config.file_dialogs {
broker.attach(&shared);
self.window().serve_file_dialogs(&broker.serving());
*shared.file_dialogs.lock().unwrap() = Some(broker);
}
#[cfg(feature = "router")]
if let Some(navigator) = config.navigator {
*shared.navigator.write().unwrap() = Some(navigator);
}
let (sender, receiver) = std_mpsc::channel();
if config.hosted {
tracing::info!("lurq MCP tools are served by the app's own MCP server");
self.mcp = Some(Box::new(McpState {
shared: shared.clone(),
registry: registry.clone(),
receiver,
include_devtools: config.include_devtools,
held: Default::default(),
server: None,
discovery_path: None,
}));
return McpHandle {
shared,
registry,
sender,
port: 0,
};
}
let server = match server::spawn(shared.clone(), registry.clone(), sender.clone(), config.port) {
Ok(server) => server,
Err(message) => {
shared.set_enabled(false);
let broker = shared.file_dialogs.lock().unwrap().clone();
if let Some(broker) = broker {
broker.shutdown();
}
tracing::error!("failed to start MCP server: {message}");
self.mcp = Some(Box::new(McpState {
shared: shared.clone(),
registry: registry.clone(),
receiver,
include_devtools: config.include_devtools,
held: Default::default(),
server: None,
discovery_path: None,
}));
return McpHandle {
shared,
registry,
sender,
port: 0,
};
}
};
let port = server.port;
let discovery_path = discovery::write(&shared.app_name, port, &shared.token);
tracing::info!(
"lurq MCP server listening on http://127.0.0.1:{port}/mcp{}",
discovery_path
.as_deref()
.map(|path| format!(" (discovery: {})", path.display()))
.unwrap_or_default()
);
self.mcp = Some(Box::new(McpState {
shared: shared.clone(),
registry: registry.clone(),
receiver,
include_devtools: config.include_devtools,
held: Default::default(),
server: Some(server),
discovery_path,
}));
McpHandle {
shared,
registry,
sender,
port,
}
}
#[cfg_attr(not(feature = "winit"), allow(dead_code))]
pub(crate) fn set_mcp_waker(&self, waker: Arc<dyn Fn() + Send + Sync>) {
if let Some(mcp) = &self.mcp {
*mcp.shared.waker.lock().unwrap() = Some(waker);
}
}
pub fn drain_mcp_requests(&mut self, app: &mut App) -> bool {
crate::app::events::with_synthetic_input(|| self.drain_mcp_requests_synthetic(app))
}
fn drain_mcp_requests_synthetic(&mut self, app: &mut App) -> bool {
self.reconcile_file_dialogs();
let Some(state) = self.mcp.take() else {
return false;
};
let mut did_work = false;
while let Ok(request) = state.receiver.try_recv() {
if request.reply.is_closed() {
tracing::debug!(tool = %request.tool, "dropped an MCP call whose caller stopped waiting");
continue;
}
did_work = true;
tools::execute(self, app, &state, request);
}
did_work |= tools::release_unreachable_holds(self, &state);
self.mcp = Some(state);
did_work
}
pub(crate) fn mcp_idle(&self) -> bool {
!self.needs_redraw() && !self.has_active_timeline() && !self.has_moving_canvas() && self.finger_deadline().is_none()
}
pub(crate) fn mcp_notify_pass(&mut self, report: &crate::app::runtime::PassReport) {
self.reconcile_file_dialogs();
if self.mcp_wait_entries.is_empty() {
return;
}
let rendered = report.rendered;
let idle = self.mcp_idle();
let mut keep_producing_frames = false;
self.mcp_wait_entries.retain_mut(|entry| {
let Some(reply) = entry.reply.take() else {
return false;
};
if reply.is_closed() {
return false;
}
let done = match &mut entry.mode {
McpWaitMode::Frames(remaining) => {
if rendered {
*remaining = remaining.saturating_sub(1);
}
*remaining == 0
}
McpWaitMode::Idle => rendered && idle,
};
if done {
let _ = reply.send(Ok(McpToolOutput::Text("done".into())));
false
} else {
if matches!(entry.mode, McpWaitMode::Frames(_)) {
keep_producing_frames = true;
}
entry.reply = Some(reply);
true
}
});
if keep_producing_frames {
self.request_redraw();
}
}
pub fn shutdown_mcp(&mut self) {
let Some(mut state) = self.mcp.take() else {
return;
};
crate::app::events::with_synthetic_input(|| tools::release_all_holds(self, &state));
let broker = state.shared.file_dialogs.lock().unwrap().clone();
if let Some(broker) = broker {
broker.shutdown();
}
if let Some(path) = &state.discovery_path {
discovery::remove(path);
}
if let Some(server) = state.server.take() {
server.cancel.cancel();
let _ = server.join.join();
}
}
}
impl Drop for McpState {
fn drop(&mut self) {
self.shared.set_enabled(false);
let broker = self.shared.file_dialogs.lock().unwrap().clone();
if let Some(broker) = broker {
broker.shutdown();
}
}
}