stateknot-integrations 0.1.0-alpha.1

Bounded protocol and model-provider adapters for StateKnot
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
// Copyright 2026 StateKnot contributors
// SPDX-License-Identifier: Apache-2.0

//! Composite StateKnot-owned MCP 2026-07-28 server application.

use std::{borrow::Cow, fmt, sync::Arc};

use rmcp::{
    ErrorData, RoleServer, ServerHandler,
    model::{
        CallToolRequestParams, CallToolResponse, CompleteRequestParams, CompleteResult,
        CustomRequest, CustomResult, DiscoverResult, ErrorCode, GetPromptRequestParams,
        GetPromptResponse, Implementation, ListPromptsResult, ListResourceTemplatesResult,
        ListResourcesResult, ListToolsResult, PaginatedRequestParams, PromptsCapability,
        ProtocolVersion, ReadResourceRequestParams, ReadResourceResponse, ResourcesCapability,
        ServerCapabilities, ServerConfig, Tool, ToolsCapability,
    },
    service::RequestContext,
};
use thiserror::Error;

use crate::{
    McpServerApplicationOptions, McpServerCompletionProvider, McpServerPromptAuthorization,
    McpServerPromptCatalog, McpServerPromptRenderer, McpServerPromptService,
    McpServerPromptServiceBuildError, McpServerResourceAuthorization, McpServerResourceCatalog,
    McpServerResourceReader, McpServerResourceService, McpServerResourceServiceBuildError,
    McpServerSkillAuthorization, McpServerSkillCatalog, McpServerSkillService,
    McpServerSkillServiceBuildError, McpServerToolAuthorization, McpServerToolRegistry,
    McpServerToolService, McpServerToolServiceBuildError,
};

/// Startup-only builder for a composite MCP application.
pub struct McpServerApplicationBuilder {
    options: McpServerApplicationOptions,
    tools: Option<McpServerToolService>,
    resources: Option<McpServerResourceService>,
    skills: Option<McpServerSkillService>,
    prompts: Option<McpServerPromptService>,
    completion: Option<Arc<dyn McpServerCompletionProvider>>,
}

impl McpServerApplicationBuilder {
    /// Creates a builder with one shared identity, pagination, and cache policy.
    #[must_use]
    pub fn new(options: McpServerApplicationOptions) -> Self {
        Self {
            options,
            tools: None,
            resources: None,
            skills: None,
            prompts: None,
            completion: None,
        }
    }

    /// Adds the immutable Tool registry and decoded authorization policy.
    pub fn with_tools<A>(
        mut self,
        registry: McpServerToolRegistry,
        authorization: A,
    ) -> Result<Self, McpServerApplicationBuildError>
    where
        A: McpServerToolAuthorization,
    {
        if self.tools.is_some() {
            return Err(McpServerApplicationBuildError::DuplicateTools);
        }
        self.tools = Some(
            McpServerToolService::new(registry, self.options.clone(), authorization)
                .map_err(McpServerApplicationBuildError::ToolService)?,
        );
        Ok(self)
    }

    /// Adds immutable Resource metadata, a reader, and decoded authorization.
    pub fn with_resources<R, A>(
        mut self,
        catalog: McpServerResourceCatalog,
        reader: R,
        authorization: A,
    ) -> Result<Self, McpServerApplicationBuildError>
    where
        R: McpServerResourceReader,
        A: McpServerResourceAuthorization,
    {
        if self.resources.is_some() {
            return Err(McpServerApplicationBuildError::DuplicateResources);
        }
        self.resources = Some(
            McpServerResourceService::new(catalog, self.options.clone(), reader, authorization)
                .map_err(McpServerApplicationBuildError::ResourceService)?,
        );
        Ok(self)
    }

    /// Adds an immutable SEP-2640 Skill registry and decoded authorization.
    pub fn with_skills<A>(
        mut self,
        catalog: McpServerSkillCatalog,
        authorization: A,
    ) -> Result<Self, McpServerApplicationBuildError>
    where
        A: McpServerSkillAuthorization,
    {
        if self.skills.is_some() {
            return Err(McpServerApplicationBuildError::DuplicateSkills);
        }
        self.skills = Some(
            McpServerSkillService::new(catalog, self.options.clone(), authorization)
                .map_err(McpServerApplicationBuildError::SkillService)?,
        );
        Ok(self)
    }

    /// Adds immutable Prompt metadata, a renderer, and decoded authorization.
    pub fn with_prompts<R, A>(
        mut self,
        catalog: McpServerPromptCatalog,
        renderer: R,
        authorization: A,
    ) -> Result<Self, McpServerApplicationBuildError>
    where
        R: McpServerPromptRenderer,
        A: McpServerPromptAuthorization,
    {
        if self.prompts.is_some() {
            return Err(McpServerApplicationBuildError::DuplicatePrompts);
        }
        self.prompts = Some(
            McpServerPromptService::new(catalog, self.options.clone(), renderer, authorization)
                .map_err(McpServerApplicationBuildError::PromptService)?,
        );
        Ok(self)
    }

    /// Adds a Prompt/Resource Completion provider.
    pub fn with_completion_provider<C>(
        mut self,
        provider: C,
    ) -> Result<Self, McpServerApplicationBuildError>
    where
        C: McpServerCompletionProvider,
    {
        if self.completion.is_some() {
            return Err(McpServerApplicationBuildError::DuplicateCompletion);
        }
        self.completion = Some(Arc::new(provider));
        Ok(self)
    }

    /// Freezes a non-empty application.
    pub fn build(mut self) -> Result<McpServerApplication, McpServerApplicationBuildError> {
        if self.tools.is_none()
            && self.resources.is_none()
            && self.skills.is_none()
            && self.prompts.is_none()
        {
            return Err(McpServerApplicationBuildError::Empty);
        }
        if let (Some(resources), Some(skills)) = (&self.resources, &self.skills)
            && skills
                .resource_uris()
                .any(|uri| resources.contains_resource(uri))
        {
            return Err(McpServerApplicationBuildError::ConflictingResourceUri);
        }
        if let Some(completion) = self.completion {
            let prompts = self
                .prompts
                .take()
                .ok_or(McpServerApplicationBuildError::CompletionRequiresPrompts)?;
            self.prompts = Some(prompts.with_shared_completion_provider(completion));
        }
        Ok(McpServerApplication {
            options: self.options,
            tools: self.tools,
            resources: self.resources,
            skills: self.skills,
            prompts: self.prompts,
        })
    }
}

impl fmt::Debug for McpServerApplicationBuilder {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("McpServerApplicationBuilder")
            .field("options", &self.options)
            .field("tools", &self.tools.is_some())
            .field("resources", &self.resources.is_some())
            .field("skills", &self.skills.is_some())
            .field("prompts", &self.prompts.is_some())
            .field("completion", &self.completion.is_some())
            .finish_non_exhaustive()
    }
}

/// Composite application construction failure.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum McpServerApplicationBuildError {
    /// At least one server capability must be configured.
    #[error("MCP server application has no capabilities")]
    Empty,
    /// Tool surface was configured twice.
    #[error("MCP tool surface is already configured")]
    DuplicateTools,
    /// Resource surface was configured twice.
    #[error("MCP resource surface is already configured")]
    DuplicateResources,
    /// Skill surface was configured twice.
    #[error("MCP Skill surface is already configured")]
    DuplicateSkills,
    /// Prompt surface was configured twice.
    #[error("MCP prompt surface is already configured")]
    DuplicatePrompts,
    /// Completion was configured twice.
    #[error("MCP completion surface is already configured")]
    DuplicateCompletion,
    /// This profile binds Completion through the Prompt service.
    #[error("MCP completion requires a configured prompt surface")]
    CompletionRequiresPrompts,
    /// A generic Resource and Skill file claimed the same exact URI.
    #[error("MCP Resource and Skill catalogs contain the same URI")]
    ConflictingResourceUri,
    /// Tool service policy was inconsistent.
    #[error("invalid MCP tool service: {0}")]
    ToolService(McpServerToolServiceBuildError),
    /// Resource service policy was inconsistent.
    #[error("invalid MCP resource service: {0}")]
    ResourceService(McpServerResourceServiceBuildError),
    /// Skill service policy was inconsistent.
    #[error("invalid MCP Skill service: {0}")]
    SkillService(McpServerSkillServiceBuildError),
    /// Prompt service policy was inconsistent.
    #[error("invalid MCP prompt service: {0}")]
    PromptService(McpServerPromptServiceBuildError),
}

/// Cloneable composite Tools, Resources, Prompts, and Completion handler.
#[derive(Clone)]
pub struct McpServerApplication {
    options: McpServerApplicationOptions,
    tools: Option<McpServerToolService>,
    resources: Option<McpServerResourceService>,
    skills: Option<McpServerSkillService>,
    prompts: Option<McpServerPromptService>,
}

impl McpServerApplication {
    /// Returns whether the Tool surface is configured.
    #[must_use]
    pub const fn has_tools(&self) -> bool {
        self.tools.is_some()
    }

    /// Returns whether the Resource surface is configured.
    #[must_use]
    pub const fn has_resources(&self) -> bool {
        self.resources.is_some() || self.skills.is_some()
    }

    /// Returns whether the SEP-2640 Skill extension is configured.
    #[must_use]
    pub const fn has_skills(&self) -> bool {
        self.skills.is_some()
    }

    /// Returns whether the Prompt surface is configured.
    #[must_use]
    pub const fn has_prompts(&self) -> bool {
        self.prompts.is_some()
    }

    /// Returns whether Completion is advertised.
    #[must_use]
    pub fn has_completion(&self) -> bool {
        self.prompts
            .as_ref()
            .is_some_and(|service| service.get_info().capabilities.completions.is_some())
    }

    fn capabilities(&self) -> ServerCapabilities {
        let mut capabilities = ServerCapabilities::default();
        if self.tools.is_some() {
            capabilities.tools = Some(ToolsCapability::default());
        }
        if self.resources.is_some() || self.skills.is_some() {
            capabilities.resources = Some(ResourcesCapability::default());
        }
        if self.skills.is_some() {
            capabilities.extensions = McpServerSkillService::capabilities().extensions;
        }
        if self.prompts.is_some() {
            capabilities.prompts = Some(PromptsCapability::default());
        }
        if self.has_completion() {
            capabilities.completions = Some(serde_json::Map::new());
        }
        capabilities
    }
}

impl fmt::Debug for McpServerApplication {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("McpServerApplication")
            .field("options", &self.options)
            .field("tools", &self.has_tools())
            .field("resources", &self.has_resources())
            .field("skills", &self.has_skills())
            .field("prompts", &self.has_prompts())
            .field("completion", &self.has_completion())
            .finish_non_exhaustive()
    }
}

impl ServerHandler for McpServerApplication {
    fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
        Cow::Borrowed(&[ProtocolVersion::V_2026_07_28])
    }

    fn get_info(&self) -> ServerConfig {
        let mut info =
            ServerConfig::new(self.capabilities()).with_server_info(Implementation::new(
                self.options.server_name.to_string(),
                self.options.server_version.to_string(),
            ));
        if let Some(instructions) = &self.options.instructions {
            info = info.with_instructions(instructions.to_string());
        }
        info
    }

    async fn discover(
        &self,
        _context: RequestContext<RoleServer>,
    ) -> Result<DiscoverResult, ErrorData> {
        Ok(
            DiscoverResult::from_server_info(vec![ProtocolVersion::V_2026_07_28], self.get_info())
                .with_ttl_ms(self.options.cache_ttl_ms)
                .with_cache_scope(self.options.cache_scope.into()),
        )
    }

    fn get_tool(&self, name: &str) -> Option<Tool> {
        self.tools
            .as_ref()
            .and_then(|service| ServerHandler::get_tool(service, name))
    }

    async fn list_tools(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        let Some(service) = &self.tools else {
            return Err(method_not_found("tools/list"));
        };
        ServerHandler::list_tools(service, request, context).await
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, ErrorData> {
        let Some(service) = &self.tools else {
            return Err(method_not_found("tools/call"));
        };
        ServerHandler::call_tool(service, request, context).await
    }

    async fn on_custom_request(
        &self,
        request: CustomRequest,
        context: RequestContext<RoleServer>,
    ) -> Result<CustomResult, ErrorData> {
        let Some(service) = &self.skills else {
            return Err(method_not_found_owned(request.method));
        };
        service.dispatch_custom(request, context).await
    }

    async fn list_resources(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, ErrorData> {
        if let Some(service) = &self.resources {
            return ServerHandler::list_resources(service, request, context).await;
        }
        if let Some(service) = &self.skills {
            return ServerHandler::list_resources(service, request, context).await;
        }
        Err(method_not_found("resources/list"))
    }

    async fn list_resource_templates(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListResourceTemplatesResult, ErrorData> {
        if let Some(service) = &self.resources {
            return ServerHandler::list_resource_templates(service, request, context).await;
        }
        if let Some(service) = &self.skills {
            return ServerHandler::list_resource_templates(service, request, context).await;
        }
        Err(method_not_found("resources/templates/list"))
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResponse, ErrorData> {
        if let Some(service) = &self.skills
            && service.contains_resource(&request.uri)
        {
            return service.dispatch_read(request, context).await;
        }
        if let Some(service) = &self.resources {
            return ServerHandler::read_resource(service, request, context).await;
        }
        if let Some(service) = &self.skills {
            return service.dispatch_read(request, context).await;
        }
        Err(method_not_found("resources/read"))
    }

    async fn list_prompts(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListPromptsResult, ErrorData> {
        let Some(service) = &self.prompts else {
            return Err(method_not_found("prompts/list"));
        };
        ServerHandler::list_prompts(service, request, context).await
    }

    async fn get_prompt(
        &self,
        request: GetPromptRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<GetPromptResponse, ErrorData> {
        let Some(service) = &self.prompts else {
            return Err(method_not_found("prompts/get"));
        };
        ServerHandler::get_prompt(service, request, context).await
    }

    async fn complete(
        &self,
        request: CompleteRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CompleteResult, ErrorData> {
        let Some(service) = &self.prompts else {
            return Err(method_not_found("completion/complete"));
        };
        ServerHandler::complete(service, request, context).await
    }
}

fn method_not_found(method: &'static str) -> ErrorData {
    ErrorData::new(ErrorCode::METHOD_NOT_FOUND, method, None)
}

fn method_not_found_owned(method: String) -> ErrorData {
    ErrorData::new(ErrorCode::METHOD_NOT_FOUND, method, None)
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use bytes::Bytes;
    use http::{Request, StatusCode};
    use http_body_util::{BodyExt as _, Full};
    use serde_json::{Value, json};
    use tower_service::Service as _;

    use super::*;
    use crate::{
        AllowMcpServerPromptAuthorization, AllowMcpServerResourceAuthorization,
        AllowMcpServerSkillAuthorization, AllowMcpServerToolAuthorization, MCP_SKILLS_EXTENSION_ID,
        McpServerAuthentication, McpServerCacheScope, McpServerContent, McpServerHttpOptions,
        McpServerHttpService, McpServerPromptCatalogBuilder, McpServerPromptContext,
        McpServerPromptDefinition, McpServerPromptMessage, McpServerPromptOutcome,
        McpServerPromptRender, McpServerPromptRendererError, McpServerPromptResult,
        McpServerPromptRole, McpServerResourceCatalogBuilder, McpServerResourceContent,
        McpServerResourceContext, McpServerResourceDefinition, McpServerResourceOutcome,
        McpServerResourceRead, McpServerResourceReaderError, McpServerResourceResult,
        McpServerSkillCatalogBuilder, McpServerSkillDefinition, McpServerSkillFile,
        McpServerToolCall, McpServerToolContext, McpServerToolDefinition,
        McpServerToolHandlerError, McpServerToolOutcome, McpServerToolRegistryBuilder,
        McpServerToolResult,
    };

    #[derive(Clone, Copy)]
    struct TestTool;

    impl crate::McpServerToolHandler for TestTool {
        fn call(
            &self,
            _call: McpServerToolCall,
            _context: McpServerToolContext,
        ) -> stateknot_core::BoxFuture<'_, Result<McpServerToolOutcome, McpServerToolHandlerError>>
        {
            Box::pin(async {
                let content = McpServerContent::text("tool").unwrap();
                Ok(McpServerToolResult::success([content]).unwrap().into())
            })
        }
    }

    #[derive(Clone, Copy)]
    struct TestReader;

    impl McpServerResourceReader for TestReader {
        fn read(
            &self,
            request: McpServerResourceRead,
            _context: McpServerResourceContext,
        ) -> stateknot_core::BoxFuture<
            '_,
            Result<McpServerResourceOutcome, McpServerResourceReaderError>,
        > {
            let uri = request.uri().to_owned();
            Box::pin(async move {
                let content =
                    McpServerResourceContent::text(uri, Some("text/plain"), "resource").unwrap();
                Ok(McpServerResourceResult::new(
                    [content],
                    Duration::ZERO,
                    McpServerCacheScope::Private,
                )
                .unwrap()
                .into())
            })
        }
    }

    #[derive(Clone, Copy)]
    struct TestRenderer;

    impl McpServerPromptRenderer for TestRenderer {
        fn render(
            &self,
            _request: McpServerPromptRender,
            _context: McpServerPromptContext,
        ) -> stateknot_core::BoxFuture<
            '_,
            Result<McpServerPromptOutcome, McpServerPromptRendererError>,
        > {
            Box::pin(async {
                let content = McpServerContent::text("prompt").unwrap();
                Ok(McpServerPromptResult::new([McpServerPromptMessage::new(
                    McpServerPromptRole::User,
                    content,
                )])
                .unwrap()
                .into())
            })
        }
    }

    fn application() -> McpServerHttpService<McpServerApplication> {
        let mut tools = McpServerToolRegistryBuilder::default();
        tools
            .register(
                McpServerToolDefinition::new(
                    "test_tool",
                    json!({ "type": "object", "additionalProperties": false }),
                )
                .unwrap(),
                TestTool,
            )
            .unwrap();
        let mut resources = McpServerResourceCatalogBuilder::default();
        resources
            .register_resource(McpServerResourceDefinition::new("test://one", "One").unwrap())
            .unwrap();
        let mut prompts = McpServerPromptCatalogBuilder::default();
        prompts
            .register(McpServerPromptDefinition::new("test_prompt").unwrap())
            .unwrap();
        let mut skills = McpServerSkillCatalogBuilder::default();
        skills
            .register(
                McpServerSkillDefinition::new(
                    "skill://test-skill/SKILL.md",
                    [McpServerSkillFile::text(
                        "SKILL.md",
                        "text/markdown",
                        "---\nname: test-skill\ndescription: Composite application test Skill.\n---\n",
                    )
                    .unwrap()],
                )
                .unwrap(),
            )
            .unwrap();
        let options = McpServerApplicationOptions::new(
            "stateknot-composite-test",
            "0.0.0",
            32,
            Duration::from_secs(60),
            McpServerCacheScope::Private,
        )
        .unwrap();
        let application = McpServerApplicationBuilder::new(options)
            .with_tools(tools.build().unwrap(), AllowMcpServerToolAuthorization)
            .unwrap()
            .with_resources(
                resources.build().unwrap(),
                TestReader,
                AllowMcpServerResourceAuthorization,
            )
            .unwrap()
            .with_skills(skills.build().unwrap(), AllowMcpServerSkillAuthorization)
            .unwrap()
            .with_prompts(
                prompts.build().unwrap(),
                TestRenderer,
                AllowMcpServerPromptAuthorization,
            )
            .unwrap()
            .build()
            .unwrap();
        McpServerHttpService::new(
            application,
            McpServerHttpOptions::loopback(32127).unwrap(),
            McpServerAuthentication::anonymous_loopback(),
        )
        .unwrap()
    }

    fn request(method: &str, mut params: Value) -> Request<Full<Bytes>> {
        params.as_object_mut().unwrap().insert(
            "_meta".to_owned(),
            json!({
                "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientInfo": { "name": "test", "version": "0" },
                "io.modelcontextprotocol/clientCapabilities": {
                    "extensions": { (MCP_SKILLS_EXTENSION_ID): {} }
                }
            }),
        );
        let body = serde_json::to_vec(&json!({
            "jsonrpc": "2.0", "id": 1, "method": method, "params": params
        }))
        .unwrap();
        Request::builder()
            .method("POST")
            .uri("http://127.0.0.1:32127/mcp")
            .header("host", "127.0.0.1:32127")
            .header("origin", "http://127.0.0.1:32127")
            .header("content-type", "application/json")
            .header("accept", "application/json, text/event-stream")
            .header("mcp-protocol-version", "2026-07-28")
            .header("mcp-method", method)
            .body(Full::new(Bytes::from(body)))
            .unwrap()
    }

    #[tokio::test]
    async fn composite_discovery_advertises_only_configured_surfaces() {
        let mut service = application();
        let response = service
            .call(request("server/discover", json!({})))
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let bytes = response.into_body().collect().await.unwrap().to_bytes();
        let value: Value = serde_json::from_slice(&bytes).unwrap();
        assert!(value.pointer("/result/capabilities/tools").is_some());
        assert!(value.pointer("/result/capabilities/resources").is_some());
        assert!(value.pointer("/result/capabilities/prompts").is_some());
        assert!(value.pointer("/result/capabilities/completions").is_none());
        assert_eq!(
            value.pointer("/result/capabilities/extensions/io.modelcontextprotocol~1skills"),
            Some(&json!({}))
        );
    }

    #[tokio::test]
    async fn composite_dispatches_the_skills_extension() {
        let mut service = application();
        let response = service
            .call(request(
                "skills/get",
                json!({ "uri": "skill://test-skill/SKILL.md" }),
            ))
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let bytes = response.into_body().collect().await.unwrap().to_bytes();
        let value: Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            value.pointer("/result/skill/frontmatter/name"),
            Some(&json!("test-skill"))
        );
    }
}