pmcp-server-toolkit 0.1.0

Runtime library for config-driven MCP servers — auth, secrets, static resources/prompts, [[tools]] synthesizer, code-mode wiring
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
// Net-new code for Phase 83 PATTERNS §13 (builder extension surface).
// Hosts the `ServerBuilderExt` trait + `try_*` fallible variants per review R7.

//! Builder extension trait for [`pmcp::ServerBuilder`] — connects config-driven
//! synthesis (Plans 04, 05, 06) to the public Phase 82 builder API.
//!
//! Per CONTEXT.md D-10 + D-11, this is the "common path" surface — power users
//! call [`crate::tools::synthesize_from_config`] +
//! [`crate::code_mode::register_code_mode_tools`] directly. Shape C ≤15-line
//! `main.rs` users compose this trait.
//!
//! Per review R7, each method has a panicking convenience form
//! ([`ServerBuilderExt::tools_from_config`],
//! [`ServerBuilderExt::code_mode_from_config`]) AND a fallible companion
//! ([`ServerBuilderExt::try_tools_from_config`],
//! [`ServerBuilderExt::try_code_mode_from_config`]). The panicking forms
//! delegate to the `try_*` variants with documented panic messages — production
//! servers should prefer the `try_*` shape so misconfiguration surfaces as a
//! `Result`, not a crash.

use std::sync::Arc;

use pmcp::ServerBuilder;

use crate::config::ServerConfig;
use crate::error::Result;
use crate::sql::SqlConnector;

/// Composable builder extensions for config-driven `pmcp` servers.
///
/// Implemented for [`pmcp::ServerBuilder`] (Phase 82's public, `Arc`-aware
/// builder) so config-driven wiring composes with the standard chained-method
/// builder DSL.
pub trait ServerBuilderExt: Sized {
    /// Register every `[[tools]]` entry from `config` as a `tool_arc` handler
    /// (TKIT-07). Panicking convenience wrapping
    /// [`ServerBuilderExt::try_tools_from_config`].
    ///
    /// # Panics
    ///
    /// Panics with `"tools_from_config: ..."` if
    /// [`crate::tools::synthesize_from_config`] returns `Err`. Prefer
    /// [`ServerBuilderExt::try_tools_from_config`] for production servers
    /// where misconfiguration must surface as a `Result`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use pmcp::Server;
    /// use pmcp_server_toolkit::{ServerBuilderExt, ServerConfig};
    ///
    /// let cfg = ServerConfig::default();
    /// let _builder = Server::builder()
    ///     .name("demo")
    ///     .version("0.1.0")
    ///     .tools_from_config(&cfg);
    /// ```
    fn tools_from_config(self, config: &ServerConfig) -> Self;

    /// Fallible companion to [`ServerBuilderExt::tools_from_config`]
    /// (review R7).
    ///
    /// # Errors
    ///
    /// Returns [`crate::ToolkitError`] if synthesis fails — typically
    /// [`crate::ToolkitError::Synth`] or [`crate::ToolkitError::Validation`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use pmcp::Server;
    /// use pmcp_server_toolkit::{ServerBuilderExt, ServerConfig};
    ///
    /// # fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let cfg = ServerConfig::default();
    /// let _builder = Server::builder()
    ///     .name("demo")
    ///     .version("0.1.0")
    ///     .try_tools_from_config(&cfg)?;
    /// # Ok(()) }
    /// ```
    fn try_tools_from_config(self, config: &ServerConfig) -> Result<Self>;

    /// Register every `[[tools]]` entry from `config` as a `tool_arc` handler,
    /// threading `connector` into each handler so `tools/call` executes SQL and
    /// emits `structuredContent` (Phase 84 CONN-01 / D-06). Panicking
    /// convenience wrapping [`ServerBuilderExt::try_tools_from_config_with_connector`].
    ///
    /// This is the Shape A wiring point: production servers with a live
    /// connector use this entry point; the connector-less
    /// [`ServerBuilderExt::tools_from_config`] remains for callers that only
    /// need the synthesized tool schemas (handlers error at runtime if invoked).
    ///
    /// # Panics
    ///
    /// Panics with `"tools_from_config_with_connector: ..."` if
    /// [`crate::tools::synthesize_from_config_with_connector`] returns `Err`.
    /// Prefer [`ServerBuilderExt::try_tools_from_config_with_connector`] for
    /// production servers.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use pmcp::Server;
    /// use pmcp_server_toolkit::{ServerBuilderExt, ServerConfig};
    /// use pmcp_server_toolkit::sql::SqlConnector;
    ///
    /// fn build(connector: Arc<dyn SqlConnector>) {
    ///     let cfg = ServerConfig::default();
    ///     let _builder = Server::builder()
    ///         .name("demo")
    ///         .version("0.1.0")
    ///         .tools_from_config_with_connector(&cfg, connector);
    /// }
    /// ```
    fn tools_from_config_with_connector(
        self,
        config: &ServerConfig,
        connector: Arc<dyn SqlConnector>,
    ) -> Self;

    /// Fallible companion to
    /// [`ServerBuilderExt::tools_from_config_with_connector`].
    ///
    /// # Errors
    ///
    /// Returns [`crate::ToolkitError`] if synthesis fails — typically
    /// [`crate::ToolkitError::Synth`] or [`crate::ToolkitError::Validation`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use pmcp::Server;
    /// use pmcp_server_toolkit::{ServerBuilderExt, ServerConfig};
    /// use pmcp_server_toolkit::sql::SqlConnector;
    ///
    /// # fn run(connector: Arc<dyn SqlConnector>) -> Result<(), Box<dyn std::error::Error>> {
    /// let cfg = ServerConfig::default();
    /// let _builder = Server::builder()
    ///     .name("demo")
    ///     .version("0.1.0")
    ///     .try_tools_from_config_with_connector(&cfg, connector)?;
    /// # Ok(()) }
    /// ```
    fn try_tools_from_config_with_connector(
        self,
        config: &ServerConfig,
        connector: Arc<dyn SqlConnector>,
    ) -> Result<Self>;

    /// Wire the `[code_mode]` block. Panicking convenience wrapping
    /// [`ServerBuilderExt::try_code_mode_from_config`].
    ///
    /// When the `code-mode` feature is disabled, this is a no-op that emits
    /// a `tracing::warn!` so operators auditing logs can spot the feature gap
    /// (threat T-83-08-02 mitigation).
    ///
    /// # Panics
    ///
    /// Panics if [`ServerBuilderExt::try_code_mode_from_config`] errors —
    /// commonly because `token_secret`'s referenced env var is unset, or an
    /// inline literal `token_secret` was supplied without the dev-only escape
    /// hatch (review R9). Prefer
    /// [`ServerBuilderExt::try_code_mode_from_config`] for production servers.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use pmcp::Server;
    /// use pmcp_server_toolkit::{ServerBuilderExt, ServerConfig};
    ///
    /// let cfg = ServerConfig::default();
    /// let _builder = Server::builder()
    ///     .name("demo")
    ///     .version("0.1.0")
    ///     .code_mode_from_config(&cfg);
    /// ```
    fn code_mode_from_config(self, config: &ServerConfig) -> Self;

    /// Fallible companion to [`ServerBuilderExt::code_mode_from_config`]
    /// (review R7) — the CONNECTORLESS, **validation-only / no-tool** path.
    ///
    /// Tolerant of `config.code_mode = None` (returns the builder unchanged).
    /// When `[code_mode]` IS present this builds + validates the pipeline (so
    /// R9 / secret-resolution errors fire) but registers NO tools, because no
    /// executor is available to bind `execute_code` to. For the path that
    /// actually registers `validate_code` + `execute_code`, use the LOCKED
    /// connector-aware
    /// [`ServerBuilderExt::try_code_mode_from_config_with_connector`].
    ///
    /// # Errors
    ///
    /// Returns [`crate::ToolkitError`] if code-mode wiring fails — commonly
    /// [`crate::ToolkitError::CodeMode`] (env var missing) or
    /// [`crate::ToolkitError::Validation`] (inline `token_secret` rejected
    /// per review R9).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use pmcp::Server;
    /// use pmcp_server_toolkit::{ServerBuilderExt, ServerConfig};
    ///
    /// # fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let cfg = ServerConfig::default();
    /// let _builder = Server::builder()
    ///     .name("demo")
    ///     .version("0.1.0")
    ///     .try_code_mode_from_config(&cfg)?;
    /// # Ok(()) }
    /// ```
    fn try_code_mode_from_config(self, config: &ServerConfig) -> Result<Self>;

    /// Wire the `[code_mode]` block, registering BOTH `validate_code` and
    /// `execute_code` over `connector` (the LOCKED connector-aware API — the
    /// pure-config binary's path; SHAP-A-01 / SC-3).
    ///
    /// When `[code_mode]` is present this constructs a
    /// [`crate::code_mode::SqlCodeExecutor`] from `connector` and delegates to
    /// [`crate::code_mode::code_mode_tools_from_executor`], which registers the
    /// two tools with the static `[code_mode]` policy baked into the validation
    /// pipeline (allow_writes / allow_deletes / allow_ddl enforced; DELETE/DDL
    /// on a read-only config are rejected). When `[code_mode]` is absent this is
    /// a no-op (registers neither tool). Unlike the connectorless
    /// [`ServerBuilderExt::try_code_mode_from_config`], this is the tool-
    /// registering path because it has an executor to bind `execute_code` to.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ToolkitError`] if code-mode wiring fails — commonly
    /// [`crate::ToolkitError::CodeMode`] (env var missing / secret too short)
    /// or [`crate::ToolkitError::Validation`] (inline `token_secret` rejected
    /// per review R9).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use pmcp::Server;
    /// use pmcp_server_toolkit::{ServerBuilderExt, ServerConfig};
    /// use pmcp_server_toolkit::sql::SqlConnector;
    ///
    /// # fn run(connector: Arc<dyn SqlConnector>) -> Result<(), Box<dyn std::error::Error>> {
    /// let cfg = ServerConfig::default();
    /// let _builder = Server::builder()
    ///     .name("demo")
    ///     .version("0.1.0")
    ///     .try_code_mode_from_config_with_connector(&cfg, connector)?;
    /// # Ok(()) }
    /// ```
    fn try_code_mode_from_config_with_connector(
        self,
        config: &ServerConfig,
        connector: Arc<dyn SqlConnector>,
    ) -> Result<Self>;
}

impl ServerBuilderExt for ServerBuilder {
    fn tools_from_config(self, config: &ServerConfig) -> Self {
        self.try_tools_from_config(config).expect(
            "tools_from_config: synthesize_from_config returned an error — \
             prefer try_tools_from_config to handle this as a Result",
        )
    }

    fn try_tools_from_config(mut self, config: &ServerConfig) -> Result<Self> {
        let synthesized = crate::tools::synthesize_from_config(config)?;
        // T-83-08-02 mitigation: emit a visible signal when the [[tools]]
        // block is empty so an operator notices the gap rather than seeing a
        // silently-empty server.
        if synthesized.is_empty() {
            tracing::warn!(
                target: "pmcp_server_toolkit::builder_ext",
                "try_tools_from_config: config declared zero [[tools]] entries — \
                 server will expose no tools (set RUST_LOG=warn to surface this)"
            );
        }
        for (name, _info, handler) in synthesized {
            self = self.tool_arc(name, handler);
        }
        Ok(self)
    }

    fn tools_from_config_with_connector(
        self,
        config: &ServerConfig,
        connector: Arc<dyn SqlConnector>,
    ) -> Self {
        self.try_tools_from_config_with_connector(config, connector)
            .expect(
                "tools_from_config_with_connector: synthesize_from_config_with_connector \
                 returned an error — prefer try_tools_from_config_with_connector to handle \
                 this as a Result",
            )
    }

    fn try_tools_from_config_with_connector(
        mut self,
        config: &ServerConfig,
        connector: Arc<dyn SqlConnector>,
    ) -> Result<Self> {
        let synthesized = crate::tools::synthesize_from_config_with_connector(config, connector)?;
        // T-83-08-02 mitigation: visible signal when the [[tools]] block is
        // empty so an operator notices the gap rather than a silently-empty server.
        if synthesized.is_empty() {
            tracing::warn!(
                target: "pmcp_server_toolkit::builder_ext",
                "try_tools_from_config_with_connector: config declared zero [[tools]] entries — \
                 server will expose no tools (set RUST_LOG=warn to surface this)"
            );
        }
        for (name, _info, handler) in synthesized {
            self = self.tool_arc(name, handler);
        }
        Ok(self)
    }

    fn code_mode_from_config(self, config: &ServerConfig) -> Self {
        self.try_code_mode_from_config(config).expect(
            "code_mode_from_config: register_code_mode_tools errored — \
             prefer try_code_mode_from_config to handle (e.g. missing env var)",
        )
    }

    fn try_code_mode_from_config(self, config: &ServerConfig) -> Result<Self> {
        #[cfg(feature = "code-mode")]
        {
            crate::code_mode::register_code_mode_tools(self, config)
        }
        #[cfg(not(feature = "code-mode"))]
        {
            let _ = config;
            tracing::warn!(
                target: "pmcp_server_toolkit::builder_ext",
                "try_code_mode_from_config called but `code-mode` feature is \
                 disabled at compile-time — skipping (T-83-08-02 visibility)"
            );
            Ok(self)
        }
    }

    fn try_code_mode_from_config_with_connector(
        self,
        config: &ServerConfig,
        connector: Arc<dyn SqlConnector>,
    ) -> Result<Self> {
        #[cfg(feature = "code-mode")]
        {
            if config.code_mode.is_none() {
                return Ok(self); // no-op when block absent (mirrors connectorless path)
            }
            // Coerce the SQL executor to the backend-agnostic `Arc<dyn
            // CodeExecutor>` the generalized wiring fn takes (OAPI-10 / D-02).
            // `CodeExecutor` is `#[async_trait]` and object-safe, so this is a
            // plain unsize coercion. The SQL path passes `ValidationFlavor::Sql`.
            let executor: Arc<dyn crate::code_mode::CodeExecutor> = Arc::new(
                crate::code_mode::SqlCodeExecutor::new(connector, config.clone())?,
            );
            crate::code_mode::code_mode_tools_from_executor(
                self,
                config,
                executor,
                crate::code_mode::ValidationFlavor::Sql,
            )
        }
        #[cfg(not(feature = "code-mode"))]
        {
            let _ = (config, connector);
            tracing::warn!(
                target: "pmcp_server_toolkit::builder_ext",
                "try_code_mode_from_config_with_connector called but `code-mode` \
                 feature is disabled at compile-time — skipping (T-83-08-02 visibility)"
            );
            Ok(self)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{ServerConfig, ServerSection, ToolDecl};
    use pmcp::Server;

    fn min_cfg() -> ServerConfig {
        ServerConfig {
            server: ServerSection {
                name: "test".to_string(),
                version: "0.1.0".to_string(),
                ..Default::default()
            },
            tools: vec![ToolDecl {
                name: "ping".to_string(),
                description: Some("ping".to_string()),
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    #[test]
    fn tools_from_config_registers_synthesized_handlers() {
        let cfg = min_cfg();
        let server = Server::builder()
            .name("test")
            .version("0.1.0")
            .tools_from_config(&cfg)
            .build()
            .expect("build");
        assert!(
            server.get_tool("ping").is_some(),
            "tools_from_config must wire each [[tools]] entry via tool_arc (Phase 82)"
        );
    }

    #[test]
    fn try_tools_from_config_returns_ok_on_valid_config() {
        let cfg = min_cfg();
        let builder = Server::builder().name("t").version("0.1.0");
        let result = builder.try_tools_from_config(&cfg);
        assert!(result.is_ok(), "valid config must return Ok");
    }

    #[test]
    fn code_mode_from_config_is_noop_when_block_absent() {
        // Plan 06 Task 2 ensures register_code_mode_tools tolerates
        // config.code_mode = None.
        let cfg = min_cfg();
        let _builder = Server::builder()
            .name("t")
            .version("0.1.0")
            .code_mode_from_config(&cfg);
        // No panic means tolerance works.
    }

    #[test]
    fn try_code_mode_from_config_is_ok_when_block_absent() {
        let cfg = min_cfg();
        let builder = Server::builder().name("t").version("0.1.0");
        let result = builder.try_code_mode_from_config(&cfg);
        assert!(
            result.is_ok(),
            "code_mode = None must produce Ok (no-op) so callers can invoke unconditionally"
        );
    }
}