stygian-plugin 0.14.1

Visual data extraction fallback subsystem with CSS/XPath selectors, idempotent request handling, and composable transformation pipelines.
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
#![allow(
    clippy::panic,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::missing_const_for_fn
)]
//! Integration tests for the HTTP transport of the stygian-plugin MCP server.
//!
//! These tests spin up the actual axum server on a random port, make real HTTP
//! requests using `reqwest`, and verify JSON-RPC 2.0 compliance end-to-end.

#![cfg(feature = "http")]
// serde_json::Value's Index impl never panics — it returns Value::Null for
// missing keys/indices.  The lint fires conservatively on all Index usage.
#![expect(
    clippy::indexing_slicing,
    reason = "serde_json::Value::index is infallible"
)]

use reqwest::Client;
use serde_json::{Value, json};
use std::net::SocketAddr;
use stygian_plugin::config::Config;
use stygian_plugin::http::{AppState, build_router};
use tokio::net::TcpListener;

type TestResult = Result<(), Box<dyn std::error::Error>>;

// ─────────────────────────────────────────────────────────────────────────────
// Test helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Bind to port 0 (OS picks a free port) and return a running server base URL.
async fn start_test_server()
-> Result<(String, tokio::task::JoinHandle<()>), Box<dyn std::error::Error>> {
    let config = Config::testing();
    let state = AppState::new(config)?;
    let app = build_router(state);

    let listener = TcpListener::bind("127.0.0.1:0").await?;
    let addr: SocketAddr = listener.local_addr()?;
    let base_url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, app).await.ok();
    });

    Ok((base_url, handle))
}

// ─────────────────────────────────────────────────────────────────────────────
// Health endpoint
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn test_health_returns_ok() -> TestResult {
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let resp = client.get(format!("{base}/health")).send().await?;

    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await?;
    assert_eq!(body["status"], "ok");
    assert_eq!(body["service"], "stygian-plugin-mcp");
    Ok(())
}

// ─────────────────────────────────────────────────────────────────────────────
// CORS headers
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn test_cors_headers_present() -> TestResult {
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    // Preflight OPTIONS
    let resp = client
        .request(reqwest::Method::OPTIONS, format!("{base}/mcp/tools/list"))
        .header(
            "Origin",
            "chrome-extension://abcdefghijklmnopqrstuvwxyz123456",
        )
        .header("Access-Control-Request-Method", "GET")
        .send()
        .await?;

    // CORS middleware should allow any origin
    let allow_origin = resp
        .headers()
        .get("access-control-allow-origin")
        .map_or("", |v| v.to_str().unwrap_or(""));
    assert!(
        allow_origin == "*" || allow_origin.contains("chrome-extension"),
        "expected CORS allow-origin, got: {allow_origin}"
    );
    Ok(())
}

// ─────────────────────────────────────────────────────────────────────────────
// tools/list
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn test_tools_list_via_get() -> TestResult {
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let resp = client.get(format!("{base}/mcp/tools/list")).send().await?;

    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await?;

    // Must be a valid JSON-RPC 2.0 response
    assert_eq!(body["jsonrpc"], "2.0");
    assert!(body["result"]["tools"].is_array(), "expected tools array");

    let tools = body["result"]["tools"]
        .as_array()
        .ok_or("expected tools to be an array")?;
    assert!(
        !tools.is_empty(),
        "expected at least one tool in the registry"
    );

    // Spot-check the mandatory tool names
    let names: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect();
    for expected in &[
        "plugin_create_template",
        "plugin_list_templates",
        "plugin_get_template",
        "plugin_delete_template",
        "plugin_apply_template",
    ] {
        assert!(
            names.contains(expected),
            "missing tool: {expected}; available: {names:?}"
        );
    }
    Ok(())
}

// ─────────────────────────────────────────────────────────────────────────────
// tools/call — via POST /mcp/tools/call
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn test_tools_call_list_templates_jsonrpc_envelope() -> TestResult {
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let req_body = json!({
        "jsonrpc": "2.0",
        "id": 42,
        "method": "tools/call",
        "params": {
            "name": "plugin_list_templates",
            "arguments": {}
        }
    });

    let resp = client
        .post(format!("{base}/mcp/tools/call"))
        .json(&req_body)
        .send()
        .await?;

    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await?;

    assert_eq!(body["jsonrpc"], "2.0");
    assert_eq!(body["id"], 42);
    assert!(body.get("error").is_none(), "unexpected error: {body}");
    assert!(body["result"].is_object() || body["result"].is_array());
    Ok(())
}

#[tokio::test]
async fn test_tools_call_bare_envelope() -> TestResult {
    // Chrome extension may send without the jsonrpc wrapper
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let payload = json!({
        "name": "plugin_list_templates",
        "arguments": {}
    });

    let resp = client
        .post(format!("{base}/mcp/tools/call"))
        .json(&payload)
        .send()
        .await?;

    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await?;
    assert_eq!(body["jsonrpc"], "2.0");
    Ok(())
}

#[tokio::test]
async fn test_tools_call_unknown_tool_returns_error() -> TestResult {
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let req_body = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "does_not_exist",
            "arguments": {}
        }
    });

    let resp = client
        .post(format!("{base}/mcp/tools/call"))
        .json(&req_body)
        .send()
        .await?;

    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await?;
    assert_eq!(body["jsonrpc"], "2.0");

    // The MCP protocol returns tool errors as `result.isError = true` content,
    // NOT as a top-level JSON-RPC `error` field.
    let is_error = body["result"]["isError"].as_bool().unwrap_or(false);
    let has_rpc_error = body.get("error").is_some();
    assert!(
        is_error || has_rpc_error,
        "expected isError=true or JSON-RPC error for unknown tool, got: {body}"
    );
    Ok(())
}

#[tokio::test]
async fn test_tools_call_missing_name_returns_400() -> TestResult {
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let req_body = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "arguments": {}
        }
        // deliberately missing "name"
    });

    let resp = client
        .post(format!("{base}/mcp/tools/call"))
        .json(&req_body)
        .send()
        .await?;

    assert_eq!(resp.status(), 400);
    let body: Value = resp.json().await?;
    assert_eq!(body["error"]["code"], -32602);
    Ok(())
}

// ─────────────────────────────────────────────────────────────────────────────
// Full JSON-RPC dispatch — POST /mcp
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn test_mcp_dispatch_initialize() -> TestResult {
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let req_body = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2025-11-25",
            "clientInfo": { "name": "test-client", "version": "0.0.1" },
            "capabilities": {}
        }
    });

    let resp = client
        .post(format!("{base}/mcp"))
        .json(&req_body)
        .send()
        .await?;

    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await?;
    assert_eq!(body["jsonrpc"], "2.0");
    assert_eq!(body["id"], 1);
    assert!(body.get("error").is_none(), "unexpected error: {body}");
    assert!(body["result"]["serverInfo"].is_object());
    Ok(())
}

#[tokio::test]
async fn test_mcp_dispatch_tools_list() -> TestResult {
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let req_body = json!({
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/list",
        "params": {}
    });

    let resp = client
        .post(format!("{base}/mcp"))
        .json(&req_body)
        .send()
        .await?;

    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await?;
    assert_eq!(body["jsonrpc"], "2.0");
    assert!(body["result"]["tools"].is_array());
    Ok(())
}

#[tokio::test]
async fn test_mcp_dispatch_notification_returns_204() -> TestResult {
    // A notification (no id field) must return 204 No Content
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let notification = json!({
        "jsonrpc": "2.0",
        "method": "notifications/initialized",
        "params": {}
        // no "id" field — this is a notification
    });

    let resp = client
        .post(format!("{base}/mcp"))
        .json(&notification)
        .send()
        .await?;

    assert_eq!(resp.status(), 204);
    Ok(())
}

#[tokio::test]
async fn test_mcp_dispatch_parse_error() -> TestResult {
    // Sending a non-JSON-RPC body (invalid structure) should return a JSON-RPC
    // parse error wrapped in HTTP 200 (since the JSON was valid, just wrong shape).
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let junk = json!({ "not": "jsonrpc", "at": "all" });

    let resp = client
        .post(format!("{base}/mcp"))
        .json(&junk)
        .send()
        .await?;

    // Handler returns Some(error_response) with HTTP 200, or None with 204.
    // Either is acceptable for garbage input.
    assert!(
        resp.status() == 200 || resp.status() == 204,
        "unexpected status: {}",
        resp.status()
    );
    Ok(())
}

// ─────────────────────────────────────────────────────────────────────────────
// JSON-RPC error codes
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn test_jsonrpc_method_not_found() -> TestResult {
    let (base, _handle) = start_test_server().await?;
    let client = Client::new();

    let req_body = json!({
        "jsonrpc": "2.0",
        "id": 99,
        "method": "bananas/eat",
        "params": {}
    });

    let resp = client
        .post(format!("{base}/mcp"))
        .json(&req_body)
        .send()
        .await?;

    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await?;
    assert_eq!(body["id"], 99);

    // Should be error code -32601 (Method not found) or similar
    let code = body["error"]["code"].as_i64();
    assert!(
        code.is_some(),
        "expected error.code in response, got: {body}"
    );
    Ok(())
}