laburnum 1.17.0

An LSP framework for building language servers and compilers, powered by an incremental query tree with content-addressed storage, task-based dataflow, and parallel queries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

//! MCP (Model Context Protocol) server for laburnum.
//!
//! Exposes a curated subset of LSP capabilities to AI agents as
//! [MCP](https://modelcontextprotocol.io) tools. Gated behind the `mcp`
//! Cargo feature. See ADR0010 for the design rationale and the
//! exclusion list (LSP methods that are deliberately not surfaced).
//!
//! # Process model
//!
//! Each implementing crate ships a CLI subcommand (e.g. `patina mcp`) that
//! spawns an `McpServer` and runs it on stdin/stdout. The MCP server is a
//! separate process from the language-server daemon — it connects to the
//! daemon as a regular IPC client (with the new
//! [`ClientKind::Mcp`](crate::connect::lsp::ClientKind) variant) and forwards
//! curated requests on the agent's behalf.
//!
//! ```text
//!   AI agent ──── MCP/stdio (NDJSON) ────► McpServer ──── LSP/IPC ────► laburnum daemon
//!                                          (this crate)                  (ClientKind::Mcp)
//! ```
//!
//! Notifications from the daemon (`publishDiagnostics`, `$/progress`,
//! `$/serverShutdown`, etc.) are not forwarded to MCP — MCP is
//! request/response with no push channel. Diagnostics are exposed via the
//! pull-mode `file_diagnostics` / `workspace_diagnostics` tools.
//!
//! # Quickstart
//!
//! ```ignore
//! use laburnum::{
//!   connect::mcp::McpServer,
//!   daemon::DaemonConfig,
//!   protocol::mcp::Implementation,
//! };
//!
//! # async fn run(workspace_id: String) -> Result<(), Box<dyn std::error::Error>> {
//! let server = McpServer::connect(
//!   DaemonConfig::new("patina", workspace_id),
//!   Implementation {
//!     name:    "patina-mcp".to_string(),
//!     version: env!("CARGO_PKG_VERSION").to_string(),
//!   },
//! )
//! .await?
//! .with_default_tools()
//! .build();
//!
//! server.run_stdio().await?;
//! # Ok(())
//! # }
//! ```
//!
//! [`McpServer::connect`] handles the full bring-up: IPC handshake (as
//! [`ClientKind::Mcp`](crate::connect::lsp::ClientKind::Mcp) — the daemon
//! skips notification broadcasts to MCP clients), LSP `initialize`, and
//! UTF-8 position-encoding negotiation.
//!
//! # Position encoding
//!
//! Per ADR0010 the MCP server requests UTF-8 from the daemon during
//! `initialize`, so the `character` field of `Position` in every tool's
//! input is a UTF-8 byte offset within the line (not the LSP default
//! UTF-16). If the daemon won't negotiate UTF-8, [`McpServer::connect`]
//! returns [`ConnectError::PositionEncoding`] — no silent fallback.
//!
//! # Built-in tool catalog
//!
//! [`McpServerBuilder::with_default_tools`] registers a language-agnostic
//! catalog wrapping LSP requests. See [`tools`] for the full list and the
//! comment block in `tools/mod.rs` for what's deliberately excluded and
//! why. Highlights:
//!
//! - `find_symbol`, `document_symbols`
//! - `goto_definition` / `goto_declaration` / `goto_type_definition` /
//!   `goto_implementation`
//! - `find_references`, `hover`
//! - `file_diagnostics`, `workspace_diagnostics`
//! - `call_hierarchy_incoming` / `call_hierarchy_outgoing`
//! - `type_hierarchy_supertypes` / `type_hierarchy_subtypes`
//! - `code_actions`
//! - `prepare_rename`, `rename` (returns the `WorkspaceEdit` JSON; the
//!   agent applies edits with its own file-write tools)
//!
//! # Adding language-specific tools
//!
//! Implement [`Tool`] on a zero-sized marker type. `Input` and `Output`
//! should be LSP types from [`crate::protocol::lsp`] wherever possible —
//! the framework deserializes/serializes them at the wire boundary so
//! tool bodies stay typed end-to-end.
//!
//! ```ignore
//! use laburnum::{
//!   connect::{
//!     lsp::{LspClient, request::WorkspaceSymbolRequest},
//!     mcp::{schema, Tool, ToolError},
//!   },
//!   protocol::lsp::{WorkspaceSymbolParams, WorkspaceSymbolResponse},
//! };
//!
//! pub enum FindCrateRoots {}
//!
//! impl Tool for FindCrateRoots {
//!   type Input  = WorkspaceSymbolParams;
//!   type Output = Option<WorkspaceSymbolResponse>;
//!
//!   const NAME: &'static str = "find_crate_roots";
//!   const DESCRIPTION: &'static str =
//!     "Find Cargo.toml files defining workspace crate roots.";
//!
//!   fn input_schema() -> serde_json::Value {
//!     serde_json::json!({
//!       "type": "object",
//!       "properties": { "query": { "type": "string" } },
//!       "required": ["query"]
//!     })
//!   }
//!
//!   async fn call(
//!     client: &LspClient,
//!     input: Self::Input,
//!   ) -> Result<Self::Output, ToolError> {
//!     Ok(client.send_request::<WorkspaceSymbolRequest>(input).await?)
//!   }
//! }
//!
//! # use laburnum::{connect::mcp::McpServer, daemon::DaemonConfig, protocol::mcp::Implementation};
//! # async fn build() -> Result<(), Box<dyn std::error::Error>> {
//! McpServer::connect(DaemonConfig::new("patina", "ws"), Implementation {
//!   name: "patina-mcp".into(), version: env!("CARGO_PKG_VERSION").into(),
//! })
//! .await?
//! .with_default_tools()
//! .tool::<FindCrateRoots>()
//! .build();
//! # Ok(()) }
//! ```
//!
//! [`crate::connect::mcp::schema`] provides composable JSON Schema fragments for
//! LSP primitives (`uri`, `position`, `range`, `text_document_position`,
//! `hierarchy_item`) — use them so your tool's schema stays in sync with
//! the LSP types it accepts.
//!
//! # Exposing language-specific commands
//!
//! For tools that wrap your language server's `workspace/executeCommand`
//! handlers, use [`CommandDescriptor`] instead of the [`Tool`] trait. Each
//! descriptor becomes a typed MCP tool named `execute_<command>` (with
//! `/`, `.`, `-`, and spaces sanitized to `_`):
//!
//! ```ignore
//! # use laburnum::{
//! #   connect::mcp::{McpServer, CommandDescriptor},
//! #   daemon::DaemonConfig,
//! #   protocol::mcp::Implementation,
//! # };
//! # async fn build() -> Result<(), Box<dyn std::error::Error>> {
//! McpServer::connect(DaemonConfig::new("patina", "ws"), Implementation {
//!   name: "patina-mcp".into(), version: env!("CARGO_PKG_VERSION").into(),
//! })
//! .await?
//! .with_default_tools()
//! .commands([
//!   CommandDescriptor {
//!     command: "patina.runTests".into(),
//!     description: "Run the test suite for the current package.".into(),
//!     input_schema: serde_json::json!({
//!       "type": "object",
//!       "properties": { "package": { "type": "string" } },
//!       "required": ["package"]
//!     }),
//!   },
//! ])
//! .build();
//! # Ok(()) }
//! ```
//!
//! If you never call `.commands(...)`, no `execute_*` tool appears in the
//! agent's tool list. The implementing crate owns the schema and the
//! safety judgement for each command it registers — the framework has no
//! way to validate whether a given command is safe to invoke from an
//! agent context.
//!
//! # Errors
//!
//! Two error channels per the MCP spec:
//!
//! - **Protocol errors** (unknown tool, malformed arguments) flow back as
//!   JSON-RPC errors on the wire. The dispatcher handles these.
//! - **Tool execution errors** (LSP timeout, deserialization failure,
//!   business-logic failure) flow back as
//!   `CallToolResult { is_error: true, content: [{ text: ... }] }`.
//!   Surface them from your `Tool::call` by returning
//!   `Err(ToolError::Other(...))` or letting the `?` operator convert an
//!   `LspClientError`.

pub mod schema;
pub mod tool;
pub mod tools;
pub mod transport;

pub use {
  crate::protocol::mcp::PROTOCOL_VERSION,
  tool::{
    Tool,
    ToolError,
    ToolRegistry,
  },
  tools::execute_command::CommandDescriptor,
};

use {
  crate::{
    connect::{
      ipc::IpcHandle,
      lsp::{
        ClientKind,
        DaemonConnection,
        LspClient,
        errors::LspClientError,
      },
    },
    daemon::DaemonConfig,
    protocol::{
      jsonrpc::{
        self,
        Error,
        ErrorCode,
        Id,
        Message,
        Response,
      },
      lsp::{
        ClientCapabilities,
        ClientInfo,
        GeneralClientCapabilities,
        InitializeParams,
        PositionEncodingKind,
      },
      mcp::{
        CallToolParams,
        CallToolResult,
        Implementation,
        InitializeResult,
        ListToolsResult,
        ServerCapabilities,
        ToolsCapability,
      },
    },
  },
  std::{
    collections::HashMap,
    io,
  },
};

/// Errors from [`McpServer::connect`].
#[derive(Debug)]
pub enum ConnectError {
  /// IPC transport failure (socket, handshake, etc.).
  Io(io::Error),
  /// LSP `initialize` request failed.
  Initialize(LspClientError),
  /// The daemon did not negotiate the position encoding required by ADR0010
  /// (the MCP server always requests `utf-8`). Starting fails fast — no
  /// silent fallback to UTF-16.
  PositionEncoding {
    want: PositionEncodingKind,
    got:  Option<PositionEncodingKind>,
  },
}

impl From<io::Error> for ConnectError {
  fn from(value: io::Error) -> Self {
    Self::Io(value)
  }
}

impl std::fmt::Display for ConnectError {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      | Self::Io(e) => write!(f, "failed to connect to laburnum daemon: {e}"),
      | Self::Initialize(e) => write!(f, "LSP initialize failed: {e}"),
      | Self::PositionEncoding { want, got } => write!(
        f,
        "daemon did not negotiate required position encoding {want:?} \
         (got {got:?})"
      ),
    }
  }
}

impl std::error::Error for ConnectError {}

/// MCP server bound to a single LSP connection.
///
/// One `McpServer` serves one MCP client at a time over stdio — matching
/// how agents spawn MCP servers as child processes.
pub struct McpServer {
  client:      LspClient,
  registry:    ToolRegistry,
  server_info: Implementation,
  /// Held to keep IPC I/O tasks alive for the lifetime of the server.
  /// `None` only for in-process test connections that don't have I/O
  /// tasks to keep alive.
  _ipc_handle: Option<IpcHandle>,
}

impl McpServer {
  /// Connect to a laburnum daemon and prepare an MCP server.
  ///
  /// Performs the IPC handshake as [`ClientKind::Mcp`] (so the daemon
  /// skips LSP notification broadcasts to this client), sends LSP
  /// `initialize` requesting [`PositionEncodingKind::UTF8`], and verifies
  /// the daemon agreed. Fails fast on encoding mismatch — no silent
  /// UTF-16 fallback (see ADR0010).
  ///
  /// `server_info.version` is used as both the IPC handshake version
  /// (compatibility check) and the LSP `client_info.version` (informational).
  pub async fn connect(
    daemon_config: DaemonConfig,
    server_info: Implementation,
  ) -> Result<McpServerBuilder, ConnectError> {
    let mut metadata = HashMap::new();
    metadata.insert("client_name".to_string(), server_info.name.clone());
    metadata.insert("client_version".to_string(), server_info.version.clone());

    let connection = DaemonConnection::connect_as(
      daemon_config,
      &server_info.version,
      ClientKind::Mcp,
      metadata,
    )
    .await?;

    let init_params = InitializeParams {
      capabilities: ClientCapabilities {
        general: Some(GeneralClientCapabilities {
          position_encodings: Some(vec![PositionEncodingKind::UTF8]),
          ..Default::default()
        }),
        ..Default::default()
      },
      client_info: Some(ClientInfo {
        name:    server_info.name.clone(),
        version: Some(server_info.version.clone()),
      }),
      ..Default::default()
    };

    let init_result = connection
      .client
      .start(init_params)
      .await
      .map_err(ConnectError::Initialize)?;

    let got = init_result.capabilities.position_encoding.clone();
    if got.as_ref() != Some(&PositionEncodingKind::UTF8) {
      return Err(ConnectError::PositionEncoding {
        want: PositionEncodingKind::UTF8,
        got,
      });
    }

    Ok(McpServerBuilder {
      client:      connection.client,
      registry:    ToolRegistry::new(),
      server_info,
      ipc_handle:  Some(connection.handle),
    })
  }

  /// Test-only: build a server directly from a prebuilt `LspClient`,
  /// skipping the daemon connection and LSP handshake.
  #[cfg(test)]
  #[doc(hidden)]
  pub(crate) fn from_client_for_test(client: LspClient) -> McpServerBuilder {
    McpServerBuilder {
      client,
      registry: ToolRegistry::new(),
      server_info: Implementation {
        name:    "laburnum-mcp-test".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
      },
      ipc_handle: None,
    }
  }

  /// Run the MCP server loop on stdin/stdout until the agent closes its
  /// end of the pipe.
  ///
  /// Requests are dispatched sequentially: the next message is read only
  /// after the current tool call resolves. This matches MCP's typical
  /// agent-side usage pattern (one tool call at a time) and avoids
  /// interleaved writes on stdout.
  pub async fn run_stdio(self) -> io::Result<()> {
    let mut stdin =
      smol::io::BufReader::new(smol::Unblock::new(std::io::stdin()));
    let mut stdout = smol::Unblock::new(std::io::stdout());
    self.run(&mut stdin, &mut stdout).await
  }

  /// Run against arbitrary async streams. Useful for tests with in-memory
  /// pipes.
  pub async fn run<R, W>(self, reader: &mut R, writer: &mut W) -> io::Result<()>
  where
    R: smol::io::AsyncBufReadExt + Unpin,
    W: smol::io::AsyncWriteExt + Unpin,
  {
    while let Some(msg) = transport::read_message(reader).await? {
      match msg {
        | Message::Request(req) => {
          let (method, id, params) = req.into_parts();
          let response = self.dispatch_request(&method, id, params).await;
          transport::write_message(writer, &Message::Response(response)).await?;
        },
        | Message::Notification(_) => {
          // initialized / cancelled accepted as no-ops in v1.
        },
        | Message::Response(_) => {
          // We don't issue requests to the agent.
        },
      }
    }
    Ok(())
  }

  #[doc(hidden)] // pub(crate) so tests can drive dispatch without the transport
  pub(crate) async fn dispatch_request(
    &self,
    method: &str,
    id: Id,
    params: Option<serde_json::Value>,
  ) -> Response {
    match method {
      | "initialize" => self.handle_initialize(id),
      | "tools/list" => self.handle_list_tools(id),
      | "tools/call" => self.handle_call_tool(id, params).await,
      | other => Response::from_error(
        id,
        Error {
          code:    ErrorCode::MethodNotFound,
          message: format!("unknown method: {other}").into(),
          data:    None,
        },
      ),
    }
  }

  fn handle_initialize(&self, id: Id) -> Response {
    let result = InitializeResult {
      protocol_version: PROTOCOL_VERSION.to_string(),
      capabilities:    ServerCapabilities {
        tools: Some(ToolsCapability { list_changed: false }),
      },
      server_info:     self.server_info.clone(),
    };
    Response::from_ok(id, json_or_internal_error(&result))
  }

  fn handle_list_tools(&self, id: Id) -> Response {
    let result = ListToolsResult {
      tools:       self.registry.descriptors(),
      next_cursor: None,
    };
    Response::from_ok(id, json_or_internal_error(&result))
  }

  async fn handle_call_tool(
    &self,
    id: Id,
    params: Option<serde_json::Value>,
  ) -> Response {
    let params: CallToolParams = match params {
      | Some(v) => match serde_json::from_value(v) {
        | Ok(p) => p,
        | Err(e) => return Response::from_error(id, invalid_params(e.to_string())),
      },
      | None => {
        return Response::from_error(
          id,
          invalid_params("tools/call requires a params object"),
        );
      },
    };

    let Some(tool) = self.registry.get(&params.name) else {
      return Response::from_error(
        id,
        Error {
          code:    ErrorCode::InvalidParams,
          message: format!("unknown tool: {}", params.name).into(),
          data:    None,
        },
      );
    };

    let result: CallToolResult = tool.call(&self.client, params.arguments).await;
    Response::from_ok(id, json_or_internal_error(&result))
  }
}

fn invalid_params(message: impl Into<String>) -> Error {
  Error {
    code:    ErrorCode::InvalidParams,
    message: message.into().into(),
    data:    None,
  }
}

fn json_or_internal_error<T: serde::Serialize>(value: &T) -> serde_json::Value {
  serde_json::to_value(value)
    .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }))
}

pub struct McpServerBuilder {
  client:      LspClient,
  registry:    ToolRegistry,
  server_info: Implementation,
  ipc_handle:  Option<IpcHandle>,
}

impl McpServerBuilder {
  /// Register the language-agnostic default tools (see
  /// [`tools::register_defaults`]).
  #[must_use]
  pub fn with_default_tools(mut self) -> Self {
    tools::register_defaults(&mut self.registry);
    self
  }

  /// Register a single custom tool by its zero-sized marker type.
  ///
  /// ```ignore
  /// builder.tool::<MyCustomTool>()
  /// ```
  #[must_use]
  pub fn tool<T: Tool>(mut self) -> Self {
    self.registry.register::<T>();
    self
  }

  /// Register implementer-supplied `workspace/executeCommand` wrappers.
  ///
  /// Each `CommandDescriptor` becomes its own typed MCP tool. If this
  /// method is never called, no `execute_*` tool appears in the catalog.
  #[must_use]
  pub fn commands(
    mut self,
    commands: impl IntoIterator<Item = CommandDescriptor>,
  ) -> Self {
    tools::execute_command::register_commands(&mut self.registry, commands);
    self
  }

  pub fn build(self) -> McpServer {
    McpServer {
      client:      self.client,
      registry:    self.registry,
      server_info: self.server_info,
      _ipc_handle: self.ipc_handle,
    }
  }
}

// Re-export the type so doc links resolve.
#[allow(unused_imports)]
use jsonrpc as _jsonrpc;

#[cfg(test)]
mod tests {
  use {
    super::*,
    crate::connect::ipc::Connection,
    serde::{
      Deserialize,
      Serialize,
    },
  };

  fn server_with_echo() -> McpServer {
    let (server_conn, _client_conn) = Connection::memory();
    McpServer::from_client_for_test(LspClient::new(server_conn))
      .tool::<EchoTool>()
      .build()
  }

  #[derive(Deserialize, Serialize)]
  struct EchoInput {
    message: String,
  }

  enum EchoTool {}
  impl Tool for EchoTool {
    type Input = EchoInput;
    type Output = EchoInput;
    const NAME: &'static str = "echo";
    const DESCRIPTION: &'static str = "Echoes its arguments back as text.";
    fn input_schema() -> serde_json::Value {
      serde_json::json!({
        "type": "object",
        "properties": { "message": { "type": "string" } },
        "required": ["message"]
      })
    }
    async fn call(
      _client: &LspClient,
      input: Self::Input,
    ) -> Result<Self::Output, ToolError> {
      Ok(input)
    }
  }

  #[test]
  fn initialize_declares_tools_capability() {
    smol::block_on(async {
      let server = server_with_echo();
      let resp = server.dispatch_request("initialize", Id::Number(1), None).await;
      let body = serde_json::to_value(&resp).unwrap();
      assert_eq!(body["id"], 1);
      let result = &body["result"];
      assert_eq!(result["protocolVersion"], PROTOCOL_VERSION);
      assert!(result["capabilities"]["tools"].is_object());
      assert!(result["serverInfo"]["name"].is_string());
    });
  }

  #[test]
  fn tools_list_returns_registered_tools_sorted() {
    smol::block_on(async {
      let server = server_with_echo();
      let resp = server.dispatch_request("tools/list", Id::Number(2), None).await;
      let body = serde_json::to_value(&resp).unwrap();
      let tools = body["result"]["tools"].as_array().unwrap();
      assert_eq!(tools.len(), 1);
      assert_eq!(tools[0]["name"], "echo");
      assert!(tools[0]["description"].is_string());
      assert!(tools[0]["inputSchema"].is_object());
    });
  }

  #[test]
  fn tools_call_dispatches_to_tool() {
    smol::block_on(async {
      let server = server_with_echo();
      let params = serde_json::json!({
        "name": "echo",
        "arguments": { "message": "hello" }
      });
      let resp = server
        .dispatch_request("tools/call", Id::Number(3), Some(params))
        .await;
      let body = serde_json::to_value(&resp).unwrap();
      let content = &body["result"]["content"][0];
      assert_eq!(content["type"], "text");
      assert!(content["text"].as_str().unwrap().contains("\"hello\""));
      assert_eq!(body["result"]["isError"], false);
    });
  }

  #[test]
  fn tools_call_unknown_tool_returns_invalid_params() {
    smol::block_on(async {
      let server = server_with_echo();
      let params = serde_json::json!({ "name": "missing", "arguments": {} });
      let resp = server
        .dispatch_request("tools/call", Id::Number(4), Some(params))
        .await;
      let body = serde_json::to_value(&resp).unwrap();
      assert_eq!(body["error"]["code"], -32602);
      assert!(body["error"]["message"].as_str().unwrap().contains("missing"));
    });
  }

  #[test]
  fn tools_call_invalid_args_returns_is_error() {
    // Using a real tool from the default set so we exercise the parse_args
    // path — args missing required "query" field should come back as a
    // tool-execution error (is_error: true), not a protocol error.
    smol::block_on(async {
      let (server_conn, _client_conn) = Connection::memory();
      let server = McpServer::from_client_for_test(LspClient::new(server_conn))
        .with_default_tools()
        .build();
      let params = serde_json::json!({
        "name": "find_symbol",
        "arguments": {}
      });
      let resp = server
        .dispatch_request("tools/call", Id::Number(6), Some(params))
        .await;
      let body = serde_json::to_value(&resp).unwrap();
      // ok response wrapping is_error: true result
      assert!(body["error"].is_null());
      assert_eq!(body["result"]["isError"], true);
      assert!(
        body["result"]["content"][0]["text"]
          .as_str()
          .unwrap()
          .contains("invalid arguments")
      );
    });
  }

  #[test]
  fn unknown_method_returns_method_not_found() {
    smol::block_on(async {
      let server = server_with_echo();
      let resp = server
        .dispatch_request("bogus/method", Id::Number(5), None)
        .await;
      let body = serde_json::to_value(&resp).unwrap();
      assert_eq!(body["error"]["code"], -32601);
    });
  }
}