ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/t/c04_client.t
Revision: 1.4
Committed: Wed Nov 25 05:42:42 2026 UTC (3 days ago) by root
Content type: application/x-troff
Branch: MAIN
CVS Tags: HEAD
Changes since 1.3: +177 -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.4 print "1..94\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 root 1.4 # A modern discovery probe can receive an empty HTTP 400 from a 2025
169     # Streamable HTTP server. Distinguish this from modern protocol errors.
170     my ($probe, $legacy_reply) = ("", "2025-06-18");
171     my %seen;
172     my ($tool_version, $init_version, $tool_meta);
173     $server = AnyEvent::MCP::Server::HTTP->new (
174     auth => "none",
175     on_http_request => sub {
176     my ($server, $request, $reply) = @_;
177     my $message = JSON::XS::decode_json $request->{body};
178     ++$seen{$message->{method}};
179    
180     my ($status, $body) = ("200 OK", undef);
181     if ($message->{method} eq "server/discover") {
182     $status = $probe eq "auth" ? "401 Unauthorized"
183     : $probe eq "unavailable" ? "503 Service Unavailable"
184     : $probe eq "method404" ? "404 Not Found"
185     : $probe eq "method200" ? "200 OK" : "400 Bad Request";
186     if ($probe eq "text") {
187     $body = "Bad protocol version";
188     } elsif ($probe eq "unknown") {
189     $body = JSON::XS::encode_json ({
190     jsonrpc => "2.0", id => $message->{id},
191     error => { code => -32603, message => "Unknown request" },
192     });
193     } elsif ($probe =~ /\A(-3202[012])(?:-only)?\z/) {
194     my $code = $1;
195     $body = JSON::XS::encode_json ({
196     jsonrpc => "2.0", id => $message->{id},
197     error => {
198     code => 0 + $code, message => "Modern protocol error",
199     ($code eq "-32022"
200     ? (data => { supported => [$probe =~ /only/ ? "2026-07-28" : "2025-06-18"] }) : ()),
201     },
202     });
203     } elsif ($probe =~ /\Amethod(?:200|404)\z/) {
204     $body = JSON::XS::encode_json ({
205     jsonrpc => "2.0", id => $message->{id},
206     error => { code => -32601, message => "Method not found" },
207     });
208     } elsif ($probe eq "auth") {
209     $body = JSON::XS::encode_json ({
210     jsonrpc => "2.0", id => $message->{id},
211     error => { code => -32603, message => "Unauthorized" },
212     });
213     }
214     } elsif ($message->{method} eq "initialize") {
215     $init_version = $message->{params}{protocolVersion};
216     $body = JSON::XS::encode_json ({
217     jsonrpc => "2.0", id => $message->{id},
218     result => {
219     protocolVersion => $legacy_reply,
220     serverInfo => { name => "legacy-test", version => "1" }, capabilities => {},
221     },
222     });
223     } elsif ($message->{method} eq "notifications/initialized") {
224     $status = "202 Accepted";
225     } elsif ($message->{method} eq "tools/list") {
226     $body = JSON::XS::encode_json ({
227     jsonrpc => "2.0", id => $message->{id},
228     result => { tools => [{ name => "echo", inputSchema => { type => "object" } }] },
229     });
230     } elsif ($message->{method} eq "tools/call") {
231     $tool_version = $request->{"mcp-protocol-version"};
232     $tool_meta = $message->{params}{_meta};
233     $body = JSON::XS::encode_json ({
234     jsonrpc => "2.0", id => $message->{id},
235     result => { content => [], structuredContent => $message->{params}{arguments} },
236     });
237     } else {
238     die "Unexpected method $message->{method}\n";
239     }
240     my ($code, $reason) = split / /, $status, 2;
241     $reply->($code, $reason, { "Content-Type" => "application/json" }, $body // "");
242     1;
243     },
244     );
245     $server->listen;
246     for my $case (qw(empty text unknown)) {
247     %seen = ();
248     $probe = $case;
249     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
250     ($success, $result) = wait_for (sub { $client->tools ($_[0]) });
251     ok $success && @$result == 1 && $result->[0]{name} eq "echo"
252     && $seen{"server/discover"} == 1 && $seen{initialize} == 1
253     && $seen{"notifications/initialized"} == 1 && $seen{"tools/list"} == 1,
254     "HTTP 400 $case falls back through complete legacy initialization";
255     $client->close;
256     }
257     for my $code (-32020, -32021) {
258     %seen = ();
259     $probe = $code;
260     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
261     ($success, $result) = wait_for (sub { $client->connect ($_[0]) });
262     ok !$success && $result->{code} == $code && !$seen{initialize},
263     "recognized modern error $code does not downgrade";
264     $client->close;
265     }
266     %seen = ();
267     $probe = "-32022";
268     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
269     ($success, $result) = wait_for (sub { $client->connect ($_[0]) });
270     ok $success && $client->{protocol_version} eq "2025-06-18"
271     && $seen{initialize} == 1, "modern unsupported-version error selects advertised compatible legacy version";
272     $client->close;
273     %seen = ();
274     $probe = "-32022-only";
275     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
276     ($success, $result) = wait_for (sub { $client->connect ($_[0]) });
277     ok !$success && $result->{code} == -32022 && !$seen{initialize},
278     "modern unsupported-version error without common legacy protocol is reported";
279     $client->close;
280     for my $case (qw(method200 method404)) {
281     %seen = ();
282     $probe = $case;
283     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
284     ($success, $result) = wait_for (sub { $client->connect ($_[0]) });
285     ok $case eq "method200"
286     ? $success && $seen{initialize} == 1
287     : !$success && $result->{http_status} == 404 && !$seen{initialize},
288     "HTTP $case method-not-found response has appropriate discovery behavior";
289     $client->close;
290     }
291     for my $case (qw(auth unavailable)) {
292     %seen = ();
293     $probe = $case;
294     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
295     ($success, $result) = wait_for (sub { $client->connect ($_[0]) });
296     ok !$success && !$seen{initialize}
297     && $result->{http_status} == ($case eq "auth" ? 401 : 503),
298     "HTTP $case is not mistaken for a legacy server";
299     $client->close;
300     }
301     %seen = ();
302     $probe = "empty";
303     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url, versions => ["2026-07-28"]);
304     ($success, $result) = wait_for (sub { $client->connect ($_[0]) });
305     ok !$success && !$seen{initialize} && $result->{http_status} == 400,
306     "HTTP 400 cannot downgrade when legacy support is disabled";
307     $client->close;
308     $legacy_reply = "2024-11-05";
309     %seen = ();
310     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url, force_protocol => "2025-11-25");
311     ($success, $result) = wait_for (sub {
312     $client->call ("echo", { forced => 1 }, $_[0], _meta => {
313     progressToken => "retained",
314     "io.modelcontextprotocol/protocolVersion" => "2026-07-28",
315     "io.modelcontextprotocol/clientCapabilities" => {},
316     });
317     });
318     ok $success && $result->{structuredContent}{forced}
319     && $client->{protocol_version} eq "2025-11-25"
320     && $tool_meta->{progressToken} eq "retained"
321     && !grep (m{\Aio\.modelcontextprotocol/}, keys %$tool_meta)
322     && $tool_version eq "2025-11-25" && !$seen{"server/discover"} && $seen{initialize} == 1,
323     "force_protocol overrides bogus negotiated version and subsequent request headers";
324     $client->close;
325     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url, force_protocol => "2025-06-18");
326     ($success, $result) = wait_for (sub { $client->connect ($_[0]) });
327     ok $success && $init_version eq "2025-06-18"
328     && $client->{protocol_version} eq "2025-06-18",
329     "forced legacy revision also controls the initial version offer";
330     $client->close;
331     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url, versions => ["2025-11-25"]);
332     ($success, $result) = wait_for (sub { $client->connect ($_[0]) });
333     ok !$success && $result->{message} =~ /Unsupported negotiated protocol version/,
334     "without override bogus legacy version still rejected";
335     $client->close;
336     eval { AnyEvent::MCP::Client::HTTP->new (url => $server->url, force_protocol => "2024-11-05") };
337     ok $@ =~ /Unsupported forced protocol version/, "force_protocol refuses unsupported local revision";
338     eval { AnyEvent::MCP::Client::HTTP->new (
339     url => $server->url, versions => ["2025-06-18"], force_protocol => "2025-11-25",
340     ) };
341     ok $@ =~ /excluded by versions/, "force_protocol respects caller's supported-version restriction";
342     $server->close;
343    
344 root 1.1 my $calls = 0;
345     my @input;
346     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
347     my ($server, $req, $args) = @_;
348     ++$calls;
349     if (exists $req->{params}{inputResponses}) {
350     ok $req->{params}{requestState} eq "opaque", "request state echoed";
351     ok $req->{params}{inputResponses}{question}{content}{answer} == 42, "input answer echoed";
352     ok $args->{original} eq "keep", "original tool arguments preserved";
353     $req->result ({ answer => 42 });
354     } else {
355     $req->reply ({
356     resultType => "input_required", requestState => "opaque",
357     inputRequests => { question => {
358     method => "elicitation/create", params => { message => "question" },
359     } },
360     });
361     }
362     });
363     $server->listen;
364     $client = AnyEvent::MCP::Client::HTTP->new (
365     url => $server->url, client_capabilities => { elicitation => { form => {} } },
366     on_request => sub {
367     my ($client, $req) = @_;
368     push @input, $req;
369     $req->reply ({ action => "accept", content => { answer => 42 } });
370     },
371     );
372     ($success, $result) = wait_for (sub { $client->call (question => { original => "keep" }, $_[0]) });
373     ok $success && $result->{structuredContent}{answer} == 42, "modern input continuation";
374     ok $calls == 2 && @input == 1 && $input[0]{finished}, "input handled once";
375     ($success, $result) = wait_for (sub {
376     $client->rpc ("tools/call", { name => "question", arguments => {} }, $_[0]);
377     });
378     ok $success && $result->{resultType} eq "input_required" && @input == 1, "raw RPC preserves challenge";
379     $client->close;
380     $server->close;
381     @input = ();
382    
383 root 1.3 # State-only continuations are retries without elicitation or inputResponses.
384     my $state_calls = 0;
385     my $state_ok = 1;
386     my @state_times;
387     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
388     my ($server, $req, $args) = @_;
389     $state_ok &&= $state_calls
390     ? ($req->{params}{requestState} // "") eq "state-$state_calls"
391     && !exists $req->{params}{inputResponses}
392     : !exists $req->{params}{requestState};
393     push @state_times, AE::now;
394     ++$state_calls;
395     if ($state_calls <= 3) {
396     $req->reply ({ resultType => "input_required", requestState => "state-$state_calls" });
397     } else {
398     $req->result ({ count => $state_calls, original => $args->{original} });
399     }
400     });
401     $server->listen;
402     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
403     ($success, $result) = wait_for (sub {
404     $client->call (progress => { original => "untouched" }, $_[0]);
405     });
406     ok $success && $result->{structuredContent}{count} == 4
407     && $result->{structuredContent}{original} eq "untouched" && $state_ok,
408     "state-only continuation preserves opaque state and original arguments without a handler";
409     ok @state_times == 4 && $state_times[2] - $state_times[1] >= .18
410     && $state_times[3] - $state_times[2] >= .42,
411     "state-only retries start immediately, then back off by 250ms per round";
412     $state_calls = 0;
413     ($success, $result) = wait_for (sub {
414     $client->rpc ("tools/call", { name => "progress", arguments => {} }, $_[0]);
415     });
416     ok $success && $result->{resultType} eq "input_required" && $state_calls == 1,
417     "raw RPC does not retry state-only challenges";
418     $server->{on_tools_call} = sub {
419     $_[1]->reply ({ resultType => "input_required" });
420     };
421     ($success, $result) = wait_for (sub { $client->call (progress => {}, $_[0]) });
422     ok !$success && $result->{message} =~ /Invalid input-required/,
423     "state-only challenge without requestState is rejected";
424     $state_calls = 0;
425     $server->{on_tools_call} = sub {
426     ++$state_calls;
427     $_[1]->reply ({ resultType => "input_required", requestState => "again" });
428     };
429     ($success, $result) = wait_for (sub { $client->call (progress => {}, $_[0]) });
430     ok !$success && $result->{message} =~ /Too many state-only retries/ && $state_calls == 11,
431     "state-only retries stop after ten retries";
432     $state_calls = 0;
433     my $state_cancel;
434     my $state_id = $client->call (progress => {}, sub { $state_cancel = $_[1] });
435     my $cancel_timer = AnyEvent->timer (after => .1, cb => sub { $client->cancel ($state_id) });
436     my $cancel_cv = AnyEvent->condvar;
437     my $check_timer = AnyEvent->timer (after => .65, cb => sub { $cancel_cv->send });
438     $cancel_cv->recv;
439     ok $state_cancel->{cancelled} && $state_calls == 2,
440     "cancellation prevents pending state-only retry";
441     undef $cancel_timer;
442     undef $check_timer;
443     $client->close;
444     $server->close;
445    
446 root 1.1 my $page = 0;
447     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_list => sub {
448     $_[1]->reply ({ tools => [{ name => ++$page }], ($page == 1 ? (nextCursor => "second") : ()) });
449     });
450     $server->listen;
451     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
452     ($success, $result) = wait_for (sub { $client->tools ($_[0]) });
453     ok $success && @$result == 2 && $result->[1]{name} == 2, "tool pagination";
454     $server->{on_tools_list} = sub { $_[1]->reply ({ tools => [], nextCursor => "repeat" }) };
455     ($success, $result) = wait_for (sub { $client->tools ($_[0]) });
456     ok !$success && $result->{message} =~ /Repeated/, "pagination loop rejected";
457     $client->close;
458     $server->close;
459    
460     socketpair my $a, my $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
461     $server = AnyEvent::MCP::Server::JSONL->new (toolsets => [$toolset]);
462     $server->accept ($a);
463     $client = AnyEvent::MCP::Client::JSONL->new;
464     $client->attach ($b);
465     my @order;
466     ($success, $result) = wait_for (sub {
467     my $done = $_[0];
468     $client->call (slow => {}, sub { push @order, "slow"; $done->(@_) });
469     $client->rpc ("ping", {}, sub { push @order, "ping"; $pending->reply ({}); undef $pending });
470     });
471     ok $success && join (",", @order) eq "ping,slow", "JSONL replies can be out of order";
472    
473     my ($id, $cancelled, $completions);
474     $id = $client->call (slow => {}, sub { ++$completions; $cancelled = $_[1] });
475     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
476     $client->cancel ($id);
477     ok $completions == 1 && $cancelled->{cancelled}, "local cancellation once";
478     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
479     ok $pending->{cancelled}, "wire cancellation reaches server";
480     undef $pending;
481     $client->cancel ($id);
482     ok $completions == 1, "repeated cancellation ignored";
483    
484     $id = $client->call (slow => {}, sub { ++$completions; $cancelled = $_[1] });
485     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
486     $client->close;
487     ok $completions == 2 && $cancelled->{transport}, "close fails outstanding call";
488     $server->close;
489     undef $pending;
490    
491     $client = AnyEvent::MCP::Client::JSONL->new (
492     command => [$^X, "-Ilib", "-e", '
493     use AnyEvent::MCP::Server::Simple;
494     mcp_tool echo => "echo", {}, sub { $_[0]->result ($_[1]) };
495     mcp_start;
496     '],
497     env => { PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL => "stdio" },
498     );
499     ($success, $result) = wait_for (sub { $client->call (echo => { subprocess => 1 }, $_[0]) });
500     ok $success && $result->{structuredContent}{subprocess}, "direct subprocess command";
501     my $pid = $client->{pid};
502     $client->close;
503     ok !$client->{pid}, "close detaches child";
504     ($success, $result) = wait_for (sub { $client->call (echo => { restarted => 1 }, $_[0]) });
505     ok $success && $result->{structuredContent}{restarted} && $client->{pid} != $pid, "new call restarts child";
506     $client->close;
507    
508     # A real streaming response: progress arrives before the final event.
509     my ($sse_handle, $release, $listener, $port, $finished, $progress);
510     $listener = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
511     $sse_handle = AnyEvent::Handle->new (fh => $_[0], on_error => sub { die $_[2] });
512     $sse_handle->push_read (line => "\r\n\r\n", sub {
513     my ($handle, $header) = @_;
514     my ($length) = $header =~ /Content-Length: ([0-9]+)/i;
515     $handle->push_read (chunk => $length, sub {
516     my $msg = JSON::XS::decode_json $_[1];
517     my $first = "data: " . JSON::XS::encode_json ({
518     jsonrpc => "2.0", method => "notifications/progress", params => { progress => 1 },
519     }) . "\r\n\r\n";
520     my $last = "data: " . JSON::XS::encode_json ({
521     jsonrpc => "2.0", id => $msg->{id}, result => { resultType => "complete", streamed => 1 },
522     }) . "\r\n\r\n";
523     $handle->push_write (
524     "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n"
525     . "Content-Length: " . (length ($first) + length ($last)) . "\r\n\r\n"
526     . substr ($first, 0, 8)
527     );
528     $release = AnyEvent->timer (after => 0.02, cb => sub {
529     $handle->push_write (substr ($first, 8));
530     $release = AnyEvent->timer (after => 0.02, cb => sub {
531     $handle->push_write ($last);
532     });
533     });
534     });
535     });
536     }, sub { $port = $_[2]; () };
537     $client = AnyEvent::MCP::Client::HTTP->new (
538     url => "http://127.0.0.1:$port/", on_notification => sub {
539     $progress = $_[1] eq "notifications/progress" && !$finished;
540     },
541     );
542     $client->{connected} = 1;
543     $client->{protocol_version} = "2026-07-28";
544     ($success, $result) = wait_for (sub {
545     my $done = $_[0];
546     $client->rpc ("ping", {}, sub { $finished = 1; $done->(@_) });
547     });
548     ok $progress, "fragmented SSE progress delivered while streaming";
549     print STDERR "SSE progress missing; RPC success=$success, result=", JSON::XS::encode_json ($result), "\n"
550     unless $progress;
551     ok $success && $result->{streamed}, "SSE matching final response";
552     $client->close;
553     $sse_handle->destroy;
554     undef $release;
555     undef $listener;
556    
557 root 1.2 my $config = AnyEvent::MCP::Config::global_config ();
558 root 1.1 $config->{section}{"client example"} = { url => "http://example.invalid/", bearer => "configured", timeout => 7 };
559     $client = AnyEvent::MCP::Client::HTTP->new (name => "example", timeout => 9);
560     ok $client->{url} eq "http://example.invalid/" && $client->{bearer} eq "configured", "named client defaults";
561     ok $client->{timeout} == 9, "explicit client option wins";
562     $client->close;
563     $client = AnyEvent::MCP::Client::HTTP->new (name => "example", bearer => undef);
564     ok !defined $client->{bearer}, "explicit undef disables named auth";
565     $client->close;
566    
567     $config->{section}{"instance example"} = { path => "/named/", tokens => "configured,secondary" };
568     $server = AnyEvent::MCP::Server::HTTP->new ($config->http_settings ("example"), port => 31740);
569     ok $server->{path} eq "/named/" && $server->{tokens}[0] eq "configured", "resolved named server settings";
570     ok @{$server->{tokens}} == 2 && $server->{tokens}[1] eq "secondary", "ordered configured tokens";
571     ok $server->url eq "http://127.0.0.1:31740/configured/named/", "first token is the advertised URL token";
572     $server->close;
573    
574     my $req = AnyEvent::MCP::Client::Request->new (client => $client, on_reply => sub {});
575     $req->reply ({});
576     eval { $req->reply ({}) };
577     ok $@ =~ /already finished/, "duplicate input reply dies";
578     my $dismissed = 0;
579     $req = AnyEvent::MCP::Client::Request->new (client => $client, on_cancel => sub { ++$dismissed }, on_reply => sub {});
580     $req->cancel;
581     $req->cancel;
582     ok $req->{cancelled} && $dismissed == 1, "cancel dismisses input once";
583    
584     # Pending operations must not keep the client alive through its own callbacks.
585     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
586     $server = AnyEvent::MCP::Server::JSONL->new (toolsets => [$toolset]);
587     $server->accept ($a);
588     $client = AnyEvent::MCP::Client::JSONL->new;
589     $client->attach ($b);
590     my $released;
591     $client->call (slow => {}, sub { $released = $_[1] });
592     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
593     my $weak = $client;
594     weaken $weak;
595     undef $client;
596     ok !defined $weak && $released->{transport}, "dropping pending client releases it and fails callback";
597     $server->close;
598     undef $pending;
599    
600     # A close callback must still know which operations were interrupted, even
601     # though ordinary request callbacks have already been failed.
602     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
603     $server = AnyEvent::MCP::Server::JSONL->new (toolsets => [$toolset]);
604     $server->accept ($a);
605     $client = AnyEvent::MCP::Client::JSONL->new;
606     $client->attach ($b);
607     my $interrupted;
608     $client->call (slow => {}, sub { $interrupted = $_[1] });
609     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
610     my $close_error;
611     $client->{on_close} = sub { $close_error = $_[1] };
612     $client->close ("simulated broken stream");
613     ok $close_error->{pending} == 1 && $interrupted->{transport},
614     "close reports the interrupted operation count after failing callbacks";
615     $server->close;
616     undef $pending;
617    
618     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
619     $server = AnyEvent::MCP::Server::JSONL->new (toolsets => [$toolset]);
620     $server->accept ($a);
621     $client = AnyEvent::MCP::Client::JSONL->new (request_timeout => 0.02);
622     $client->attach ($b);
623     ($success, $result) = wait_for (sub { $client->call (slow => {}, $_[0]) });
624     ok !$success && $result->{cancelled} && $result->{message} =~ /timed out/, "overall request deadline";
625     $client->close;
626     $server->close;
627     undef $pending;
628    
629     # Keep an asynchronous input prompt open, then cancel its originating call.
630     my $prompt;
631     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
632     $_[1]->reply ({
633     resultType => "input_required", requestState => "opaque",
634     inputRequests => { q => { method => "elicitation/create", params => {} } },
635     });
636     });
637     $server->listen;
638     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
639     ($success, $result) = wait_for (sub { $client->call (question => {}, $_[0]) });
640     ok !$success && $result->{message} =~ /without a client handler/, "no implicit input approval";
641     my $prompt_ready;
642     my $dismiss = 0;
643     $client->{on_request} = sub {
644     $prompt = $_[1];
645     $prompt->{on_cancel} = sub { ++$dismiss };
646     $prompt_ready->();
647     };
648     ($success, $result) = wait_for (sub {
649     $prompt_ready = $_[0];
650     $id = $client->call (question => {}, sub { $cancelled = $_[1] });
651     });
652     $client->cancel ($id);
653     ok $prompt->{cancelled} && $dismiss == 1 && $cancelled->{cancelled}, "cancelling call dismisses asynchronous prompt";
654     $client->close;
655     $server->close;
656     undef $prompt;
657    
658     # Modern tool-name headers must encode non-ASCII names.
659     my $unicode = "echo-" . chr 0x3bb;
660     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
661     $_[1]->result ({ name => $_[1]{tool} });
662     });
663     $server->listen;
664     $client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
665     ($success, $result) = wait_for (sub { $client->call ($unicode, {}, $_[0]) });
666     ok $success && $result->{structuredContent}{name} eq $unicode, "Unicode Mcp-Name header";
667     $client->close;
668     $server->close;
669    
670     # Two asynchronous answers can arrive in any order; continuation happens once.
671     my $rounds = 0;
672     $server = AnyEvent::MCP::Server::HTTP->new (auth => "none", on_tools_call => sub {
673     my ($server, $req) = @_;
674     ++$rounds;
675     if ($req->{params}{inputResponses}) {
676     $req->result ({ inputs => $req->{params}{inputResponses} });
677     } else {
678     $req->reply ({
679     resultType => "input_required", inputRequests => {
680     a => { method => "elicitation/create", params => {} },
681     b => { method => "elicitation/create", params => {} },
682     },
683     });
684     }
685     });
686     $server->listen;
687     my %prompts;
688     $client = AnyEvent::MCP::Client::HTTP->new (
689     url => $server->url, on_request => sub {
690     $prompts{$_[1]{id}} = $_[1];
691     if (keys %prompts == 2) {
692     $prompts{b}->reply ({ action => "decline" });
693     $prompts{a}->reply ({ action => "accept" });
694     }
695     },
696     );
697     ($success, $result) = wait_for (sub { $client->call (question => {}, $_[0]) });
698     ok $success && $rounds == 2, "multiple input answers produce one continuation";
699     ok $result->{structuredContent}{inputs}{a}{action} eq "accept"
700     && $result->{structuredContent}{inputs}{b}{action} eq "decline", "input keys and decisions preserved";
701     $client->close;
702     $server->close;
703     %prompts = ();
704    
705     # Named token settings authenticate either by bearer header or URL path.
706     $server = AnyEvent::MCP::Server::HTTP->new ($config->http_settings ("example"));
707     $server->listen;
708     $client = AnyEvent::MCP::Client::HTTP->new (
709     url => $server->url (0), bearer => "secondary",
710     );
711     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
712     ok $success, "second configured token authenticates";
713     $client->close;
714     $client = AnyEvent::MCP::Client::HTTP->new (
715     url => $server->url (0), bearer => "unlisted",
716     );
717     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
718     ok !$success && $result->{message} =~ /401/, "unlisted token rejected";
719     $client->close;
720     $server->close;
721    
722     my $exit_cv = AnyEvent->condvar;
723     my $reap_poll = AnyEvent->timer (after => 0, interval => 0.02, cb => sub {
724     $exit_cv->send (1) unless kill 0 => $pid;
725     });
726     my $reap_timeout = AnyEvent->timer (after => 30, cb => sub { $exit_cv->send (0) });
727     ok $exit_cv->recv && waitpid ($pid, 1) == -1, "subprocess child was reaped";
728     undef $reap_poll;
729     undef $reap_timeout;
730     eval { AnyEvent::MCP::Client::HTTP->new (url => "http://localhost/", bearer => "bad\nheader") };
731     ok $@ =~ /Invalid bearer/, "credential header injection rejected";
732    
733     # A legacy session ID belongs to initialization and must accompany later POSTs.
734     my (@http_handles, $initializations, $session_header);
735     $listener = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
736     my $handle = AnyEvent::Handle->new (
737     fh => $_[0], on_error => sub { $_[0]->destroy }, on_eof => sub { $_[0]->destroy },
738     );
739     push @http_handles, $handle;
740     $handle->push_read (line => "\r\n\r\n", sub {
741     my ($handle, $header) = @_;
742     my ($length) = $header =~ /Content-Length: ([0-9]+)/i;
743     $handle->push_read (chunk => $length, sub {
744     my $msg = JSON::XS::decode_json $_[1];
745     my ($status, $extra, $body) = ("202 Accepted", "", "");
746     if ($msg->{method} eq "initialize") {
747     ++$initializations;
748     $status = "200 OK";
749     $extra = "Mcp-Session-Id: test-session\r\n";
750     $body = JSON::XS::encode_json ({
751     jsonrpc => "2.0", id => $msg->{id}, result => {
752     protocolVersion => "2025-06-18", capabilities => {},
753     serverInfo => { name => "legacy", version => "0" },
754     },
755     });
756     } elsif ($msg->{method} eq "ping") {
757     $session_header = $header =~ /Mcp-Session-Id: test-session/i;
758     $status = "404 Not Found";
759     }
760     $handle->push_write (
761     "HTTP/1.1 $status\r\nContent-Type: application/json\r\n"
762     . $extra . "Content-Length: " . length ($body) . "\r\nConnection: close\r\n\r\n$body"
763     );
764     });
765     });
766     }, sub { $port = $_[2]; () };
767     $client = AnyEvent::MCP::Client::HTTP->new (
768     url => "http://127.0.0.1:$port/", versions => ["2025-06-18"],
769     );
770     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
771     ok !$success && $result->{message} =~ /session expired/ && !$client->{connected}, "session expiry invalidates client";
772     ok $session_header && $initializations == 1, "session header retained without retry";
773     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
774     ok !$success && $initializations == 2, "later operation creates a fresh session";
775     $client->close;
776     $_->destroy for @http_handles;
777     @http_handles = ();
778     undef $listener;
779    
780     my $sent = 0;
781     $listener = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
782     my $handle = AnyEvent::Handle->new (
783     fh => $_[0], on_error => sub { $_[0]->destroy }, on_eof => sub { $_[0]->destroy },
784     );
785     push @http_handles, $handle;
786     $handle->push_read (line => "\r\n\r\n", sub {
787     ++$sent;
788     $_[0]->destroy;
789     });
790     }, sub { $port = $_[2]; () };
791     $client = AnyEvent::MCP::Client::HTTP->new (url => "http://127.0.0.1:$port/");
792     $client->{connected} = 1;
793     $client->{protocol_version} = "2026-07-28";
794     ($success, $result) = wait_for (sub { $client->call (change => {}, $_[0]) });
795     ok !$success && $result->{transport} && $sent == 1, "broken HTTP tool call is not replayed";
796     $client->close;
797     $_->destroy for @http_handles;
798     @http_handles = ();
799     undef $listener;
800    
801     my ($redirect_target, $redirect_port, $redirected);
802     $redirect_target = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
803     ++$redirected;
804     close $_[0];
805     }, sub { $redirect_port = $_[2]; () };
806     $listener = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
807     my $handle = AnyEvent::Handle->new (
808     fh => $_[0], on_error => sub { $_[0]->destroy }, on_eof => sub { $_[0]->destroy },
809     );
810     push @http_handles, $handle;
811     $handle->push_read (line => "\r\n\r\n", sub {
812     $_[0]->push_write (
813     "HTTP/1.1 302 Found\r\nContent-Length: 0\r\nConnection: close\r\n"
814     . "Location: http://127.0.0.1:$redirect_port/\r\n\r\n"
815     );
816     });
817     }, sub { $port = $_[2]; () };
818     $client = AnyEvent::MCP::Client::HTTP->new (url => "http://127.0.0.1:$port/", bearer => "secret");
819     $client->{connected} = 1;
820     $client->{protocol_version} = "2026-07-28";
821     ($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
822     ok !$success && !$redirected && $result->{message} =~ /302/, "redirect does not forward credentials";
823     $client->close;
824     $_->destroy for @http_handles;
825     undef $listener;
826     undef $redirect_target;