ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/t/01_server.t
Revision: 1.4
Committed: Sat Oct 10 08:47:18 2026 UTC (6 weeks, 5 days ago) by root
Content type: application/x-troff
Branch: MAIN
Changes since 1.3: +4 -1 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 use common::sense;
2     use Test::More;
3     use AnyEvent ();
4     use AnyEvent::Handle ();
5     use AnyEvent::MCP::Server ();
6     use AnyEvent::MCP::Server::Toolset ();
7     use AnyEvent::MCP::Server::JSONL ();
8     use AnyEvent::MCP::Server::HTTP ();
9     use JSON::XS ();
10     use Socket;
11    
12     my $toolset = AnyEvent::MCP::Server::Toolset->new;
13     my $pending;
14    
15     $toolset->tool (echo => "echo", {}, sub { $_[0]->result ($_[1]) });
16     $toolset->tool (slow => "slow", {}, sub { $pending = $_[0] });
17     $toolset->tool (fail => "fail", {}, sub { die "tool failed\n" });
18    
19     my $server = AnyEvent::MCP::Server->new (toolsets => [$toolset]);
20     my $meta = {
21     "io.modelcontextprotocol/protocolVersion" => "2026-07-28",
22     "io.modelcontextprotocol/clientCapabilities" => {},
23     };
24    
25     sub message {
26     my ($id, $method, $params) = @_;
27    
28     { jsonrpc => "2.0", id => $id, method => $method, params => { %{$params || {}}, _meta => {%$meta} } }
29     }
30    
31     my $response;
32 root 1.3 for my $id (1, 0, -1, 1.5, "1", "opaque") {
33     for my $method ("ping", "unknown") {
34     my $json = JSON::XS::encode_json ({
35     jsonrpc => "2.0", id => $id, method => $method, params => {},
36     });
37     $server->json_rpc ($json, sub { $response = shift }, protocol_version => "2025-11-25");
38     is JSON::XS::encode_json ([JSON::XS::decode_json ($response)->{id}]),
39     JSON::XS::encode_json ([$id]), "wire ID type preserved for $method";
40     }
41     }
42     $server->json_rpc (
43     '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"probe","version":"0"}}}',
44     sub { $response = shift },
45     );
46     like $response, qr/"id":1(?:,|})/, "initialization preserves numeric probe ID";
47    
48 root 1.1 $server->rpc (message (1, "server/discover"), sub { $response = shift });
49     is $response->{result}{resultType}, "complete", "modern result type";
50     is $response->{result}{supportedVersions}[0], "2026-07-28", "discovery";
51     is $response->{result}{_meta}{"io.modelcontextprotocol/serverInfo"}{name}, "AnyEvent::MCP", "server identity";
52    
53     my $request = $server->rpc (message (2, "tools/call", { name => "echo", arguments => { a => 42 } }),
54     sub { $response = shift });
55     is $response->{result}{structuredContent}{a}, 42, "structured result";
56     is JSON::XS::decode_json ($response->{result}{content}[0]{text})->{a}, 42, "JSON text fallback";
57     ok !exists $request->{on_reply} && !exists $request->{_reply}, "release reply callbacks";
58     eval { $request->reply ({}) };
59     like $@, qr/already finished/, "duplicate reply dies";
60    
61     $server->rpc (message (3, "tools/call", { name => "fail" }), sub { $response = shift });
62     ok $response->{result}{isError}, "tool exception is a tool error";
63     is $response->{result}{content}[0]{text}, "tool failed\n", "tool exception text";
64    
65     $server->rpc (message (4, "tools/call", { name => "absent" }), sub { $response = shift });
66     is $response->{error}{code}, -32602, "unknown tool is a protocol error";
67     $server->rpc (message (5, "unknown"), sub { $response = shift });
68     is $response->{error}{code}, -32601, "unknown method";
69     $server->json_rpc ("{", sub { $response = JSON::XS::decode_json shift });
70     is $response->{error}{code}, -32700, "parse error";
71     $server->rpc ([], sub { $response = shift });
72     is $response->{error}{code}, -32600, "reject batches";
73     $server->rpc (message (6, "tools/call", { name => "echo", arguments => [] }), sub { $response = shift });
74     is $response->{error}{code}, -32602, "invalid arguments";
75    
76     my $unsupported = message (7, "ping");
77     $unsupported->{params}{_meta}{"io.modelcontextprotocol/protocolVersion"} = "2099-01-01";
78     $server->rpc ($unsupported, sub { $response = shift });
79     is $response->{error}{code}, -32022, "unsupported version";
80     is $response->{error}{data}{requested}, "2099-01-01", "requested version in error";
81    
82     my $peer = {};
83     $server->rpc ({
84     jsonrpc => "2.0", id => 8, method => "initialize",
85     params => { protocolVersion => "2025-06-18", capabilities => {}, clientInfo => { name => "test", version => "0" } },
86     }, sub { $response = shift }, peer => $peer);
87     is $response->{result}{protocolVersion}, "2025-06-18", "legacy initialization";
88     ok !exists $response->{result}{resultType}, "legacy result shape";
89     $server->rpc ({ jsonrpc => "2.0", id => 9, method => "tools/call", params => { name => "echo" } },
90     sub { $response = shift }, peer => $peer);
91     is_deeply $response->{result}{structuredContent}, {}, "omitted arguments";
92     $server->rpc (message (10, "ping"), sub { $response = shift }, peer => $peer);
93     is $response->{result}{resultType}, "complete", "modern metadata overrides legacy peer";
94 root 1.2 is $peer->{protocol_version}, "2025-06-18", "modern request does not alter legacy state";
95 root 1.1
96     $request = $server->rpc (message (11, "tools/call", { name => "slow" }),
97     sub { die "cancelled reply" }, peer => $peer);
98     my $cancels = 0;
99     $request->{on_cancel} = sub { ++$cancels };
100     $server->rpc ({ jsonrpc => "2.0", method => "notifications/cancelled", params => { requestId => 11 } },
101     sub { ok !defined $_[0], "notification has no JSON-RPC response" }, peer => $peer);
102     ok $request->{cancelled}, "cancellation";
103     $request->cancel;
104     is $cancels, 1, "cancel callback once";
105     eval { $request->reply ({}) };
106     like $@, qr/already finished/, "reply after cancellation dies";
107     $pending = undef;
108    
109     my @notifications;
110     $request = AnyEvent::MCP::Server::Request->new (
111     params => { _meta => { progressToken => 0 } },
112     on_notify => sub { push @notifications, $_[2] },
113     );
114     $request->progress (1);
115     is $notifications[0]{progressToken}, 0, "zero progress token";
116     $request->reply ({});
117     $request->progress (2);
118     is scalar @notifications, 1, "late progress ignored";
119    
120     my $custom = AnyEvent::MCP::Server->new (
121     on_tools_call => sub {
122     my ($server, $req, $args) = @_;
123     is $args, $req->{args}, "custom dispatch receives same arguments";
124     $req->error ("custom error");
125     },
126     );
127     $custom->rpc (message (12, "tools/call", { name => "custom" }), sub { $response = shift });
128     is $response->{result}{content}[0]{text}, "custom error", "dispatch override";
129    
130     socketpair my $a, my $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
131     my $jsonl = AnyEvent::MCP::Server::JSONL->new (toolsets => [$toolset]);
132     $jsonl->accept ($a);
133     my $client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
134     my $cv = AnyEvent->condvar;
135     my $timer = AnyEvent->timer (after => 3, cb => sub { die "JSONL timeout" });
136    
137     $client->push_write (
138     JSON::XS::encode_json (message (20, "tools/call", { name => "slow" })) . "\n"
139     . JSON::XS::encode_json (message (21, "ping")) . "\n"
140     );
141     $client->push_read (line => sub {
142 root 1.3 like $_[1], qr/"id":21(?:,|})/, "JSONL preserves numeric ID";
143 root 1.1 is JSON::XS::decode_json ($_[1])->{id}, 21, "JSONL out-of-order reply";
144     $pending->reply ({});
145     $pending = undef;
146     });
147     $client->push_read (line => sub {
148     is JSON::XS::decode_json ($_[1])->{id}, 20, "delayed JSONL reply";
149     $cv->send;
150     });
151     $cv->recv;
152     undef $timer;
153     $jsonl->close;
154     $client->destroy;
155    
156     sub post {
157     my ($msg, $extra) = @_;
158    
159     my $body = JSON::XS::encode_json $msg;
160     "POST /mcp/ HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: " . length ($body)
161     . "\r\nMCP-Protocol-Version: 2026-07-28\r\nMcp-Method: $msg->{method}\r\n"
162     . ($msg->{method} eq "tools/call" ? "Mcp-Name: $msg->{params}{name}\r\n" : "")
163     . ($extra || "") . "\r\n$body"
164     }
165    
166     sub http_read {
167     my ($handle, $callback) = @_;
168    
169     $handle->push_read (line => "\r\n\r\n", sub {
170     my ($handle, $header) = @_;
171     my ($length) = $header =~ /Content-Length: ([0-9]+)/;
172    
173     $handle->push_read (chunk => $length, sub { $callback->($header, $_[1]) });
174     });
175     }
176    
177     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
178     my $http = AnyEvent::MCP::Server::HTTP->new (toolsets => [$toolset]);
179     $http->accept ($a);
180     $client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
181     $cv = AnyEvent->condvar;
182     $timer = AnyEvent->timer (after => 3, cb => sub { die "HTTP timeout" });
183    
184     $client->push_write (
185     post (message (30, "tools/call", { name => "slow" }))
186     . post (message (31, "ping"))
187     );
188     my $release = AnyEvent->timer (after => 0.01, cb => sub {
189     $pending->reply ({});
190     $pending = undef;
191     });
192     http_read ($client, sub {
193     like $_[0], qr/HTTP\/1.1 200 OK/, "HTTP status";
194 root 1.3 like $_[1], qr/"id":30(?:,|})/, "HTTP preserves numeric ID";
195 root 1.1 is JSON::XS::decode_json ($_[1])->{id}, 30, "HTTP first reply";
196     http_read ($client, sub {
197     is JSON::XS::decode_json ($_[1])->{id}, 31, "HTTP pipelined reply order";
198     $cv->send;
199     });
200     });
201     $cv->recv;
202     undef $timer;
203     undef $release;
204     $http->close;
205     $client->destroy;
206    
207 root 1.4 $http = AnyEvent::MCP::Server::HTTP->new (toolsets => [$toolset], origins => []);
208 root 1.1 for my $case (
209     ["Origin: https://invalid.example\r\n", 403, undef],
210     ["Mcp-Method: different\r\n", 400, -32020],
211     ) {
212     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
213     $http->accept ($a);
214     $client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
215     $cv = AnyEvent->condvar;
216     $timer = AnyEvent->timer (after => 3, cb => sub { die "HTTP rejection timeout" });
217    
218     $client->push_write (post (message (40, "ping"), $case->[0]));
219     http_read ($client, sub {
220     like $_[0], qr/HTTP\/1.1 $case->[1]/, "HTTP rejection";
221     is JSON::XS::decode_json ($_[1])->{error}{code}, $case->[2], "HTTP protocol error"
222     if defined $case->[2];
223     $cv->send;
224     });
225     $cv->recv;
226     undef $timer;
227     $http->close;
228     $client->destroy;
229     }
230    
231 root 1.3 for my $case (
232 root 1.4 [undef, "https://browser.example", "POST", 200, "*", 1],
233     [undef, "https://browser.example", "OPTIONS", 204, "*", 0],
234 root 1.3 [["*"], "https://browser.example", "POST", 200, "*", 1],
235     [["https://browser.example"], "https://browser.example", "POST", 200, "https://browser.example", 1],
236     [["https://browser.example"], "https://other.example", "POST", 403, undef, 1],
237     [["*"], "https://browser.example", "OPTIONS", 204, "*", 0],
238     [[], "https://browser.example", "OPTIONS", 403, undef, 0],
239     [[], undef, "OPTIONS", 405, undef, 0],
240     [["*"], "https://browser.example", "POST", 401, "*", 0],
241     ) {
242     my ($origins, $origin, $method, $status, $allowed, $cookie) = @$case;
243    
244     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
245     $http = AnyEvent::MCP::Server::HTTP->new (
246 root 1.4 toolsets => [$toolset], (defined $origins ? (origins => $origins) : ()), cookie => "token",
247 root 1.3 );
248     $http->accept ($a);
249     $client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
250     $cv = AnyEvent->condvar;
251     $timer = AnyEvent->timer (after => 3, cb => sub { die "CORS timeout" });
252    
253     my $request = $method eq "POST"
254     ? post (message (50, "ping"), defined $origin ? "Origin: $origin\r\n" : "")
255     : "OPTIONS /mcp/ HTTP/1.1\r\n"
256     . (defined $origin ? "Origin: $origin\r\n" : "")
257     . "Access-Control-Request-Method: POST\r\n"
258     . "Access-Control-Request-Headers: content-type,mcp-method\r\n\r\n";
259     $request =~ s{POST /mcp/}{POST /token/mcp/} if $cookie;
260    
261     $client->push_write ($request);
262     http_read ($client, sub {
263     my ($header) = @_;
264    
265     like $header, qr/HTTP\/1.1 $status /, "CORS $method status";
266     if (defined $allowed) {
267     like $header, qr/^Access-Control-Allow-Origin: \Q$allowed\E\r?$/m, "allowed origin";
268     like $header, qr/^Vary: Origin\r?$/m, "vary by allowed origin" if $allowed ne "*";
269     } else {
270     unlike $header, qr/Access-Control-Allow-Origin:/, "no allowed origin";
271     }
272     if ($status == 204) {
273     like $header, qr/Access-Control-Allow-Methods: POST, OPTIONS/, "preflight methods";
274     like $header, qr/Access-Control-Allow-Headers: .*mcp-method,mcp-name/, "modern preflight headers";
275     like $header, qr/Access-Control-Max-Age: 86400/, "preflight cache";
276     }
277     $cv->send;
278     });
279     $cv->recv;
280     undef $timer;
281     $http->close;
282     $client->destroy;
283     }
284    
285     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
286     my $dispatched = 0;
287     $http = AnyEvent::MCP::Server::HTTP->new (
288     toolsets => [$toolset], connection_close => 1, on_request => sub { ++$dispatched },
289     );
290     $http->accept ($a);
291     undef $a;
292     $cv = AnyEvent->condvar;
293     my $received = 0;
294     $client = AnyEvent::Handle->new (
295     fh => $b,
296     on_error => sub { die $_[2] },
297     on_read => sub { fail "unexpected second HTTP response"; $cv->send },
298     on_eof => sub {
299     ok $received, "response drained before EOF";
300     is $_[0]{rbuf}, "", "no pipelined second response";
301     is $dispatched, 1, "connection_close prevents dispatch of the next request";
302     $cv->send;
303     },
304     );
305     $timer = AnyEvent->timer (after => 3, cb => sub { $cv->croak ("connection_close timeout") });
306     $client->push_write (
307     post (message (60, "tools/call", { name => "slow" }))
308     . post (message (61, "ping"))
309     );
310     $release = AnyEvent->timer (after => 0.01, cb => sub {
311     $pending->reply ({ content => [{ type => "text", text => "x" x 131072 }] });
312     $pending = undef;
313     });
314     http_read ($client, sub {
315     my ($header, $body) = @_;
316    
317     like $header, qr/^Connection: close\r?$/m, "connection_close header for HTTP/1.1";
318     my $response = JSON::XS::decode_json $body;
319     is $response->{id}, 60, "delayed response delivered";
320     is length $response->{result}{content}[0]{text}, 131072, "complete response body before close";
321     $received = 1;
322     });
323     $cv->recv;
324     undef $timer;
325     undef $release;
326     $http->close;
327     $client->destroy;
328    
329 root 1.1 done_testing;