ferrik-core 0.0.4

Core runtime, triple-response engine, AI discovery, and testing framework for Ferrik
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
//! Built-in Model Context Protocol (MCP) server for Ferrik applications.
//!
//! Exposes `.ai` GET endpoints as MCP Resources (`ferrik://<resource>`) and mutation
//! controller actions as MCP Tools using `schemars`-generated JSON Schemas.
//! Supports both local `stdio` transport (`ferrik mcp serve`) and remote `/mcp` HTTP/SSE.

use axum::body::Body;
use axum::http::{header, HeaderMap, Method, Request, StatusCode};
use axum::response::IntoResponse;
use axum::routing::get;
use axum::{Json, Router};
use http_body_util::BodyExt;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::io::{BufRead, Write};
use std::sync::Arc;
use tower::ServiceExt;

use crate::auth::{extract_raw_api_key, hash_agent_key, AgentKeyStore, AgentPrincipal};
use crate::discovery::AgentManifest;

/// MCP protocol version advertised during `initialize`.
pub const MCP_PROTOCOL_VERSION: &str = "2024-11-05";

/// JSON-RPC 2.0 request envelope.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JsonRpcRequest {
    pub jsonrpc: String,
    #[serde(default)]
    pub id: Option<Value>,
    pub method: String,
    #[serde(default)]
    pub params: Value,
}

/// JSON-RPC 2.0 error object.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct JsonRpcError {
    pub code: i32,
    pub message: String,
}

/// JSON-RPC 2.0 response envelope.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JsonRpcResponse {
    pub jsonrpc: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcError>,
}

impl JsonRpcResponse {
    pub fn ok(id: Option<Value>, result: Value) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id,
            result: Some(result),
            error: None,
        }
    }

    pub fn err(id: Option<Value>, code: i32, message: impl Into<String>) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id: Some(id.unwrap_or(Value::Null)),
            result: None,
            error: Some(JsonRpcError {
                code,
                message: message.into(),
            }),
        }
    }
}

/// MCP Resource descriptor auto-mapped from a `.ai` `GET` route.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct McpResource {
    pub uri: String,
    pub name: String,
    pub description: String,
    #[serde(rename = "mimeType")]
    pub mime_type: String,
    #[serde(skip_serializing)]
    pub route_path: String,
}

/// MCP Tool descriptor auto-mapped from a mutation `ActionAffordance`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct McpTool {
    pub name: String,
    pub description: String,
    #[serde(rename = "inputSchema")]
    pub input_schema: Value,
    #[serde(skip_serializing)]
    pub method: String,
    #[serde(skip_serializing)]
    pub route_path: String,
}

type ToolHandler = Arc<dyn Fn(Value) -> Result<Value, String> + Send + Sync>;
type ResourceHandler = Arc<dyn Fn(&str) -> Result<String, String> + Send + Sync>;

/// Native MCP server built from a Ferrik [`AgentManifest`].
#[derive(Clone)]
pub struct McpServer {
    pub server_name: String,
    pub server_version: String,
    pub resources: Vec<McpResource>,
    pub tools: Vec<McpTool>,
    tool_handlers: HashMap<String, ToolHandler>,
    resource_handlers: HashMap<String, ResourceHandler>,
    key_store: Option<Arc<dyn AgentKeyStore>>,
    require_auth: bool,
}

impl McpServer {
    /// Builds an [`McpServer`] automatically mapping `.ai` GET endpoints to MCP Resources
    /// (`ferrik://<name>`) and manifest actions to MCP Tools.
    pub fn from_manifest(manifest: &AgentManifest) -> Self {
        let resources = manifest
            .endpoints
            .iter()
            .filter(|e| e.method.eq_ignore_ascii_case("GET"))
            .map(|e| McpResource {
                uri: format!("ferrik://{}", e.name),
                name: e.name.clone(),
                description: e.description.clone(),
                mime_type: if e.path.ends_with(".json") {
                    "application/json".to_string()
                } else {
                    "text/markdown".to_string()
                },
                route_path: e.path.clone(),
            })
            .collect();

        let tools = manifest
            .actions
            .iter()
            .map(|a| McpTool {
                name: a.name.clone(),
                description: a.description.clone(),
                input_schema: a.input_schema.clone().unwrap_or_else(|| {
                    json!({
                        "type": "object",
                        "properties": {},
                        "additionalProperties": false
                    })
                }),
                method: a.method.clone(),
                route_path: a.path.clone(),
            })
            .collect();

        Self {
            server_name: manifest.app_name.clone(),
            server_version: manifest.version.clone(),
            resources,
            tools,
            tool_handlers: HashMap::new(),
            resource_handlers: HashMap::new(),
            key_store: None,
            require_auth: false,
        }
    }

    /// Configures an [`AgentKeyStore`] and enforces Agent API key authentication on `/mcp`.
    pub fn with_key_store(mut self, store: Arc<dyn AgentKeyStore>) -> Self {
        self.key_store = Some(store);
        self.require_auth = true;
        self
    }

    /// Controls whether `/mcp` requires a valid Agent API key.
    pub fn with_auth_required(mut self, required: bool) -> Self {
        self.require_auth = required;
        self
    }

    /// Registers a custom synchronous handler for an MCP tool call.
    pub fn with_tool_handler<F>(mut self, tool_name: impl Into<String>, handler: F) -> Self
    where
        F: Fn(Value) -> Result<Value, String> + Send + Sync + 'static,
    {
        self.tool_handlers
            .insert(tool_name.into(), Arc::new(handler));
        self
    }

    /// Registers a custom synchronous handler for an MCP resource URI (`ferrik://...`).
    pub fn with_resource_handler<F>(mut self, uri: impl Into<String>, handler: F) -> Self
    where
        F: Fn(&str) -> Result<String, String> + Send + Sync + 'static,
    {
        self.resource_handlers.insert(uri.into(), Arc::new(handler));
        self
    }

    /// Handles a single JSON-RPC 2.0 MCP request.
    pub fn handle_request(&self, req: JsonRpcRequest) -> JsonRpcResponse {
        match req.method.as_str() {
            "initialize" => JsonRpcResponse::ok(
                req.id,
                json!({
                    "protocolVersion": MCP_PROTOCOL_VERSION,
                    "capabilities": {
                        "resources": { "listChanged": false },
                        "tools": { "listChanged": false }
                    },
                    "serverInfo": {
                        "name": self.server_name,
                        "version": self.server_version
                    }
                }),
            ),
            "ping" => JsonRpcResponse::ok(req.id, json!({})),
            "resources/list" => JsonRpcResponse::ok(
                req.id,
                json!({ "resources": self.resources }),
            ),
            "resources/read" => self.handle_resource_read(req.id, &req.params),
            "tools/list" => JsonRpcResponse::ok(req.id, json!({ "tools": self.tools })),
            "tools/call" => self.handle_tool_call(req.id, &req.params),
            other => JsonRpcResponse::err(req.id, -32601, format!("Method not found: {}", other)),
        }
    }

    fn handle_resource_read(&self, id: Option<Value>, params: &Value) -> JsonRpcResponse {
        let Some(uri) = params.get("uri").and_then(|v| v.as_str()) else {
            return JsonRpcResponse::err(id, -32602, "Missing required parameter 'uri'");
        };
        let Some(resource) = self.resources.iter().find(|r| r.uri == uri) else {
            return JsonRpcResponse::err(id, -32002, format!("Resource not found: {}", uri));
        };

        if let Some(handler) = self.resource_handlers.get(uri) {
            return match handler(uri) {
                Ok(text) => JsonRpcResponse::ok(
                    id,
                    json!({
                        "contents": [{
                            "uri": resource.uri,
                            "mimeType": resource.mime_type,
                            "text": text
                        }]
                    }),
                ),
                Err(err) => JsonRpcResponse::err(id, -32000, err),
            };
        }

        JsonRpcResponse::err(
            id,
            -32002,
            format!(
                "No handler or HTTP router registered for MCP resource '{}'",
                resource.uri
            ),
        )
    }

    fn handle_tool_call(&self, id: Option<Value>, params: &Value) -> JsonRpcResponse {
        let Some(name) = params.get("name").and_then(|v| v.as_str()) else {
            return JsonRpcResponse::err(id, -32602, "Missing required parameter 'name'");
        };
        let arguments = params
            .get("arguments")
            .cloned()
            .unwrap_or_else(|| json!({}));

        let Some(tool) = self.tools.iter().find(|t| t.name == name) else {
            return JsonRpcResponse::err(id, -32602, format!("Unknown MCP tool: {}", name));
        };

        if let Some(handler) = self.tool_handlers.get(name) {
            return match handler(arguments) {
                Ok(val) => JsonRpcResponse::ok(
                    id,
                    json!({
                        "content": [{
                            "type": "text",
                            "text": serde_json::to_string_pretty(&val).unwrap_or_default()
                        }],
                        "isError": false
                    }),
                ),
                Err(err) => JsonRpcResponse::ok(
                    id,
                    json!({
                        "content": [{ "type": "text", "text": err }],
                        "isError": true
                    }),
                ),
            };
        }

        JsonRpcResponse::err(
            id,
            -32601,
            format!(
                "No handler or HTTP router registered for MCP tool '{}'",
                tool.name
            ),
        )
    }

    async fn authenticate(&self, headers: &HeaderMap) -> Result<Option<AgentPrincipal>, JsonRpcError> {
        if !self.require_auth && self.key_store.is_none() {
            return Ok(None);
        }
        let Some(raw_key) = extract_raw_api_key(headers) else {
            return Err(JsonRpcError {
                code: -32001,
                message: "Unauthorized: valid Agent API key required".to_string(),
            });
        };
        let Some(store) = &self.key_store else {
            return Err(JsonRpcError {
                code: -32001,
                message: "Unauthorized: AgentKeyStore is not configured on MCP server".to_string(),
            });
        };
        let key_hash = hash_agent_key(&raw_key);
        match store.resolve_by_hash(&key_hash).await {
            Ok(Some(principal)) => Ok(Some(principal)),
            Ok(None) => Err(JsonRpcError {
                code: -32001,
                message: "Unauthorized: invalid or revoked Agent API key".to_string(),
            }),
            Err(err) => Err(JsonRpcError {
                code: -32001,
                message: format!("Unauthorized: {}", err.public_message()),
            }),
        }
    }

    /// Handles a JSON-RPC 2.0 MCP request asynchronously, enforcing auth/scopes when configured
    /// and optionally proxying `tools/call` and `resources/read` to `app_router`.
    pub async fn handle_http_request(
        &self,
        req: JsonRpcRequest,
        headers: &HeaderMap,
        app_router: Option<Router>,
    ) -> JsonRpcResponse {
        let principal = match self.authenticate(headers).await {
            Ok(p) => p,
            Err(err) => return JsonRpcResponse::err(req.id, err.code, err.message),
        };

        match req.method.as_str() {
            "tools/call" => {
                let Some(name) = req.params.get("name").and_then(|v| v.as_str()) else {
                    return JsonRpcResponse::err(req.id, -32602, "Missing required parameter 'name'");
                };
                let Some(tool) = self.tools.iter().find(|t| t.name == name) else {
                    return JsonRpcResponse::err(
                        req.id,
                        -32602,
                        format!("Unknown MCP tool: {}", name),
                    );
                };
                if let Some(agent) = &principal {
                    let resource_scope = route_resource_scope(&tool.route_path, "write");
                    let allowed = agent.has_scope(&tool.name)
                        || resource_scope
                            .as_deref()
                            .is_some_and(|s| agent.has_scope(s));
                    if !allowed {
                        return JsonRpcResponse::err(
                            req.id,
                            -32001,
                            format!(
                                "Forbidden: agent '{}' lacks scope for tool '{}'",
                                agent.name, tool.name
                            ),
                        );
                    }
                }
                if self.tool_handlers.contains_key(name) {
                    return self.handle_tool_call(req.id, &req.params);
                }
                let Some(router) = app_router else {
                    return self.handle_tool_call(req.id, &req.params);
                };
                let arguments = req
                    .params
                    .get("arguments")
                    .cloned()
                    .unwrap_or_else(|| json!({}));
                proxy_tool_call(req.id, tool, arguments, headers, router).await
            }
            "resources/read" => {
                let Some(uri) = req.params.get("uri").and_then(|v| v.as_str()) else {
                    return JsonRpcResponse::err(req.id, -32602, "Missing required parameter 'uri'");
                };
                let Some(resource) = self.resources.iter().find(|r| r.uri == uri) else {
                    return JsonRpcResponse::err(
                        req.id,
                        -32002,
                        format!("Resource not found: {}", uri),
                    );
                };
                if let Some(agent) = &principal {
                    let resource_scope = route_resource_scope(&resource.route_path, "read");
                    let allowed = agent.has_scope(&resource.name)
                        || resource_scope
                            .as_deref()
                            .is_some_and(|s| agent.has_scope(s));
                    if !allowed {
                        return JsonRpcResponse::err(
                            req.id,
                            -32001,
                            format!(
                                "Forbidden: agent '{}' lacks scope for resource '{}'",
                                agent.name, resource.uri
                            ),
                        );
                    }
                }
                if self.resource_handlers.contains_key(uri) {
                    return self.handle_resource_read(req.id, &req.params);
                }
                let Some(router) = app_router else {
                    return self.handle_resource_read(req.id, &req.params);
                };
                proxy_resource_read(req.id, resource, headers, router).await
            }
            _ => self.handle_request(req),
        }
    }

    /// Processes a single JSON-RPC line and returns the serialized JSON response line.
    pub fn handle_json_line(&self, line: &str) -> Option<String> {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            return None;
        }
        let resp = match serde_json::from_str::<JsonRpcRequest>(trimmed) {
            Ok(req) => {
                // Notifications have no `id` and expect no reply per JSON-RPC 2.0
                if req.id.is_none() && req.method.starts_with("notifications/") {
                    return None;
                }
                self.handle_request(req)
            }
            Err(err) => JsonRpcResponse::err(None, -32700, format!("Parse error: {}", err)),
        };
        serde_json::to_string(&resp).ok()
    }

    /// Serves JSON-RPC 2.0 MCP requests over any buffered reader/writer (e.g. `stdin`/`stdout`).
    pub fn serve_io<R: BufRead, W: Write>(&self, reader: R, mut writer: W) -> std::io::Result<()> {
        for line in reader.lines() {
            let line = line?;
            if let Some(out) = self.handle_json_line(&line) {
                writeln!(writer, "{}", out)?;
                writer.flush()?;
            }
        }
        Ok(())
    }
}

fn route_resource_scope(route_path: &str, action: &str) -> Option<String> {
    let trimmed = route_path.trim_start_matches('/');
    let seg = trimmed.split('/').next()?;
    let seg = seg
        .strip_suffix(".ai")
        .or_else(|| seg.strip_suffix(".json"))
        .or_else(|| seg.strip_suffix(".html"))
        .unwrap_or(seg);
    if seg.is_empty() || seg == "ai" {
        return None;
    }
    Some(format!("{}:{}", seg, action))
}

fn substitute_path_params(route_path: &str, arguments: &mut Value) -> Result<String, String> {
    let mut resolved = route_path.to_string();
    let mut start = 0;
    while let Some(open) = resolved[start..].find('{') {
        let abs_open = start + open;
        let Some(close) = resolved[abs_open..].find('}') else {
            break;
        };
        let abs_close = abs_open + close;
        let param_name = resolved[abs_open + 1..abs_close].to_string();
        let val = arguments
            .as_object_mut()
            .and_then(|map| map.remove(&param_name))
            .ok_or_else(|| format!("Missing required path parameter '{}'", param_name))?;
        let val_str = match val {
            Value::String(s) => s,
            Value::Number(n) => n.to_string(),
            Value::Bool(b) => b.to_string(),
            other => other.to_string(),
        };
        resolved.replace_range(abs_open..=abs_close, &val_str);
        start = abs_open + val_str.len();
    }
    Ok(resolved)
}

async fn proxy_tool_call(
    id: Option<Value>,
    tool: &McpTool,
    mut arguments: Value,
    incoming_headers: &HeaderMap,
    router: Router,
) -> JsonRpcResponse {
    let path = match substitute_path_params(&tool.route_path, &mut arguments) {
        Ok(p) => p,
        Err(err) => return JsonRpcResponse::err(id, -32602, err),
    };
    let method = match Method::from_bytes(tool.method.as_bytes()) {
        Ok(m) => m,
        Err(_) => {
            return JsonRpcResponse::err(
                id,
                -32603,
                format!("Invalid HTTP method '{}'", tool.method),
            )
        }
    };

    let mut builder = Request::builder()
        .method(method.clone())
        .uri(&path)
        .header(header::ACCEPT, "application/json");
    if let Some(auth) = incoming_headers.get(header::AUTHORIZATION) {
        builder = builder.header(header::AUTHORIZATION, auth);
    }
    if let Some(key) = incoming_headers.get("x-agent-key") {
        builder = builder.header("x-agent-key", key);
    }

    let body = if matches!(method, Method::POST | Method::PUT | Method::PATCH) {
        builder = builder.header(header::CONTENT_TYPE, "application/json");
        let bytes = serde_json::to_vec(&arguments).unwrap_or_default();
        Body::from(bytes)
    } else {
        Body::empty()
    };

    let req = match builder.body(body) {
        Ok(r) => r,
        Err(err) => {
            return JsonRpcResponse::err(id, -32603, format!("Failed to build request: {}", err))
        }
    };

    let resp = match router.oneshot(req).await {
        Ok(r) => r,
        Err(err) => {
            return JsonRpcResponse::err(id, -32603, format!("Failed to dispatch tool: {}", err))
        }
    };
    let status = resp.status();
    let bytes = resp
        .into_body()
        .collect()
        .await
        .map(|c| c.to_bytes())
        .unwrap_or_default();
    let text = String::from_utf8_lossy(&bytes).to_string();

    JsonRpcResponse::ok(
        id,
        json!({
            "content": [{
                "type": "text",
                "text": text
            }],
            "isError": !status.is_success()
        }),
    )
}

async fn proxy_resource_read(
    id: Option<Value>,
    resource: &McpResource,
    incoming_headers: &HeaderMap,
    router: Router,
) -> JsonRpcResponse {
    let mut builder = Request::builder()
        .method(Method::GET)
        .uri(&resource.route_path)
        .header(header::ACCEPT, &resource.mime_type);
    if let Some(auth) = incoming_headers.get(header::AUTHORIZATION) {
        builder = builder.header(header::AUTHORIZATION, auth);
    }
    if let Some(key) = incoming_headers.get("x-agent-key") {
        builder = builder.header("x-agent-key", key);
    }
    let req = match builder.body(Body::empty()) {
        Ok(r) => r,
        Err(err) => {
            return JsonRpcResponse::err(id, -32603, format!("Failed to build request: {}", err))
        }
    };
    let resp = match router.oneshot(req).await {
        Ok(r) => r,
        Err(err) => {
            return JsonRpcResponse::err(id, -32603, format!("Failed to read resource: {}", err))
        }
    };
    let status = resp.status();
    let bytes = resp
        .into_body()
        .collect()
        .await
        .map(|c| c.to_bytes())
        .unwrap_or_default();
    let text = String::from_utf8_lossy(&bytes).to_string();
    if !status.is_success() {
        return JsonRpcResponse::err(
            id,
            -32002,
            format!("Resource request failed with HTTP {}: {}", status.as_u16(), text),
        );
    }
    JsonRpcResponse::ok(
        id,
        json!({
            "contents": [{
                "uri": resource.uri,
                "mimeType": resource.mime_type,
                "text": text
            }]
        }),
    )
}

/// Mounts the `/mcp` HTTP/SSE endpoint on an Axum [`Router`] with live route proxying.
///
/// Tool calls and resource reads without custom handlers are proxied directly to `app_router`.
pub fn mount_mcp(app_router: Router, server: McpServer) -> Router {
    let post_server = server.clone();
    let sse_server = server;
    let proxy_router = app_router.clone();

    let mcp = Router::new().route(
        "/mcp",
        get(move |headers: HeaderMap| {
            let srv = sse_server.clone();
            async move {
                if let Err(err) = srv.authenticate(&headers).await {
                    return (
                        StatusCode::UNAUTHORIZED,
                        Json(JsonRpcResponse::err(None, err.code, err.message)),
                    )
                        .into_response();
                }
                let info = json!({
                    "endpoint": "/mcp",
                    "protocolVersion": MCP_PROTOCOL_VERSION,
                    "server": srv.server_name,
                    "version": srv.server_version
                });
                let body = format!("event: endpoint\ndata: {}\n\n", info);
                (
                    [(header::CONTENT_TYPE, "text/event-stream; charset=utf-8")],
                    body,
                )
                    .into_response()
            }
        })
        .post(move |headers: HeaderMap, Json(req): Json<JsonRpcRequest>| {
            let srv = post_server.clone();
            let router = proxy_router.clone();
            async move { Json(srv.handle_http_request(req, &headers, Some(router)).await) }
        }),
    );

    app_router.merge(mcp)
}

/// Mounts the `/mcp` HTTP/SSE endpoint on an Axum [`Router`] (standalone, without live route proxying).
///
/// - `POST /mcp`: Streamable HTTP JSON-RPC 2.0 endpoint
/// - `GET /mcp`: SSE endpoint advertising the MCP server info and endpoint
pub fn mcp_router<S>(server: McpServer) -> Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    let post_server = server.clone();
    let sse_server = server;

    Router::new().route(
        "/mcp",
        get(move |headers: HeaderMap| {
            let srv = sse_server.clone();
            async move {
                if let Err(err) = srv.authenticate(&headers).await {
                    return (
                        StatusCode::UNAUTHORIZED,
                        Json(JsonRpcResponse::err(None, err.code, err.message)),
                    )
                        .into_response();
                }
                let info = json!({
                    "endpoint": "/mcp",
                    "protocolVersion": MCP_PROTOCOL_VERSION,
                    "server": srv.server_name,
                    "version": srv.server_version
                });
                let body = format!("event: endpoint\ndata: {}\n\n", info);
                (
                    [(header::CONTENT_TYPE, "text/event-stream; charset=utf-8")],
                    body,
                )
                    .into_response()
            }
        })
        .post(move |headers: HeaderMap, Json(req): Json<JsonRpcRequest>| {
            let srv = post_server.clone();
            async move { Json(srv.handle_http_request(req, &headers, None).await) }
        }),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::discovery::AgentEndpoint;
    use crate::response::ActionAffordance;
    use crate::testing::TestApp;
    use schemars::JsonSchema;
    use std::io::Cursor;

    #[derive(Serialize, JsonSchema)]
    struct CreatePostInput {
        title: String,
    }

    fn sample_server() -> McpServer {
        let manifest = AgentManifest::new("blog_app", "0.1.0")
            .with_endpoint(AgentEndpoint::new(
                "posts",
                "GET",
                "/posts.ai",
                "List all posts",
            ))
            .with_action(ActionAffordance::with_schema::<CreatePostInput>(
                "posts_create",
                "POST",
                "/posts",
                "Create a new post",
            ));
        McpServer::from_manifest(&manifest)
            .with_resource_handler("ferrik://posts", |_| Ok("# Posts\n\n- Hello".to_string()))
            .with_tool_handler("posts_create", |args| {
                Ok(json!({ "id": 1, "title": args["title"] }))
            })
    }

    #[test]
    fn handles_stdio_json_rpc_lifecycle() {
        let server = sample_server();
        let input = concat!(
            "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}\n",
            "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\",\"params\":{}}\n",
            "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"resources/list\",\"params\":{}}\n",
            "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"resources/read\",\"params\":{\"uri\":\"ferrik://posts\"}}\n",
            "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/list\",\"params\":{}}\n",
            "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/call\",\"params\":{\"name\":\"posts_create\",\"arguments\":{\"title\":\"AI\"}}}\n",
            "{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"unknown/method\",\"params\":{}}\n",
            "not-json\n"
        );
        let mut output = Vec::new();
        server.serve_io(Cursor::new(input), &mut output).unwrap();
        let lines: Vec<String> = String::from_utf8(output)
            .unwrap()
            .lines()
            .map(String::from)
            .collect();
        assert_eq!(lines.len(), 7);

        let init: Value = serde_json::from_str(&lines[0]).unwrap();
        assert_eq!(init["result"]["protocolVersion"], MCP_PROTOCOL_VERSION);

        let resources: Value = serde_json::from_str(&lines[1]).unwrap();
        assert!(resources["result"]["resources"]
            .as_array()
            .unwrap()
            .iter()
            .any(|r| r["uri"] == "ferrik://posts"));

        let read: Value = serde_json::from_str(&lines[2]).unwrap();
        assert!(read["result"]["contents"][0]["text"]
            .as_str()
            .unwrap()
            .contains("# Posts"));

        let tools: Value = serde_json::from_str(&lines[3]).unwrap();
        assert_eq!(tools["result"]["tools"][0]["name"], "posts_create");

        let call: Value = serde_json::from_str(&lines[4]).unwrap();
        assert_eq!(call["result"]["isError"], false);
        assert!(call["result"]["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("AI"));

        let unknown: Value = serde_json::from_str(&lines[5]).unwrap();
        assert_eq!(unknown["error"]["code"], -32601);

        let parse_err: Value = serde_json::from_str(&lines[6]).unwrap();
        assert_eq!(parse_err["error"]["code"], -32700);
    }

    #[tokio::test]
    async fn mounts_http_and_sse_mcp_endpoint() {
        let server = sample_server();
        let app = TestApp::spawn_with(move |_db| async move { mcp_router(server) }).await;

        app.get_html("/mcp")
            .await
            .assert_ok()
            .assert_header_contains("content-type", "text/event-stream")
            .assert_contains("event: endpoint");

        let resp: Value = app
            .as_agent(&["posts:write"])
            .call_mcp_tool("posts_create", json!({ "title": "Remote MCP" }))
            .await
            .assert_ok()
            .json();
        assert_eq!(resp["result"]["isError"], false);
        assert!(resp["result"]["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("Remote MCP"));
    }
}