atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
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
//! JSON-RPC 2.0 and MCP 2026-07-28 message types.
//!
//! This module holds the wire vocabulary: message structs, error codes, the
//! request-id key used to correlate cancellations, and the single result
//! builder every handler goes through.
//!
//! # Why there is exactly one result builder
//!
//! Every result in this revision **MUST** carry a `resultType`, and servers
//! **SHOULD** identify themselves in each result's `_meta`. Both are easy to
//! forget on a method added later, and neither is visible in a handler that
//! returns a bare payload. [`complete`] is the only way a result is
//! constructed, so a new method cannot omit them.

pub mod cancel;
pub mod discover;
pub mod meta;
pub mod progress;
pub mod serve;
pub mod subs;
pub mod writer;

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

/// The MCP protocol version this server implements.
///
/// There is exactly one. The `initialize` handshake was removed in this
/// revision, so a client that opens with it is answered with a diagnostic
/// (see [`serve`]) rather than served.
pub const PROTOCOL_VERSION: &str = "2026-07-28";

/// JSON-RPC error code for parse errors.
pub const PARSE_ERROR: i64 = -32700;

/// JSON-RPC error code for invalid requests.
pub const INVALID_REQUEST: i64 = -32600;

/// JSON-RPC error code for method not found.
pub const METHOD_NOT_FOUND: i64 = -32601;

/// JSON-RPC error code for invalid params.
///
/// This is also the code for "resource not found" and for "unknown tool" in
/// this revision.
pub const INVALID_PARAMS: i64 = -32602;

/// JSON-RPC error code for internal errors.
pub const INTERNAL_ERROR: i64 = -32603;

/// MCP error code for a protocol version this server does not implement.
///
/// Part of the `-32020`..`-32099` range the specification reserves for itself.
pub const UNSUPPORTED_PROTOCOL_VERSION: i64 = -32022;

// The 2026-07-28 revision reserves `-32002` (resource not found, used by
// 2025-11-25 and earlier) and `-32042` (URL elicitation required, 2025-11-25
// only), and forbids implementations of this revision from emitting either.
// Resource-not-found is `INVALID_PARAMS`. Do not add either constant here.

/// An incoming JSON-RPC 2.0 request or notification.
#[derive(Debug, Deserialize)]
pub struct JsonRpcMessage {
    /// Must be "2.0".
    pub jsonrpc: String,
    /// Request ID. Absent for notifications.
    ///
    /// Deserialized through [`present_or_absent`] rather than as a plain
    /// `Option`, which would fold an explicit `"id": null` into `None`. The
    /// two are different messages: an absent id is a notification, while a
    /// null id is a malformed request — the specification says the id
    /// **MUST NOT** be null — and silently answering nothing would leave the
    /// caller waiting forever for a reply that is never coming.
    #[serde(default, deserialize_with = "present_or_absent")]
    pub id: Option<Value>,
    /// Method name.
    pub method: String,
    /// Optional parameters.
    pub params: Option<Value>,
}

/// An outgoing JSON-RPC 2.0 response.
#[derive(Debug, Serialize)]
pub struct JsonRpcResponse {
    /// Always "2.0".
    pub jsonrpc: &'static str,
    /// The id of the request this answers.
    pub id: Value,
    /// The result, when the request succeeded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    /// The error, when it did not.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcError>,
}

/// An outgoing JSON-RPC 2.0 notification.
#[derive(Debug, Serialize)]
pub struct JsonRpcNotification {
    /// Always "2.0".
    pub jsonrpc: &'static str,
    /// The notification method.
    pub method: String,
    /// The notification parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<Value>,
}

/// A JSON-RPC 2.0 error object.
#[derive(Debug, Serialize)]
pub struct JsonRpcError {
    /// The error code.
    pub code: i64,
    /// A human-readable message.
    pub message: String,
    /// Structured detail, such as the URI a resource error concerns.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

/// Distinguish a field that is absent from one that is present and null.
fn present_or_absent<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Value::deserialize(deserializer).map(Some)
}

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

    /// Create an error response.
    #[must_use]
    pub fn error(id: Value, code: i64, message: impl Into<String>) -> Self {
        Self {
            jsonrpc: "2.0",
            id,
            result: None,
            error: Some(JsonRpcError {
                code,
                message: message.into(),
                data: None,
            }),
        }
    }

    /// Create an error response carrying structured detail.
    #[must_use]
    pub fn error_with_data(id: Value, code: i64, message: impl Into<String>, data: Value) -> Self {
        Self {
            jsonrpc: "2.0",
            id,
            result: None,
            error: Some(JsonRpcError {
                code,
                message: message.into(),
                data: Some(data),
            }),
        }
    }
}

impl JsonRpcNotification {
    /// Create a notification.
    #[must_use]
    pub fn new(method: impl Into<String>, params: Value) -> Self {
        Self {
            jsonrpc: "2.0",
            method: method.into(),
            params: Some(params),
        }
    }
}

/// A JSON-RPC request id, normalized so cancellation lookups cannot
/// mis-compare.
///
/// JSON-RPC ids may be a string or an integer, and `notifications/cancelled`
/// carries `requestId` in the same shape. Id `1` and id `"1"` are therefore
/// *different requests*, and a `to_string()` normalization would silently
/// conflate them. The specification also forbids a null id.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum RequestKey {
    /// An integer id.
    Num(i64),
    /// A string id.
    Str(String),
}

impl RequestKey {
    /// Build a key from a JSON value, rejecting anything that is not a string
    /// or an integer.
    #[must_use]
    pub fn from_value(value: &Value) -> Option<Self> {
        match value {
            Value::Number(n) => n.as_i64().map(Self::Num),
            Value::String(s) => Some(Self::Str(s.clone())),
            _ => None,
        }
    }

    /// Render the key back as the JSON value it came from.
    #[must_use]
    pub fn to_value(&self) -> Value {
        match self {
            Self::Num(n) => Value::Number((*n).into()),
            Self::Str(s) => Value::String(s.clone()),
        }
    }
}

/// Who may cache a result, and for how long.
#[derive(Clone, Copy, Debug)]
pub struct CacheHints {
    /// Freshness hint in milliseconds. Must be `>= 0`; zero means
    /// immediately stale.
    pub ttl_ms: u64,
    /// Whether a shared cache may serve this result to another caller.
    pub scope: CacheScope,
}

/// The `cacheScope` of a result.
#[derive(Clone, Copy, Debug)]
pub enum CacheScope {
    /// No user-specific data; any cache may store and share it.
    Public,
    /// Reusable only within the same authorization context.
    ///
    /// Nothing emits this yet: every resource this server serves lives in the
    /// unauthenticated `atpmcp://public/` namespace. It is the scope an
    /// authenticated read would carry, and naming it here is what keeps the
    /// distinction visible to whoever adds one.
    #[expect(
        dead_code,
        reason = "no authenticated resource yet; fires when one emits this scope"
    )]
    Private,
}

impl CacheScope {
    /// The wire spelling.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Public => "public",
            Self::Private => "private",
        }
    }
}

impl CacheHints {
    /// Hints for a result that is constant for the life of the process.
    #[must_use]
    pub const fn constant() -> Self {
        Self {
            ttl_ms: 3_600_000,
            scope: CacheScope::Public,
        }
    }

    /// Hints for a content-addressed read.
    ///
    /// A day, not forever: the URI names a CID and a CID is a hash, so the
    /// content behind it cannot change. The bound exists because the blob can
    /// be *deleted* or taken down upstream, not because it can differ.
    #[must_use]
    pub const fn immutable_content() -> Self {
        Self {
            ttl_ms: 86_400_000,
            scope: CacheScope::Public,
        }
    }

    /// Hints for a short-lived list.
    #[must_use]
    pub const fn short_list() -> Self {
        Self {
            ttl_ms: 60_000,
            scope: CacheScope::Public,
        }
    }
}

/// Build a `resultType: "complete"` result.
///
/// `payload` must be a JSON object; anything else is a programming error and
/// is wrapped under a `value` key rather than panicking, so a malformed
/// handler degrades instead of taking the process down.
#[must_use]
pub fn complete(payload: Value, hints: Option<CacheHints>, server_info: &Value) -> Value {
    let mut object = match payload {
        Value::Object(map) => map,
        other => {
            let mut map = serde_json::Map::new();
            map.insert("value".to_string(), other);
            map
        }
    };

    object.insert(
        "resultType".to_string(),
        Value::String("complete".to_string()),
    );

    if let Some(hints) = hints {
        object.insert("ttlMs".to_string(), Value::Number(hints.ttl_ms.into()));
        object.insert(
            "cacheScope".to_string(),
            Value::String(hints.scope.as_str().to_string()),
        );
    }

    // Merged, not replaced: a payload may already carry `_meta` of its own —
    // the graceful subscription closure puts `subscriptionId` there — and
    // overwriting it would silently drop the field a client correlates on.
    match object.get_mut("_meta") {
        Some(Value::Object(existing)) => {
            existing.insert(meta::KEY_SERVER_INFO.to_string(), server_info.clone());
        }
        _ => {
            object.insert(
                "_meta".to_string(),
                serde_json::json!({ meta::KEY_SERVER_INFO: server_info }),
            );
        }
    }

    Value::Object(object)
}

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

    #[test]
    fn request_key_distinguishes_string_from_number() {
        let numeric = RequestKey::from_value(&serde_json::json!(1)).unwrap();
        let textual = RequestKey::from_value(&serde_json::json!("1")).unwrap();
        assert_ne!(numeric, textual);
    }

    #[test]
    fn request_key_rejects_null_and_composite_ids() {
        assert!(RequestKey::from_value(&Value::Null).is_none());
        assert!(RequestKey::from_value(&serde_json::json!([1])).is_none());
        assert!(RequestKey::from_value(&serde_json::json!({})).is_none());
    }

    #[test]
    fn request_key_round_trips() {
        for value in [serde_json::json!(7), serde_json::json!("abc")] {
            let key = RequestKey::from_value(&value).unwrap();
            assert_eq!(key.to_value(), value);
        }
    }

    #[test]
    fn complete_always_stamps_result_type_and_server_info() {
        let info = serde_json::json!({ "name": "atpmcp", "version": "1" });
        let result = complete(serde_json::json!({ "tools": [] }), None, &info);
        assert_eq!(result["resultType"], "complete");
        assert_eq!(result["_meta"]["io.modelcontextprotocol/serverInfo"], info);
        assert!(result.get("ttlMs").is_none());
        assert!(result.get("cacheScope").is_none());
    }

    #[test]
    fn complete_preserves_meta_the_payload_already_carries() {
        let info = serde_json::json!({ "name": "atpmcp" });
        let payload = serde_json::json!({
            "_meta": { "io.modelcontextprotocol/subscriptionId": 7 }
        });
        let result = complete(payload, None, &info);
        assert_eq!(result["_meta"]["io.modelcontextprotocol/subscriptionId"], 7);
        assert_eq!(result["_meta"][meta::KEY_SERVER_INFO], info);
    }

    #[test]
    fn complete_emits_cache_hints_when_given() {
        let info = serde_json::json!({ "name": "atpmcp" });
        let result = complete(
            serde_json::json!({ "resources": [] }),
            Some(CacheHints::constant()),
            &info,
        );
        assert_eq!(result["ttlMs"], 3_600_000);
        assert_eq!(result["cacheScope"], "public");
    }

    #[test]
    fn cache_hint_ttls_are_non_negative() {
        // The specification requires `ttlMs >= 0`; the type makes it so, but a
        // future edit could pick a signed type, and this pins the intent.
        for hints in [
            CacheHints::constant(),
            CacheHints::immutable_content(),
            CacheHints::short_list(),
        ] {
            assert!(hints.ttl_ms > 0);
        }
    }
}