ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/t/c25_http.t
Revision: 1.7
Committed: Mon Nov 30 11:29:17 2026 UTC (4 days, 5 hours ago) by root
Content type: application/x-troff
Branch: MAIN
CVS Tags: HEAD
Changes since 1.6: +8 -2 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 use common::sense;
2 use Types::Serialiser ();
3 use Test::More;
4 use AnyEvent ();
5 use AnyEvent::Socket ();
6 use AnyEvent::Handle ();
7 use AnyEvent::MCP::Client::JSONL ();
8 use AnyEvent::MCP ();
9 use MIME::Base64 ( );
10 use File::Temp ( );
11
12 my $port;
13 my @seen;
14 my $listener = AnyEvent::Socket::tcp_server "127.0.0.1", 0, sub {
15 my ($fh) = @_;
16
17 my $handle;
18 $handle = AnyEvent::Handle->new (
19 fh => $fh,
20 on_error => sub { $handle->destroy; undef $handle },
21 on_eof => sub { $handle->destroy; undef $handle },
22 );
23 $handle->push_read (line => "\r\n\r\n", sub {
24 my ($h, $head) = @_;
25 my ($method, $path) = $head =~ m{\A(\S+) (\S+) HTTP/};
26 my ($length) = $head =~ /^content-length:\s*(\d+)/im;
27 my $respond = sub {
28 my ($body) = @_;
29 push @seen, [$method, $path, $head, $body];
30 my ($code, $extra, $data) = (200, "", "alpha\nbeta\nALPHA\n");
31 if ($path eq "/cookie") {
32 $extra = "Set-Cookie: sid=abc; Path=/\r\n";
33 } elsif ($path eq "/headers") {
34 $extra = "Content-Disposition: attachment; filename=report.txt\r\nRetry-After: 5\r\nAllow: GET\r\nContent-Range: bytes 0-2/3\r\nWWW-Authenticate: Basic realm=test\r\n";
35 } elsif ($path eq "/binary") {
36 $data = "\x00\xff\x80";
37 } elsif ($path eq "/redirect-twice") {
38 $code = 302;
39 $extra = "Location: /redirect\r\n";
40 $data = "";
41 } elsif ($path eq "/redirect") {
42 $code = 302;
43 $extra = "Location: /unexpected\r\n";
44 $data = "";
45 } elsif ($path eq "/post") {
46 $data = $body;
47 } elsif ($path eq "/long") {
48 $data = "x" x 100;
49 }
50 $h->push_write ("HTTP/1.1 $code Test\r\n"
51 . "Content-Length: " . length ($data) . "\r\nConnection: close\r\n"
52 . "Content-Type: text/plain\r\nX-Debug: trace\r\nLink: </preload.css>; rel=preload\r\n"
53 . $extra . "\r\n" . $data);
54 $h->on_drain (sub { $h->destroy; undef $handle });
55 };
56 if ($length) {
57 $h->push_read (chunk => $length, sub { $respond->($_[1]) });
58 } else {
59 $respond->("");
60 }
61 });
62 }, sub { $port = $_[2] };
63
64 my $client = AnyEvent::MCP::Client::JSONL->new (
65 command => [$^X, "-Ilib", "bin/mcp-http", "--stdio", "--auto-allow", "GET,HEAD,POST", "--ask", "none"],
66 );
67 sub wait_for {
68 my ($start) = @_;
69
70 my $cv = AE::cv;
71 my $timer = AE::timer 10, 0, sub { $cv->croak ("mcp-http test timeout") };
72 $start->(sub { $cv->send ([@_]) });
73 @{$cv->recv}
74 }
75 sub call_http {
76 my ($args) = @_;
77
78 my ($ok, $result) = wait_for (sub {
79 $client->rpc ("tools/call", { name => "request", arguments => $args }, $_[0]);
80 });
81 ok $ok, "MCP transport success";
82 $result
83 }
84
85 my $base = "http://127.0.0.1:$port";
86 my ($ok, $tools) = wait_for (sub { $client->rpc ("tools/list", {}, $_[0]) });
87 ok $ok, "tool list transport works";
88 is_deeply [sort map $_->{name}, @{$tools->{tools}}],
89 [sort qw(request meta-instructions)], "one request tool and metadata";
90 my ($request_tool) = grep { $_->{name} eq "request" } @{$tools->{tools}};
91 is $request_tool->{inputSchema}{properties}{verify_tls}{type}, "boolean", "verify_tls is a boolean";
92 ok $request_tool->{inputSchema}{properties}{verify_tls}{default}, "TLS verification defaults to on";
93 is $request_tool->{inputSchema}{properties}{recurse}{default}, 10, "redirect recursion defaults to AnyEvent::HTTP's limit";
94 is $request_tool->{inputSchema}{properties}{response_headers}{type}, "string",
95 "response header selection is a regular expression";
96
97 my $r = call_http ({ url => "$base/cookie", cookie_jar => {} });
98 ok !$r->{isError}, "GET succeeded";
99 is $r->{structuredContent}{status}, 200, "HTTP status returned";
100 is $r->{structuredContent}{body}, "alpha\nbeta\nALPHA\n", "text response";
101 is_deeply $r->{structuredContent}{headers}, { "content-type" => "text/plain" },
102 "default returns only useful response headers; ignores cookies, link and debugging headers";
103 ok !exists $r->{structuredContent}{url}, "ordinary response omits redundant final URL";
104 like $seen[-1][2], qr/^user-agent:\s*mcp-http\/\Q$AnyEvent::MCP::VERSION\E\s*$/im,
105 "default User-Agent identifies versioned mcp-http";
106 is $r->{structuredContent}{cookie_jar}{version}, 2, "versioned cookie jar returned";
107 ok $r->{structuredContent}{cookie_jar}{"127.0.0.1"}, "jar contains response cookie";
108 my $jar = $r->{structuredContent}{cookie_jar};
109
110 $r = call_http ({ url => "$base/page", verify_tls => Types::Serialiser::false });
111 is $r->{structuredContent}{status}, 200, "verify_tls=false accepted";
112 $r = call_http ({ url => "$base/page", verify_tls => Types::Serialiser::true });
113 is $r->{structuredContent}{status}, 200, "verify_tls=true accepted";
114 $r = call_http ({ url => "$base/page", verify_tls => "false" });
115 ok $r->{isError}, "non-boolean verify_tls rejected";
116
117 $r = call_http ({
118 url => "$base/post", method => "POST", cookie_jar => $jar,
119 headers => { "content-type" => "application/octet-stream" },
120 body_base64 => MIME::Base64::encode_base64 ("A\0B", ""),
121 });
122 is $r->{structuredContent}{body}, "A\0B", "binary request body preserved";
123 like $seen[-1][2], qr/^cookie:\s*sid=abc/im, "cookie sent from caller-provided jar";
124 is $seen[-1][0], "POST", "HTTP method forwarded";
125
126 $r = call_http ({ url => "$base/page", headers => { "uSeR-aGeNt" => "custom-agent/1" } });
127 is $r->{structuredContent}{status}, 200, "custom User-Agent request succeeded";
128 like $seen[-1][2], qr/^user-agent:\s*custom-agent\/1\s*$/im,
129 "explicit User-Agent is not overridden";
130
131 $r = call_http ({ url => "$base/page", response_headers => "" });
132 is $r->{structuredContent}{headers}{"x-debug"}, "trace", "empty regex includes non-default response headers";
133 ok exists $r->{structuredContent}{headers}{link}, "empty regex includes noisy Link header";
134 ok !exists $r->{structuredContent}{headers}{Status}, "response headers exclude AnyEvent::HTTP pseudo-headers";
135
136 $r = call_http ({ url => "$base/page", response_headers => '^X-DEBUG$' });
137 is_deeply $r->{structuredContent}{headers}, { "x-debug" => "trace" },
138 "case-insensitive positive response-header regex selects exactly matching names";
139
140 $r = call_http ({ url => "$base/headers" });
141 is_deeply $r->{structuredContent}{headers}, {
142 "content-type" => "text/plain",
143 "content-disposition" => "attachment; filename=report.txt",
144 "retry-after" => "5",
145 "allow" => "GET",
146 "content-range" => "bytes 0-2/3",
147 "www-authenticate" => "Basic realm=test",
148 }, "rare useful response headers are retained by default";
149
150 $r = call_http ({ url => "$base/page", grep => "alpha" });
151 is $r->{structuredContent}{body}, "alpha\n", "literal grep selects lines";
152 $r = call_http ({
153 url => "$base/page", regex => "(?i)^alpha",
154 substitute => { pattern => "(?i)alpha", replacement => "X" },
155 });
156 is $r->{structuredContent}{body}, "X\nX\n", "regex selection followed by global substitution";
157
158 $r = call_http ({ url => "$base/binary" });
159 is $r->{structuredContent}{body_base64}, MIME::Base64::encode_base64 ("\x00\xff\x80", ""),
160 "non-UTF-8 response returns Base64";
161
162 $r = call_http ({ url => "$base/long", max_bytes => 12 });
163 is length $r->{structuredContent}{body}, 12, "response size bounded";
164 ok $r->{structuredContent}{truncated}, "truncated response indicated";
165 is $r->{structuredContent}{status}, 200, "HTTP status retained after early stop";
166
167 my $count = @seen;
168 $r = call_http ({ url => "$base/redirect" });
169 is $r->{structuredContent}{status}, 200, "redirect followed by default";
170 is $r->{structuredContent}{url}, "$base/unexpected", "final URL returned when redirect changes it";
171 is scalar @seen, $count + 2, "redirected request was sent";
172 is_deeply $r->{structuredContent}{headers}, { "content-type" => "text/plain" },
173 "only final response headers are returned after redirect";
174
175 $count = @seen;
176 $r = call_http ({ url => "$base/redirect", recurse => 0 });
177 is $r->{structuredContent}{status}, 302, "recurse=0 returns original redirect status";
178 is $r->{structuredContent}{headers}{location}, "$base/unexpected",
179 "redirect location is useful without following redirects";
180 ok !exists $r->{structuredContent}{url}, "unfollowed redirect omits redundant URL";
181 is scalar @seen, $count + 1, "recurse=0 does not fetch redirect destination";
182
183 $r = call_http ({ url => "$base/redirect-twice", recurse => 1 });
184 is $r->{structuredContent}{status}, 302, "recurse=1 follows only one redirect";
185 is $r->{structuredContent}{url}, "$base/redirect", "partial redirect final URL returned";
186 $r = call_http ({ url => "$base/redirect-twice", recurse => 2 });
187 is $r->{structuredContent}{status}, 200, "recurse=2 follows both redirects";
188 is $r->{structuredContent}{url}, "$base/unexpected", "final URL returned after multiple redirects";
189
190 for my $bad (
191 { url => "http://user:pw\@example.com/" },
192 { url => "$base/page", headers => { "x-test" => "bad\nheader" } },
193 { url => "$base/page", regex => "[" },
194 { url => "$base/page", response_headers => "[" },
195 { url => "$base/page", recurse => -1 },
196 { url => "$base/page", body => "x", body_base64 => "WA==" },
197 ) {
198 my $before = @seen;
199 $r = call_http ($bad);
200 ok $r->{isError}, "invalid request is rejected";
201 is scalar @seen, $before, "invalid request performed no network I/O";
202 }
203
204 my $restricted = AnyEvent::MCP::Client::JSONL->new (
205 command => [$^X, "-Ilib", "bin/mcp-http", "--stdio", "--ask", "mcp", "--auto-allow", "GET,HEAD"],
206 env => { XDG_CONFIG_HOME => File::Temp::tempdir (CLEANUP => 1) },
207 client_capabilities => { elicitation => { form => {} }, extensions => { "de.schmorp.anyevent-mcp/permission" => { version => 1 } } },
208 );
209 for my $method (qw(GET HEAD)) {
210 ($ok, $r) = wait_for (sub {
211 $restricted->rpc ("tools/call", { name => "request", arguments => { url => "$base/page", method => $method } }, $_[0]);
212 });
213 ok $ok && !$r->{isError} && $r->{structuredContent}{status} == 200, "$method auto-approved";
214 }
215 my $before = @seen;
216 ($ok, $r) = wait_for (sub {
217 $restricted->rpc ("tools/call", {
218 name => "request",
219 arguments => { url => "$base/page?q=1", method => "PUT", verify_tls => Types::Serialiser::false },
220 }, $_[0]);
221 });
222 ok $ok, "permission request transport success";
223 is $r->{resultType}, "input_required", "new method and URL require approval";
224 is scalar @seen, $before, "no HTTP call before permission granted";
225 my $question = (values %{$r->{inputRequests} || {}})[0];
226 my $permission = $r->{_meta}{"de.schmorp.anyevent-mcp/permission"}{permission};
227 is $permission->{action}, "PUT", "HTTP method is permission action";
228 is_deeply [sort keys %{$permission->{dimensions}}], ["url"], "verify_tls does not affect permission dimensions";
229 is $permission->{dimensions}{url}{value}, "$base/page?q=1", "URL is separate permission dimension";
230 is_deeply [map $_->{label}, @{$permission->{dimensions}{url}{choices}}], [
231 "Exact URL: $base/page?q=1", "This path: $base/page (any query)", "This origin: $base",
232 "This hostname: 127.0.0.1 (any scheme or port)", "Any HTTP(S) URL",
233 ], "IP URL offers exact, path, origin, hostname and universal scopes";
234
235 ($ok, $r) = wait_for (sub {
236 $restricted->rpc ("tools/call", {
237 name => "request",
238 arguments => { url => "HTTPS://Example.COM:443/path?q=1#fragment", method => "PROPFIND" },
239 }, $_[0]);
240 });
241 is $r->{resultType}, "input_required", "arbitrary HTTP method recognized";
242 $question = (values %{$r->{inputRequests} || {}})[0];
243 $permission = $r->{_meta}{"de.schmorp.anyevent-mcp/permission"}{permission};
244 is $permission->{dimensions}{url}{value}, "https://example.com/path?q=1",
245 "URL normalizes origin and removes fragments";
246 is scalar @{$permission->{dimensions}{url}{choices}}, 6, "DNS hostname offers subdomain scope";
247
248 undef $restricted;
249 undef $client;
250 undef $listener;
251 done_testing;