nekolas note

毎日書くことを目指しているけど全然達成できてないブログ

2.0 KB Raw
//! cc-ide-server: Zed の language server 兼 Claude Code MCP "ide" サーバ(T026/T028)。
//! 参照: contracts/zed-ide-bridge.md, plan.md
//!
//! Zed から `cc-ide-server --lsp` として起動される。stdio で LSP を話しつつ、
//! initialize 受信時に WebSocket(MCP "ide") サーバを起動して Claude の `/ide` を待つ。

use anyhow::Result;
use cc_ide_server::{ide_ws, lsp, notify::Notifier, state::SharedState};
use tokio::io::{stdin, stdout};
use tokio::sync::{mpsc, oneshot};

#[tokio::main]
async fn main() -> Result<()> {
    // ログは stderr へ(stdout は LSP 専用)。
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    let shared = SharedState::new();

    // LSP stdout writer(notify と lsp が共有)。
    let (out_tx, out_rx) = mpsc::unbounded_channel::<serde_json::Value>();
    let notifier = Notifier::new(out_tx.clone());

    // writer タスク。
    let writer = tokio::spawn(lsp::writer_task(stdout(), out_rx));

    // initialize を受け取ったら WS サーバを起動する。
    let (init_tx, init_rx) = oneshot::channel::<lsp::InitInfo>();
    {
        let shared = shared.clone();
        let notifier = notifier.clone();
        tokio::spawn(async move {
            if let Ok(info) = init_rx.await {
                if let Err(e) =
                    ide_ws::serve(shared, notifier.clone(), info.port_min, info.port_max).await
                {
                    notifier.connect_failed(&format!("IDE サーバ起動失敗: {e}"));
                    tracing::error!("ide_ws::serve 終了: {e}");
                }
            }
        });
    }

    // LSP メインループ(stdin を読む)。EOF で終了。
    let lsp_result = lsp::run(stdin(), out_tx, shared, init_tx).await;

    // stdin が閉じたら writer も畳む。
    writer.abort();
    lsp_result
}