jflib-agent-core 0.1.0

Transport-independent action contracts and bounded JSON for JFLib's agent interface
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
// MCP 2026-07-28 stateless metadata and 2025-11-25 legacy initialization adapter.
// Implemented from the public MCP transport/schema contracts; no external SDK/code.

use crate::rpc::{
    allowed, base64, control, optional_str, required_str, RpcError, RpcSession, MCP_LEGACY_VERSION,
    MCP_VERSION,
};
use crate::{
    json,
    schema::{self, Property, Schema},
    Dispatcher, Host, Value,
};
use alloc::{string::String, vec, vec::Vec};

static NAME: Schema = Schema::String {
    min: 1,
    max: 128,
    choices: &[],
};
static QUERY: Schema = Schema::String {
    min: 0,
    max: 256,
    choices: &[],
};
static LIMIT: Schema = Schema::Unsigned { min: 1, max: 100 };
static RESOURCE_LIMIT: Schema = Schema::Unsigned {
    min: 1,
    max: 65_536,
};
static SEARCH: Schema = Schema::Object {
    properties: &[
        Property {
            name: "query",
            schema: &QUERY,
            required: false,
        },
        Property {
            name: "cursor",
            schema: &NAME,
            required: false,
        },
        Property {
            name: "limit",
            schema: &LIMIT,
            required: false,
        },
    ],
    additional: false,
};
static DESCRIBE: Schema = Schema::Object {
    properties: &[Property {
        name: "action",
        schema: &NAME,
        required: true,
    }],
    additional: false,
};
static EXECUTE: Schema = Schema::Object {
    properties: &[
        Property {
            name: "action",
            schema: &NAME,
            required: true,
        },
        Property {
            name: "input",
            schema: &schema::ANY,
            required: false,
        },
        Property {
            name: "expectedRevision",
            schema: &schema::U64,
            required: false,
        },
    ],
    additional: false,
};
static CALLS: Schema = Schema::Array {
    items: &EXECUTE,
    min: 1,
    max: 128,
};
static BATCH: Schema = Schema::Object {
    properties: &[
        Property {
            name: "calls",
            schema: &CALLS,
            required: true,
        },
        Property {
            name: "atomic",
            schema: &schema::BOOLEAN,
            required: false,
        },
        Property {
            name: "stopOnError",
            schema: &schema::BOOLEAN,
            required: false,
        },
    ],
    additional: false,
};
static TASK: Schema = Schema::Object {
    properties: &[Property {
        name: "id",
        schema: &schema::U64,
        required: true,
    }],
    additional: false,
};
static RESOURCE: Schema = Schema::Object {
    properties: &[
        Property {
            name: "uri",
            schema: &schema::STRING,
            required: true,
        },
        Property {
            name: "offset",
            schema: &schema::U64,
            required: false,
        },
        Property {
            name: "limit",
            schema: &RESOURCE_LIMIT,
            required: false,
        },
    ],
    additional: false,
};

struct Tool {
    name: &'static str,
    method: &'static str,
    description: &'static str,
    schema: &'static Schema,
    read: bool,
}

const TOOLS: &[Tool] = &[
    Tool { name: "jfgui.actions.batch", method: "actions/batch", description: "Execute ordered registered actions. Atomic batches require one supported transaction domain; otherwise rejected before execution.", schema: &BATCH, read: false },
    Tool { name: "jfgui.actions.describe", method: "actions/describe", description: "Get the exact input/output schemas, availability and revision/undo/capability contract of one action.", schema: &DESCRIBE, read: true },
    Tool { name: "jfgui.actions.execute", method: "actions/execute", description: "Execute a discovered application action. Supply expectedRevision for revision-checked mutations.", schema: &EXECUTE, read: false },
    Tool { name: "jfgui.actions.search", method: "actions/list", description: "Search registered actions by name/description. Results are paginated; fetch schemas only for the actions needed.", schema: &SEARCH, read: true },
    Tool { name: "jfgui.resources.read", method: "resources/read", description: "Read a bounded chunk of an application resource as base64, using its opaque URI and byte offset.", schema: &RESOURCE, read: true },
    Tool { name: "jfgui.state.inspect", method: "state/inspect", description: "Inspect semantic app state. Query filters, pagination and sinceRevision are defined by the application's inspection contract.", schema: &schema::OBJECT, read: true },
    Tool { name: "jfgui.tasks.cancel", method: "tasks/cancel", description: "Request cancellation of an application task at its next defined safe interruption point.", schema: &TASK, read: false },
    Tool { name: "jfgui.tasks.status", method: "tasks/get", description: "Query a task by explicit identifier for progress, completion, failure or cancellation.", schema: &TASK, read: true },
    Tool { name: "jfgui.view.render", method: "view/render", description: "Invoke the registered ui.render action and receive image resource links. Describe ui.render for its exact parameters.", schema: &schema::OBJECT, read: true },
];

impl RpcSession {
    pub(crate) fn mcp_request(
        &mut self,
        dispatcher: &Dispatcher,
        host: &mut impl Host,
        method: &str,
        params: &Value,
    ) -> Result<Value, RpcError> {
        if method == "initialize"
            && params
                .get("_meta")
                .and_then(|m| m.get("io.modelcontextprotocol/protocolVersion"))
                .is_none()
        {
            if self.legacy_initialized {
                return Err(RpcError::new(
                    -32600,
                    "Legacy initialization already completed",
                ));
            }
            if params
                .get("protocolVersion")
                .and_then(Value::as_str)
                .is_none()
                || params
                    .get("capabilities")
                    .and_then(Value::as_object)
                    .is_none()
                || !valid_info(params.get("clientInfo"))
            {
                return Err(RpcError::new(
                    -32602,
                    "Invalid legacy initialization parameters",
                ));
            }
            self.legacy_initialized = true;
            return Ok(Value::object([("protocolVersion", Value::string(MCP_LEGACY_VERSION)), ("capabilities", capabilities()), ("serverInfo", self.server_info()), ("instructions", Value::string("Search actions, describe the required schema, inspect state, then execute with expectedRevision. No embedded AI is started."))]));
        }
        let modern = if let Some(meta) = params
            .get("_meta")
            .filter(|m| m.get("io.modelcontextprotocol/protocolVersion").is_some())
        {
            let Some(version) = meta
                .get("io.modelcontextprotocol/protocolVersion")
                .and_then(Value::as_str)
            else {
                return Err(RpcError::new(
                    -32602,
                    "MCP protocol version must be a string",
                ));
            };
            if version != MCP_VERSION {
                return Err(RpcError {
                    code: -32022,
                    message: String::from("Unsupported MCP protocol version"),
                    data: Value::object([
                        ("requested", Value::string(version)),
                        ("supported", Value::Array(vec![Value::string(MCP_VERSION)])),
                    ]),
                });
            }
            if meta
                .get("io.modelcontextprotocol/clientCapabilities")
                .and_then(Value::as_object)
                .is_none()
            {
                return Err(RpcError::new(
                    -32602,
                    "Per-request clientCapabilities is required",
                ));
            }
            if meta.get("io.modelcontextprotocol/clientInfo").is_some()
                && !valid_info(meta.get("io.modelcontextprotocol/clientInfo"))
            {
                return Err(RpcError::new(-32602, "Invalid per-request clientInfo"));
            }
            true
        } else {
            if !self.legacy_initialized || (!self.legacy_ready && method != "ping") {
                return Err(RpcError::new(
                    -32600,
                    "Provide modern MCP request metadata or complete legacy initialization",
                ));
            }
            false
        };
        let mut params = params.clone();
        if let Value::Object(fields) = &mut params {
            fields.retain(|(key, _)| key != "_meta");
        }
        let mut result = match method {
            "server/discover" if modern => {
                allowed(&params, &[]).map_err(RpcError::action)?;
                Value::object([("supportedVersions", Value::Array(vec![Value::string(MCP_VERSION)])), ("capabilities", capabilities()), ("ttlMs", Value::u64(0)), ("cacheScope", Value::string("private")), ("instructions", Value::string("Search semantic actions, fetch their schemas, inspect revision, then execute. Resources and tasks use explicit application-owned identifiers."))])
            }
            "ping" => {
                allowed(&params, &[]).map_err(RpcError::action)?;
                Value::object([])
            }
            "tools/list" => {
                allowed(&params, &["cursor"]).map_err(RpcError::action)?;
                let cursor = optional_str(&params, "cursor").map_err(RpcError::action)?;
                if cursor.is_some_and(|name| !TOOLS.iter().any(|t| t.name == name)) {
                    return Err(RpcError::new(-32602, "Unknown tools cursor"));
                }
                let tools: Vec<Value> = TOOLS
                    .iter()
                    .filter(|t| cursor.is_none_or(|name| t.name > name))
                    .map(|t| {
                        Value::object([
                            ("name", Value::string(t.name)),
                            ("description", Value::string(t.description)),
                            ("inputSchema", t.schema.to_json()),
                            ("outputSchema", schema::OBJECT.to_json()),
                            (
                                "annotations",
                                Value::object([
                                    ("readOnlyHint", Value::Bool(t.read)),
                                    ("openWorldHint", Value::Bool(false)),
                                ]),
                            ),
                        ])
                    })
                    .collect();
                let mut value = Value::object([("tools", Value::Array(tools))]);
                if modern {
                    value.insert("ttlMs", Value::u64(0));
                    value.insert("cacheScope", Value::string("private"));
                }
                value
            }
            "tools/call" => {
                allowed(&params, &["name", "arguments"]).map_err(RpcError::action)?;
                let name = required_str(&params, "name").map_err(RpcError::action)?;
                let Some(tool) = TOOLS.iter().find(|t| t.name == name) else {
                    return Err(RpcError::new(-32602, "Unknown tool"));
                };
                let empty = Value::object([]);
                let arguments = params.get("arguments").unwrap_or(&empty);
                let result = tool
                    .schema
                    .validate(arguments)
                    .map_err(|e| {
                        crate::ActionError::new(
                            crate::ErrorCode::InvalidInput,
                            "Tool arguments fail their schema",
                        )
                        .with_details(Value::object([
                            ("path", Value::string(e.path)),
                            ("reason", Value::string(e.reason)),
                        ]))
                    })
                    .and_then(|()| control(dispatcher, host, tool.method, arguments));
                let is_error = result.is_err();
                let data = match result {
                    Ok(value) => Value::object([("ok", Value::Bool(true)), ("data", value)]),
                    Err(error) => {
                        Value::object([("ok", Value::Bool(false)), ("error", error.to_json())])
                    }
                };
                let text = json::stringify(&data)
                    .map_err(|_| RpcError::new(-32603, "Tool result exceeds encoding limits"))?;
                Value::object([
                    (
                        "content",
                        Value::Array(vec![Value::object([
                            ("type", Value::string("text")),
                            ("text", Value::string(text)),
                        ])]),
                    ),
                    ("structuredContent", data),
                    ("isError", Value::Bool(is_error)),
                ])
            }
            "resources/list" => {
                allowed(&params, &["cursor"]).map_err(RpcError::action)?;
                if params.get("cursor").is_some() {
                    return Err(RpcError::new(
                        -32602,
                        "Resources are discovered through action results",
                    ));
                }
                Value::object([("resources", Value::Array(Vec::new()))])
            }
            "resources/templates/list" => {
                allowed(&params, &[]).map_err(RpcError::action)?;
                Value::object([("resourceTemplates", Value::Array(Vec::new()))])
            }
            "resources/read" => {
                allowed(&params, &["uri"]).map_err(RpcError::action)?;
                let uri = required_str(&params, "uri").map_err(RpcError::action)?;
                let info = host.resource_info(uri).map_err(|_| RpcError {
                    code: -32602,
                    message: "Resource not found".into(),
                    data: Value::object([("uri", Value::string(uri))]),
                })?;
                let Some(size) = info.size.filter(|size| *size <= 65_536) else {
                    return Err(RpcError::new(
                        -32602,
                        "Use jfgui.resources.read for resources above 64 KiB or of unknown size",
                    ));
                };
                let data = host
                    .resource_read(uri, 0, size as usize)
                    .map_err(RpcError::action)?;
                if data.len() != size as usize {
                    return Err(RpcError::new(-32603, "Resource changed during read"));
                }
                Value::object([(
                    "contents",
                    Value::Array(vec![Value::object([
                        ("uri", Value::string(uri)),
                        ("mimeType", Value::string(info.mime_type)),
                        ("blob", Value::string(base64(&data))),
                    ])]),
                )])
            }
            _ => return Err(RpcError::new(-32601, "Method not found")),
        };
        if modern {
            result.insert("resultType", Value::string("complete"));
            result.insert(
                "_meta",
                Value::object([("io.modelcontextprotocol/serverInfo", self.server_info())]),
            );
        }
        Ok(result)
    }
}

fn capabilities() -> Value {
    Value::object([
        (
            "tools",
            Value::object([("listChanged", Value::Bool(false))]),
        ),
        (
            "resources",
            Value::object([
                ("subscribe", Value::Bool(false)),
                ("listChanged", Value::Bool(false)),
            ]),
        ),
    ])
}
fn valid_info(value: Option<&Value>) -> bool {
    value.is_some_and(|v| {
        v.get("name")
            .and_then(Value::as_str)
            .is_some_and(|s| !s.is_empty() && s.len() <= 256)
            && v.get("version")
                .and_then(Value::as_str)
                .is_some_and(|s| !s.is_empty() && s.len() <= 256)
    })
}