nekolas note

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

8.2 KB Raw
//! 実ソケット越しの full-MCP E2E(Claude 役クライアント)。
//! 参照: contracts/zed-ide-bridge.md, quickstart.md シナリオ5
//!
//! 実 `ide_ws::serve`(ロックファイル + WS + auth + MCP + push)を起動し、
//! tokio-tungstenite で Claude のように接続して以下を検証する:
//!   - ロックファイル探索 → port/authToken 取得
//!   - auth ヘッダ付き WS 接続(不正トークンは拒否)
//!   - MCP initialize / tools/list(getDiagnostics 等の存在)
//!   - LSP 相当の選択更新 → selection_changed の push 受信(FR-024)
//!   - getCurrentSelection の pull(FR-026)
//!   - getDiagnostics は空(FR-022)

use cc_ide_server::notify::Notifier;
use cc_ide_server::state::{EditorContext, Position, Selection, SharedState};
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::Message;

const AUTH_HEADER: &str = "x-claude-code-ide-authorization";

async fn read_lockfile(dir: &std::path::Path) -> (u16, String) {
    for _ in 0..50 {
        if let Ok(rd) = std::fs::read_dir(dir) {
            for ent in rd.flatten() {
                let p = ent.path();
                if p.extension().and_then(|e| e.to_str()) == Some("lock") {
                    let txt = std::fs::read_to_string(&p).unwrap();
                    let v: Value = serde_json::from_str(&txt).unwrap();
                    let port: u16 = p.file_stem().unwrap().to_str().unwrap().parse().unwrap();
                    let token = v["authToken"].as_str().unwrap().to_string();
                    return (port, token);
                }
            }
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    panic!("lockfile が生成されませんでした");
}

async fn connect(
    port: u16,
    token: &str,
) -> tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>> {
    let url = format!("ws://127.0.0.1:{port}/");
    let mut req = url.into_client_request().unwrap();
    req.headers_mut()
        .insert(AUTH_HEADER, HeaderValue::from_str(token).unwrap());
    // Claude Code 同様にサブプロトコルを要求する。サーバがエコーしないと
    // tokio-tungstenite クライアントはハンドシェイクを失敗扱いにする(本修正の回帰防止)。
    req.headers_mut()
        .insert("sec-websocket-protocol", HeaderValue::from_static("mcp"));
    let (ws, resp) = tokio_tungstenite::connect_async(req)
        .await
        .expect("ws connect");
    // サーバがサブプロトコルをエコーしていること。
    assert_eq!(
        resp.headers()
            .get("sec-websocket-protocol")
            .and_then(|v| v.to_str().ok()),
        Some("mcp"),
        "サーバが Sec-WebSocket-Protocol をエコーしていない"
    );
    ws
}

/// メソッド/id 一致のメッセージを最大 N 件読むまで待つ(push と応答が交錯するため)。
async fn read_until<F: Fn(&Value) -> bool>(
    ws: &mut tokio_tungstenite::WebSocketStream<
        tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
    >,
    pred: F,
) -> Value {
    for _ in 0..50 {
        if let Ok(Some(Ok(Message::Text(t)))) =
            tokio::time::timeout(Duration::from_secs(2), ws.next()).await
        {
            if let Ok(v) = serde_json::from_str::<Value>(&t) {
                if pred(&v) {
                    return v;
                }
            }
        }
    }
    panic!("期待するメッセージを受信できませんでした");
}

#[tokio::test]
async fn full_mcp_pipeline_over_socket() {
    // ロックファイル隔離用の一時 HOME。
    let home = std::env::temp_dir().join(format!("cc-ide-e2e-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&home);
    std::fs::create_dir_all(&home).unwrap();
    std::env::set_var("HOME", &home);
    let ide_dir = home.join(".claude").join("ide");

    // 実サーバ起動。
    let state = SharedState::new();
    let (out_tx, mut out_rx) = mpsc::unbounded_channel::<Value>();
    // notifier(window/showMessage)出力は捨てる。
    tokio::spawn(async move { while out_rx.recv().await.is_some() {} });
    let notifier = Notifier::new(out_tx);
    {
        let s = state.clone();
        tokio::spawn(async move {
            let _ = cc_ide_server::ide_ws::serve(s, notifier, 21500, 21540).await;
        });
    }

    // ロックファイルから port/token を取得。
    let (port, token) = read_lockfile(&ide_dir).await;
    assert!((21500..=21540).contains(&port), "port {port} が範囲外");

    // --- 不正トークンは拒否される ---
    let bad = format!("ws://127.0.0.1:{port}/");
    let mut bad_req = bad.into_client_request().unwrap();
    bad_req
        .headers_mut()
        .insert(AUTH_HEADER, HeaderValue::from_static("wrong-token"));
    assert!(
        tokio_tungstenite::connect_async(bad_req).await.is_err(),
        "不正トークンが受理されてしまった"
    );

    // --- 正規トークンで接続 ---
    let mut ws = connect(port, &token).await;

    // MCP initialize。
    ws.send(Message::Text(
        json!({"jsonrpc":"2.0","id":1,"method":"initialize",
               "params":{"protocolVersion":"2025-03-26","capabilities":{}}})
        .to_string(),
    ))
    .await
    .unwrap();
    let init = read_until(&mut ws, |v| v["id"] == json!(1)).await;
    assert_eq!(init["result"]["serverInfo"]["name"], "cc-ide-server");
    assert_eq!(init["result"]["protocolVersion"], "2025-03-26");

    // tools/list。
    ws.send(Message::Text(
        json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}).to_string(),
    ))
    .await
    .unwrap();
    let tools = read_until(&mut ws, |v| v["id"] == json!(2)).await;
    let names: Vec<String> = tools["result"]["tools"]
        .as_array()
        .unwrap()
        .iter()
        .map(|t| t["name"].as_str().unwrap().to_string())
        .collect();
    for expected in [
        "getCurrentSelection",
        "getLatestSelection",
        "getOpenEditors",
        "getDiagnostics",
    ] {
        assert!(
            names.contains(&expected.to_string()),
            "tool {expected} 欠落"
        );
    }

    // --- LSP 相当の選択更新 → push(selection_changed)受信 ---
    state
        .update(EditorContext {
            file_path: Some("/Users/x/proj/main.rs".into()),
            file_url: Some("file:///Users/x/proj/main.rs".into()),
            text: "sel".to_string(),
            selection: Some(Selection {
                start: Position {
                    line: 3,
                    character: 2,
                },
                end: Position {
                    line: 5,
                    character: 8,
                },
                is_empty: false,
            }),
        })
        .await;
    let push = read_until(&mut ws, |v| v["method"] == json!("selection_changed")).await;
    assert_eq!(push["params"]["filePath"], "/Users/x/proj/main.rs");
    assert_eq!(push["params"]["selection"]["start"]["line"], 3);
    assert_eq!(push["params"]["selection"]["isEmpty"], false);

    // --- pull: getCurrentSelection ---
    ws.send(Message::Text(
        json!({"jsonrpc":"2.0","id":3,"method":"tools/call",
               "params":{"name":"getCurrentSelection","arguments":{}}})
        .to_string(),
    ))
    .await
    .unwrap();
    let pull = read_until(&mut ws, |v| v["id"] == json!(3)).await;
    let text = pull["result"]["content"][0]["text"].as_str().unwrap();
    let parsed: Value = serde_json::from_str(text).unwrap();
    assert_eq!(parsed["filePath"], "/Users/x/proj/main.rs");

    // --- getDiagnostics は空(スコープ外, FR-022) ---
    ws.send(Message::Text(
        json!({"jsonrpc":"2.0","id":4,"method":"tools/call",
               "params":{"name":"getDiagnostics","arguments":{}}})
        .to_string(),
    ))
    .await
    .unwrap();
    let diag = read_until(&mut ws, |v| v["id"] == json!(4)).await;
    let dtext = diag["result"]["content"][0]["text"].as_str().unwrap();
    assert_eq!(dtext, "[]");

    // 後始末。
    let _ = ws.close(None).await;
    let _ = std::fs::remove_dir_all(&home);
}