agent-block 0.25.0

Lua-first Agent Runtime built on AgentMesh
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
//! MCP echo harness — a reference server for exercising the rich MCP client.
//!
//! Provides tools / resources / prompts / logging / sampling so that every
//! capability path in the agent-block MCP bridge can be smoke-tested against
//! a real, independently-running server.
//!
//! # Usage
//!
//! ```sh
//! # stdio (default)
//! cargo run --example echo_mcp_server
//!
//! # HTTP on a fixed port
//! cargo run --example echo_mcp_server -- --transport http --port 8765
//!
//! # HTTP on an ephemeral port — prints ECHO_MCP_URL=http://127.0.0.1:<port>/mcp
//! cargo run --example echo_mcp_server -- --transport http --port 0
//!
//! # Enable periodic log notifications (5 × 1-second ticks after connect)
//! cargo run --example echo_mcp_server -- --transport http --port 0 --emit-logs
//!
//! # Ask the client to do a sampling round-trip immediately after connect
//! cargo run --example echo_mcp_server -- --transport http --port 0 --request-sampling
//! ```

use std::{
    future::Future,
    sync::{
        atomic::{AtomicU8, Ordering},
        Arc,
    },
};

use clap::{Parser, ValueEnum};
use rmcp::{
    model::{
        CallToolRequestParams, CallToolResult, Content, CreateMessageRequestParams,
        GetPromptRequestParams, GetPromptResult, ListPromptsResult, ListResourcesResult,
        ListToolsResult, LoggingLevel, LoggingMessageNotificationParam, PaginatedRequestParams,
        ProgressNotificationParam, ProgressToken, Prompt, PromptArgument, PromptMessage,
        PromptMessageRole, RawResource, ReadResourceRequestParams, ReadResourceResult,
        ResourceContents, SamplingMessage, ServerCapabilities, ServerInfo, SetLevelRequestParams,
        Tool,
    },
    service::{MaybeSendFuture, RequestContext},
    transport::streamable_http_server::{
        session::local::LocalSessionManager, StreamableHttpServerConfig, StreamableHttpService,
    },
    ErrorData as McpError, RoleServer, ServerHandler, ServiceExt,
};
use tokio_util::sync::CancellationToken;

// ── CLI ───────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, ValueEnum)]
enum Transport {
    Stdio,
    Http,
}

#[derive(Debug, Parser)]
#[command(name = "echo_mcp_server", about = "MCP echo harness for agent-block")]
struct Cli {
    /// Transport to use: stdio (default) or http.
    #[arg(long, default_value = "stdio")]
    transport: Transport,

    /// TCP port for HTTP mode. 0 means OS-assigned ephemeral port.
    #[arg(long, default_value = "8765")]
    port: u16,

    /// After a client connects, emit 5 LoggingMessageNotifications at 1-second
    /// intervals (level=info, logger="echo", data="tick N").
    #[arg(long)]
    emit_logs: bool,

    /// After a client connects, send one sampling/createMessage request to the
    /// client (prompt="say hi"). The response is logged; failures are ignored.
    #[arg(long)]
    request_sampling: bool,
}

// ── Server implementation ─────────────────────────────────────────────────────

/// Flags passed from the CLI into the server handler.
#[derive(Debug, Clone)]
struct Flags {
    emit_logs: bool,
    request_sampling: bool,
    /// Current log level as set by logging/setLevel (stored as u8 to allow
    /// atomic access without a Mutex).  Maps to `LoggingLevel` discriminants.
    log_level: Arc<AtomicU8>,
}

#[derive(Clone)]
struct EchoServer {
    flags: Flags,
}

impl EchoServer {
    fn new(flags: Flags) -> Self {
        Self { flags }
    }
}

impl ServerHandler for EchoServer {
    // rmcp v1.4: `enable_logging()` is deprecated by SEP-2577. Kept on
    // this example until the migration to the post-2577 logging API
    // lands (tracked separately).
    #[allow(deprecated)]
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .enable_prompts()
                .enable_logging()
                .build(),
        )
    }

    // ── tools/list ───────────────────────────────────────────────────────────

    fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _ctx: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<ListToolsResult, McpError>> + MaybeSendFuture + '_ {
        let tools = vec![
            Tool::new(
                "echo",
                "Return the input string unchanged",
                Arc::new(serde_json::json!({
                    "type": "object",
                    "properties": {
                        "msg": { "type": "string", "description": "Message to echo" }
                    },
                    "required": ["msg"]
                })
                .as_object()
                .cloned()
                .unwrap_or_default()),
            ),
            Tool::new(
                "slow_echo",
                "Echo with incremental progress notifications (100 ms per step)",
                Arc::new(serde_json::json!({
                    "type": "object",
                    "properties": {
                        "msg":   { "type": "string",  "description": "Message to echo" },
                        "steps": { "type": "integer", "description": "Number of progress steps (default 5)" }
                    },
                    "required": ["msg"]
                })
                .as_object()
                .cloned()
                .unwrap_or_default()),
            ),
        ];
        std::future::ready(Ok(ListToolsResult::with_all_items(tools)))
    }

    // ── tools/call ───────────────────────────────────────────────────────────

    // rmcp v1.4: `peer.create_message()` and `peer.notify_logging_message()`
    // are deprecated by SEP-2577. Kept on this example until the migration
    // to the post-2577 sampling/logging APIs lands (tracked separately).
    #[allow(deprecated)]
    async fn call_tool(
        &self,
        params: CallToolRequestParams,
        ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let args = params.arguments.clone().unwrap_or_default();

        match params.name.as_ref() {
            "echo" => {
                let msg = args
                    .get("msg")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                // If --request-sampling was given, attempt a sampling round-trip.
                if self.flags.request_sampling {
                    let peer = ctx.peer.clone();
                    tokio::spawn(async move {
                        let req = CreateMessageRequestParams::new(
                            vec![SamplingMessage::user_text("say hi")],
                            256,
                        );
                        match peer.create_message(req).await {
                            Ok(resp) => {
                                eprintln!("[echo-harness] sampling response model={}", resp.model);
                            }
                            Err(e) => {
                                eprintln!("[echo-harness] sampling request failed: {e}");
                            }
                        }
                    });
                }

                // If --emit-logs was given, spawn a background task that fires
                // 5 log notifications at 1-second intervals.
                if self.flags.emit_logs {
                    let peer = ctx.peer.clone();
                    tokio::spawn(async move {
                        for n in 1u8..=5 {
                            tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                            let _ = peer
                                .notify_logging_message(LoggingMessageNotificationParam {
                                    level: LoggingLevel::Info,
                                    logger: Some("echo".into()),
                                    data: serde_json::json!(format!("tick {n}")),
                                })
                                .await;
                        }
                    });
                }

                Ok(CallToolResult::success(vec![Content::text(msg)]))
            }

            "slow_echo" => {
                let msg = args
                    .get("msg")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let steps: u32 = args
                    .get("steps")
                    .and_then(|v| v.as_u64())
                    .map(|v| v as u32)
                    .unwrap_or(5)
                    .max(1);

                // Extract progress token from _meta if provided.
                // In rmcp 1.4.0, `_meta` is deserialized into `ctx.meta` (via
                // extensions), not `params.meta` which is always None after the
                // wire round-trip.
                let token_opt: Option<ProgressToken> = ctx.meta.get_progress_token();

                for step in 1..=steps {
                    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

                    if let Some(ref token) = token_opt {
                        let _ = ctx
                            .peer
                            .notify_progress(ProgressNotificationParam {
                                progress_token: ProgressToken(token.0.clone()),
                                progress: step as f64,
                                total: Some(steps as f64),
                                message: Some(format!("step {step}/{steps}")),
                            })
                            .await;
                    }
                }

                Ok(CallToolResult::success(vec![Content::text(msg)]))
            }

            other => Err(McpError::invalid_params(
                format!("unknown tool: {other}"),
                None,
            )),
        }
    }

    // ── resources/list ───────────────────────────────────────────────────────

    fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _ctx: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<ListResourcesResult, McpError>> + MaybeSendFuture + '_ {
        let resources = vec![
            rmcp::model::Resource::new(RawResource::new("text://hello", "hello"), None),
            rmcp::model::Resource::new(RawResource::new("text://note", "note"), None),
        ];
        std::future::ready(Ok(ListResourcesResult::with_all_items(resources)))
    }

    // ── resources/read ───────────────────────────────────────────────────────

    fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _ctx: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<ReadResourceResult, McpError>> + MaybeSendFuture + '_ {
        let uri = request.uri.clone();
        let text = match uri.as_str() {
            "text://hello" => "hello world".to_string(),
            "text://note" => "a note".to_string(),
            other => {
                return std::future::ready(Err(McpError::invalid_params(
                    format!("unknown resource uri: {other}"),
                    None,
                )));
            }
        };
        std::future::ready(Ok(ReadResourceResult::new(vec![ResourceContents::text(
            text, uri,
        )])))
    }

    // ── prompts/list ─────────────────────────────────────────────────────────

    fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParams>,
        _ctx: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<ListPromptsResult, McpError>> + MaybeSendFuture + '_ {
        let prompts = vec![Prompt::new(
            "greet",
            Some("Greeting prompt"),
            Some(vec![PromptArgument::new("name")
                .with_description("Name to greet")
                .with_required(true)]),
        )];
        std::future::ready(Ok(ListPromptsResult::with_all_items(prompts)))
    }

    // ── prompts/get ──────────────────────────────────────────────────────────

    fn get_prompt(
        &self,
        request: GetPromptRequestParams,
        _ctx: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<GetPromptResult, McpError>> + MaybeSendFuture + '_ {
        if request.name != "greet" {
            return std::future::ready(Err(McpError::invalid_params(
                format!("unknown prompt: {}", request.name),
                None,
            )));
        }

        let name = request
            .arguments
            .as_ref()
            .and_then(|a| a.get("name"))
            .and_then(|v| v.as_str())
            .unwrap_or("world")
            .to_string();

        let message = PromptMessage::new_text(PromptMessageRole::User, format!("hello, {name}"));
        std::future::ready(Ok(GetPromptResult::new(vec![message])))
    }

    // ── logging/setLevel ─────────────────────────────────────────────────────

    fn set_level(
        &self,
        params: SetLevelRequestParams,
        _ctx: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
        self.flags
            .log_level
            .store(params.level as u8, Ordering::Relaxed);
        std::future::ready(Ok(()))
    }
}

// ── entry point ───────────────────────────────────────────────────────────────

#[tokio::main]
async fn main() {
    let cli = Cli::parse();

    let flags = Flags {
        emit_logs: cli.emit_logs,
        request_sampling: cli.request_sampling,
        log_level: Arc::new(AtomicU8::new(LoggingLevel::Info as u8)),
    };

    match cli.transport {
        Transport::Stdio => run_stdio(flags).await,
        Transport::Http => run_http(flags, cli.port).await,
    }
}

async fn run_stdio(flags: Flags) {
    let server = EchoServer::new(flags);
    let transport = tokio::io::join(tokio::io::stdin(), tokio::io::stdout());
    match server.serve(transport).await {
        Ok(running) => {
            if let Err(e) = running.waiting().await {
                eprintln!("[echo-harness] server error: {e}");
                std::process::exit(1);
            }
        }
        Err(e) => {
            eprintln!("[echo-harness] failed to start stdio server: {e}");
            std::process::exit(1);
        }
    }
}

async fn run_http(flags: Flags, port: u16) {
    let ct = CancellationToken::new();

    let config = StreamableHttpServerConfig::default()
        .with_sse_keep_alive(None)
        .with_cancellation_token(ct.child_token());

    let flags_clone = flags.clone();
    let service: StreamableHttpService<EchoServer, LocalSessionManager> =
        StreamableHttpService::new(
            move || Ok(EchoServer::new(flags_clone.clone())),
            Default::default(),
            config,
        );

    let router = axum::Router::new().nest_service("/mcp", service);

    let addr = format!("127.0.0.1:{port}");
    let listener = match tokio::net::TcpListener::bind(&addr).await {
        Ok(l) => l,
        Err(e) => {
            eprintln!("[echo-harness] failed to bind {addr}: {e}");
            std::process::exit(1);
        }
    };

    let bound_addr = match listener.local_addr() {
        Ok(a) => a,
        Err(e) => {
            eprintln!("[echo-harness] local_addr failed: {e}");
            std::process::exit(1);
        }
    };

    // Print the URL so that callers (scripts / tests) can pick it up.
    println!("ECHO_MCP_URL=http://{bound_addr}/mcp");

    let ct_shutdown = ct.clone();
    tokio::spawn(async move {
        if let Err(e) = axum::serve(listener, router)
            .with_graceful_shutdown(async move { ct_shutdown.cancelled_owned().await })
            .await
        {
            eprintln!("[echo-harness] http server error: {e}");
        }
    });

    // Wait for SIGINT / SIGTERM.
    wait_for_signal().await;
    ct.cancel();
}

#[cfg(unix)]
async fn wait_for_signal() {
    use tokio::signal::unix::{signal, SignalKind};
    let mut sigint = signal(SignalKind::interrupt()).expect("SIGINT handler");
    let mut sigterm = signal(SignalKind::terminate()).expect("SIGTERM handler");
    tokio::select! {
        _ = sigint.recv() => {},
        _ = sigterm.recv() => {},
    }
}

#[cfg(not(unix))]
async fn wait_for_signal() {
    let _ = tokio::signal::ctrl_c().await;
}