sdd-layer 0.14.1

Spec-Driven Development CLI and agent harness
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
use anyhow::{anyhow, Result};
use serde::Serialize;
use serde_json::{json, Value};
use std::io::{self, BufRead, Write};

pub const MCP_PROTOCOL_VERSION: &str = "2025-06-18";

#[derive(Clone, Debug, Serialize)]
pub struct RuntimeAdapterDefinition {
    pub id: &'static str,
    pub kind: &'static str,
    pub crate_name: &'static str,
    pub feature: &'static str,
    pub enabled: bool,
    pub version_requirement: &'static str,
    pub role: &'static str,
    pub fallback: &'static str,
    pub capabilities: &'static [&'static str],
}

pub struct McpResource {
    pub uri: String,
    pub mime_type: String,
    pub text: String,
}

pub trait McpBackend {
    fn call_tool(&self, name: &str, arguments: &Value) -> Result<Value>;
    fn list_resources(&self) -> Result<Vec<Value>>;
    fn read_resource(&self, uri: &str) -> Result<McpResource>;
    fn get_prompt(&self, name: &str, arguments: &Value) -> Result<Value>;
}

pub fn serve_stdio<B: McpBackend>(backend: &B) -> Result<()> {
    let stdin = io::stdin();
    let mut stdout = io::stdout();
    serve_lines(stdin.lock(), &mut stdout, backend)
}

pub fn serve_lines<R: BufRead, W: Write, B: McpBackend>(
    reader: R,
    writer: &mut W,
    backend: &B,
) -> Result<()> {
    for line in reader.lines() {
        let line = line?;
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let request: Value = match serde_json::from_str(trimmed) {
            Ok(value) => value,
            Err(error) => {
                writeln!(
                    writer,
                    "{}",
                    jsonrpc_error(Value::Null, -32700, &error.to_string())
                )?;
                continue;
            }
        };
        if let Some(response) = handle_request(backend, request) {
            writeln!(writer, "{}", serde_json::to_string(&response)?)?;
            writer.flush()?;
        }
    }
    Ok(())
}

fn handle_request<B: McpBackend>(backend: &B, request: Value) -> Option<Value> {
    let id = request.get("id").cloned().unwrap_or(Value::Null);
    let method = request.get("method").and_then(Value::as_str).unwrap_or("");
    if id.is_null() && method.starts_with("notifications/") {
        return None;
    }
    let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
    let result = match method {
        "initialize" => Ok(initialize_result(&params)),
        "tools/list" => Ok(json!({ "tools": tool_definitions() })),
        "tools/call" => call_tool(backend, &params),
        "resources/list" => backend
            .list_resources()
            .map(|resources| json!({ "resources": resources })),
        "resources/templates/list" => Ok(json!({ "resourceTemplates": resource_templates() })),
        "resources/read" => read_resource(backend, &params),
        "prompts/list" => Ok(json!({ "prompts": prompt_definitions() })),
        "prompts/get" => get_prompt(backend, &params),
        _ => Err(anyhow!("method not found: {method}")),
    };
    Some(match result {
        Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
        Err(error) => jsonrpc_error(id, -32603, &error.to_string()),
    })
}

fn initialize_result(params: &Value) -> Value {
    let protocol_version = params
        .get("protocolVersion")
        .and_then(Value::as_str)
        .unwrap_or(MCP_PROTOCOL_VERSION);
    json!({
        "protocolVersion": protocol_version,
        "capabilities": {
            "tools": { "listChanged": false },
            "resources": { "listChanged": false },
            "prompts": { "listChanged": false }
        },
        "serverInfo": {
            "name": "sdd-layer",
            "version": env!("CARGO_PKG_VERSION")
        }
    })
}

pub fn runtime_adapters() -> Vec<RuntimeAdapterDefinition> {
    vec![
        RuntimeAdapterDefinition {
            id: "rmcp",
            kind: "mcp-sdk",
            crate_name: "rmcp",
            feature: "mcp-rmcp",
            enabled: cfg!(feature = "mcp-rmcp"),
            version_requirement: "^1.7",
            role: "Official Rust MCP SDK compatibility layer for typed server metadata.",
            fallback: "manual-jsonrpc-stdio",
            capabilities: &["tools", "resources", "prompts", "stdio"],
        },
        RuntimeAdapterDefinition {
            id: "rig",
            kind: "provider-tool-adapter",
            crate_name: "rig-core",
            feature: "rig-adapter",
            enabled: cfg!(feature = "rig-adapter"),
            version_requirement: "^0.38",
            role: "Optional provider/tool abstraction for future direct model and tool execution.",
            fallback: "provider-registry-and-local-cli-adapters",
            capabilities: &["chat", "tools", "provider-routing"],
        },
    ]
}

pub fn rmcp_server_info_json() -> Result<Option<Value>> {
    #[cfg(feature = "mcp-rmcp")]
    {
        use rmcp::model::{Implementation, InitializeResult, ServerCapabilities};

        let capabilities = ServerCapabilities::builder()
            .enable_tools()
            .enable_resources()
            .enable_prompts()
            .build();
        let server_info = InitializeResult::new(capabilities).with_server_info(
            Implementation::new("sdd-layer", env!("CARGO_PKG_VERSION"))
                .with_title("SDD Layer MCP")
                .with_description(
                    "Read-only SDD artifacts, context packs, traces and client diagnostics.",
                ),
        );
        Ok(Some(serde_json::to_value(server_info)?))
    }
    #[cfg(not(feature = "mcp-rmcp"))]
    {
        Ok(None)
    }
}

fn call_tool<B: McpBackend>(backend: &B, params: &Value) -> Result<Value> {
    let name = params
        .get("name")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow!("tools/call missing params.name"))?;
    let arguments = params.get("arguments").unwrap_or(&Value::Null);
    let value = backend.call_tool(name, arguments)?;
    Ok(tool_result(value, false))
}

fn read_resource<B: McpBackend>(backend: &B, params: &Value) -> Result<Value> {
    let uri = params
        .get("uri")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow!("resources/read missing params.uri"))?;
    let resource = backend.read_resource(uri)?;
    Ok(json!({
        "contents": [{
            "uri": resource.uri,
            "mimeType": resource.mime_type,
            "text": resource.text
        }]
    }))
}

fn get_prompt<B: McpBackend>(backend: &B, params: &Value) -> Result<Value> {
    let name = params
        .get("name")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow!("prompts/get missing params.name"))?;
    let arguments = params.get("arguments").unwrap_or(&Value::Null);
    backend.get_prompt(name, arguments)
}

fn tool_result(value: Value, is_error: bool) -> Value {
    let text = if let Some(text) = value.as_str() {
        text.to_string()
    } else {
        serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string())
    };
    json!({
        "content": [{ "type": "text", "text": text }],
        "isError": is_error
    })
}

fn jsonrpc_error(id: Value, code: i32, message: &str) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": { "code": code, "message": message }
    })
}

fn tool_definitions() -> Vec<Value> {
    vec![
        tool(
            "sdd_trace_list",
            "List SDD trace events",
            json!({
                "type": "object",
                "properties": {
                    "orchestration": { "type": "string" }
                }
            }),
        ),
        tool(
            "sdd_trace_show",
            "Show one trace tree by run_id",
            json!({
                "type": "object",
                "properties": { "run_id": { "type": "string" } },
                "required": ["run_id"]
            }),
        ),
        tool(
            "sdd_trace_summary",
            "Summarize SDD traces",
            json!({
                "type": "object",
                "properties": { "orchestration": { "type": "string" } }
            }),
        ),
        tool(
            "sdd_artifact_status",
            "Read local artifact store status",
            json!({
                "type": "object",
                "properties": { "orchestration": { "type": "string" } }
            }),
        ),
        tool(
            "sdd_context_build",
            "Build read-only SDD context from local artifacts",
            json!({
                "type": "object",
                "properties": {
                    "orchestration": { "type": "string" },
                    "stage": { "type": "string" },
                    "task": { "type": "string" }
                },
                "required": ["orchestration", "stage"]
            }),
        ),
        tool(
            "sdd_clients_doctor",
            "Run clients doctor data in read-only mode",
            json!({ "type": "object", "properties": {} }),
        ),
        tool(
            "sdd_runtime_adapters",
            "Inspect optional MCP/provider runtime adapters compiled into this sdd binary",
            json!({ "type": "object", "properties": {} }),
        ),
    ]
}

fn tool(name: &str, description: &str, input_schema: Value) -> Value {
    json!({
        "name": name,
        "title": name,
        "description": description,
        "inputSchema": input_schema,
        "annotations": { "readOnlyHint": true }
    })
}

fn resource_templates() -> Vec<Value> {
    vec![
        json!({
            "uriTemplate": "sdd://artifact/{orchestration}/{artifact}",
            "name": "sdd_artifact",
            "title": "SDD artifact",
            "description": "Read a local SDD artifact from docs/<slug>/",
            "mimeType": "text/markdown"
        }),
        json!({
            "uriTemplate": "sdd://trace/{run_id}",
            "name": "sdd_trace",
            "title": "SDD trace tree",
            "description": "Read an SDD trace tree as JSON",
            "mimeType": "application/json"
        }),
        json!({
            "uriTemplate": "sdd://context/{orchestration}/{stage}",
            "name": "sdd_context",
            "title": "SDD context pack",
            "description": "Read a generated context pack for one stage",
            "mimeType": "text/markdown"
        }),
        json!({
            "uriTemplate": "sdd://runtime/adapters",
            "name": "sdd_runtime_adapters",
            "title": "SDD runtime adapters",
            "description": "Read optional MCP/provider adapter metadata for this sdd binary",
            "mimeType": "application/json"
        }),
    ]
}

fn prompt_definitions() -> Vec<Value> {
    vec![
        json!({
            "name": "sdd_orchestration",
            "title": "Run SDD orchestration",
            "description": "Prompt for starting a full SDD orchestration",
            "arguments": [{ "name": "idea", "required": true }]
        }),
        json!({
            "name": "sdd_stage_handoff",
            "title": "Prepare stage handoff",
            "description": "Prompt for handing off one SDD stage with trace context",
            "arguments": [
                { "name": "orchestration", "required": true },
                { "name": "stage", "required": true }
            ]
        }),
        json!({
            "name": "sdd_trace_review",
            "title": "Review SDD trace",
            "description": "Prompt for reviewing an execution trace",
            "arguments": [{ "name": "run_id", "required": true }]
        }),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;

    struct DummyBackend;

    impl McpBackend for DummyBackend {
        fn call_tool(&self, name: &str, arguments: &Value) -> Result<Value> {
            Ok(json!({ "name": name, "arguments": arguments }))
        }

        fn list_resources(&self) -> Result<Vec<Value>> {
            Ok(vec![json!({"uri": "sdd://trace/root", "name": "root"})])
        }

        fn read_resource(&self, uri: &str) -> Result<McpResource> {
            Ok(McpResource {
                uri: uri.to_string(),
                mime_type: "text/plain".to_string(),
                text: "ok".to_string(),
            })
        }

        fn get_prompt(&self, name: &str, arguments: &Value) -> Result<Value> {
            Ok(json!({
                "description": name,
                "messages": [{ "role": "user", "content": { "type": "text", "text": arguments.to_string() } }]
            }))
        }
    }

    #[test]
    fn serves_jsonrpc_tools_over_lines() {
        let input = br#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sdd_trace_list","arguments":{}}}
"#;
        let mut output = Vec::new();
        serve_lines(&input[..], &mut output, &DummyBackend).unwrap();
        let text = String::from_utf8(output).unwrap();
        assert!(text.contains("\"tools\""));
        assert!(text.contains("sdd_trace_list"));
        assert!(text.contains("\"isError\":false"));
    }

    #[test]
    fn lists_prompts_and_reads_resources() {
        let input = br#"{"jsonrpc":"2.0","id":1,"method":"prompts/list","params":{}}
{"jsonrpc":"2.0","id":2,"method":"resources/read","params":{"uri":"sdd://trace/root"}}
"#;
        let mut output = Vec::new();
        serve_lines(&input[..], &mut output, &DummyBackend).unwrap();
        let text = String::from_utf8(output).unwrap();
        assert!(text.contains("sdd_orchestration"));
        assert!(text.contains("sdd://trace/root"));
    }

    #[test]
    fn exposes_runtime_adapter_metadata() {
        let adapters = runtime_adapters();
        assert!(adapters.iter().any(|adapter| adapter.id == "rmcp"));
        assert!(adapters.iter().any(|adapter| adapter.id == "rig"));

        let input = br#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}
"#;
        let mut output = Vec::new();
        serve_lines(&input[..], &mut output, &DummyBackend).unwrap();
        let text = String::from_utf8(output).unwrap();
        assert!(text.contains("sdd_runtime_adapters"));
    }

    #[cfg(feature = "mcp-rmcp")]
    #[test]
    fn builds_rmcp_server_info_when_feature_is_enabled() {
        let info = rmcp_server_info_json().unwrap().unwrap();
        assert_eq!(info["serverInfo"]["name"], "sdd-layer");
        assert!(info["capabilities"]["tools"].is_object());
        assert!(info["capabilities"]["resources"].is_object());
        assert!(info["capabilities"]["prompts"].is_object());
    }
}