objectiveai-mcp 2.2.12

MCP (Model Context Protocol) server for ObjectiveAI
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
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;

use futures::FutureExt;
use futures::StreamExt;
use objectiveai_sdk::agent::ClientObjectiveaiMcpEntry;
use objectiveai_sdk::cli::Error as CliError;
use objectiveai_sdk::cli::ErrorType as CliErrorType;
use objectiveai_sdk::cli::Level as CliLevel;
use objectiveai_sdk::cli::command::AgentArguments;
use objectiveai_sdk::cli::command::CommandExecutor;
use objectiveai_sdk::cli::command::CommandRequest;
use objectiveai_sdk::cli::command::CommandResponse;
use objectiveai_sdk::cli::command::McpResponseItem;
use objectiveai_sdk::cli::command::Request;
use objectiveai_sdk::cli::command::ResponseItem;
use objectiveai_sdk::cli::command::RequestBase;
use objectiveai_sdk::cli::command::Transform;
use objectiveai_sdk::cli::command::parse_request;
use objectiveai_sdk::cli::command::plugins;
use objectiveai_sdk::cli::command::tools;
use rmcp::{
    ServerHandler,
    handler::server::router::tool::{ToolRoute, ToolRouter},
    handler::server::tool::{Extension, parse_json_object, schema_for_type},
    handler::server::wrapper::Parameters,
    model::{
        CallToolResult, Implementation, ProtocolVersion, ServerCapabilities, ServerInfo, Tool,
    },
    schemars, tool, tool_router,
};

use crate::agent_args_registry::AgentArgumentsRegistry;
use crate::format::format_items;

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ObjectiveAiRequest {
    #[schemars(
        description = "The command arguments to pass to the ObjectiveAI CLI (e.g. [\"agents\", \"list\"] or [\"functions\", \"executions\", \"create\", \"--help\"])"
    )]
    pub command: Vec<String>,
    #[schemars(
        description = "Timeout for the whole command, humantime (e.g. \"30s\", \"5m\", \"1h30m\")."
    )]
    pub timeout: String,
    #[schemars(description = "Output token budget for the response.")]
    pub max_tokens: u64,
    #[schemars(
        description = "Optional jq filter applied to each output line. Return null to discard the output line. Ignored when `python` is also set."
    )]
    pub jq: Option<String>,
    #[schemars(
        description = "Optional Python transform applied to each output line. The item arrives as the global `input`; print the transformed result as valid JSON, or return null to discard the output line. Overrides `jq` when both are set."
    )]
    pub python: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct PluginRequest {
    #[schemars(description = "Args forwarded to the plugin binary's argv.")]
    pub args: Vec<String>,
    #[schemars(
        description = "Timeout for the whole command, humantime (e.g. \"30s\", \"5m\", \"1h30m\")."
    )]
    pub timeout: String,
    #[schemars(description = "Output token budget for the response.")]
    pub max_tokens: u64,
    #[schemars(
        description = "Optional jq filter applied to each output line. Return null to discard the output line. Ignored when `python` is also set."
    )]
    pub jq: Option<String>,
    #[schemars(
        description = "Optional Python transform applied to each output line. The item arrives as the global `input`; print the transformed result as valid JSON, or return null to discard the output line. Overrides `jq` when both are set."
    )]
    pub python: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ToolRequest {
    #[schemars(description = "Args appended verbatim to the tool's exec command.")]
    pub args: Vec<String>,
    #[schemars(
        description = "Timeout for the whole command, humantime (e.g. \"30s\", \"5m\", \"1h30m\")."
    )]
    pub timeout: String,
    #[schemars(description = "Output token budget for the response.")]
    pub max_tokens: u64,
    #[schemars(
        description = "Optional jq filter applied to each output line. Return null to discard the output line. Ignored when `python` is also set."
    )]
    pub jq: Option<String>,
    #[schemars(
        description = "Optional Python transform applied to each output line. The item arrives as the global `input`; print the transformed result as valid JSON, or return null to discard the output line. Overrides `jq` when both are set."
    )]
    pub python: Option<String>,
}

/// Validate the shared `timeout` / `max_tokens` tool arguments. Parses
/// the humantime `timeout` to whole seconds (erroring on a bad string
/// or a sub-second-rounds-to-zero value) and rejects a zero
/// `max_tokens`. Returns `(timeout_seconds, max_tokens)`.
fn parse_caps(timeout: &str, max_tokens: u64) -> Result<(u64, u64), String> {
    let secs = humantime::parse_duration(timeout)
        .map_err(|e| format!("invalid timeout {timeout:?}: {e}"))?
        .as_secs();
    if secs == 0 {
        return Err("timeout must be >= 1s".to_string());
    }
    if max_tokens == 0 {
        return Err("max_tokens must be >= 1".to_string());
    }
    Ok((secs, max_tokens))
}

/// The active output transform from the tool args — python overrides
/// jq, matching `RequestBase::transform`.
fn build_transform(jq: Option<String>, python: Option<String>) -> Option<Transform> {
    if let Some(code) = python {
        Some(Transform::Python(code))
    } else {
        jq.map(Transform::Jq)
    }
}

#[derive(Debug)]
pub struct ObjectiveAiMcpCli<E> {
    pub tool_router: ToolRouter<Self>,
    pub executor: Arc<E>,
    /// Per-rmcp-session bag of [`AgentArguments`] captured from the
    /// six `X-OBJECTIVEAI-*` request headers at `initialize` time.
    /// Tool dispatchers look up the inbound `Mcp-Session-Id` against
    /// this registry to recover the caller's identity — request
    /// headers on non-initialize calls are intentionally ignored.
    pub registry: Arc<AgentArgumentsRegistry>,
    /// Tool-name → manifest triple for every CLI tool registered as
    /// a dynamic route. Used by the hand-written `list_tools`
    /// handler to classify each routed tool by origin and apply the
    /// per-session `X-OBJECTIVEAI-MCP-TOOLS` filter.
    pub tools_by_tool_name: HashMap<String, ClientObjectiveaiMcpEntry>,
    /// Same as `tools_by_tool_name`, but for CLI plugins. A
    /// tool-name collision between a plugin and a CLI tool ends up
    /// classified as a *tool*: the existing `with_plugins_and_tools`
    /// loop registers plugins first then tools, so
    /// `tool_router.add_route` last-writer-wins makes the live
    /// route a tool. The hand-written `list_tools` mirrors this by
    /// checking `tools_by_tool_name` first.
    pub plugins_by_tool_name: HashMap<String, ClientObjectiveaiMcpEntry>,
}

impl<E> Clone for ObjectiveAiMcpCli<E> {
    fn clone(&self) -> Self {
        Self {
            tool_router: self.tool_router.clone(),
            executor: self.executor.clone(),
            registry: self.registry.clone(),
            tools_by_tool_name: self.tools_by_tool_name.clone(),
            plugins_by_tool_name: self.plugins_by_tool_name.clone(),
        }
    }
}

#[tool_router]
impl<E> ObjectiveAiMcpCli<E>
where
    E: CommandExecutor + Send + Sync + 'static,
    E::Error: std::fmt::Display + Send + 'static,
{
    /// Build a handler with one dynamic tool per discovered CLI plugin
    /// and CLI tool, plus the static `ObjectiveAI` catch-all. Plugins
    /// and tools are listed once at server startup (see `run::setup`);
    /// this constructor is not re-invoked when either is added later,
    /// so hot reload is intentionally out of scope.
    ///
    /// Name collisions: if a CLI plugin and a CLI tool happen to share
    /// a name (or with `ObjectiveAI`), the plugin registers first and
    /// the tool's `add_route` overwrites it (last-writer-wins) — but
    /// `ObjectiveAI` itself is always skipped on both sides so the
    /// built-in catch-all is never shadowed.
    pub fn with_plugins_and_tools(
        executor: Arc<E>,
        plugins_list: Vec<plugins::list::ResponseItem>,
        tools_list: Vec<tools::list::ResponseItem>,
        registry: Arc<AgentArgumentsRegistry>,
    ) -> Self {
        let mut tool_router = Self::tool_router();
        let mut plugins_by_tool_name: HashMap<String, ClientObjectiveaiMcpEntry> =
            HashMap::new();
        let mut tools_by_tool_name: HashMap<String, ClientObjectiveaiMcpEntry> =
            HashMap::new();
        for plugin in plugins_list {
            if plugin.name == "ObjectiveAI" {
                continue;
            }
            plugins_by_tool_name.insert(
                plugin.tool_name(),
                ClientObjectiveaiMcpEntry {
                    owner: plugin.owner.clone(),
                    name: plugin.name.clone(),
                    version: plugin.version.clone(),
                },
            );
            let plugin_owner = plugin.owner.clone();
            let plugin_name = plugin.name.clone();
            let plugin_version = plugin.version.clone();
            let executor_for_route = executor.clone();
            let tool = Tool::new(
                Cow::Owned(plugin.tool_name()),
                Cow::Owned(plugin.description.clone()),
                schema_for_type::<PluginRequest>(),
            );
            let registry_for_route = registry.clone();
            tool_router.add_route(ToolRoute::new_dyn(tool, move |ctx| {
                let executor = executor_for_route.clone();
                let plugin_owner = plugin_owner.clone();
                let plugin_name = plugin_name.clone();
                let plugin_version = plugin_version.clone();
                let registry = registry_for_route.clone();
                let session_id = session_id_from_extensions(&ctx.request_context.extensions);
                async move {
                    let arguments = ctx.arguments.unwrap_or_default();
                    let req: PluginRequest = parse_json_object(arguments)?;
                    let (timeout_seconds, max_tokens) =
                        match parse_caps(&req.timeout, req.max_tokens) {
                            Ok(v) => v,
                            Err(msg) => {
                                let item = synthetic_error(msg).into_mcp();
                                return Ok(CallToolResult::success(format_items(vec![item])));
                            }
                        };
                    let transform = build_transform(req.jq, req.python);
                    let request = plugins::run::Request {
                        path_type: plugins::run::Path::PluginsRun,
                        owner: plugin_owner,
                        name: plugin_name,
                        version: plugin_version,
                        args: req.args,
                        base: RequestBase {
                            jq: None,
                            python: None,
                            timeout_seconds: Some(timeout_seconds),
                            max_tokens: Some(max_tokens),
                        },
                    };
                    let state = match session_id {
                        Some(sid) => registry.get(&sid.into()).await,
                        None => None,
                    };
                    let blocks = dispatch_plugins_run(
                        &*executor,
                        request,
                        transform,
                        state.as_deref().map(|s| &s.args),
                    )
                    .await;
                    Ok(CallToolResult::success(blocks))
                }
                .boxed()
            }));
        }
        for cli_tool in tools_list {
            if cli_tool.name == "ObjectiveAI" {
                continue;
            }
            tools_by_tool_name.insert(
                cli_tool.tool_name(),
                ClientObjectiveaiMcpEntry {
                    owner: cli_tool.owner.clone(),
                    name: cli_tool.name.clone(),
                    version: cli_tool.version.clone(),
                },
            );
            let tool_owner = cli_tool.owner.clone();
            let tool_name = cli_tool.name.clone();
            let tool_version = cli_tool.version.clone();
            let executor_for_route = executor.clone();
            let tool = Tool::new(
                Cow::Owned(cli_tool.tool_name()),
                Cow::Owned(cli_tool.description.clone()),
                schema_for_type::<ToolRequest>(),
            );
            let registry_for_route = registry.clone();
            tool_router.add_route(ToolRoute::new_dyn(tool, move |ctx| {
                let executor = executor_for_route.clone();
                let tool_owner = tool_owner.clone();
                let tool_name = tool_name.clone();
                let tool_version = tool_version.clone();
                let registry = registry_for_route.clone();
                let session_id = session_id_from_extensions(&ctx.request_context.extensions);
                async move {
                    let arguments = ctx.arguments.unwrap_or_default();
                    let req: ToolRequest = parse_json_object(arguments)?;
                    let (timeout_seconds, max_tokens) =
                        match parse_caps(&req.timeout, req.max_tokens) {
                            Ok(v) => v,
                            Err(msg) => {
                                let item = synthetic_error(msg).into_mcp();
                                return Ok(CallToolResult::success(format_items(vec![item])));
                            }
                        };
                    let transform = build_transform(req.jq, req.python);
                    let request = tools::run::Request {
                        path_type: tools::run::Path::ToolsRun,
                        owner: tool_owner,
                        name: tool_name,
                        version: tool_version,
                        args: req.args,
                        base: RequestBase {
                            jq: None,
                            python: None,
                            timeout_seconds: Some(timeout_seconds),
                            max_tokens: Some(max_tokens),
                        },
                    };
                    let state = match session_id {
                        Some(sid) => registry.get(&sid.into()).await,
                        None => None,
                    };
                    let blocks = dispatch_tools_run(
                        &*executor,
                        request,
                        transform,
                        state.as_deref().map(|s| &s.args),
                    )
                    .await;
                    Ok(CallToolResult::success(blocks))
                }
                .boxed()
            }));
        }
        Self {
            tool_router,
            executor,
            registry,
            tools_by_tool_name,
            plugins_by_tool_name,
        }
    }

    #[tool(name = "ObjectiveAI", description = "Run an ObjectiveAI command.")]
    async fn objectiveai(
        &self,
        Parameters(req): Parameters<ObjectiveAiRequest>,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        // Validate the caps, parse the command, then inject the caps
        // directly onto the parsed request's base — no argv round-trip.
        // The transform is passed to dispatch (not into the base) — its
        // leaf `execute_transform` sets it on the base itself.
        let (timeout_seconds, max_tokens) = match parse_caps(&req.timeout, req.max_tokens) {
            Ok(v) => v,
            Err(msg) => {
                let item = synthetic_error(msg).into_mcp();
                return Ok(CallToolResult::success(format_items(vec![item])));
            }
        };
        let mut request = match parse_request(&req.command) {
            Ok(r) => r,
            Err(e) => {
                let item = synthetic_error(e.to_string()).into_mcp();
                return Ok(CallToolResult::success(format_items(vec![item])));
            }
        };
        if let Some(base) = request.request_base_mut() {
            base.timeout_seconds = Some(timeout_seconds);
            base.max_tokens = Some(max_tokens);
        }
        let transform = build_transform(req.jq, req.python);
        let session_id = session_id_from_headers(&parts.headers);
        let state = match session_id {
            Some(sid) => self.registry.get(&sid.into()).await,
            None => None,
        };
        let blocks = dispatch_root(
            &*self.executor,
            request,
            transform,
            state.as_deref().map(|s| &s.args),
        )
        .await;
        Ok(CallToolResult::success(blocks))
    }
}

/// Pull `Mcp-Session-Id` out of an inbound HTTP request's headers
/// (case-insensitive, trimmed, empty → `None`).
fn session_id_from_headers(headers: &http::HeaderMap) -> Option<String> {
    headers
        .get("mcp-session-id")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// Same as [`session_id_from_headers`] but reads through the
/// `http::request::Parts` injected into rmcp's request-context
/// extensions. Used by the dynamic plugin/tool routes whose
/// closures take a [`rmcp::handler::server::tool::ToolCallContext`]
/// rather than an [`rmcp::handler::server::tool::Extension`]
/// extractor.
fn session_id_from_extensions(extensions: &rmcp::model::Extensions) -> Option<String> {
    extensions
        .get::<http::request::Parts>()
        .and_then(|p| session_id_from_headers(&p.headers))
}

async fn dispatch_root<E>(
    executor: &E,
    request: Request,
    transform: Option<Transform>,
    agent_arguments: Option<&AgentArguments>,
) -> Vec<rmcp::model::Content>
where
    E: CommandExecutor,
    E::Error: std::fmt::Display,
{
    match transform {
        None => {
            let stream =
                match objectiveai_sdk::cli::command::execute(executor, request, agent_arguments)
                    .await
                {
                    Ok(s) => s,
                    Err(e) => return format_items(vec![convert::<ResponseItem, _>(Err(e))]),
                };
            let items: Vec<McpResponseItem> =
                stream.map(convert::<ResponseItem, _>).collect().await;
            format_items(items)
        }
        Some(t) => {
            let stream = match objectiveai_sdk::cli::command::execute_transform(
                executor,
                request,
                t,
                agent_arguments,
            )
            .await
            {
                Ok(s) => s,
                Err(e) => return format_items(vec![convert_value(Err(e))]),
            };
            let items: Vec<McpResponseItem> = stream.map(convert_value).collect().await;
            format_items(items)
        }
    }
}

async fn dispatch_plugins_run<E>(
    executor: &E,
    request: plugins::run::Request,
    transform: Option<Transform>,
    agent_arguments: Option<&AgentArguments>,
) -> Vec<rmcp::model::Content>
where
    E: CommandExecutor,
    E::Error: std::fmt::Display,
{
    match transform {
        None => {
            let stream = match plugins::run::execute(executor, request, agent_arguments).await {
                Ok(s) => s,
                Err(e) => {
                    return format_items(vec![convert::<plugins::run::ResponseItem, _>(Err(e))]);
                }
            };
            let items: Vec<McpResponseItem> =
                stream.map(convert::<plugins::run::ResponseItem, _>).collect().await;
            format_items(items)
        }
        Some(t) => {
            let stream =
                match plugins::run::execute_transform(executor, request, t, agent_arguments).await {
                    Ok(s) => s,
                    Err(e) => return format_items(vec![convert_value(Err(e))]),
                };
            let items: Vec<McpResponseItem> = stream.map(convert_value).collect().await;
            format_items(items)
        }
    }
}

async fn dispatch_tools_run<E>(
    executor: &E,
    request: tools::run::Request,
    transform: Option<Transform>,
    agent_arguments: Option<&AgentArguments>,
) -> Vec<rmcp::model::Content>
where
    E: CommandExecutor,
    E::Error: std::fmt::Display,
{
    match transform {
        None => {
            let stream = match tools::run::execute(executor, request, agent_arguments).await {
                Ok(s) => s,
                Err(e) => {
                    return format_items(vec![convert::<tools::run::ResponseItem, _>(Err(e))]);
                }
            };
            let items: Vec<McpResponseItem> =
                stream.map(convert::<tools::run::ResponseItem, _>).collect().await;
            format_items(items)
        }
        Some(t) => {
            let stream =
                match tools::run::execute_transform(executor, request, t, agent_arguments).await {
                    Ok(s) => s,
                    Err(e) => return format_items(vec![convert_value(Err(e))]),
                };
            let items: Vec<McpResponseItem> = stream.map(convert_value).collect().await;
            format_items(items)
        }
    }
}

/// Collapse a `Result<T, ExecErr>` (the executor's per-item shape)
/// into an `McpResponseItem`. The executor's error gets formatted
/// via `Display` into a synthetic `cli::Error` so it renders through
/// the same `Result<T, cli::Error>: CommandResponse` path.
fn convert<T: CommandResponse, ExecErr: std::fmt::Display>(
    r: Result<T, ExecErr>,
) -> McpResponseItem {
    let result: Result<T, CliError> = r.map_err(|e| synthetic_error(format!("{e}")));
    result.into_mcp()
}

/// Like [`convert`], but for the raw `serde_json::Value` items an
/// `execute_transform` stream yields (the transform replaced the typed
/// shape). An `Ok` value rides through as JSONL; an executor error
/// becomes a synthetic `cli::Error`.
fn convert_value<ExecErr: std::fmt::Display>(
    r: Result<serde_json::Value, ExecErr>,
) -> McpResponseItem {
    match r {
        Ok(value) => McpResponseItem::JSONL(value),
        Err(e) => synthetic_error(format!("{e}")).into_mcp(),
    }
}

/// Build a `cli::Error` envelope from a free-form message. Used at the
/// pre-dispatch failure sites (clap parse errors, `TryFrom<Command>`
/// errors) and as the wrapper for non-`Cli` `binary::Error` variants.
fn synthetic_error(message: impl Into<String>) -> CliError {
    CliError {
        r#type: CliErrorType::Error,
        level: Some(CliLevel::Error),
        fatal: Some(true),
        message: serde_json::Value::String(message.into()),
    }
}

// Hand-written `ServerHandler` impl, replacing `#[tool_handler]`.
// `call_tool` and `get_tool` are byte-identical copies of what the
// macro emits (see `rmcp-macros::tool_handler`). `list_tools` is the
// custom bit: it filters the macro-default's `self.tool_router
// .list_all()` by the per-session `ClientObjectiveaiMcpSessionFilter`
// stamped by `header_session_manager::extract_mcp_filter`.
//
// Classification order in `list_tools`:
//   1. `ObjectiveAI` ⇒ gated on `filter.root`.
//   2. Tool name in `tools_by_tool_name` ⇒ filtered by
//      `filter.tools` (None ⇒ allow; Some ⇒ membership check).
//   3. Tool name in `plugins_by_tool_name` ⇒ same with
//      `filter.plugins`.
//   4. Anything else ⇒ allow (defensive; the existing route loop
//      registers nothing outside those three categories).
//
// No filter recorded for the session (no header parser ran, e.g.
// GET-only flow) ⇒ behave as `root=true, tools=None, plugins=None`
// — every tool advertised. Mirrors the user-spelled "absent ⇒
// default" semantics for each field.
impl<E> ServerHandler for ObjectiveAiMcpCli<E>
where
    E: CommandExecutor + Send + Sync + 'static,
    E::Error: std::fmt::Display + Send + 'static,
{
    fn get_info(&self) -> ServerInfo {
        // rmcp 1.7 marks `ServerInfo`/`Implementation` `#[non_exhaustive]`,
        // so build via `Default` + explicit field assignment.
        let mut server_info = Implementation::default();
        server_info.name = "oai".into();
        server_info.version = env!("CARGO_PKG_VERSION").into();
        let mut info = ServerInfo::default();
        info.protocol_version = ProtocolVersion::V_2025_06_18;
        info.capabilities = ServerCapabilities::builder().enable_tools().build();
        info.server_info = server_info;
        info.instructions = None;
        info
    }

    async fn call_tool(
        &self,
        request: rmcp::model::CallToolRequestParams,
        context: rmcp::service::RequestContext<rmcp::RoleServer>,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
        self.tool_router.call(tcc).await
    }

    async fn list_tools(
        &self,
        _request: Option<rmcp::model::PaginatedRequestParams>,
        context: rmcp::service::RequestContext<rmcp::RoleServer>,
    ) -> Result<rmcp::model::ListToolsResult, rmcp::ErrorData> {
        let session_id = session_id_from_extensions(&context.extensions);
        let state = match session_id {
            Some(sid) => self.registry.get(&sid.into()).await,
            None => None,
        };
        let root = state.as_deref().map(|s| s.mcp_root).unwrap_or(true);
        let tool_filter = state.as_deref().and_then(|s| s.mcp_tools.as_deref());
        let plugin_filter = state.as_deref().and_then(|s| s.mcp_plugins.as_deref());

        let tools = self
            .tool_router
            .list_all()
            .into_iter()
            .filter(|t| {
                if t.name.as_ref() == "ObjectiveAI" {
                    return root;
                }
                if let Some(entry) = self.tools_by_tool_name.get(t.name.as_ref()) {
                    return tool_filter.map_or(true, |f| f.contains(entry));
                }
                if let Some(entry) = self.plugins_by_tool_name.get(t.name.as_ref()) {
                    return plugin_filter.map_or(true, |f| f.contains(entry));
                }
                true
            })
            .collect();

        Ok(rmcp::model::ListToolsResult {
            tools,
            meta: None,
            next_cursor: None,
        })
    }

    fn get_tool(&self, name: &str) -> Option<rmcp::model::Tool> {
        self.tool_router.get(name).cloned()
    }
}