agent-sdk-toolkit 0.1.0-alpha.4

Optional tool-pack helpers layered over agent-sdk-core primitive contracts.
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
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use agent_sdk_core::{
    DestinationKind, DestinationRef, EffectId, EffectIntent, EffectKind, ExecutionEnvironment,
    IsolationCapability, IsolationClass, IsolationRequirement, NetworkIsolationPolicy,
    SecretExposurePolicy, SourceKind, SourceRef, WorkspaceMountMode, testing::FakeIsolationRuntime,
};
use agent_sdk_toolkit::{
    JsonRpcFrame, JsonRpcId, JsonRpcLineCodec, JsonRpcLineEndpoint,
    testing::{
        IsolatedJsonRpcProcess, McpHostProxy, ScriptedAcpAgent, ScriptedAcpClient,
        ScriptedMcpServer,
    },
};
use serde_json::json;

#[test]
fn acp_mock_prompt_cancel_and_denials_cross_json_rpc_lines() {
    let (client_endpoint, agent_endpoint) = JsonRpcLineEndpoint::pair("acp-client", "acp-agent");
    let mut client = ScriptedAcpClient::new(client_endpoint.clone());
    let mut agent = ScriptedAcpAgent::new("session.acp.fake")
        .with_prompt_output("review sdk", "review completed through ACP transport");

    client.initialize().expect("initialize request sent");
    assert!(
        agent
            .handle_next(&agent_endpoint)
            .expect("agent handles init")
    );
    let init = client.response().expect("initialize response");
    assert_eq!(
        init.result
            .as_ref()
            .and_then(|value| value.get("protocolVersion"))
            .and_then(|value| value.as_i64()),
        Some(1)
    );

    client
        .new_session("/workspace/project")
        .expect("session/new request sent");
    assert!(
        agent
            .handle_next(&agent_endpoint)
            .expect("agent handles session/new")
    );
    let new_session = client.response().expect("session/new response");
    let session_id = new_session
        .result
        .as_ref()
        .and_then(|value| value.get("sessionId"))
        .and_then(|value| value.as_str())
        .expect("session id")
        .to_string();
    assert_eq!(session_id, "session.acp.fake");

    client
        .prompt(&session_id, "review sdk")
        .expect("prompt request sent");
    assert!(
        agent
            .handle_next(&agent_endpoint)
            .expect("agent handles prompt")
    );
    let update = client.notification().expect("session update notification");
    assert_eq!(update.method, "session/update");
    let accepted = client.response().expect("prompt completed");
    assert_eq!(
        accepted
            .result
            .as_ref()
            .and_then(|value| value.get("stopReason"))
            .and_then(|value| value.as_str()),
        Some("end_turn")
    );

    client
        .cancel(&session_id)
        .expect("session/cancel notification sent");
    assert!(
        agent
            .handle_next(&agent_endpoint)
            .expect("agent handles cancel notification")
    );
    assert!(
        client
            .endpoint()
            .try_receive_frame()
            .expect("no cancel response check")
            .is_none(),
        "ACP session/cancel is a notification and must not receive a response"
    );
    assert!(agent.cancelled_sessions().contains(&session_id));

    agent
        .request_file_read(&agent_endpoint, &session_id, "/workspace/private.txt")
        .expect("agent fs/read_text_file request");
    assert!(
        client
            .handle_next(&client_endpoint)
            .expect("client handles file denial")
    );
    let file_denial = agent
        .response(&agent_endpoint)
        .expect("file denial response");
    assert_eq!(file_denial.error.expect("file denied").code, -32003);

    agent
        .request_terminal_create(&agent_endpoint, &session_id, "cargo")
        .expect("agent terminal/create request");
    assert!(
        client
            .handle_next(&client_endpoint)
            .expect("client handles terminal denial")
    );
    let terminal_denial = agent
        .response(&agent_endpoint)
        .expect("terminal denial response");
    assert_eq!(terminal_denial.error.expect("terminal denied").code, -32004);

    agent
        .request_permission(&agent_endpoint, &session_id, "tool.call.1")
        .expect("agent session/request_permission request");
    assert!(
        client
            .handle_next(&client_endpoint)
            .expect("client handles permission request")
    );
    let tool_response = agent
        .response(&agent_endpoint)
        .expect("tool approval response");
    assert_eq!(
        tool_response
            .result
            .as_ref()
            .and_then(|value| value.get("outcome"))
            .and_then(|value| value.get("outcome"))
            .and_then(|value| value.as_str()),
        Some("cancelled")
    );

    client
        .endpoint()
        .send_raw_line("{not-json")
        .expect("malformed raw frame sent");
    assert!(
        agent
            .handle_next(&agent_endpoint)
            .expect("agent handles parse error")
    );
    let parse_error = client.response().expect("parse error response");
    assert_eq!(parse_error.id, JsonRpcId::Null);
    assert_eq!(parse_error.error.expect("parse error").code, -32700);

    assert!(
        client_endpoint
            .sent_lines()
            .iter()
            .any(|line| line.contains("\"method\":\"session/prompt\"")),
        "ACP prompt must cross encoded JSON-RPC lines"
    );
    assert!(
        agent_endpoint
            .received_lines()
            .iter()
            .any(|line| line.contains("\"method\":\"session/cancel\"")),
        "ACP agent must receive encoded cancel notification"
    );
    assert!(
        client_endpoint
            .received_lines()
            .iter()
            .any(|line| line.contains("\"method\":\"terminal/create\"")),
        "ACP client must receive encoded terminal/create request"
    );
    assert!(
        client_endpoint
            .received_lines()
            .iter()
            .any(|line| line.contains("\"method\":\"session/request_permission\"")),
        "ACP client must receive encoded permission request"
    );

    client
        .prompt("session.acp.unknown", "review sdk")
        .expect("unknown-session prompt request sent");
    assert!(
        agent
            .handle_next(&agent_endpoint)
            .expect("agent handles unknown session")
    );
    let unknown_session = client.response().expect("unknown session response");
    assert_eq!(
        unknown_session
            .error
            .expect("unknown session rejected")
            .code,
        -32602
    );
}

#[test]
fn mcp_host_proxy_filters_capabilities_and_calls_allowed_tool_over_json_rpc() {
    let (proxy_endpoint, server_endpoint) =
        JsonRpcLineEndpoint::pair("mcp-host-proxy", "mcp-server");
    let mut proxy = McpHostProxy::new(proxy_endpoint.clone())
        .allow_tool("git.status")
        .allow_resource("docs://sdk")
        .allow_prompt("review");
    let mut server = ScriptedMcpServer::new()
        .tool("git.status", json!({"summary": "clean"}))
        .tool("git.diff", json!({"summary": "hidden sibling"}))
        .resource("docs://sdk", "SDK docs")
        .resource("docs://secret", "hidden resource")
        .prompt("review", json!({"description": "allowed prompt"}))
        .prompt("secret-review", json!({"description": "hidden prompt"}));

    proxy.initialize().expect("initialize request");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server handles initialize")
    );
    assert!(
        proxy
            .response()
            .expect("initialize response")
            .error
            .is_none()
    );
    proxy.initialized().expect("initialized notification");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server handles initialized notification")
    );
    assert!(server.initialized());

    proxy.list_tools().expect("tools/list request");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server handles list")
    );
    let list = proxy.response().expect("tools/list response");
    assert_eq!(
        list.result
            .as_ref()
            .and_then(|value| value.get("tools"))
            .and_then(|value| value.as_array())
            .expect("filtered tools")
            .len(),
        1,
        "host proxy response must not expose unselected sibling tools"
    );
    assert_eq!(
        proxy
            .allowed_tool_names_from_response(&list)
            .expect("filter allowed tools"),
        vec!["git.status".to_string()]
    );

    proxy.list_resources().expect("resources/list request");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server handles resources/list")
    );
    let resources = proxy.response().expect("resources/list response");
    assert_eq!(
        resources
            .result
            .as_ref()
            .and_then(|value| value.get("resources"))
            .and_then(|value| value.as_array())
            .and_then(|items| items.first())
            .and_then(|item| item.get("uri"))
            .and_then(|value| value.as_str()),
        Some("docs://sdk")
    );

    proxy.list_prompts().expect("prompts/list request");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server handles prompts/list")
    );
    let prompts = proxy.response().expect("prompts/list response");
    assert_eq!(
        prompts
            .result
            .as_ref()
            .and_then(|value| value.get("prompts"))
            .and_then(|value| value.as_array())
            .and_then(|items| items.first())
            .and_then(|item| item.get("name"))
            .and_then(|value| value.as_str()),
        Some("review")
    );

    proxy
        .call_tool("git.status", json!({"path": "."}))
        .expect("allowed tool request sent");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server handles allowed tool")
    );
    let call = proxy.response().expect("tool call response");
    assert!(call.error.is_none());
    assert!(
        call.result
            .as_ref()
            .and_then(|value| value.get("content"))
            .is_some()
    );

    let denied = proxy
        .call_tool("git.diff", json!({}))
        .expect_err("unselected sibling tool is denied before server call");
    assert_eq!(denied.kind(), agent_sdk_core::AgentErrorKind::PolicyDenial);
    assert!(
        !proxy_endpoint
            .sent_lines()
            .iter()
            .any(|line| line.contains("\"name\":\"git.diff\"")),
        "unselected MCP sibling tool must not be sent to the server"
    );

    proxy
        .read_resource("docs://sdk")
        .expect("allowed resource read request");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server handles resource")
    );
    let resource = proxy.response().expect("resource read response");
    assert!(resource.error.is_none());

    proxy_endpoint
        .send_raw_line("{bad-mcp-json")
        .expect("malformed raw MCP frame");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server handles malformed frame")
    );
    let malformed = proxy.response().expect("malformed response");
    assert_eq!(malformed.error.expect("parse error").code, -32700);

    assert!(
        server_endpoint
            .received_lines()
            .iter()
            .any(|line| line.contains("\"method\":\"tools/call\"")),
        "MCP allowed tool call must cross encoded JSON-RPC lines"
    );

    server
        .request_sampling(&server_endpoint)
        .expect("server sampling request");
    assert!(
        proxy
            .handle_next(&proxy_endpoint)
            .expect("proxy handles sampling denial")
    );
    let sampling_denial = server
        .response(&server_endpoint)
        .expect("sampling denial response");
    assert_eq!(sampling_denial.error.expect("sampling denied").code, -32010);

    server
        .request_elicitation(&server_endpoint)
        .expect("server elicitation request");
    assert!(
        proxy
            .handle_next(&proxy_endpoint)
            .expect("proxy handles elicitation denial")
    );
    let elicitation_denial = server
        .response(&server_endpoint)
        .expect("elicitation denial response");
    assert_eq!(
        elicitation_denial.error.expect("elicitation denied").code,
        -32010
    );

    server_endpoint
        .send_result(JsonRpcId::Number(999), json!({}))
        .expect("unexpected duplicate/unknown response sent");
    assert!(
        proxy.response().is_err(),
        "host proxy must reject responses that do not match an outstanding request"
    );
}

#[test]
fn mcp_server_rejects_operation_before_initialized_notification() {
    let (proxy_endpoint, server_endpoint) =
        JsonRpcLineEndpoint::pair("mcp-host-proxy", "mcp-server");
    let mut proxy = McpHostProxy::new(proxy_endpoint.clone()).allow_tool("git.status");
    let mut server = ScriptedMcpServer::new().tool("git.status", json!({"summary": "clean"}));

    proxy.initialize().expect("initialize request");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server handles initialize")
    );
    assert!(
        proxy
            .response()
            .expect("initialize response")
            .error
            .is_none()
    );

    proxy.list_tools().expect("premature tools/list request");
    assert!(
        server
            .handle_next(&server_endpoint)
            .expect("server sends lifecycle error")
    );
    let error = proxy.response().expect("premature list response");
    assert_eq!(error.error.expect("lifecycle error").code, -32002);
    assert!(!server.initialized());
}

#[test]
fn mcp_inside_isolation_starts_runtime_before_json_rpc_exchange() {
    let runtime = FakeIsolationRuntime::with_report(
        agent_sdk_core::IsolationCapabilityReport::sandbox("runtime.fake.mcp"),
    );
    let environment = isolated_environment("env.protocol.mcp", "runtime.fake.mcp");
    let process = environment
        .process(["mcp-server", "--stdio"])
        .build()
        .expect("isolated MCP process spec");
    let isolated = IsolatedJsonRpcProcess::start(
        &runtime,
        environment.clone(),
        process,
        effect_intent(&environment, "effect.protocol.mcp.start"),
    )
    .expect("isolated MCP process started");
    let mut proxy = McpHostProxy::new(isolated.host_endpoint.clone()).allow_tool("project.index");
    let mut server = ScriptedMcpServer::new().tool("project.index", json!({"indexed": true}));

    proxy.initialize().expect("initialize request");
    assert!(
        server
            .handle_next(&isolated.process_endpoint)
            .expect("isolated server handles initialize")
    );
    assert!(
        proxy
            .response()
            .expect("initialize response")
            .error
            .is_none()
    );
    proxy.initialized().expect("initialized notification");
    assert!(
        server
            .handle_next(&isolated.process_endpoint)
            .expect("isolated server handles initialized notification")
    );
    proxy
        .call_tool("project.index", json!({"workspace": "workspace.primary"}))
        .expect("allowed isolated MCP tool call");
    assert!(
        server
            .handle_next(&isolated.process_endpoint)
            .expect("isolated server handles call")
    );
    assert!(proxy.response().expect("tool response").error.is_none());

    assert_eq!(
        runtime.calls(),
        vec!["capability_report".to_string(), "start_process".to_string()],
        "isolation runtime launch must happen before MCP protocol exchange"
    );
    assert!(
        isolated
            .host_endpoint
            .sent_lines()
            .iter()
            .any(|line| line.contains("\"method\":\"tools/call\""))
    );
    assert_eq!(
        isolated
            .start_result
            .adapter_session_ref
            .expect("adapter session ref")
            .as_str(),
        "adapter.session.fake.isolation"
    );
}

#[test]
fn acp_external_agent_inside_isolation_uses_json_rpc_after_runtime_start() {
    let runtime = FakeIsolationRuntime::with_report(
        agent_sdk_core::IsolationCapabilityReport::sandbox("runtime.fake.acp"),
    );
    let environment = isolated_environment("env.protocol.acp", "runtime.fake.acp");
    let process = environment
        .process(["acp-agent", "--stdio"])
        .build()
        .expect("isolated ACP process spec");
    let isolated = IsolatedJsonRpcProcess::start(
        &runtime,
        environment.clone(),
        process,
        effect_intent(&environment, "effect.protocol.acp.start"),
    )
    .expect("isolated ACP process started");
    let mut client = ScriptedAcpClient::new(isolated.host_endpoint.clone());
    let mut agent = ScriptedAcpAgent::new("session.acp.isolated")
        .with_prompt_output("summarize", "summary via isolated ACP");

    client.initialize().expect("initialize request");
    assert!(
        agent
            .handle_next(&isolated.process_endpoint)
            .expect("isolated ACP initialize")
    );
    assert!(
        client
            .response()
            .expect("initialize response")
            .error
            .is_none()
    );
    client
        .new_session("/workspace/project")
        .expect("session/new request");
    assert!(
        agent
            .handle_next(&isolated.process_endpoint)
            .expect("isolated ACP session/new")
    );
    let session_id = client
        .response()
        .expect("session/new response")
        .result
        .as_ref()
        .and_then(|value| value.get("sessionId"))
        .and_then(|value| value.as_str())
        .expect("session id")
        .to_string();
    client
        .prompt(&session_id, "summarize")
        .expect("prompt request");
    assert!(
        agent
            .handle_next(&isolated.process_endpoint)
            .expect("isolated ACP prompt")
    );
    assert_eq!(
        client.notification().expect("prompt output").method,
        "session/update"
    );
    assert_eq!(
        client
            .response()
            .expect("prompt response")
            .result
            .as_ref()
            .and_then(|value| value.get("stopReason"))
            .and_then(|value| value.as_str()),
        Some("end_turn")
    );

    assert_eq!(
        runtime.calls(),
        vec!["capability_report".to_string(), "start_process".to_string()],
        "isolation runtime launch must happen before ACP protocol exchange"
    );
    assert!(
        isolated
            .process_endpoint
            .received_lines()
            .iter()
            .any(|line| line.contains("\"method\":\"session/prompt\""))
    );
}

#[test]
fn raw_json_rpc_frame_parser_rejects_non_json_direct_calls() {
    let error = JsonRpcFrame::from_line("not-json").expect_err("invalid JSON denied");
    assert_eq!(
        error.kind(),
        agent_sdk_core::AgentErrorKind::InvalidStateTransition
    );

    let (left, _right) = JsonRpcLineEndpoint::pair("left", "right");
    let newline = left
        .send_raw_line("{\"jsonrpc\":\"2.0\"}\n{\"jsonrpc\":\"2.0\"}")
        .expect_err("embedded newline denied");
    assert_eq!(
        newline.kind(),
        agent_sdk_core::AgentErrorKind::InvalidStateTransition
    );
}

#[test]
fn json_rpc_response_contract_rejects_invalid_response_shapes() {
    let parse_error = JsonRpcFrame::from_line(
        r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}}"#,
    )
    .expect("parse-error response with null id is valid");
    let JsonRpcFrame::Response(response) = parse_error else {
        panic!("expected response frame");
    };
    assert_eq!(response.id, JsonRpcId::Null);

    assert!(
        JsonRpcFrame::from_line(
            r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"}}"#
        )
        .is_err(),
        "JSON-RPC responses must include id, using null when no request id is available"
    );
    assert!(
        JsonRpcFrame::from_line(
            r#"{"jsonrpc":"2.0","id":1,"result":{},"error":{"code":-32603,"message":"bad"}}"#
        )
        .is_err(),
        "JSON-RPC responses cannot include both result and error"
    );
    assert!(
        JsonRpcFrame::from_line(r#"{"jsonrpc":"2.0","id":null,"method":"tools/list"}"#).is_err(),
        "JSON-RPC request ids must not be null"
    );
}

#[test]
fn json_rpc_line_codec_round_trips_stdio_delimited_bytes() {
    let frame = JsonRpcFrame::Request(agent_sdk_toolkit::JsonRpcRequest::new(
        1,
        "tools/list",
        json!({}),
    ));
    let mut bytes = Vec::new();

    JsonRpcLineCodec::write_frame(&mut bytes, &frame).expect("frame written");

    assert!(bytes.ends_with(b"\n"));
    assert_eq!(
        bytes.iter().filter(|byte| **byte == b'\n').count(),
        1,
        "stdio transport must use one newline delimiter and no embedded newlines"
    );

    let mut reader = std::io::Cursor::new(bytes);
    assert_eq!(
        JsonRpcLineCodec::read_frame(&mut reader).expect("frame read"),
        Some(frame)
    );
    assert!(
        JsonRpcLineCodec::read_frame(&mut reader)
            .expect("eof read")
            .is_none()
    );
}

fn isolated_environment(environment_id: &str, runtime_ref: &str) -> ExecutionEnvironment {
    ExecutionEnvironment::require(
        IsolationRequirement::at_least(IsolationClass::Sandbox)
            .prefer(runtime_ref)
            .require_capabilities([
                IsolationCapability::NoNetworkGuarantee,
                IsolationCapability::ReadOnlyRoot,
                IsolationCapability::Cleanup,
                IsolationCapability::ProcessTimeout,
                IsolationCapability::IoRedaction,
            ]),
    )
    .environment_id(environment_id)
    .workspace("workspace.primary", WorkspaceMountMode::Snapshot)
    .network(NetworkIsolationPolicy::Disabled)
    .secrets(SecretExposurePolicy::no_ambient())
    .ephemeral()
    .source(SourceRef::with_kind(SourceKind::Sdk, "source.sdk.protocol"))
    .destination(DestinationRef::with_kind(
        DestinationKind::ExternalRuntime,
        "destination.protocol.runtime",
    ))
    .build()
    .expect("environment builds")
}

fn effect_intent(environment: &ExecutionEnvironment, effect_id: &str) -> EffectIntent {
    let mut intent = EffectIntent::new(
        EffectId::new(effect_id),
        EffectKind::IsolatedProcessStart,
        environment.subject_ref(),
        environment.source.clone(),
        "start protocol mock inside isolated process",
    );
    intent.destination = Some(environment.destination.clone());
    intent
}