greentic-aw-runtime 1.2.0

Enterprise Agentic Worker runtime — Plan-Act-Observe loop, Redis state, tool dispatch via greentic-ext-runtime
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
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
//! Catalog-building, role filtering, TTL cache, and allowed-tools tests.

#![allow(clippy::unwrap_used, clippy::expect_used)]

use std::sync::Arc;

use serde_json::json;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use crate::mcp_source::source::{McpToolSource, dispatch_route};
use crate::mcp_source::types::{MCP_ROLE_AGENTIC_WORKER, MCP_ROLE_FLOW_EDITOR, McpCallerIdentity};
use crate::tenant::TenantContext;

// --- Shared helpers ---

pub(super) fn initialize_ok() -> ResponseTemplate {
    ResponseTemplate::new(200)
        .insert_header("Mcp-Session-Id", "sess-1")
        .set_body_json(json!({
            "jsonrpc": "2.0", "id": 1,
            "result": {
                "protocolVersion": "2025-06-18",
                "serverInfo": { "name": "fake", "version": "1.0.0" }
            }
        }))
}

/// Mount the 4-call MCP JSON-RPC contract on a fresh wiremock server.
pub(super) async fn fake_mcp_server(
    tools_json: serde_json::Value,
    call_result_json: serde_json::Value,
) -> MockServer {
    use wiremock::matchers::body_partial_json;

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(body_partial_json(json!({ "method": "initialize" })))
        .respond_with(initialize_ok())
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(
            json!({ "method": "notifications/initialized" }),
        ))
        .respond_with(ResponseTemplate::new(202))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(json!({ "method": "tools/list" })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 2,
            "result": { "tools": tools_json }
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(json!({ "method": "tools/call" })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 3,
            "result": call_result_json
        })))
        .mount(&server)
        .await;
    server
}

pub(super) fn two_tools() -> serde_json::Value {
    json!([
        { "name": "get_issue", "description": "Get an issue",
          "inputSchema": { "type": "object", "properties": { "id": { "type": "string" } } } },
        { "name": "search_code", "description": "Search code",
          "inputSchema": { "type": "object" } }
    ])
}

/// Build a `{servers:[...]}` admin body for one agentic-worker server.
pub(super) fn admin_body_agentic(
    id: &str,
    url: &str,
    allowed: Option<Vec<&str>>,
    roles: Vec<&str>,
) -> serde_json::Value {
    json!({
        "servers": [
            {
                "id": id,
                "name": "Server",
                "transport_url": url,
                "auth_header_name": null,
                "auth_token": null,
                "allowed_tools": allowed.map(|v| v.into_iter().collect::<Vec<_>>()),
                "roles": roles,
            }
        ]
    })
}

/// Mount the admin `mcp-servers` endpoint returning `body`.
pub(super) async fn mount_admin(server: &MockServer, body: serde_json::Value) {
    Mock::given(method("GET"))
        .and(path("/api/v1/designer/tenant/me/mcp-servers"))
        .and(header("authorization", "Bearer gtc_live_x"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(server)
        .await;
}

pub(super) fn tenant() -> TenantContext {
    TenantContext::new("acme", "prod")
}

// --- Tests ---

#[tokio::test]
async fn source_fetches_and_filters_agentic_worker() {
    // One agentic_worker server (→ fake MCP) and one flow_editor server.
    let mcp = fake_mcp_server(two_tools(), json!({})).await;
    let admin = MockServer::start().await;
    let body = json!({
        "servers": [
            {
                "id": "worker", "name": "Worker", "transport_url": mcp.uri(),
                "auth_header_name": null, "auth_token": null,
                "allowed_tools": null, "roles": ["agentic_worker"]
            },
            {
                "id": "editor", "name": "Editor", "transport_url": "http://127.0.0.1:1/",
                "auth_header_name": null, "auth_token": null,
                "allowed_tools": null, "roles": ["flow_editor"]
            }
        ]
    });
    mount_admin(&admin, body).await;

    let source = McpToolSource::new(admin.uri(), "gtc_live_x");
    let catalog = source.catalog(&tenant()).await;

    // Only the agentic_worker server's two tools land.
    assert_eq!(catalog.len(), 2);
    assert!(catalog.tool_entry("worker", "get_issue").is_some());
    assert!(catalog.tool_entry("worker", "search_code").is_some());
    // The flow_editor server is never probed/ingested.
    assert!(catalog.tool_entry("editor", "get_issue").is_none());
}

#[tokio::test]
async fn catalog_for_role_filters_flow_editor() {
    // One flow_editor server (→ fake MCP) and one agentic_worker server.
    let mcp = fake_mcp_server(two_tools(), json!({})).await;
    let admin = MockServer::start().await;
    let body = json!({
        "servers": [
            {
                "id": "editor", "name": "Editor", "transport_url": mcp.uri(),
                "auth_header_name": null, "auth_token": null,
                "allowed_tools": null, "roles": ["flow_editor"]
            },
            {
                "id": "worker", "name": "Worker", "transport_url": "http://127.0.0.1:1/",
                "auth_header_name": null, "auth_token": null,
                "allowed_tools": null, "roles": ["agentic_worker"]
            }
        ]
    });
    mount_admin(&admin, body).await;

    let source = McpToolSource::new(admin.uri(), "gtc_live_x");
    let catalog = source
        .catalog_for_role(&tenant(), MCP_ROLE_FLOW_EDITOR)
        .await;

    // Only the flow_editor server's two tools land.
    assert_eq!(catalog.len(), 2);
    assert!(catalog.tool_entry("editor", "get_issue").is_some());
    assert!(catalog.tool_entry("editor", "search_code").is_some());
    // The agentic_worker server is never probed/ingested for this role.
    assert!(catalog.tool_entry("worker", "get_issue").is_none());
}

#[tokio::test]
async fn role_catalogs_are_cached_independently() {
    // Same admin exposes one server per role at distinct fake MCP servers;
    // the per-role cache keys must not collide.
    let editor_mcp = fake_mcp_server(two_tools(), json!({})).await;
    let admin = MockServer::start().await;
    let body = json!({
        "servers": [
            {
                "id": "editor", "name": "Editor", "transport_url": editor_mcp.uri(),
                "auth_header_name": null, "auth_token": null,
                "allowed_tools": null, "roles": ["flow_editor"]
            },
            {
                "id": "worker", "name": "Worker", "transport_url": "http://127.0.0.1:1/",
                "auth_header_name": null, "auth_token": null,
                "allowed_tools": null, "roles": ["agentic_worker"]
            }
        ]
    });
    mount_admin(&admin, body).await;

    let source = McpToolSource::new(admin.uri(), "gtc_live_x");
    let t = tenant();
    let editor = source.catalog_for_role(&t, MCP_ROLE_FLOW_EDITOR).await;
    let worker = source.catalog_for_role(&t, MCP_ROLE_AGENTIC_WORKER).await;
    // Distinct cache entries: flow-editor has tools, agentic-worker's dead
    // server yields none — proving the keys did not alias.
    assert_eq!(editor.len(), 2);
    assert_eq!(worker.len(), 0);
    assert!(!Arc::ptr_eq(&editor, &worker));
}

#[tokio::test]
async fn catalog_applies_allowed_tools() {
    let mcp = fake_mcp_server(two_tools(), json!({})).await;
    let admin = MockServer::start().await;
    mount_admin(
        &admin,
        admin_body_agentic(
            "s1",
            &mcp.uri(),
            Some(vec!["get_issue"]),
            vec!["agentic_worker"],
        ),
    )
    .await;

    let source = McpToolSource::new(admin.uri(), "gtc_live_x");
    let catalog = source.catalog(&tenant()).await;

    assert_eq!(catalog.len(), 1);
    assert!(catalog.tool_entry("s1", "get_issue").is_some());
    assert!(catalog.tool_entry("s1", "search_code").is_none());
}

#[tokio::test]
async fn unreachable_server_degrades() {
    let admin = MockServer::start().await;
    mount_admin(
        &admin,
        admin_body_agentic("s1", "http://127.0.0.1:1/", None, vec!["agentic_worker"]),
    )
    .await;

    let source = McpToolSource::new(admin.uri(), "gtc_live_x");
    // Must not panic and must return a catalog (with no tools for the
    // dead server).
    let catalog = source.catalog(&tenant()).await;
    assert_eq!(catalog.len(), 0);
    assert!(catalog.is_empty());
}

#[tokio::test]
async fn admin_unreachable_degrades_to_empty() {
    let admin = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/designer/tenant/me/mcp-servers"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&admin)
        .await;

    let source = McpToolSource::new(admin.uri(), "gtc_live_x");
    let catalog = source.catalog(&tenant()).await;
    assert!(catalog.is_empty());
}

#[tokio::test]
async fn ttl_cache_reuses_within_window() {
    let mcp = fake_mcp_server(two_tools(), json!({})).await;
    let admin = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/designer/tenant/me/mcp-servers"))
        .and(header("authorization", "Bearer gtc_live_x"))
        .respond_with(ResponseTemplate::new(200).set_body_json(admin_body_agentic(
            "s1",
            &mcp.uri(),
            None,
            vec!["agentic_worker"],
        )))
        .expect(1) // second call must hit the TTL cache
        .mount(&admin)
        .await;

    let source = McpToolSource::new(admin.uri(), "gtc_live_x");
    let t = tenant();
    let first = source.catalog(&t).await;
    let second = source.catalog(&t).await;
    assert!(Arc::ptr_eq(&first, &second));
}

#[tokio::test]
async fn dispatch_route_calls_server_and_wraps() {
    // Success: fake returns structuredContent.
    let mcp = fake_mcp_server(two_tools(), json!({ "structuredContent": { "ok": 1 } })).await;
    let admin = MockServer::start().await;
    mount_admin(
        &admin,
        admin_body_agentic(
            "s1",
            &mcp.uri(),
            Some(vec!["get_issue"]),
            vec!["agentic_worker"],
        ),
    )
    .await;

    let source = McpToolSource::new(admin.uri(), "gtc_live_x");
    let catalog = source.catalog(&tenant()).await;
    let route = catalog.route("s1", "get_issue").expect("route present");

    let scope = crate::mcp_scope::McpCallScope::new(TenantContext::new("acme", "prod"));
    let out = dispatch_route(route, "{}", &scope).await;
    // `ToolOutput::to_value` unwraps `structuredContent`, so the value is
    // the server's structured payload itself.
    assert_eq!(out, json!({ "ok": 1 }), "got: {out}");
    assert!(!out.to_string().contains("\"error\""), "got: {out}");

    // isError: fake returns an error envelope → Value contains "error".
    let mcp_err = fake_mcp_server(
        two_tools(),
        json!({ "isError": true, "content": [{ "type": "text", "text": "boom" }] }),
    )
    .await;
    let admin_err = MockServer::start().await;
    mount_admin(
        &admin_err,
        admin_body_agentic(
            "s1",
            &mcp_err.uri(),
            Some(vec!["get_issue"]),
            vec!["agentic_worker"],
        ),
    )
    .await;
    let source_err = McpToolSource::new(admin_err.uri(), "gtc_live_x");
    let catalog_err = source_err.catalog(&TenantContext::new("acme", "stg")).await;
    let route_err = catalog_err.route("s1", "get_issue").expect("route present");
    let scope_err = crate::mcp_scope::McpCallScope::new(TenantContext::new("acme", "prod"));
    let out_err = dispatch_route(route_err, "{}", &scope_err).await;
    assert!(out_err.to_string().contains("error"), "got: {out_err}");
}

#[test]
fn source_carries_secrets_into_its_catalog() {
    use crate::mcp_source::source::McpToolSource;
    use async_trait::async_trait;
    use std::sync::Arc;

    struct FakeSecrets;
    #[async_trait]
    impl greentic_secrets_lib::SecretsManager for FakeSecrets {
        async fn read(&self, _: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
            Ok(b"v".to_vec())
        }
        async fn write(&self, _: &str, _: &[u8]) -> greentic_secrets_lib::Result<()> {
            Ok(())
        }
        async fn delete(&self, _: &str) -> greentic_secrets_lib::Result<()> {
            Ok(())
        }
    }

    let source = McpToolSource::with_secrets("http://admin.test", "tok", Arc::new(FakeSecrets));
    assert!(
        source.secrets().is_some(),
        "a source built with secrets must expose them to the catalogs it builds"
    );
}

/// A fake [`greentic_secrets_lib::SecretsManager`] used to prove the manager
/// itself (not just `Option::is_some`) rides from the source into a
/// real, network-built catalog.
struct FakeSecrets;

#[async_trait::async_trait]
impl greentic_secrets_lib::SecretsManager for FakeSecrets {
    async fn read(&self, _: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
        Ok(b"v".to_vec())
    }
    async fn write(&self, _: &str, _: &[u8]) -> greentic_secrets_lib::Result<()> {
        Ok(())
    }
    async fn delete(&self, _: &str) -> greentic_secrets_lib::Result<()> {
        Ok(())
    }
}

/// `build_catalog`'s normal-build branch (admin responds 200 with zero
/// servers) must still copy the source's secrets manager onto the catalog it
/// returns. This drives a REAL catalog through `catalog_for_role` against a
/// mock admin — unlike `source_carries_secrets_into_its_catalog`, which only
/// checks the source itself and never builds a catalog, so it stays green
/// even if the `catalog.secrets = self.secrets();` copy in `build_catalog` is
/// deleted.
#[tokio::test]
async fn build_catalog_normal_branch_carries_secrets() {
    use std::sync::Arc;

    let admin = MockServer::start().await;
    mount_admin(&admin, json!({ "servers": [] })).await;

    let source = McpToolSource::with_secrets(admin.uri(), "gtc_live_x", Arc::new(FakeSecrets));
    let catalog = source
        .catalog_for_role(&tenant(), MCP_ROLE_AGENTIC_WORKER)
        .await;

    assert!(catalog.is_empty());
    assert!(
        catalog.secrets().is_some(),
        "build_catalog's normal-build branch must copy the source's secrets \
         manager onto the returned catalog"
    );
}

/// `build_catalog`'s early-return "fetch failed" branch (admin responds
/// non-200) must ALSO copy the source's secrets manager onto the empty
/// catalog it returns.
#[tokio::test]
async fn build_catalog_fetch_failed_branch_carries_secrets() {
    use std::sync::Arc;

    let admin = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/designer/tenant/me/mcp-servers"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&admin)
        .await;

    let source = McpToolSource::with_secrets(admin.uri(), "gtc_live_x", Arc::new(FakeSecrets));
    let catalog = source
        .catalog_for_role(&tenant(), MCP_ROLE_AGENTIC_WORKER)
        .await;

    assert!(catalog.is_empty());
    assert!(
        catalog.secrets().is_some(),
        "build_catalog's fetch-failed branch must copy the source's secrets \
         manager onto the empty catalog it returns"
    );
}

/// A source built with an identity must send the `X-Greentic-Tenant` /
/// `X-Greentic-User` headers the admin resolves RBAC from.
///
/// Without them the bearer alone has to imply the tenant, which forces a
/// tenant-scoped `gtc_live_*` token per tenant — unusable from an embedding
/// host that serves many tenants from ONE process (the designer, whose Run
/// Demo builds a host per tenant but reads a single process-global env). With
/// them the same `gts_` service key the designer already holds works, and the
/// tenant travels per request instead of per process.
///
/// The assertion is behavioural, not a spy: the mock only answers when both
/// headers match, so a source that fails to send them gets no response, the
/// fetch fails, and `build_catalog` degrades to an EMPTY catalog.
#[tokio::test]
async fn identity_headers_are_sent_so_the_admin_can_resolve_the_tenant() {
    let mcp = fake_mcp_server(two_tools(), json!({})).await;
    let admin = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/designer/tenant/me/mcp-servers"))
        .and(header("authorization", "Bearer gts_x"))
        .and(header("x-greentic-tenant", "acme"))
        .and(header("x-greentic-user", "ops@acme.test"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "servers": [{
                "id": "worker", "name": "Worker", "transport_url": mcp.uri(),
                "auth_header_name": null, "auth_token": null,
                "allowed_tools": null, "roles": ["agentic_worker"]
            }]
        })))
        .mount(&admin)
        .await;

    let source = McpToolSource::new(admin.uri(), "gts_x")
        .with_identity(McpCallerIdentity::new("acme", "ops@acme.test"));
    let catalog = source.catalog(&tenant()).await;

    assert_eq!(
        catalog.len(),
        2,
        "the admin only answers when both identity headers are present; an \
         empty catalog means the source authenticated without saying which \
         tenant it was asking for"
    );
}

/// MCP servers are stored per-team on the admin, so an identity carrying a
/// team must say so — otherwise an embedding host resolves a DIFFERENT server
/// set at run time than the one its authoring UI listed, and the mismatch is
/// silent (a tool simply reports "not found in the catalog").
#[tokio::test]
async fn team_header_is_sent_when_the_identity_carries_a_team() {
    let mcp = fake_mcp_server(two_tools(), json!({})).await;
    let admin = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/designer/tenant/me/mcp-servers"))
        .and(header("x-greentic-team", "support"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "servers": [{
                "id": "worker", "name": "Worker", "transport_url": mcp.uri(),
                "auth_header_name": null, "auth_token": null,
                "allowed_tools": null, "roles": ["agentic_worker"]
            }]
        })))
        .mount(&admin)
        .await;

    let source = McpToolSource::new(admin.uri(), "gts_x")
        .with_identity(McpCallerIdentity::new("acme", "ops@acme.test").with_team("support"));
    let catalog = source.catalog(&tenant()).await;

    assert_eq!(
        catalog.len(),
        2,
        "the admin only answers when the team header names the caller's team"
    );
}

/// An identity with no team must send NO team header at all, rather than an
/// empty one. The designer leaves `team_slug` unset for operator sessions,
/// which span tenants and belong to no team; an empty `X-Greentic-Team` is a
/// different assertion from an absent one and the admin is entitled to reject
/// it.
#[tokio::test]
async fn a_team_less_identity_sends_no_team_header() {
    let mcp = fake_mcp_server(two_tools(), json!({})).await;
    let admin = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/designer/tenant/me/mcp-servers"))
        .and(|req: &wiremock::Request| req.headers.get("x-greentic-team").is_none())
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "servers": [{
                "id": "worker", "name": "Worker", "transport_url": mcp.uri(),
                "auth_header_name": null, "auth_token": null,
                "allowed_tools": null, "roles": ["agentic_worker"]
            }]
        })))
        .mount(&admin)
        .await;

    let source = McpToolSource::new(admin.uri(), "gts_x")
        .with_identity(McpCallerIdentity::new("acme", "ops@acme.test"));
    let catalog = source.catalog(&tenant()).await;

    assert_eq!(
        catalog.len(),
        2,
        "a team-less identity must send no team header; an empty one is a \
         different claim and the admin may reject it"
    );
}