axterminator 0.7.1

macOS GUI testing framework with background testing, sub-millisecond element access, and self-healing locators
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
//! MCP 2025-11-05 protocol types.
//!
//! Covers the wire types for Phase 1 and Phase 2:
//! - `initialize` handshake with resources + prompts capabilities
//! - `tools/list` and `tools/call`
//! - `resources/list`, `resources/templates/list`, and `resources/read`
//! - `prompts/list` and `prompts/get`
//!
//! All types derive `serde::{Serialize, Deserialize}` so they round-trip
//! cleanly through `serde_json`.
//!
//! ## Adding new capabilities
//!
//! Extend [`ServerCapabilities`] and add the corresponding request/result
//! types following the existing pattern. Wire the method in `server.rs`.

use serde::{Deserialize, Serialize};
use serde_json::Value;

// ---------------------------------------------------------------------------
// JSON-RPC 2.0 envelope
// ---------------------------------------------------------------------------

/// A JSON-RPC 2.0 request (server receives from client).
#[derive(Debug, Deserialize)]
pub struct JsonRpcRequest {
    pub jsonrpc: String,
    #[serde(default)]
    pub id: Option<RequestId>,
    pub method: String,
    #[serde(default)]
    pub params: Option<Value>,
}

/// A JSON-RPC 2.0 response (server sends to client).
#[derive(Debug, Serialize)]
pub struct JsonRpcResponse {
    pub jsonrpc: &'static str,
    pub id: RequestId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<RpcError>,
}

/// A JSON-RPC 2.0 notification (server sends to client, no id).
#[derive(Debug, Serialize)]
pub struct JsonRpcNotification {
    pub jsonrpc: &'static str,
    pub method: &'static str,
    pub params: Value,
}

/// JSON-RPC request identifier — either a number or a string.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RequestId {
    Number(i64),
    String(String),
}

/// JSON-RPC error object.
#[derive(Debug, Serialize)]
pub struct RpcError {
    pub code: i32,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

impl RpcError {
    pub const PARSE_ERROR: i32 = -32_700;
    pub const INVALID_REQUEST: i32 = -32_600;
    pub const METHOD_NOT_FOUND: i32 = -32_601;
    pub const INVALID_PARAMS: i32 = -32_602;
    pub const INTERNAL_ERROR: i32 = -32_603;

    /// Convenience constructor.
    #[must_use]
    pub fn new(code: i32, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            data: None,
        }
    }
}

impl JsonRpcResponse {
    /// Build a successful response.
    #[must_use]
    pub fn ok(id: RequestId, result: Value) -> Self {
        Self {
            jsonrpc: "2.0",
            id,
            result: Some(result),
            error: None,
        }
    }

    /// Build an error response.
    #[must_use]
    pub fn err(id: RequestId, error: RpcError) -> Self {
        Self {
            jsonrpc: "2.0",
            id,
            result: None,
            error: Some(error),
        }
    }
}

// ---------------------------------------------------------------------------
// MCP initialize
// ---------------------------------------------------------------------------

/// Client sends this in `params` of the `initialize` request.
#[derive(Debug, Deserialize)]
pub struct InitializeParams {
    #[serde(rename = "protocolVersion")]
    pub protocol_version: String,
    pub capabilities: ClientCapabilities,
    #[serde(rename = "clientInfo")]
    pub client_info: ClientInfo,
}

/// Subset of client capabilities we inspect.
#[derive(Debug, Default, Deserialize)]
pub struct ClientCapabilities {
    pub roots: Option<Value>,
    pub sampling: Option<Value>,
    pub elicitation: Option<Value>,
}

impl ClientCapabilities {
    /// Returns `true` when the client advertised elicitation support.
    ///
    /// MCP clients that support `elicitation/create` include the `elicitation`
    /// key in their capabilities object (value may be an empty object `{}`).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serde_json::json;
    /// use axterminator::mcp::protocol::ClientCapabilities;
    ///
    /// let mut caps = ClientCapabilities::default();
    /// assert!(!caps.supports_elicitation());
    ///
    /// caps.elicitation = Some(json!({}));
    /// assert!(caps.supports_elicitation());
    /// ```
    #[must_use]
    pub fn supports_elicitation(&self) -> bool {
        self.elicitation.is_some()
    }

    /// Returns `true` when the client advertised sampling support.
    #[must_use]
    pub fn supports_sampling(&self) -> bool {
        self.sampling.is_some()
    }
}

/// Client identity (name + version).
#[derive(Debug, Deserialize)]
pub struct ClientInfo {
    pub name: String,
    pub version: String,
}

/// Server sends this as `result` of the `initialize` response.
#[derive(Debug, Serialize)]
pub struct InitializeResult {
    #[serde(rename = "protocolVersion")]
    pub protocol_version: &'static str,
    pub capabilities: ServerCapabilities,
    #[serde(rename = "serverInfo")]
    pub server_info: ServerInfo,
    pub instructions: &'static str,
}

/// Capabilities the server advertises in the `initialize` response.
///
/// Phase 2 adds `resources` and `prompts` alongside the existing `tools`
/// and `logging` capabilities.
///
/// Phase 4 adds `elicitation` — the server can ask the user questions
/// mid-operation via `elicitation/create`.
///
/// The `experimental` field carries non-standard capabilities such as
/// `claude/channel` for push notifications to Claude Code sessions.
#[derive(Debug, Serialize)]
pub struct ServerCapabilities {
    pub tools: ToolsCapability,
    pub logging: LoggingCapability,
    pub resources: ResourcesCapability,
    pub prompts: PromptsCapability,
    pub elicitation: ElicitationCapability,
    /// Experimental capabilities map.  Present only when the `watch` feature
    /// is enabled; omitted entirely otherwise.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub experimental: Option<Value>,
}

/// Elicitation capability advertised in `initialize`.
///
/// Presence signals that the server may send `elicitation/create` requests.
/// The value is an empty object per the MCP 2025-11-05 spec.
#[derive(Debug, Serialize)]
pub struct ElicitationCapability {}

/// Tool list capability.
#[derive(Debug, Serialize)]
pub struct ToolsCapability {
    #[serde(rename = "listChanged")]
    pub list_changed: bool,
}

/// Logging capability (empty — presence signals support).
#[derive(Debug, Serialize)]
pub struct LoggingCapability {}

/// Resource capability advertised in `initialize`.
///
/// `subscribe: false` — Phase 2 provides static read access only.
/// Reactive subscriptions are a Phase 3 feature.
#[derive(Debug, Serialize)]
pub struct ResourcesCapability {
    pub subscribe: bool,
    #[serde(rename = "listChanged")]
    pub list_changed: bool,
}

/// Prompt capability advertised in `initialize`.
#[derive(Debug, Serialize)]
pub struct PromptsCapability {
    #[serde(rename = "listChanged")]
    pub list_changed: bool,
}

/// Server identity.
#[derive(Debug, Serialize)]
pub struct ServerInfo {
    pub name: &'static str,
    pub version: &'static str,
    pub title: &'static str,
}

// ---------------------------------------------------------------------------
// MCP tools
// ---------------------------------------------------------------------------

/// A single tool descriptor returned by `tools/list`.
#[derive(Debug, Clone, Serialize)]
pub struct Tool {
    pub name: &'static str,
    pub title: &'static str,
    pub description: &'static str,
    #[serde(rename = "inputSchema")]
    pub input_schema: Value,
    #[serde(rename = "outputSchema")]
    pub output_schema: Value,
    pub annotations: ToolAnnotations,
}

/// Semantic hints for MCP clients (MCP 2025-11-05 §6.3).
///
/// These four boolean fields are a direct serialisation of the MCP wire format —
/// each maps to a distinct JSON property. Refactoring into an enum would break
/// the protocol contract.
#[derive(Debug, Clone, Serialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct ToolAnnotations {
    /// True if the tool never mutates state.
    #[serde(rename = "readOnlyHint")]
    pub read_only: bool,
    /// True if the action cannot be undone.
    #[serde(rename = "destructiveHint")]
    pub destructive: bool,
    /// True if calling multiple times has the same effect as once.
    #[serde(rename = "idempotentHint")]
    pub idempotent: bool,
    /// True if the tool may interact with external services.
    #[serde(rename = "openWorldHint")]
    pub open_world: bool,
}

/// `tools/list` result.
#[derive(Debug, Serialize)]
pub struct ToolListResult {
    pub tools: Vec<Tool>,
}

/// `tools/call` params.
#[derive(Debug, Deserialize)]
pub struct ToolCallParams {
    pub name: String,
    #[serde(default)]
    pub arguments: Option<Value>,
}

/// A single content item returned by `tools/call`.
#[derive(Debug, Serialize)]
pub struct ContentItem {
    #[serde(rename = "type")]
    pub kind: &'static str,
    pub text: String,
}

impl ContentItem {
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            kind: "text",
            text: text.into(),
        }
    }
}

/// `tools/call` result.
#[derive(Debug, Serialize)]
pub struct ToolCallResult {
    pub content: Vec<ContentItem>,
    #[serde(rename = "isError")]
    pub is_error: bool,
}

impl ToolCallResult {
    #[must_use]
    pub fn ok(text: impl Into<String>) -> Self {
        Self {
            content: vec![ContentItem::text(text)],
            is_error: false,
        }
    }

    #[must_use]
    pub fn error(text: impl Into<String>) -> Self {
        Self {
            content: vec![ContentItem::text(text)],
            is_error: true,
        }
    }
}

// ---------------------------------------------------------------------------
// MCP ping
// ---------------------------------------------------------------------------

/// `ping` result — empty object per spec.
#[derive(Debug, Serialize)]
pub struct PingResult {}

// ---------------------------------------------------------------------------
// MCP resources — Phase 2
// ---------------------------------------------------------------------------

/// A single resource descriptor returned by `resources/list`.
///
/// Static resources have a concrete `uri`; dynamic resources use
/// `uri_template` (RFC 6570) and appear in `resources/templates/list`.
#[derive(Debug, Clone, Serialize)]
pub struct Resource {
    pub uri: &'static str,
    pub name: &'static str,
    pub title: &'static str,
    pub description: &'static str,
    #[serde(rename = "mimeType")]
    pub mime_type: &'static str,
}

/// A URI template descriptor returned by `resources/templates/list`.
#[derive(Debug, Clone, Serialize)]
pub struct ResourceTemplate {
    #[serde(rename = "uriTemplate")]
    pub uri_template: &'static str,
    pub name: &'static str,
    pub title: &'static str,
    pub description: &'static str,
    #[serde(rename = "mimeType")]
    pub mime_type: &'static str,
}

/// `resources/list` result.
#[derive(Debug, Serialize)]
pub struct ResourceListResult {
    pub resources: Vec<Resource>,
}

/// `resources/templates/list` result.
#[derive(Debug, Serialize)]
pub struct ResourceTemplateListResult {
    #[serde(rename = "resourceTemplates")]
    pub resource_templates: Vec<ResourceTemplate>,
}

/// `resources/read` params.
#[derive(Debug, Deserialize)]
pub struct ResourceReadParams {
    pub uri: String,
}

/// A single resource content item (text or blob).
///
/// Text resources carry UTF-8 JSON in `text`.
/// Binary resources (e.g., PNG screenshots) carry base64 in `blob`.
#[derive(Debug, Serialize)]
pub struct ResourceContents {
    pub uri: String,
    #[serde(rename = "mimeType")]
    pub mime_type: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blob: Option<String>,
}

impl ResourceContents {
    /// Build a text/JSON resource content item.
    #[must_use]
    pub fn text(uri: impl Into<String>, mime_type: &'static str, text: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            mime_type,
            text: Some(text.into()),
            blob: None,
        }
    }

    /// Build a binary (base64) resource content item.
    #[must_use]
    pub fn blob(uri: impl Into<String>, mime_type: &'static str, blob: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            mime_type,
            text: None,
            blob: Some(blob.into()),
        }
    }
}

/// `resources/read` result.
#[derive(Debug, Serialize)]
pub struct ResourceReadResult {
    pub contents: Vec<ResourceContents>,
}

// ---------------------------------------------------------------------------
// MCP prompts — Phase 2
// ---------------------------------------------------------------------------

/// A single prompt descriptor returned by `prompts/list`.
#[derive(Debug, Clone, Serialize)]
pub struct Prompt {
    pub name: &'static str,
    pub title: &'static str,
    pub description: &'static str,
    pub arguments: Vec<PromptArgument>,
}

/// One argument declared by a prompt.
#[derive(Debug, Clone, Serialize)]
pub struct PromptArgument {
    pub name: &'static str,
    pub description: &'static str,
    pub required: bool,
}

/// `prompts/list` result.
#[derive(Debug, Serialize)]
pub struct PromptListResult {
    pub prompts: Vec<Prompt>,
}

/// `prompts/get` params.
#[derive(Debug, Deserialize)]
pub struct PromptGetParams {
    pub name: String,
    #[serde(default)]
    pub arguments: Option<serde_json::Map<String, serde_json::Value>>,
}

/// Role of a prompt message (MCP spec: "user" | "assistant").
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PromptRole {
    User,
    Assistant,
}

/// A single message in a prompt result.
#[derive(Debug, Serialize)]
pub struct PromptMessage {
    pub role: PromptRole,
    pub content: PromptContent,
}

/// Content of a prompt message (text only for Phase 2).
#[derive(Debug, Serialize)]
pub struct PromptContent {
    #[serde(rename = "type")]
    pub kind: &'static str,
    pub text: String,
}

impl PromptContent {
    /// Build a plain-text prompt content item.
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            kind: "text",
            text: text.into(),
        }
    }
}

/// `prompts/get` result.
#[derive(Debug, Serialize)]
pub struct PromptGetResult {
    pub description: String,
    pub messages: Vec<PromptMessage>,
}

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

    #[test]
    fn request_id_round_trips_number() {
        // GIVEN: numeric request id
        let id = RequestId::Number(42);
        // WHEN: serialised
        let json = serde_json::to_string(&id).unwrap();
        // THEN: bare number
        assert_eq!(json, "42");
    }

    #[test]
    fn request_id_round_trips_string() {
        // GIVEN: string request id
        let id = RequestId::String("abc".into());
        // WHEN: serialised
        let json = serde_json::to_string(&id).unwrap();
        // THEN: quoted string
        assert_eq!(json, r#""abc""#);
    }

    #[test]
    fn rpc_response_ok_omits_error_field() {
        // GIVEN: success response
        let resp = JsonRpcResponse::ok(RequestId::Number(1), json!({"status": "ok"}));
        // WHEN: serialised
        let v: Value = serde_json::to_value(&resp).unwrap();
        // THEN: no error key
        assert!(v.get("error").is_none());
        assert_eq!(v["result"]["status"], "ok");
    }

    #[test]
    fn rpc_response_err_omits_result_field() {
        // GIVEN: error response
        let resp = JsonRpcResponse::err(
            RequestId::Number(1),
            RpcError::new(RpcError::METHOD_NOT_FOUND, "not found"),
        );
        // WHEN: serialised
        let v: Value = serde_json::to_value(&resp).unwrap();
        // THEN: no result key
        assert!(v.get("result").is_none());
        assert_eq!(v["error"]["code"], RpcError::METHOD_NOT_FOUND);
    }

    #[test]
    fn tool_call_result_ok_is_not_error() {
        let r = ToolCallResult::ok("done");
        assert!(!r.is_error);
        assert_eq!(r.content[0].text, "done");
    }

    #[test]
    fn tool_call_result_error_is_error() {
        let r = ToolCallResult::error("boom");
        assert!(r.is_error);
        assert_eq!(r.content[0].text, "boom");
    }

    #[test]
    fn rpc_error_codes_are_correct_jsonrpc_values() {
        assert_eq!(RpcError::PARSE_ERROR, -32_700);
        assert_eq!(RpcError::METHOD_NOT_FOUND, -32_601);
    }

    // -----------------------------------------------------------------------
    // ClientCapabilities helpers
    // -----------------------------------------------------------------------

    #[test]
    fn supports_elicitation_false_by_default() {
        // GIVEN: empty capabilities
        let caps = ClientCapabilities::default();
        // THEN: elicitation not supported
        assert!(!caps.supports_elicitation());
    }

    #[test]
    fn supports_elicitation_true_when_set() {
        // GIVEN: capabilities with elicitation key
        let mut caps = ClientCapabilities::default();
        caps.elicitation = Some(json!({}));
        // THEN: elicitation supported
        assert!(caps.supports_elicitation());
    }

    #[test]
    fn supports_sampling_false_by_default() {
        let caps = ClientCapabilities::default();
        assert!(!caps.supports_sampling());
    }

    #[test]
    fn supports_sampling_true_when_set() {
        let mut caps = ClientCapabilities::default();
        caps.sampling = Some(json!({"createMessage": {}}));
        assert!(caps.supports_sampling());
    }
}