ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/t/01_server.t
Revision: 1.3
Committed: Thu Oct 8 01:37:31 2026 UTC (7 weeks ago) by root
Content type: application/x-troff
Branch: MAIN
Changes since 1.2: +114 -0 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     for my $case (
208     ["Origin: https://invalid.example\r\n", 403, undef],
209     ["Mcp-Method: different\r\n", 400, -32020],
210     ) {
211     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
212     $http->accept ($a);
213     $client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
214     $cv = AnyEvent->condvar;
215     $timer = AnyEvent->timer (after => 3, cb => sub { die "HTTP rejection timeout" });
216    
217     $client->push_write (post (message (40, "ping"), $case->[0]));
218     http_read ($client, sub {
219     like $_[0], qr/HTTP\/1.1 $case->[1]/, "HTTP rejection";
220     is JSON::XS::decode_json ($_[1])->{error}{code}, $case->[2], "HTTP protocol error"
221     if defined $case->[2];
222     $cv->send;
223     });
224     $cv->recv;
225     undef $timer;
226     $http->close;
227     $client->destroy;
228     }
229    
230 root 1.3 for my $case (
231     [["*"], "https://browser.example", "POST", 200, "*", 1],
232     [["https://browser.example"], "https://browser.example", "POST", 200, "https://browser.example", 1],
233     [["https://browser.example"], "https://other.example", "POST", 403, undef, 1],
234     [["*"], "https://browser.example", "OPTIONS", 204, "*", 0],
235     [[], "https://browser.example", "OPTIONS", 403, undef, 0],
236     [[], undef, "OPTIONS", 405, undef, 0],
237     [["*"], "https://browser.example", "POST", 401, "*", 0],
238     ) {
239     my ($origins, $origin, $method, $status, $allowed, $cookie) = @$case;
240    
241     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
242     $http = AnyEvent::MCP::Server::HTTP->new (
243     toolsets => [$toolset], origins => $origins, cookie => "token",
244     );
245     $http->accept ($a);
246     $client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
247     $cv = AnyEvent->condvar;
248     $timer = AnyEvent->timer (after => 3, cb => sub { die "CORS timeout" });
249    
250     my $request = $method eq "POST"
251     ? post (message (50, "ping"), defined $origin ? "Origin: $origin\r\n" : "")
252     : "OPTIONS /mcp/ HTTP/1.1\r\n"
253     . (defined $origin ? "Origin: $origin\r\n" : "")
254     . "Access-Control-Request-Method: POST\r\n"
255     . "Access-Control-Request-Headers: content-type,mcp-method\r\n\r\n";
256     $request =~ s{POST /mcp/}{POST /token/mcp/} if $cookie;
257    
258     $client->push_write ($request);
259     http_read ($client, sub {
260     my ($header) = @_;
261    
262     like $header, qr/HTTP\/1.1 $status /, "CORS $method status";
263     if (defined $allowed) {
264     like $header, qr/^Access-Control-Allow-Origin: \Q$allowed\E\r?$/m, "allowed origin";
265     like $header, qr/^Vary: Origin\r?$/m, "vary by allowed origin" if $allowed ne "*";
266     } else {
267     unlike $header, qr/Access-Control-Allow-Origin:/, "no allowed origin";
268     }
269     if ($status == 204) {
270     like $header, qr/Access-Control-Allow-Methods: POST, OPTIONS/, "preflight methods";
271     like $header, qr/Access-Control-Allow-Headers: .*mcp-method,mcp-name/, "modern preflight headers";
272     like $header, qr/Access-Control-Max-Age: 86400/, "preflight cache";
273     }
274     $cv->send;
275     });
276     $cv->recv;
277     undef $timer;
278     $http->close;
279     $client->destroy;
280     }
281    
282     socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
283     my $dispatched = 0;
284     $http = AnyEvent::MCP::Server::HTTP->new (
285     toolsets => [$toolset], connection_close => 1, on_request => sub { ++$dispatched },
286     );
287     $http->accept ($a);
288     undef $a;
289     $cv = AnyEvent->condvar;
290     my $received = 0;
291     $client = AnyEvent::Handle->new (
292     fh => $b,
293     on_error => sub { die $_[2] },
294     on_read => sub { fail "unexpected second HTTP response"; $cv->send },
295     on_eof => sub {
296     ok $received, "response drained before EOF";
297     is $_[0]{rbuf}, "", "no pipelined second response";
298     is $dispatched, 1, "connection_close prevents dispatch of the next request";
299     $cv->send;
300     },
301     );
302     $timer = AnyEvent->timer (after => 3, cb => sub { $cv->croak ("connection_close timeout") });
303     $client->push_write (
304     post (message (60, "tools/call", { name => "slow" }))
305     . post (message (61, "ping"))
306     );
307     $release = AnyEvent->timer (after => 0.01, cb => sub {
308     $pending->reply ({ content => [{ type => "text", text => "x" x 131072 }] });
309     $pending = undef;
310     });
311     http_read ($client, sub {
312     my ($header, $body) = @_;
313    
314     like $header, qr/^Connection: close\r?$/m, "connection_close header for HTTP/1.1";
315     my $response = JSON::XS::decode_json $body;
316     is $response->{id}, 60, "delayed response delivered";
317     is length $response->{result}{content}[0]{text}, 131072, "complete response body before close";
318     $received = 1;
319     });
320     $cv->recv;
321     undef $timer;
322     undef $release;
323     $http->close;
324     $client->destroy;
325    
326 root 1.1 done_testing;