ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/t/e19_local_forms.t
Revision: 1.3
Committed: Sun Nov 29 14:30:05 2026 UTC (2 days, 14 hours ago) by root
Content type: application/x-troff
Branch: MAIN
CVS Tags: HEAD
Changes since 1.2: +11 -10 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 use common::sense;
2 root 1.3 use AnyEvent::MCP ();
3     use Types::Serialiser ();
4 root 1.1 # the HTTP child uses a private loopback listener.
5     BEGIN { delete $ENV{http_proxy} }
6     use Test::More;
7     BEGIN {
8     plan skip_all => "extended local forms test (PERL_ANYEVENT_MCP_TESTS=1)"
9     unless ($ENV{PERL_ANYEVENT_MCP_TESTS} || 0) >= 1;
10     }
11    
12     use AnyEvent ();
13     use AnyEvent::Util ();
14     use AnyEvent::MCP::Client::JSONL ();
15     use File::Temp ();
16     use File::Path ();
17     use IO::Socket::INET ();
18     use Time::HiRes ();
19    
20     my $dir = File::Temp::tempdir (CLEANUP => 1);
21     File::Path::mkpath (["$dir/home", "$dir/config"], 0, 0700);
22     my $helper = "$dir/form-helper";
23     sub write_file {
24     my ($path, $text) = @_;
25     open my $fh, ">", $path or die "$path: $!";
26     print {$fh} $text;
27     close $fh or die "$path: $!";
28     }
29     write_file $helper, "#!$^X\n" . q{
30     use common::sense;
31 root 1.3 use JSON::PP ();
32 root 1.1 local $/;
33 root 1.3 my $request = JSON::PP::decode_json <STDIN>;
34 root 1.1 open my $log, ">>", "$ENV{MCP_TEST_FORM_DIR}/requests" or die $!;
35 root 1.3 print {$log} JSON::PP::encode_json ($request), "\n";
36 root 1.1 close $log;
37     if ($request->{message} =~ /Wait for cancellation/) {
38     open my $pid, ">", "$ENV{MCP_TEST_FORM_DIR}/waiting-pid" or die $!;
39     print {$pid} "$$";
40     close $pid;
41     sleep 60;
42     }
43     open my $reply, "<", "$ENV{MCP_TEST_FORM_DIR}/reply" or die $!;
44     print scalar <$reply>;
45     };
46     chmod 0700, $helper or die $!;
47     write_file "$dir/anyevent-mcp-form-elicitation", "#!$^X\n" . q{
48     use common::sense;
49 root 1.3 use JSON::PP ();
50 root 1.1 open my $log, ">>", "$ENV{MCP_TEST_FORM_DIR}/modes" or die $!;
51 root 1.3 print {$log} JSON::PP::encode_json (\@ARGV), "\n";
52 root 1.1 close $log or die $!;
53     exec $^X, "$ENV{MCP_TEST_FORM_DIR}/form-helper";
54     die "exec: $!";
55     };
56     chmod 0700, "$dir/anyevent-mcp-form-elicitation" or die $!;
57     my %env = (
58     HOME => "$dir/home", XDG_CONFIG_HOME => "$dir/config",
59     PERL_ANYEVENT_MCP_ELICITATION_HELPER => $helper,
60     MCP_TEST_FORM_DIR => $dir, PATH => "$dir:$ENV{PATH}",
61     );
62     write_file "$dir/reply", '{"action":"accept","content":{"choice":"Keep"}}';
63     my $args = { question => "Keep or replace?", options => [{ label => "Keep" }, { label => "Replace" }] };
64    
65     sub wait_for {
66     my ($start) = @_;
67     my $cv = AE::cv;
68     my $timer = AE::timer 30, 0, sub { $cv->croak ("Local form test timeout\n") };
69     $start->(sub { $cv->send ([@_]) });
70     @{$cv->recv}
71     }
72     sub question {
73     my ($client, $name) = @_;
74     my ($success, $result) = wait_for (sub { $client->call ($name || "ask-user", $args, $_[0]) });
75     ok $success, "question transport completed";
76     $result
77     }
78     sub requests {
79     open my $fh, "<", "$dir/requests" or die $!;
80 root 1.3 my @requests = map AnyEvent::MCP::decode_json ($_), <$fh>;
81 root 1.1 close $fh;
82     @requests
83     }
84     sub standalone {
85     my ($mode, $caps, $legacy, $on_request) = @_;
86     AnyEvent::MCP::Client::JSONL->new (
87     command => [$^X, "-Ilib", "bin/mcp-ask-user", "--stdio", "--ask", $mode],
88     env => \%env, client_capabilities => $caps,
89     ($legacy ? (versions => ["2025-11-25"]) : ()),
90     on_request => $on_request || sub { die "Local question reached upstream elicitation\n" },
91     )
92     }
93    
94     my $client = standalone ("helper", {}, 1);
95     my $result = question $client;
96     is $result->{structuredContent}{answer}, "Keep", "standalone local helper works for a legacy client";
97     write_file "$dir/reply", '{"action":"decline"}';
98     $result = question $client;
99     is $result->{structuredContent}{status}, "declined", "local decline is retained";
100     write_file "$dir/reply", '{"action":"cancel"}';
101     $result = question $client;
102     is $result->{structuredContent}{status}, "cancelled", "local cancel is distinct";
103     write_file "$dir/reply", '{"action":"accept","content":{"choice":"not offered"}}';
104     $result = question $client;
105     ok $result->{isError}, "standalone validates even a custom helper's choice";
106    
107     my $form_args = {
108     message => "Configure locally",
109     requestedSchema => {
110     type => "object", required => ["enabled", "count"],
111     properties => {
112     enabled => { type => "boolean" },
113     count => { type => "integer", minimum => 1 },
114     },
115     },
116     };
117     write_file "$dir/reply", '{"action":"accept","content":{"enabled":true,"count":2}}';
118     my ($form_ok, $form_result) = wait_for (sub {
119     $client->call ("ask-form", $form_args, $_[0])
120     });
121     ok $form_ok, "generic local form works for a legacy client";
122     is_deeply $form_result->{structuredContent},
123 root 1.3 { action => "accept", content => { enabled => Types::Serialiser::true, count => 2 } },
124 root 1.1 "local form returns standard typed response";
125     my @form_requests = requests;
126     is_deeply $form_requests[-1], { mode => "form", %$form_args },
127     "generic parameters reach the helper unchanged";
128     for my $action (qw(decline cancel)) {
129 root 1.3 write_file "$dir/reply", AnyEvent::MCP::encode_json { action => $action };
130 root 1.1 ($form_ok, $form_result) = wait_for (sub {
131     $client->call ("ask-form", $form_args, $_[0])
132     });
133     is_deeply $form_result->{structuredContent}, { action => $action },
134     "local generic form retains $action";
135     }
136     write_file "$dir/reply", '{"action":"accept","content":[]}';
137     ($form_ok, $form_result) = wait_for (sub {
138     $client->call ("ask-form", $form_args, $_[0])
139     });
140     ok $form_result->{isError}, "generic tool rejects a malformed custom helper response";
141     $client->close;
142    
143     write_file "$dir/reply", '{"action":"accept","content":{"choice":"Keep"}}';
144     $client = standalone ("auto", {});
145     $result = question $client;
146     is $result->{structuredContent}{answer}, "Keep", "standalone auto falls back when no forms are advertised";
147     $client->close;
148    
149     my @before = requests;
150     my $elicited;
151     $client = standalone ("auto", { elicitation => { form => {} } }, 0, sub {
152     ++$elicited;
153     $_[1]->reply ({ action => "decline" });
154     });
155     $result = question $client;
156     my @after = requests;
157     ok $elicited == 1 && $result->{structuredContent}{status} eq "declined" && @before == @after,
158     "auto native decline never falls back to a local helper";
159     $client->close;
160    
161     sub broker {
162     my ($mode, $caps, $legacy, $url) = @_;
163     AnyEvent::MCP::Client::JSONL->new (
164     command => [$^X, "-Ilib", "bin/mcp-multibroker", "--stdio", "--ask", $mode, "questions",
165     $url || "stdio:$^X -Ilib bin/mcp-ask-user"],
166     env => \%env, client_capabilities => $caps,
167     ($legacy ? (versions => ["2025-11-25"]) : ()),
168     on_request => sub { die "Broker local question reached upstream elicitation\n" },
169     )
170     }
171     for my $case (
172     ["helper", { elicitation => { form => {} } }, 0],
173     ["helper", {}, 0],
174     ["helper", {}, 1],
175     ["auto", {}, 0],
176     ) {
177     $client = broker (@$case);
178     $result = question $client, "questions.ask-user";
179     is $result->{structuredContent}{answer}, "Keep",
180     "broker $case->[0] handles the child form locally despite upstream capability differences";
181     my @requests = requests;
182     like $requests[-1]{message}, qr/\AServer: questions\n\n/, "broker identifies the requesting child";
183     $client->close;
184     }
185    
186     for my $mode (qw(tty yad)) {
187     local $env{PERL_ANYEVENT_MCP_ELICITATION_HELPER} = "$dir/not-a-custom-helper";
188     for my $through_broker (0, 1) {
189     $client = $through_broker ? broker ($mode, {}) : standalone ($mode, {});
190     $result = question $client, $through_broker ? "questions.ask-user" : "ask-user";
191     is $result->{structuredContent}{answer}, "Keep", "$mode works through the selected built-in form helper";
192     open my $log, "<", "$dir/modes" or die $!;
193 root 1.3 my @modes = map AnyEvent::MCP::decode_json ($_), <$log>;
194 root 1.1 close $log;
195     is_deeply $modes[-1], ["--$mode"], "$mode is forced without consulting the custom helper";
196     $client->close;
197     }
198     }
199    
200     SKIP: {
201     skip "extended form helper cancellation tests (PERL_ANYEVENT_MCP_TESTS=1)", 3 unless ($ENV{PERL_ANYEVENT_MCP_TESTS} || 0) >= 1;
202    
203     $client = broker ("helper", {});
204     $args->{question} = "Wait for cancellation";
205     my $cancelled = AE::cv;
206     my $operation = $client->call ("questions.ask-user", $args, sub { $cancelled->send ([@_]) });
207     my $poll;
208     wait_for (sub {
209     my $done = shift;
210     $poll = AE::timer 0, 0.01, sub {
211     return unless -s "$dir/waiting-pid";
212     undef $poll;
213     $done->(1);
214     };
215     });
216     open my $pidfile, "<", "$dir/waiting-pid" or die $!;
217     my $helper_pid = <$pidfile>;
218     close $pidfile;
219     $client->cancel ($operation);
220     my $cancel = $cancelled->recv;
221     ok !$cancel->[0] && $cancel->[1]{cancelled}, "broker question cancellation reaches the caller";
222     wait_for (sub {
223     my $done = shift;
224     $poll = AE::timer 0, 0.01, sub {
225     return if kill 0, $helper_pid;
226     undef $poll;
227     $done->(1);
228     };
229     });
230     ok !kill (0, $helper_pid), "broker cancels and reaps the active form helper";
231     $args->{question} = "Keep or replace?";
232     $result = question $client, "questions.ask-user";
233     is $result->{structuredContent}{answer}, "Keep", "prompt queue remains usable after cancellation";
234     $client->close;
235    
236     }
237    
238     # Independently running HTTP servers delegate to the broker too.
239     my $listener = IO::Socket::INET->new (
240     LocalAddr => "127.0.0.1", LocalPort => 0, Proto => "tcp", Listen => 1,
241     ) or die $!;
242     my $port = $listener->sockport;
243     close $listener;
244     my ($pid, $stdout, $stderr);
245 root 1.2 my $server;
246     {
247     local %ENV = (%ENV, %env);
248     $server = AnyEvent::Util::run_cmd (
249     [$^X, "-Ilib", "bin/mcp-ask-user", "--ask", "mcp", "--bind", "127.0.0.1:$port", "--token", "form-test"],
250     "<" => "/dev/null", ">" => \$stdout, "2>" => \$stderr, '$$' => \$pid,
251     );
252     }
253 root 1.1 my $ready;
254     for (1 .. 1500) {
255     $ready = IO::Socket::INET->new (PeerAddr => "127.0.0.1", PeerPort => $port, Proto => "tcp");
256     last if $ready;
257     Time::HiRes::sleep (0.02);
258     }
259     ok $ready, "standalone HTTP question server is listening";
260     close $ready if $ready;
261     $client = broker ("helper", {}, 0, "http://127.0.0.1:$port/form-test/");
262     $result = question $client, "questions.ask-user";
263     is $result->{structuredContent}{answer}, "Keep", "broker handles an independent HTTP child's form locally";
264     $client->close;
265     kill TERM => $pid if $pid;
266     $server->recv;
267    
268     done_testing;