ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/t/c04_client.t
Revision: 1.3
Committed: Tue Nov 17 04:02:15 2026 UTC (2 weeks, 3 days ago) by root
Content type: application/x-troff
Branch: MAIN
Changes since 1.2: +64 -1 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 use common::sense;
2     # These tests and their subprocesses connect to private loopback listeners.
3     BEGIN { delete $ENV{http_proxy} }
4     use AnyEvent ();
5     use AnyEvent::Handle ();
6     use AnyEvent::Socket ();
7     use AnyEvent::MCP::Client::HTTP ();
8     use AnyEvent::MCP::Client::JSONL ();
9     use AnyEvent::MCP::Server::HTTP ();
10     use AnyEvent::MCP::Server::JSONL ();
11     use AnyEvent::MCP::Server::Toolset ();
12     use AnyEvent::MCP::Config ();
13     use JSON::XS ();
14     use File::Temp ();
15     use Socket;
16     use Scalar::Util qw(weaken);
17    
18 root 1.3 print "1..77\n";
19 root 1.1
20     my $test;
21     sub ok($$) {
22     my ($condition, $name) = @_;
23     print (($condition ? "ok " : "not ok "), ++$test, " - $name\n");
24     }
25    
26     sub wait_for {
27     my ($start) = @_;
28     my $cv = AnyEvent->condvar;
29     my $timer = AnyEvent->timer (after => 30, cb => sub { die "Client test timeout\n" });
30     $start->(sub { $cv->send ([@_]) });
31     @{$cv->recv}
32     }
33    
34     my $dir = File::Temp::tempdir (CLEANUP => 1);
35     local $ENV{XDG_CONFIG_HOME} = "$dir/config";
36     my $toolset = AnyEvent::MCP::Server::Toolset->new;
37     my $pending;
38     $toolset->tool (echo => "echo", {}, sub { $_[0]->result ($_[1]) });
39     $toolset->tool (slow => "slow", {}, sub { $pending = $_[0] });
40     $toolset->tool (fail => "fail", {}, sub { $_[0]->error ("tool failure") });
41    
42     my $server = AnyEvent::MCP::Server::HTTP->new (
43     toolsets => [$toolset], tokens => ["secret"],
44     );
45     $server->listen;
46     my $ready = 0;
47     my $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url (0), bearer => "secret",
48     on_ready => sub { ++$ready });
49     ok !-e "$dir/config", "unnamed server and client read no config";
50    
51     my ($success, $result) = wait_for (sub { $client->call (echo => { text => "hello" }, $_[0]) });
52     ok $success && $result->{structuredContent}{text} eq "hello", "modern HTTP tool call";
53     ok $ready == 1, "ready event fires after successful MCP discovery";
54     ($success, $result) = wait_for (sub { $client->connect ($_[0]) });
55     ok $success && $ready == 1, "reusing an initialized connection does not repeat ready event";
56     ok $client->{protocol_version} eq "2026-07-28", "modern discovery";
57     ok $client->{server_info}{name} eq "AnyEvent::MCP", "server identity";
58     ok ref $client->{server_capabilities}{tools} eq "HASH", "server capabilities";
59     ($success, $result) = wait_for (sub { $client->tools ($_[0]) });
60     ok $success && @$result == 3, "list tools";
61     ($success, $result) = wait_for (sub { $client->call (fail => {}, $_[0]) });
62     ok $success && $result->{isError}, "tool failure remains successful RPC";
63     ($success, $result) = wait_for (sub { $client->rpc ("unknown", {}, $_[0]) });
64     ok !$success && $result->{code} == -32601, "HTTP protocol error preserved";
65     ($success, $result) = wait_for (sub { $client->notify ("notifications/initialized", {}, $_[0]) });
66     ok $success, "HTTP notification";
67     $client->close;
68     ($success, $result) = wait_for (sub { $client->call (echo => {}, $_[0]) });
69     ok $success && $ready == 2, "ready event fires again after reconnect";
70     $client->close;
71    
72     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
73     ($success, $result) = wait_for (sub { $client->call (echo => {}, $_[0]) });
74     ok $success, "URL cookie without header auth";
75     $client->close;
76     my $url = $server->url;
77     chop $url;
78     $client = AnyEvent::MCP::Client::HTTP->new (url => $url);
79     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
80     ok $success, "URL token works without trailing slash";
81     $client->close;
82     $url = $server->url (0);
83     chop $url;
84     $client = AnyEvent::MCP::Client::HTTP->new (url => $url, bearer => "secret");
85     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
86     ok $success, "bearer-authenticated endpoint works without trailing slash";
87     $client->close;
88     $url = $server->url;
89     $url =~ s{/secret/mcp/\z}{/wrong/mcp};
90     $client = AnyEvent::MCP::Client::HTTP->new (url => $url);
91     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
92     ok !$success && $result->{transport} && $result->{message} =~ /404/,
93     "unknown URL token without trailing slash still rejected";
94     $client->close;
95     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url . "extra");
96     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
97     ok !$success && $result->{transport} && $result->{message} =~ /404/,
98     "extra path component still rejected";
99     $client->close;
100     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url (0), bearer => "wrong");
101     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
102     ok !$success && $result->{transport} && $result->{message} =~ /401/, "wrong bearer fails";
103     $client->close;
104     $server->close;
105    
106     $server = AnyEvent::MCP::Server::HTTP->new (toolsets => [$toolset],
107     tokens => ["secret"], path => "/custom/");
108     $server->listen;
109     $url = $server->url;
110     chop $url;
111     $client = AnyEvent::MCP::Client::HTTP->new (url => $url);
112     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
113     ok $success, "configured endpoint path accepts omitted trailing slash";
114     $client->close;
115     $server->close;
116    
117     $server = AnyEvent::MCP::Server::HTTP->new (toolsets => [$toolset],
118     tokens => ["secret"], path => "/custom");
119     $server->listen;
120     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url . "/");
121     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
122     ok !$success && $result->{transport} && $result->{message} =~ /404/,
123     "endpoint without trailing slash still rejects an added slash";
124     $client->close;
125     $server->close;
126    
127     $server = AnyEvent::MCP::Server::HTTP->new (toolsets => [$toolset], tokens => ["alpha", "beta"]);
128     $server->listen;
129     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url (0), bearer => "beta");
130     ($success, $result) = wait_for (sub { $client->call (echo => {}, $_[0]) });
131     ok $success, "second token accepted in Authorization header";
132     $client->close;
133     $server->close;
134     eval { AnyEvent::MCP::Client::HTTP->new (url => "http://localhost/", bearer => "token", username => "alice", password => "pw") };
135     ok $@ =~ /Basic authentication is unsupported/, "Basic credentials rejected even with bearer";
136     eval { AnyEvent::MCP::Client::HTTP->new (url => "http://localhost/", username => "alice") };
137     ok $@ =~ /Basic authentication is unsupported/, "Basic client credentials rejected";
138    
139     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", toolsets => [$toolset], versions => ["2025-06-18"]);
140     $server->listen;
141     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
142     ($success, $result) = wait_for (sub { $client->call (echo => { value => 42 }, $_[0]) });
143     ok $success && $result->{structuredContent}{value} == 42, "legacy fallback tool call";
144     ok $client->{protocol_version} eq "2025-06-18", "negotiated legacy version";
145     ok $client->{server_info}{name} eq "AnyEvent::MCP", "legacy wire identity preserved";
146     $client->close;
147     $server->close;
148    
149     # Old dispatchers can return an internal error for an unknown discovery method.
150     my $discoveries = 0;
151     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none",
152     toolsets => [$toolset],
153     on_request => sub {
154     if ($_[1]{method} eq "server/discover") {
155     ++$discoveries;
156     die "Undefined discovery handler\n"
157     }
158     },
159     );
160     $server->listen;
161     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
162     ($success, $result) = wait_for (sub { $client->call (echo => { value => 42 }, $_[0]) });
163     ok $success && $result->{structuredContent}{value} == 42, "discovery internal error falls back to initialization";
164     ok $discoveries == 1 && $client->{protocol_version} eq "2025-11-25", "fallback negotiates legacy once";
165     $client->close;
166     $server->close;
167    
168     my $calls = 0;
169     my @input;
170     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
171     my ($server, $req, $args) = @_;
172     ++$calls;
173     if (exists $req->{params}{inputResponses}) {
174     ok $req->{params}{requestState} eq "opaque", "request state echoed";
175     ok $req->{params}{inputResponses}{question}{content}{answer} == 42, "input answer echoed";
176     ok $args->{original} eq "keep", "original tool arguments preserved";
177     $req->result ({ answer => 42 });
178     } else {
179     $req->reply ({
180     resultType => "input_required", requestState => "opaque",
181     inputRequests => { question => {
182     method => "elicitation/create", params => { message => "question" },
183     } },
184     });
185     }
186     });
187     $server->listen;
188     $client = AnyEvent::MCP::Client::HTTP->new (
189     url => $server->url, client_capabilities => { elicitation => { form => {} } },
190     on_request => sub {
191     my ($client, $req) = @_;
192     push @input, $req;
193     $req->reply ({ action => "accept", content => { answer => 42 } });
194     },
195     );
196     ($success, $result) = wait_for (sub { $client->call (question => { original => "keep" }, $_[0]) });
197     ok $success && $result->{structuredContent}{answer} == 42, "modern input continuation";
198     ok $calls == 2 && @input == 1 && $input[0]{finished}, "input handled once";
199     ($success, $result) = wait_for (sub {
200     $client->rpc ("tools/call", { name => "question", arguments => {} }, $_[0]);
201     });
202     ok $success && $result->{resultType} eq "input_required" && @input == 1, "raw RPC preserves challenge";
203     $client->close;
204     $server->close;
205     @input = ();
206    
207 root 1.3 # State-only continuations are retries without elicitation or inputResponses.
208     my $state_calls = 0;
209     my $state_ok = 1;
210     my @state_times;
211     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
212     my ($server, $req, $args) = @_;
213     $state_ok &&= $state_calls
214     ? ($req->{params}{requestState} // "") eq "state-$state_calls"
215     && !exists $req->{params}{inputResponses}
216     : !exists $req->{params}{requestState};
217     push @state_times, AE::now;
218     ++$state_calls;
219     if ($state_calls <= 3) {
220     $req->reply ({ resultType => "input_required", requestState => "state-$state_calls" });
221     } else {
222     $req->result ({ count => $state_calls, original => $args->{original} });
223     }
224     });
225     $server->listen;
226     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
227     ($success, $result) = wait_for (sub {
228     $client->call (progress => { original => "untouched" }, $_[0]);
229     });
230     ok $success && $result->{structuredContent}{count} == 4
231     && $result->{structuredContent}{original} eq "untouched" && $state_ok,
232     "state-only continuation preserves opaque state and original arguments without a handler";
233     ok @state_times == 4 && $state_times[2] - $state_times[1] >= .18
234     && $state_times[3] - $state_times[2] >= .42,
235     "state-only retries start immediately, then back off by 250ms per round";
236     $state_calls = 0;
237     ($success, $result) = wait_for (sub {
238     $client->rpc ("tools/call", { name => "progress", arguments => {} }, $_[0]);
239     });
240     ok $success && $result->{resultType} eq "input_required" && $state_calls == 1,
241     "raw RPC does not retry state-only challenges";
242     $server->{on_tools_call} = sub {
243     $_[1]->reply ({ resultType => "input_required" });
244     };
245     ($success, $result) = wait_for (sub { $client->call (progress => {}, $_[0]) });
246     ok !$success && $result->{message} =~ /Invalid input-required/,
247     "state-only challenge without requestState is rejected";
248     $state_calls = 0;
249     $server->{on_tools_call} = sub {
250     ++$state_calls;
251     $_[1]->reply ({ resultType => "input_required", requestState => "again" });
252     };
253     ($success, $result) = wait_for (sub { $client->call (progress => {}, $_[0]) });
254     ok !$success && $result->{message} =~ /Too many state-only retries/ && $state_calls == 11,
255     "state-only retries stop after ten retries";
256     $state_calls = 0;
257     my $state_cancel;
258     my $state_id = $client->call (progress => {}, sub { $state_cancel = $_[1] });
259     my $cancel_timer = AnyEvent->timer (after => .1, cb => sub { $client->cancel ($state_id) });
260     my $cancel_cv = AnyEvent->condvar;
261     my $check_timer = AnyEvent->timer (after => .65, cb => sub { $cancel_cv->send });
262     $cancel_cv->recv;
263     ok $state_cancel->{cancelled} && $state_calls == 2,
264     "cancellation prevents pending state-only retry";
265     undef $cancel_timer;
266     undef $check_timer;
267     $client->close;
268     $server->close;
269    
270 root 1.1 my $page = 0;
271     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_list => sub {
272     $_[1]->reply ({ tools => [{ name => ++$page }], ($page == 1 ? (nextCursor => "second") : ()) });
273     });
274     $server->listen;
275     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
276     ($success, $result) = wait_for (sub { $client->tools ($_[0]) });
277     ok $success && @$result == 2 && $result->[1]{name} == 2, "tool pagination";
278     $server->{on_tools_list} = sub { $_[1]->reply ({ tools => [], nextCursor => "repeat" }) };
279     ($success, $result) = wait_for (sub { $client->tools ($_[0]) });
280     ok !$success && $result->{message} =~ /Repeated/, "pagination loop rejected";
281     $client->close;
282     $server->close;
283    
284     socketpair my $a, my $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
285     $server = AnyEvent::MCP::Server::JSONL->new (toolsets => [$toolset]);
286     $server->accept ($a);
287     $client = AnyEvent::MCP::Client::JSONL->new;
288     $client->attach ($b);
289     my @order;
290     ($success, $result) = wait_for (sub {
291     my $done = $_[0];
292     $client->call (slow => {}, sub { push @order, "slow"; $done->(@_) });
293     $client->rpc ("ping", {}, sub { push @order, "ping"; $pending->reply ({}); undef $pending });
294     });
295     ok $success && join (",", @order) eq "ping,slow", "JSONL replies can be out of order";
296    
297     my ($id, $cancelled, $completions);
298     $id = $client->call (slow => {}, sub { ++$completions; $cancelled = $_[1] });
299     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
300     $client->cancel ($id);
301     ok $completions == 1 && $cancelled->{cancelled}, "local cancellation once";
302     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
303     ok $pending->{cancelled}, "wire cancellation reaches server";
304     undef $pending;
305     $client->cancel ($id);
306     ok $completions == 1, "repeated cancellation ignored";
307    
308     $id = $client->call (slow => {}, sub { ++$completions; $cancelled = $_[1] });
309     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
310     $client->close;
311     ok $completions == 2 && $cancelled->{transport}, "close fails outstanding call";
312     $server->close;
313     undef $pending;
314    
315     $client = AnyEvent::MCP::Client::JSONL->new (
316     command => [$^X, "-Ilib", "-e", '
317     use AnyEvent::MCP::Server::Simple;
318     mcp_tool echo => "echo", {}, sub { $_[0]->result ($_[1]) };
319     mcp_start;
320     '],
321     env => { PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL => "stdio" },
322     );
323     ($success, $result) = wait_for (sub { $client->call (echo => { subprocess => 1 }, $_[0]) });
324     ok $success && $result->{structuredContent}{subprocess}, "direct subprocess command";
325     my $pid = $client->{pid};
326     $client->close;
327     ok !$client->{pid}, "close detaches child";
328     ($success, $result) = wait_for (sub { $client->call (echo => { restarted => 1 }, $_[0]) });
329     ok $success && $result->{structuredContent}{restarted} && $client->{pid} != $pid, "new call restarts child";
330     $client->close;
331    
332     # A real streaming response: progress arrives before the final event.
333     my ($sse_handle, $release, $listener, $port, $finished, $progress);
334     $listener = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
335     $sse_handle = AnyEvent::Handle->new (fh => $_[0], on_error => sub { die $_[2] });
336     $sse_handle->push_read (line => "\r\n\r\n", sub {
337     my ($handle, $header) = @_;
338     my ($length) = $header =~ /Content-Length: ([0-9]+)/i;
339     $handle->push_read (chunk => $length, sub {
340     my $msg = JSON::XS::decode_json $_[1];
341     my $first = "data: " . JSON::XS::encode_json ({
342     jsonrpc => "2.0", method => "notifications/progress", params => { progress => 1 },
343     }) . "\r\n\r\n";
344     my $last = "data: " . JSON::XS::encode_json ({
345     jsonrpc => "2.0", id => $msg->{id}, result => { resultType => "complete", streamed => 1 },
346     }) . "\r\n\r\n";
347     $handle->push_write (
348     "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n"
349     . "Content-Length: " . (length ($first) + length ($last)) . "\r\n\r\n"
350     . substr ($first, 0, 8)
351     );
352     $release = AnyEvent->timer (after => 0.02, cb => sub {
353     $handle->push_write (substr ($first, 8));
354     $release = AnyEvent->timer (after => 0.02, cb => sub {
355     $handle->push_write ($last);
356     });
357     });
358     });
359     });
360     }, sub { $port = $_[2]; () };
361     $client = AnyEvent::MCP::Client::HTTP->new (
362     url => "http://127.0.0.1:$port/", on_notification => sub {
363     $progress = $_[1] eq "notifications/progress" && !$finished;
364     },
365     );
366     $client->{connected} = 1;
367     $client->{protocol_version} = "2026-07-28";
368     ($success, $result) = wait_for (sub {
369     my $done = $_[0];
370     $client->rpc ("ping", {}, sub { $finished = 1; $done->(@_) });
371     });
372     ok $progress, "fragmented SSE progress delivered while streaming";
373     print STDERR "SSE progress missing; RPC success=$success, result=", JSON::XS::encode_json ($result), "\n"
374     unless $progress;
375     ok $success && $result->{streamed}, "SSE matching final response";
376     $client->close;
377     $sse_handle->destroy;
378     undef $release;
379     undef $listener;
380    
381 root 1.2 my $config = AnyEvent::MCP::Config::global_config ();
382 root 1.1 $config->{section}{"client example"} = { url => "http://example.invalid/", bearer => "configured", timeout => 7 };
383     $client = AnyEvent::MCP::Client::HTTP->new (name => "example", timeout => 9);
384     ok $client->{url} eq "http://example.invalid/" && $client->{bearer} eq "configured", "named client defaults";
385     ok $client->{timeout} == 9, "explicit client option wins";
386     $client->close;
387     $client = AnyEvent::MCP::Client::HTTP->new (name => "example", bearer => undef);
388     ok !defined $client->{bearer}, "explicit undef disables named auth";
389     $client->close;
390    
391     $config->{section}{"instance example"} = { path => "/named/", tokens => "configured,secondary" };
392     $server = AnyEvent::MCP::Server::HTTP->new ($config->http_settings ("example"), port => 31740);
393     ok $server->{path} eq "/named/" && $server->{tokens}[0] eq "configured", "resolved named server settings";
394     ok @{$server->{tokens}} == 2 && $server->{tokens}[1] eq "secondary", "ordered configured tokens";
395     ok $server->url eq "http://127.0.0.1:31740/configured/named/", "first token is the advertised URL token";
396     $server->close;
397    
398     my $req = AnyEvent::MCP::Client::Request->new (client => $client, on_reply => sub {});
399     $req->reply ({});
400     eval { $req->reply ({}) };
401     ok $@ =~ /already finished/, "duplicate input reply dies";
402     my $dismissed = 0;
403     $req = AnyEvent::MCP::Client::Request->new (client => $client, on_cancel => sub { ++$dismissed }, on_reply => sub {});
404     $req->cancel;
405     $req->cancel;
406     ok $req->{cancelled} && $dismissed == 1, "cancel dismisses input once";
407    
408     # Pending operations must not keep the client alive through its own callbacks.
409     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
410     $server = AnyEvent::MCP::Server::JSONL->new (toolsets => [$toolset]);
411     $server->accept ($a);
412     $client = AnyEvent::MCP::Client::JSONL->new;
413     $client->attach ($b);
414     my $released;
415     $client->call (slow => {}, sub { $released = $_[1] });
416     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
417     my $weak = $client;
418     weaken $weak;
419     undef $client;
420     ok !defined $weak && $released->{transport}, "dropping pending client releases it and fails callback";
421     $server->close;
422     undef $pending;
423    
424     # A close callback must still know which operations were interrupted, even
425     # though ordinary request callbacks have already been failed.
426     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
427     $server = AnyEvent::MCP::Server::JSONL->new (toolsets => [$toolset]);
428     $server->accept ($a);
429     $client = AnyEvent::MCP::Client::JSONL->new;
430     $client->attach ($b);
431     my $interrupted;
432     $client->call (slow => {}, sub { $interrupted = $_[1] });
433     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
434     my $close_error;
435     $client->{on_close} = sub { $close_error = $_[1] };
436     $client->close ("simulated broken stream");
437     ok $close_error->{pending} == 1 && $interrupted->{transport},
438     "close reports the interrupted operation count after failing callbacks";
439     $server->close;
440     undef $pending;
441    
442     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
443     $server = AnyEvent::MCP::Server::JSONL->new (toolsets => [$toolset]);
444     $server->accept ($a);
445     $client = AnyEvent::MCP::Client::JSONL->new (request_timeout => 0.02);
446     $client->attach ($b);
447     ($success, $result) = wait_for (sub { $client->call (slow => {}, $_[0]) });
448     ok !$success && $result->{cancelled} && $result->{message} =~ /timed out/, "overall request deadline";
449     $client->close;
450     $server->close;
451     undef $pending;
452    
453     # Keep an asynchronous input prompt open, then cancel its originating call.
454     my $prompt;
455     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
456     $_[1]->reply ({
457     resultType => "input_required", requestState => "opaque",
458     inputRequests => { q => { method => "elicitation/create", params => {} } },
459     });
460     });
461     $server->listen;
462     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
463     ($success, $result) = wait_for (sub { $client->call (question => {}, $_[0]) });
464     ok !$success && $result->{message} =~ /without a client handler/, "no implicit input approval";
465     my $prompt_ready;
466     my $dismiss = 0;
467     $client->{on_request} = sub {
468     $prompt = $_[1];
469     $prompt->{on_cancel} = sub { ++$dismiss };
470     $prompt_ready->();
471     };
472     ($success, $result) = wait_for (sub {
473     $prompt_ready = $_[0];
474     $id = $client->call (question => {}, sub { $cancelled = $_[1] });
475     });
476     $client->cancel ($id);
477     ok $prompt->{cancelled} && $dismiss == 1 && $cancelled->{cancelled}, "cancelling call dismisses asynchronous prompt";
478     $client->close;
479     $server->close;
480     undef $prompt;
481    
482     # Modern tool-name headers must encode non-ASCII names.
483     my $unicode = "echo-" . chr 0x3bb;
484     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
485     $_[1]->result ({ name => $_[1]{tool} });
486     });
487     $server->listen;
488     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
489     ($success, $result) = wait_for (sub { $client->call ($unicode, {}, $_[0]) });
490     ok $success && $result->{structuredContent}{name} eq $unicode, "Unicode Mcp-Name header";
491     $client->close;
492     $server->close;
493    
494     # Two asynchronous answers can arrive in any order; continuation happens once.
495     my $rounds = 0;
496     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
497     my ($server, $req) = @_;
498     ++$rounds;
499     if ($req->{params}{inputResponses}) {
500     $req->result ({ inputs => $req->{params}{inputResponses} });
501     } else {
502     $req->reply ({
503     resultType => "input_required", inputRequests => {
504     a => { method => "elicitation/create", params => {} },
505     b => { method => "elicitation/create", params => {} },
506     },
507     });
508     }
509     });
510     $server->listen;
511     my %prompts;
512     $client = AnyEvent::MCP::Client::HTTP->new (
513     url => $server->url, on_request => sub {
514     $prompts{$_[1]{id}} = $_[1];
515     if (keys %prompts == 2) {
516     $prompts{b}->reply ({ action => "decline" });
517     $prompts{a}->reply ({ action => "accept" });
518     }
519     },
520     );
521     ($success, $result) = wait_for (sub { $client->call (question => {}, $_[0]) });
522     ok $success && $rounds == 2, "multiple input answers produce one continuation";
523     ok $result->{structuredContent}{inputs}{a}{action} eq "accept"
524     && $result->{structuredContent}{inputs}{b}{action} eq "decline", "input keys and decisions preserved";
525     $client->close;
526     $server->close;
527     %prompts = ();
528    
529     # Named token settings authenticate either by bearer header or URL path.
530     $server = AnyEvent::MCP::Server::HTTP->new ($config->http_settings ("example"));
531     $server->listen;
532     $client = AnyEvent::MCP::Client::HTTP->new (
533     url => $server->url (0), bearer => "secondary",
534     );
535     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
536     ok $success, "second configured token authenticates";
537     $client->close;
538     $client = AnyEvent::MCP::Client::HTTP->new (
539     url => $server->url (0), bearer => "unlisted",
540     );
541     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
542     ok !$success && $result->{message} =~ /401/, "unlisted token rejected";
543     $client->close;
544     $server->close;
545    
546     my $exit_cv = AnyEvent->condvar;
547     my $reap_poll = AnyEvent->timer (after => 0, interval => 0.02, cb => sub {
548     $exit_cv->send (1) unless kill 0 => $pid;
549     });
550     my $reap_timeout = AnyEvent->timer (after => 30, cb => sub { $exit_cv->send (0) });
551     ok $exit_cv->recv && waitpid ($pid, 1) == -1, "subprocess child was reaped";
552     undef $reap_poll;
553     undef $reap_timeout;
554     eval { AnyEvent::MCP::Client::HTTP->new (url => "http://localhost/", bearer => "bad\nheader") };
555     ok $@ =~ /Invalid bearer/, "credential header injection rejected";
556    
557     # A legacy session ID belongs to initialization and must accompany later POSTs.
558     my (@http_handles, $initializations, $session_header);
559     $listener = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
560     my $handle = AnyEvent::Handle->new (
561     fh => $_[0], on_error => sub { $_[0]->destroy }, on_eof => sub { $_[0]->destroy },
562     );
563     push @http_handles, $handle;
564     $handle->push_read (line => "\r\n\r\n", sub {
565     my ($handle, $header) = @_;
566     my ($length) = $header =~ /Content-Length: ([0-9]+)/i;
567     $handle->push_read (chunk => $length, sub {
568     my $msg = JSON::XS::decode_json $_[1];
569     my ($status, $extra, $body) = ("202 Accepted", "", "");
570     if ($msg->{method} eq "initialize") {
571     ++$initializations;
572     $status = "200 OK";
573     $extra = "Mcp-Session-Id: test-session\r\n";
574     $body = JSON::XS::encode_json ({
575     jsonrpc => "2.0", id => $msg->{id}, result => {
576     protocolVersion => "2025-06-18", capabilities => {},
577     serverInfo => { name => "legacy", version => "0" },
578     },
579     });
580     } elsif ($msg->{method} eq "ping") {
581     $session_header = $header =~ /Mcp-Session-Id: test-session/i;
582     $status = "404 Not Found";
583     }
584     $handle->push_write (
585     "HTTP/1.1 $status\r\nContent-Type: application/json\r\n"
586     . $extra . "Content-Length: " . length ($body) . "\r\nConnection: close\r\n\r\n$body"
587     );
588     });
589     });
590     }, sub { $port = $_[2]; () };
591     $client = AnyEvent::MCP::Client::HTTP->new (
592     url => "http://127.0.0.1:$port/", versions => ["2025-06-18"],
593     );
594     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
595     ok !$success && $result->{message} =~ /session expired/ && !$client->{connected}, "session expiry invalidates client";
596     ok $session_header && $initializations == 1, "session header retained without retry";
597     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
598     ok !$success && $initializations == 2, "later operation creates a fresh session";
599     $client->close;
600     $_->destroy for @http_handles;
601     @http_handles = ();
602     undef $listener;
603    
604     my $sent = 0;
605     $listener = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
606     my $handle = AnyEvent::Handle->new (
607     fh => $_[0], on_error => sub { $_[0]->destroy }, on_eof => sub { $_[0]->destroy },
608     );
609     push @http_handles, $handle;
610     $handle->push_read (line => "\r\n\r\n", sub {
611     ++$sent;
612     $_[0]->destroy;
613     });
614     }, sub { $port = $_[2]; () };
615     $client = AnyEvent::MCP::Client::HTTP->new (url => "http://127.0.0.1:$port/");
616     $client->{connected} = 1;
617     $client->{protocol_version} = "2026-07-28";
618     ($success, $result) = wait_for (sub { $client->call (change => {}, $_[0]) });
619     ok !$success && $result->{transport} && $sent == 1, "broken HTTP tool call is not replayed";
620     $client->close;
621     $_->destroy for @http_handles;
622     @http_handles = ();
623     undef $listener;
624    
625     my ($redirect_target, $redirect_port, $redirected);
626     $redirect_target = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
627     ++$redirected;
628     close $_[0];
629     }, sub { $redirect_port = $_[2]; () };
630     $listener = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
631     my $handle = AnyEvent::Handle->new (
632     fh => $_[0], on_error => sub { $_[0]->destroy }, on_eof => sub { $_[0]->destroy },
633     );
634     push @http_handles, $handle;
635     $handle->push_read (line => "\r\n\r\n", sub {
636     $_[0]->push_write (
637     "HTTP/1.1 302 Found\r\nContent-Length: 0\r\nConnection: close\r\n"
638     . "Location: http://127.0.0.1:$redirect_port/\r\n\r\n"
639     );
640     });
641     }, sub { $port = $_[2]; () };
642     $client = AnyEvent::MCP::Client::HTTP->new (url => "http://127.0.0.1:$port/", bearer => "secret");
643     $client->{connected} = 1;
644     $client->{protocol_version} = "2026-07-28";
645     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
646     ok !$success && !$redirected && $result->{message} =~ /302/, "redirect does not forward credentials";
647     $client->close;
648     $_->destroy for @http_handles;
649     undef $listener;
650     undef $redirect_target;