mcp-hub 0.2.1

Tools-only Model Context Protocol aggregation server
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
//! Mock upstream MCP server used by integration tests.

use std::{sync::Arc, time::Duration};

use anyhow::{Context, Result};
#[path = "../telemetry.rs"]
mod telemetry;

use rmcp::{
    ErrorData as McpError, ServerHandler, ServiceExt,
    model::{
        CallToolRequestParams, CallToolResult, ContentBlock, Implementation, ListToolsResult, Meta,
        PaginatedRequestParams, ProtocolVersion, Resource, ServerCapabilities, ServerInfo,
        TaskSupport, Tool, ToolAnnotations, ToolExecution,
    },
    service::{RequestContext, RoleServer},
    transport::stdio,
};
use serde_json::{Value, json};
use tokio::sync::Mutex;

/// Uses `mimalloc` as the global allocator when the default feature is enabled.
#[cfg(feature = "mimalloc")]
#[global_allocator]
static GLOBAL_ALLOCATOR: mimalloc::MiMalloc = mimalloc::MiMalloc;

/// Mock tool server with deterministic tool behavior for integration tests.
#[derive(Clone)]
struct MockUpstreamServer {
    server_name: String,
    list_tools_delay: Option<Duration>,
    protocol_version: ProtocolVersion,
    extra_star_tool_name: Option<String>,
    session_counter: Arc<Mutex<u64>>,
}

impl MockUpstreamServer {
    /// Builds the mock server from CLI args, environment variables, and defaults.
    fn from_env() -> Self {
        Self {
            server_name: configured_server_name(),
            list_tools_delay: configured_list_tools_delay(),
            protocol_version: configured_protocol_version(),
            extra_star_tool_name: configured_star_tool_name(),
            session_counter: Arc::new(Mutex::new(0)),
        }
    }

    /// Returns the static tool inventory exposed by the mock server.
    fn tools(&self) -> Vec<Tool> {
        let mut tools = vec![
            Tool::new(
                "echo",
                "Echo the provided message with the server name.",
                single_string_arg_schema("message", true),
            ),
            Tool::new(
                "duplicate",
                "Return a stable response used to test duplicate tool names.",
                empty_object_schema(),
            ),
            Tool::new(
                "session_counter",
                "Increment a session-local counter and return its new value.",
                empty_object_schema(),
            ),
            Tool::new(
                "read_snapshot",
                "Read a stable snapshot of mock state without mutating anything.",
                empty_object_schema(),
            )
            .with_title("Read Snapshot")
            .with_raw_output_schema(report_output_schema())
            .with_annotations(
                ToolAnnotations::with_title("Read Snapshot")
                    .read_only(true)
                    .destructive(false)
                    .idempotent(true)
                    .open_world(false),
            )
            .with_meta(tool_meta("read")),
            Tool::new(
                "delete_record",
                "Delete a record from the mock state.",
                single_string_arg_schema("record_id", true),
            )
            .with_title("Delete Record")
            .with_annotations(
                ToolAnnotations::with_title("Delete Record")
                    .read_only(false)
                    .destructive(true)
                    .idempotent(false)
                    .open_world(false),
            )
            .with_meta(tool_meta("destructive")),
            Tool::new(
                "publish_webhook",
                "Send an outbound webhook to an external destination.",
                single_string_arg_schema("url", true),
            )
            .with_title("Publish Webhook")
            .with_annotations(
                ToolAnnotations::with_title("Publish Webhook")
                    .read_only(false)
                    .destructive(false)
                    .idempotent(false)
                    .open_world(true),
            )
            .with_meta(tool_meta("external")),
            Tool::new(
                "structured_report",
                "Return structured content and metadata for protocol-level forwarding tests.",
                empty_object_schema(),
            )
            .with_title("Structured Report")
            .with_raw_output_schema(report_output_schema()),
            Tool::new(
                "resource_bundle",
                "Return mixed content including resource links and embedded resources.",
                empty_object_schema(),
            )
            .with_title("Resource Bundle")
            .with_meta(tool_meta("bundle")),
            Tool::new(
                "error_result",
                "Return a tool-level error result without turning it into a transport error.",
                empty_object_schema(),
            )
            .with_title("Error Result")
            .with_meta(tool_meta("error")),
            Tool::new(
                "task_only",
                "A task-required tool that the hub must filter from v1.",
                empty_object_schema(),
            )
            .with_execution(ToolExecution::new().with_task_support(TaskSupport::Required)),
        ];

        if let Some(tool_name) = &self.extra_star_tool_name {
            tools.push(Tool::new(
                tool_name.clone(),
                "A deliberately invalid tool name used to test startup rejection.",
                empty_object_schema(),
            ));
        }

        tools
    }
}

impl ServerHandler for MockUpstreamServer {
    /// Describes the mock server as a tools-only MCP peer for integration tests.
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::new(
                format!("mock-upstream-{}", self.server_name),
                env!("CARGO_PKG_VERSION"),
            ))
            .with_protocol_version(self.protocol_version.clone())
    }

    /// Returns the mock tool inventory used by integration coverage.
    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, McpError> {
        if let Some(delay) = self.list_tools_delay {
            tokio::time::sleep(delay).await;
        }

        Ok(ListToolsResult {
            tools: self.tools(),
            next_cursor: None,
            meta: None,
        })
    }

    /// Executes deterministic mock tool behavior for the requested tool name.
    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        match request.name.as_ref() {
            "echo" => {
                let message = request
                    .arguments
                    .as_ref()
                    .and_then(|arguments| arguments.get("message"))
                    .and_then(Value::as_str)
                    .unwrap_or_default();
                Ok(CallToolResult::success(vec![ContentBlock::text(format!(
                    "{}:{}",
                    self.server_name, message
                ))]))
            }
            "duplicate" => Ok(CallToolResult::success(vec![ContentBlock::text(format!(
                "duplicate:{}",
                self.server_name
            ))])),
            "session_counter" => {
                let mut counter = self.session_counter.lock().await;
                *counter += 1;
                Ok(CallToolResult::success(vec![ContentBlock::text(
                    counter.to_string(),
                )]))
            }
            "read_snapshot" => Ok(CallToolResult::structured(json!({
                "server": self.server_name,
                "kind": "read_snapshot",
                "readOnly": true
            }))
            .with_meta(Some(result_meta("read_snapshot")))),
            "delete_record" => {
                let record_id = string_argument(&request, "record_id");
                Ok(CallToolResult::success(vec![ContentBlock::text(format!(
                    "deleted:{}:{}",
                    self.server_name, record_id
                ))]))
            }
            "publish_webhook" => {
                let url = string_argument(&request, "url");
                Ok(CallToolResult::success(vec![ContentBlock::text(format!(
                    "published:{}:{}",
                    self.server_name, url
                ))]))
            }
            "structured_report" => Ok(CallToolResult::structured(json!({
                "server": self.server_name,
                "kind": "structured_report",
                "version": self.protocol_version.as_str(),
            }))
            .with_meta(Some(result_meta("structured_report")))),
            "resource_bundle" => {
                let mut resource_link = Resource::new(
                    format!("memory://{}/bundle.json", self.server_name),
                    format!("{} bundle", self.server_name),
                );
                resource_link.description =
                    Some("Structured bundle exported by the upstream".to_string());
                resource_link.mime_type = Some("application/json".to_string());
                resource_link.size = Some(128);

                Ok(CallToolResult::success(vec![
                    ContentBlock::text(format!("bundle:{}", self.server_name)),
                    ContentBlock::resource_link(resource_link),
                    ContentBlock::embedded_text(
                        format!("memory://{}/embedded.txt", self.server_name),
                        format!("embedded:{}", self.server_name),
                    ),
                    ContentBlock::image("ZmFrZS1pbWFnZS1kYXRh", "image/png"),
                ])
                .with_meta(Some(result_meta("resource_bundle"))))
            }
            "error_result" => Ok(CallToolResult::error(vec![ContentBlock::text(format!(
                "upstream-error:{}",
                self.server_name
            ))])
            .with_meta(Some(result_meta("error_result")))),
            "task_only" => Ok(CallToolResult::success(vec![ContentBlock::text(format!(
                "task-only:{}",
                self.server_name
            ))])),
            other => Err(McpError::invalid_params(
                if self.extra_star_tool_name.as_deref() == Some(other) {
                    format!("invalid-star-tool:{}:{}", self.server_name, other)
                } else {
                    format!("unknown mock tool '{other}'")
                },
                None,
            )),
        }
    }
}

/// Boots tracing, builds the Tokio runtime explicitly, and runs the mock upstream server.
fn main() -> Result<()> {
    let _tracing = telemetry::init_tracing("info");
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .context("failed to build tokio runtime for mock upstream server")?;

    runtime
        .block_on(run())
        .context("mock upstream server terminated with an error")
}

/// Runs the mock upstream MCP server over stdio for integration testing.
async fn run() -> Result<()> {
    let service = MockUpstreamServer::from_env()
        .serve(stdio())
        .await
        .context("failed to initialize mock upstream over stdio")?;
    service
        .waiting()
        .await
        .context("mock upstream service terminated unexpectedly")?;
    Ok(())
}

/// Parses the configured protocol version override for the mock upstream server.
fn configured_protocol_version() -> ProtocolVersion {
    std::env::var("MOCK_SERVER_PROTOCOL_VERSION")
        .map(|value| parse_protocol_version(&value))
        .unwrap_or_else(|_| ProtocolVersion::default())
}

/// Parses one optional tool-list delay used to simulate slow startup inventory responses.
fn configured_list_tools_delay() -> Option<Duration> {
    std::env::var("MOCK_SERVER_LIST_TOOLS_DELAY_MS")
        .ok()
        .and_then(|value| value.parse::<u64>().ok())
        .filter(|value| *value > 0)
        .map(Duration::from_millis)
}

/// Resolves one optional extra tool name used to test invalid literal `*` discovery.
fn configured_star_tool_name() -> Option<String> {
    std::env::var("MOCK_SERVER_STAR_TOOL_NAME")
        .ok()
        .filter(|value| !value.is_empty())
}

/// Resolves the configured server name from CLI args, environment, or the default name.
fn configured_server_name() -> String {
    configured_cli_value("--server-name")
        .or_else(|| std::env::var("MOCK_SERVER_NAME").ok())
        .unwrap_or_else(|| "mock".to_string())
}

/// Reads one optional `--flag value` pair from the current mock-server command line.
fn configured_cli_value(flag: &str) -> Option<String> {
    let mut args = std::env::args().skip(1);
    args.find(|argument| argument == flag)?;
    args.next()
}

/// Parses one protocol version string using `rmcp`'s own deserializer.
fn parse_protocol_version(value: &str) -> ProtocolVersion {
    serde_json::from_value(json!(value)).expect("mock protocol version must be valid JSON")
}

/// Extracts one string argument from a tool request, defaulting to the empty string.
fn string_argument(request: &CallToolRequestParams, name: &str) -> String {
    request
        .arguments
        .as_ref()
        .and_then(|arguments| arguments.get(name))
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string()
}

/// Builds an empty JSON object schema used by mock tools without arguments.
fn empty_object_schema() -> Arc<rmcp::model::JsonObject> {
    Arc::new(
        serde_json::from_value(json!({
            "type": "object",
            "properties": {},
            "additionalProperties": false
        }))
        .expect("mock schema must be valid"),
    )
}

/// Builds a simple JSON object schema with one named string property.
fn single_string_arg_schema(name: &str, required: bool) -> Arc<rmcp::model::JsonObject> {
    Arc::new(
        serde_json::from_value(json!({
            "type": "object",
            "properties": {
                name: {
                    "type": "string"
                }
            },
            "required": if required { vec![name] } else { Vec::<&str>::new() },
            "additionalProperties": false
        }))
        .expect("mock schema must be valid"),
    )
}

/// Builds a structured output schema used by metadata-preservation tests.
fn report_output_schema() -> Arc<rmcp::model::JsonObject> {
    Arc::new(
        serde_json::from_value(json!({
            "type": "object",
            "properties": {
                "server": { "type": "string" },
                "kind": { "type": "string" }
            },
            "required": ["server", "kind"],
            "additionalProperties": false
        }))
        .expect("mock output schema must be valid"),
    )
}

/// Builds tool-level metadata used by outward inventory preservation tests.
fn tool_meta(kind: &str) -> Meta {
    let mut meta = Meta::new();
    meta.insert("mockKind".to_string(), json!(kind));
    meta.insert("source".to_string(), json!("mock-upstream"));
    meta
}

/// Builds result-level metadata used by forwarded tool-result tests.
fn result_meta(kind: &str) -> Meta {
    let mut meta = Meta::new();
    meta.insert("resultKind".to_string(), json!(kind));
    meta.insert("emittedBy".to_string(), json!("mock-upstream"));
    meta
}