apoc 0.9.1

Agentic process control for LLMs
Documentation
use std::sync::Arc;

#[allow(dead_code)]
#[path = "lib.rs"]
mod apoc_apple_device;

use apoc_apple_device::{AppleDeviceService, AttachRequest, ProviderError, SystemRunner};
use incurs::cli::Cli;
use incurs::command::{CommandDef, McpAnnotations, McpCommandOptions, TypedContext, TypedResult};
use incurs::mcp::McpServeOptions;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Clone)]
struct App {
    service: Arc<AppleDeviceService<SystemRunner>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, incurs::Options)]
struct DeviceListOptions {
    /// Apple platform filter: auto, ios, tvos, watchos, or visionos.
    #[incurs(default = "auto")]
    platform: apoc_apple_device::Platform,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, incurs::Args)]
struct DeviceIdArgs {
    /// Apple device or simulator identifier.
    device_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
struct DebugProxy {
    device_id: String,
    port: u16,
}

fn build_cli(app: App) -> Cli {
    Cli::create("apoc-apple-device")
        .description("Apple device and simulator attach provider for apoc")
        .version(env!("CARGO_PKG_VERSION"))
        .mcp(McpServeOptions {
            version: Some(env!("CARGO_PKG_VERSION").to_string()),
            instructions: Some(
                "Resolve Apple devices, simulators, installed apps, and DAP attach targets."
                    .to_string(),
            ),
            ..McpServeOptions::default()
        })
        .command(
            "devices",
            CommandDef::typed::<
                (),
                DeviceListOptions,
                (),
                Vec<apoc_apple_device::DeviceTarget>,
                _,
                _,
            >("devices", {
                let app = app.clone();
                move |context: TypedContext<(), DeviceListOptions, ()>| {
                    let app = app.clone();
                    async move {
                        match app.service.devices(context.options.platform) {
                            Ok(devices) => TypedResult::ok(devices),
                            Err(error) => provider_error(error),
                        }
                    }
                }
            })
            .description("List Apple devices and simulators.")
            .mcp(read_tool("devices"))
            .done(),
        )
        .command(
            "apps",
            CommandDef::typed::<DeviceIdArgs, (), (), Vec<apoc_apple_device::AppRecord>, _, _>(
                "apps",
                {
                    let app = app.clone();
                    move |context: TypedContext<DeviceIdArgs, (), ()>| {
                        let app = app.clone();
                        async move {
                            match app.service.apps(&context.args.device_id) {
                                Ok(apps) => TypedResult::ok(apps),
                                Err(error) => provider_error(error),
                            }
                        }
                    }
                },
            )
            .description("List installed apps on one physical Apple device.")
            .mcp(read_tool("apps"))
            .done(),
        )
        .command(
            "resolve",
            CommandDef::typed::<(), AttachRequest, (), apoc_apple_device::AttachResolution, _, _>(
                "resolve",
                {
                    let app = app.clone();
                    move |context: TypedContext<(), AttachRequest, ()>| {
                        let app = app.clone();
                        async move {
                            match app.service.resolve(context.options) {
                                Ok(resolution) => TypedResult::ok(resolution),
                                Err(error) => provider_error(error),
                            }
                        }
                    }
                },
            )
            .description("Resolve or launch an Apple app for DAP attachment.")
            .mcp(write_tool("resolve"))
            .destructive(true)
            .done(),
        )
        .command(
            "debug-proxy",
            CommandDef::typed::<DeviceIdArgs, (), (), DebugProxy, _, _>("debug-proxy", {
                let app = app.clone();
                move |context: TypedContext<DeviceIdArgs, (), ()>| {
                    let app = app.clone();
                    async move {
                        match app.service.debug_proxy(&context.args.device_id) {
                            Ok(port) => TypedResult::ok(DebugProxy {
                                device_id: context.args.device_id,
                                port,
                            }),
                            Err(error) => provider_error(error),
                        }
                    }
                }
            })
            .description("Discover the CoreDevice debugproxy port for one physical device.")
            .mcp(read_tool("debug_proxy"))
            .done(),
        )
}

fn read_tool(name: &str) -> McpCommandOptions {
    McpCommandOptions {
        name: Some(name.to_string()),
        annotations: Some(McpAnnotations {
            read_only_hint: Some(true),
            destructive_hint: Some(false),
            idempotent_hint: Some(true),
            open_world_hint: Some(true),
            ..McpAnnotations::default()
        }),
        ..McpCommandOptions::default()
    }
}

fn write_tool(name: &str) -> McpCommandOptions {
    McpCommandOptions {
        name: Some(name.to_string()),
        annotations: Some(McpAnnotations {
            read_only_hint: Some(false),
            destructive_hint: Some(true),
            idempotent_hint: Some(false),
            open_world_hint: Some(true),
            ..McpAnnotations::default()
        }),
        destructive: true,
        ..McpCommandOptions::default()
    }
}

fn provider_error<T>(error: ProviderError) -> TypedResult<T> {
    TypedResult::error(error.code, error.message)
}

#[tokio::main]
async fn main() {
    let app = App {
        service: Arc::new(AppleDeviceService::new(SystemRunner)),
    };
    if let Err(error) = build_cli(app).serve().await {
        eprintln!("Error: {error}");
        std::process::exit(1);
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::*;

    #[test]
    fn generated_catalog_exposes_typed_apple_device_operations() {
        let app = App {
            service: Arc::new(AppleDeviceService::new(SystemRunner)),
        };
        let definitions = build_cli(app)
            .tool_catalog()
            .definitions()
            .into_iter()
            .map(|definition| (definition.name.clone(), definition))
            .collect::<BTreeMap<_, _>>();

        for name in ["devices", "apps", "resolve", "debug_proxy"] {
            let definition = definitions
                .get(name)
                .unwrap_or_else(|| panic!("missing generated tool {name}"));
            assert!(
                definition
                    .input_schema
                    .as_object()
                    .is_some_and(|schema| !schema.is_empty()),
                "{name} has no generated input schema"
            );
            assert!(
                definition
                    .output_schema
                    .as_ref()
                    .is_some_and(|schema| schema
                        .as_object()
                        .is_some_and(|schema| !schema.is_empty())),
                "{name} has no generated output schema"
            );
            assert!(
                definition.annotations.is_some(),
                "{name} has no MCP annotations"
            );
        }

        assert_eq!(
            definitions["devices"].input_schema["properties"]["platform"]["default"],
            "auto"
        );
        assert!(
            definitions["apps"].input_schema["required"]
                .as_array()
                .unwrap()
                .contains(&serde_json::json!("device_id"))
        );
        assert!(
            definitions["resolve"].input_schema["required"]
                .as_array()
                .unwrap()
                .contains(&serde_json::json!("bundle_id"))
        );
        assert_eq!(
            definitions["resolve"]
                .annotations
                .as_ref()
                .unwrap()
                .destructive_hint,
            Some(true)
        );
        assert!(
            definitions["debug_proxy"].input_schema["required"]
                .as_array()
                .unwrap()
                .contains(&serde_json::json!("device_id"))
        );
    }
}