MCP/Client.pm

filter: Statementstmt 87.8% 108 / 123 Branchbran 75.0% 30 / 40 Conditioncond 52.5% 21 / 40 MC/DCmcdc 23.8% 5 / 21 Subroutinesub 90.6% 29 / 32 Podpod 100% 11 / 11 totaltotal 76.4% 204 / 267 CC 45 SCAR 17.0
CC
45
Cov
78%
_renegotiate
18.6
__ANON__
8.4
_send
7.8
CRAP 5.5
« MCP/Server/Transport/HTTP.pm ↑ Summary MCP/Tool.pm »
1 package MCP::Client;
2 8 ▶use Mojo::Base 'Mojo::EventEmitter', -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 8 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 8 ▶use List::Util qw(first);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 8 ▶use MCP::Constants qw(META_CLIENT_CAPABILITIES META_CLIENT_INFO META_PROTOCOL_VERSION PROTOCOL_VERSION),
Subroutine BEGIN: called CC=1 SCAR=0.0
7 8 qw(SUPPORTED_VERSIONS UNSUPPORTED_PROTOCOL_VERSION);
8 8 ▶use Mojo::JSON qw(from_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use Mojo::Util qw(b64_encode encode);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 8 ▶use Mojo::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 8 ▶use constant NAMES => {'prompts/get' => 'name', 'resources/read' => 'uri', 'tools/call' => 'name'};
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 13 ▶has capabilities => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
15 8 ▶has headers => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
16 8 has name => 'PerlClient';
17 8 has protocol_version => PROTOCOL_VERSION;
18 0 ▶has ua => sub { Mojo::UserAgent->new };
Subroutine __ANON__: not called CC=1 SCAR=1.2
19 0 ▶has url => sub {'http://localhost:3000/mcp'};
Subroutine __ANON__: not called CC=1 SCAR=1.2
20 8 has version => '1.0.0';
21  
22 97 ▶sub build_notification ($self, $method, $params = {}) {
Subroutine build_notification: called CC=2 SCAR=6.9
Pod documented
23 97 return {jsonrpc => '2.0', method => $method, params => $params};
24 }
25  
26 97 ▶sub build_request ($self, $method, $params = {}) {
Subroutine build_request: called CC=4 SCAR=13.9
Pod documented
27 97 ▶ my $meta = {%{$params->{_meta} // {}}};
Condition100%2/2
$params->{"_meta"} // {}
l!l
394
MC/DC100%1/1
$params->{"_meta"} // {}
$params->{"_meta"}
Truth table100%2/2
A
A= $params->{"_meta"}
Aresult
11
00
28 97 $meta->{+META_CLIENT_CAPABILITIES} = $self->capabilities;
29 97 $meta->{+META_CLIENT_INFO} = {name => $self->name, version => $self->version};
30 97 $meta->{+META_PROTOCOL_VERSION} = $self->protocol_version;
31 97 my $request = $self->build_notification($method, {%$params, _meta => $meta});
32 97 ▶ $request->{id} = $self->{id} = $self->{id} ? $self->{id} + 1 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'id'} ? : 84 13 97
33 97 return $request;
34 }
35  
36 39 ▶sub call_tool ($self, $name, $args = {}, $options = {}) {
Subroutine call_tool: called CC=3 SCAR=11.0
Pod documented
37 39 my $request = $self->build_request('tools/call', {name => $name, arguments => $args, %{_retry($options)}});
38 39 return _result($self->send_request($request));
39 }
40  
41 2 ▶sub discover ($self) { _result($self->send_request($self->build_request('server/discover'))) }
Subroutine discover: called CC=1 SCAR=0.0
Pod documented
42  
43 17 ▶sub get_prompt ($self, $name, $args = {}, $options = {}) {
Subroutine get_prompt: called CC=3 SCAR=11.0
Pod documented
44 17 my $request = $self->build_request('prompts/get', {name => $name, arguments => $args, %{_retry($options)}});
45 17 return _result($self->send_request($request));
46 }
47  
48 5 ▶sub list_prompts ($self) { _result($self->send_request($self->build_request('prompts/list'))) }
Subroutine list_prompts: called CC=1 SCAR=0.0
Pod documented
49 5 ▶sub list_resources ($self) { _result($self->send_request($self->build_request('resources/list'))) }
Subroutine list_resources: called CC=1 SCAR=0.0
Pod documented
50 8 ▶sub list_tools ($self) { _result($self->send_request($self->build_request('tools/list'))) }
Subroutine list_tools: called CC=1 SCAR=0.0
Pod documented
51  
52 1 ▶sub listen ($self, $filter, $cb) {
Subroutine listen: called CC=1 SCAR=0.0
Pod documented
53 1 my $request = $self->build_request('subscriptions/listen', {notifications => $filter});
54 1 my $ua = $self->ua;
55 1 my $tx = $ua->build_tx(POST => $self->url => $self->_headers($request) => json => $request);
56  
57 3 $tx->res->content->on(
58 3 ▶ sse => sub ($content, $event = undef) {
Subroutine __ANON__: called CC=6 SCAR=18.1
59 3 ▶ return unless $event && $event->{text} && (my $message = eval { from_json($event->{text}) });
Branch: 1 branch
BranchTrueFalseTotal
unless $event and $event->{"text"} and my $message = eval { do { from_json($event->{"text"}) } } 1 2 3
Condition66%4/6
$event and $event->{"text"} and my $message = eval { do { from_json($event->{"text"}) } }
!ll&&!rl&&r
102
$event and $event->{"text"}
!ll&&!rl&&r
102
MC/DC33%1/3
$event and $event->{"text"} and my $message = eval { do { from_json($event->{"text"}) } }
$event $event->{"text"} my $message = eval { do { from_json($event->{"text"}) } }
Truth table50%2/4
A and B and C
A= $eventB= $event->{"text"}C= my $message = eval { do { from_json($event->{"text"}) } }
ABCresult
0XX0
10X0
1100
1111
60 2 ▶ $tx->res->error({message => 'Interrupted'}) unless $cb->($message);
Branch: 1 branch
BranchTrueFalseTotal
unless &$cb($message) 1 1 2
61 }
62 1 );
63 1 $ua->start($tx);
64  
65 1 return 1;
66 }
67  
68 14 ▶sub read_resource ($self, $uri, $options = {}) {
Subroutine read_resource: called CC=2 SCAR=6.9
Pod documented
69 14 my $request = $self->build_request('resources/read', {uri => $uri, %{_retry($options)}});
70 14 return _result($self->send_request($request));
71 }
72  
73 95 ▶sub send_request ($self, $request) {
Subroutine send_request: called CC=3 SCAR=18.1
Pod documented
74 95 my $res = $self->_send($request);
75 95 ▶ return $res unless my $version = _renegotiate($res);
Branch: 1 branch
BranchTrueFalseTotal
unless my $version = _renegotiate($res) 95 0 95
76 0 ▶ return $res if $version eq $self->protocol_version;
Branch: 1 branch
BranchTrueFalseTotal
if $version eq $self->protocol_version 0 0 0
77  
78 0 $self->protocol_version($version);
79 0 $request->{params}{_meta}{+META_PROTOCOL_VERSION} = $version;
80 0 return $self->_send($request);
81 }
82  
83 73 ▶sub _encode_header ($value) {
Subroutine _encode_header: called CC=3 SCAR=15.4
84 73 ▶ return $value if $value =~ /^[\x20-\x7e]*\z/ && $value !~ /^=\?base64\?.*\?=$/;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /^[\x20-\x7e]*\z/u and not $value =~ /^=\?base64\?.*\?=$/u 73 0 73
Condition33%1/3
$value =~ /^[\x20-\x7e]*\z/u and not $value =~ /^=\?base64\?.*\?=$/u
!ll&&!rl&&r
0073
MC/DC0%0/2
$value =~ /^[\x20-\x7e]*\z/u and not $value =~ /^=\?base64\?.*\?=$/u
$value =~ /^[\x20-\x7e]*\z/u not $value =~ /^=\?base64\?.*\?=$/u
Truth table33%1/3
A and not(B)
A= $value =~ /^[\x20-\x7e]*\z/uB= not $value =~ /^=\?base64\?.*\?=$/u
ABresult
0X0
100
111
85 0 return '=?base64?' . b64_encode(encode('UTF-8', $value), '') . '?=';
86 }
87  
88 96 ▶sub _headers ($self, $request) {
Subroutine _headers: called CC=4 SCAR=14.5
89 my $headers = {
90 96 ▶ %{$self->headers},
Condition33%1/3
$request->{"params"}{"_meta"}{"io.modelcontextprotocol/protocolVersion"} // $self->protocol_version
l!l&&r!l&&!r
9600
MC/DC0%0/2
$request->{"params"}{"_meta"}{"io.modelcontextprotocol/protocolVersion"} // $self->protocol_version
$request->{"params"}{"_meta"}{"io.modelcontextprotocol/protocolVersion"} $self->protocol_version
Truth table33%1/3
A // B
A= $request->{"params"}{"_meta"}{"io.modelcontextprotocol/protocolVersion"}B= $self->protocol_version
ABresult
1X1
011
000
91 Accept => 'application/json, text/event-stream',
92 'Content-Type' => 'application/json',
93 'MCP-Protocol-Version' => $request->{params}{_meta}{+META_PROTOCOL_VERSION} // $self->protocol_version,
94 'Mcp-Method' => $request->{method}
95 96 };
96 96 ▶ if (my $key = NAMES->{$request->{method}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $key = {"prompts/get" => "name","resources/read" => "uri","tools/call" => "name"}->{$request->{"method"}}) 73 23 96
97 73 ▶ $headers->{'Mcp-Name'} = _encode_header($request->{params}{$key} // '');
Condition50%1/2
$request->{"params"}{$key} // ""
l!l
730
MC/DC0%0/1
$request->{"params"}{$key} // ""
$request->{"params"}{$key}
Truth table50%1/2
A
A= $request->{"params"}{$key}
Aresult
11
00
98 }
99 96 return $headers;
100 }
101  
102 95 ▶sub _renegotiate ($res) {
Subroutine _renegotiate: called CC=7 SCAR=29.2
103 95 ▶ return undef unless ref $res eq 'HASH' && ref(my $error = $res->{error}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $res eq "HASH" and ref(my $error = $res->{"error"}) eq "HASH" 72 23 95
Condition66%2/3
ref $res eq "HASH" and ref(my $error = $res->{"error"}) eq "HASH"
!ll&&!rl&&r
07223
MC/DC50%1/2
ref $res eq "HASH" and ref(my $error = $res->{"error"}) eq "HASH"
ref $res eq "HASH" ref(my $error = $res->{"error"}) eq "HASH"
Truth table66%2/3
A and B
A= ref $res eq "HASH"B= ref(my $error = $res->{"error"}) eq "HASH"
ABresult
0X0
100
111
104 23 ▶ return undef unless ($error->{code} // 0) == UNSUPPORTED_PROTOCOL_VERSION;
Branch: 1 branch
BranchTrueFalseTotal
unless ($error->{"code"} // 0) == -32022 23 0 23
Condition50%1/2
$error->{"code"} // 0
l!l
230
MC/DC0%0/1
$error->{"code"} // 0
$error->{"code"}
Truth table50%1/2
A
A= $error->{"code"}
Aresult
11
00
105 0 ▶ my %supported = map { $_ => 1 } @{($error->{data} // {})->{supported} // []};
Condition0%0/4
+($error->{"data"} // {})->{"supported"} // []
l!l
00
$error->{"data"} // {}
l!l
00
MC/DC0%0/1
+($error->{"data"} // {})->{"supported"} // []
$error->{"data"}
Truth table0%0/2
A
A= $error->{"data"}
Aresult
11
00
106 0 ▶ return first { $supported{$_} } @{(SUPPORTED_VERSIONS)};
Subroutine __ANON__: not called CC=1 SCAR=6.9
107 }
108  
109 90 ▶sub _result ($res) {
Subroutine _result: called CC=3 SCAR=11.0
110 90 ▶ croak 'No response' unless $res;
Branch: 1 branch
BranchTrueFalseTotal
unless $res 0 90 90
111 90 ▶ if (my $err = $res->{error}) { croak "Error $err->{code}: $err->{message}" }
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $res->{"error"}) 21 69 90
112 69 return $res->{result};
113 }
114  
115 70 ▶sub _retry ($options) {
Subroutine _retry: called CC=3 SCAR=11.0
116 70 my $params = {};
117 70 ▶ $params->{inputResponses} = $options->{input_responses} if $options->{input_responses};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"input_responses"} 4 66 70
118 70 ▶ $params->{requestState} = $options->{request_state} if defined $options->{request_state};
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"request_state"} 8 62 70
119 70 return $params;
120 }
121  
122 95 ▶sub _send ($self, $request) {
Subroutine _send: called CC=7 SCAR=20.5
123 95 my $ua = $self->ua;
124 95 my $tx = $ua->build_tx(POST => $self->url => $self->_headers($request) => json => $request);
125  
126 # SSE handling
127 95 my $id = $request->{id};
128 95 my $response;
129 23 $tx->res->content->on(
130 23 ▶ sse => sub ($content, $event = undef) {
Subroutine __ANON__: called CC=8 SCAR=21.3
131 23 ▶ return unless $event && $event->{text} && (my $res = eval { from_json($event->{text}) });
Branch: 1 branch
BranchTrueFalseTotal
unless $event and $event->{"text"} and my $res = eval { do { from_json($event->{"text"}) } } 10 13 23
Condition66%4/6
$event and $event->{"text"} and my $res = eval { do { from_json($event->{"text"}) } }
!ll&&!rl&&r
10013
$event and $event->{"text"}
!ll&&!rl&&r
10013
MC/DC33%1/3
$event and $event->{"text"} and my $res = eval { do { from_json($event->{"text"}) } }
$event $event->{"text"} my $res = eval { do { from_json($event->{"text"}) } }
Truth table50%2/4
A and B and C
A= $eventB= $event->{"text"}C= my $res = eval { do { from_json($event->{"text"}) } }
ABCresult
0XX0
10X0
1100
1111
132 13 ▶ return $self->emit(notification => $res) unless defined($res->{id}) && defined($id) && $res->{id} eq $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $res->{"id"} and defined $id and $res->{"id"} eq $id 3 10 13
Condition66%4/6
defined $res->{"id"} and defined $id and $res->{"id"} eq $id
!ll&&!rl&&r
3010
defined $res->{"id"} and defined $id
!ll&&!rl&&r
3010
MC/DC33%1/3
defined $res->{"id"} and defined $id and $res->{"id"} eq $id
defined $res->{"id"} defined $id $res->{"id"} eq $id
Truth table50%2/4
A and B and C
A= defined $res->{"id"}B= defined $idC= $res->{"id"} eq $id
ABCresult
0XX0
10X0
1100
1111
133 10 $response = $res;
134 10 $tx->res->error({message => 'Interrupted'});
135 }
136 95 );
137  
138 95 $tx = $ua->start($tx);
139  
140 # Request or notification accepted without a response
141 95 ▶ return undef if $tx->res->code eq '202';
Branch: 1 branch
BranchTrueFalseTotal
if $tx->res->code eq 202 0 95 95
142  
143 95 ▶ if (my $err = $tx->error) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $tx->error) 22 73 95
144 22 ▶ return $response if $err->{message} eq 'Interrupted';
Branch: 1 branch
BranchTrueFalseTotal
if $err->{"message"} eq "Interrupted" 10 12 22
145 12 ▶ return $tx->res->json if $err->{code} && $tx->res->json;
Branch: 1 branch
BranchTrueFalseTotal
if $err->{"code"} and $tx->res->json 12 0 12
Condition33%1/3
$err->{"code"} and $tx->res->json
!ll&&!rl&&r
0012
MC/DC0%0/2
$err->{"code"} and $tx->res->json
$err->{"code"} $tx->res->json
Truth table33%1/3
A and B
A= $err->{"code"}B= $tx->res->json
ABresult
0X0
100
111
146 0 ▶ croak "$err->{code} response: $err->{message}" if $err->{code};
Branch: 1 branch
BranchTrueFalseTotal
if $err->{"code"} 0 0 0
147 0 croak "Connection error: $err->{message}";
148 }
149  
150 73 return $tx->res->json;
151 }
152  
153 8 1;
154  
155 =encoding utf8
156  
157 =head1 NAME
158  
159 MCP::Client - MCP client
160  
161 =head1 SYNOPSIS
162  
163 use MCP::Client;
164  
165 my $client = MCP::Client->new(url => 'http://localhost:3000/mcp');
166 my $tools = $client->list_tools;
167  
168 =head1 DESCRIPTION
169  
170 L<MCP::Client> is a client for MCP (Model Context Protocol) that communicates with MCP servers over HTTP.
171  
172 It is exactly conformant on the wire, sending the C<_meta> fields and routing headers every request has to carry,
173 and it is deliberately nothing more than that. TTL caching, retry loops for input requests, and the OAuth
174 authorization flow are all left to the application, so this is a good client to test a server with and a starting
175 point rather than a finished agent.
176  
177 =head1 EVENTS
178  
179 L<MCP::Client> inherits all events from L<Mojo::EventEmitter> and emits the following new ones.
180  
181 =head2 notification
182  
183 $client->on(notification => sub ($client, $notification) { ... });
184  
185 Emitted for every JSON-RPC notification the server sends on the response stream of a request, such as a progress
186 report for a long running tool call.
187  
188 =head1 ATTRIBUTES
189  
190 L<MCP::Client> inherits all attributes from L<Mojo::EventEmitter> and implements the following new ones.
191  
192 =head2 capabilities
193  
194 my $capabilities = $client->capabilities;
195 $client = $client->capabilities({elicitation => {}});
196  
197 Capabilities to declare with every request, defaults to an empty hash reference.
198  
199 =head2 headers
200  
201 my $headers = $client->headers;
202 $client = $client->headers({Authorization => 'Bearer abc123'});
203  
204 Extra HTTP headers to send with every request, as a hash reference. Useful for passing an C<Authorization> header to
205 an MCP server that requires OAuth bearer authentication. Defaults to an empty hash reference.
206  
207 =head2 name
208  
209 my $name = $client->name;
210 $client = $client->name('PerlClient');
211  
212 The name of the client, defaults to C<PerlClient>.
213  
214 =head2 protocol_version
215  
216 my $version = $client->protocol_version;
217 $client = $client->protocol_version('2026-07-28');
218  
219 The protocol version to make requests with, defaults to L<MCP::Constants/"PROTOCOL_VERSION">. A server rejecting it
220 with an C<UnsupportedProtocolVersionError> gets one more chance with the newest version both sides support, and that
221 version is remembered for subsequent requests.
222  
223 =head2 ua
224  
225 my $ua = $client->ua;
226 $client = $client->ua(Mojo::UserAgent->new);
227  
228 The user agent used for making HTTP requests, defaults to a new instance of L<Mojo::UserAgent>.
229  
230 =head2 url
231  
232 my $url = $client->url;
233 $client = $client->url('http://localhost:3000/mcp');
234  
235 The URL of the MCP server, defaults to C<http://localhost:3000/mcp>.
236  
237 =head2 version
238  
239 my $version = $client->version;
240 $client = $client->version('1.0.0');
241  
242 The version of the client, defaults to C<1.0.0>.
243  
244 =head1 METHODS
245  
246 L<MCP::Client> inherits all methods from L<Mojo::EventEmitter> and implements the following new ones.
247  
248 =head2 build_notification
249  
250 my $notification = $client->build_notification('method_name', {param1 => 'value1'});
251  
252 Builds a JSON-RPC notification with the given method name and parameters.
253  
254 =head2 build_request
255  
256 my $request = $client->build_request('method_name', {param1 => 'value1'});
257  
258 Builds a JSON-RPC request with the given method name and parameters, adding the C<_meta> fields every request has to
259 carry.
260  
261 =head2 call_tool
262  
263 my $result = $client->call_tool('tool_name');
264 my $result = $client->call_tool('tool_name', {arg1 => 'value1'});
265 my $result = $client->call_tool('tool_name', {arg1 => 'value1'}, {request_state => $state});
266  
267 Calls a tool on the MCP server with the specified name and arguments, returning the result.
268  
269 A result with C<resultType> set to C<input_required> is returned as-is; gathering the requested input and deciding
270 whether to call again is up to you.
271  
272 These options are currently available:
273  
274 =over 2
275  
276 =item input_responses
277  
278 input_responses => {confirm => {action => 'accept', content => {ok => \1}}}
279  
280 Responses to the input requests of an earlier C<input_required> result, keyed by the same names.
281  
282 =item request_state
283  
284 request_state => 'eyJ...'
285  
286 The C<requestState> of an earlier C<input_required> result, passed back verbatim.
287  
288 =back
289  
290 =head2 discover
291  
292 my $result = $client->discover;
293  
294 Discover the protocol versions, capabilities, and instructions of the MCP server.
295  
296 =head2 get_prompt
297  
298 my $result = $client->get_prompt('prompt_name');
299 my $result = $client->get_prompt('prompt_name', {arg1 => 'value1'});
300 my $result = $client->get_prompt('prompt_name', {arg1 => 'value1'}, {request_state => $state});
301  
302 Get a prompt from the MCP server with the specified name and arguments, returning the result. Takes the same options
303 as L</"call_tool">.
304  
305 =head2 list_prompts
306  
307 my $prompts = $client->list_prompts;
308  
309 Lists all available prompts on the MCP server.
310  
311 =head2 list_resources
312  
313 my $resources = $client->list_resources;
314  
315 Lists all available resources on the MCP server.
316  
317 =head2 list_tools
318  
319 my $tools = $client->list_tools;
320  
321 Lists all available tools on the MCP server.
322  
323 =head2 listen
324  
325 my $bool = $client->listen({toolsListChanged => \1}, sub ($message) {...});
326  
327 Open a C<subscriptions/listen> stream for the requested notification types and block, invoking the callback for
328 every message the server sends, starting with the acknowledgement. Returning a false value from the callback closes
329 the stream. Only servers configured with C<< streaming => 1 >> support this.
330  
331 =head2 read_resource
332  
333 my $result = $client->read_resource('file:///path/to/resource.txt');
334 my $result = $client->read_resource('file:///path/to/resource.txt', {request_state => $state});
335  
336 Reads a resource from the MCP server with the specified URI, returning the result. Takes the same options as
337 L</"call_tool">.
338  
339 =head2 send_request
340  
341 my $response = $client->send_request($request);
342  
343 Sends a JSON-RPC request to the MCP server and returns the response, or C<undef> if the server accepted it without
344 one.
345  
346 =head1 SEE ALSO
347  
348 L<MCP>, L<https://mojolicious.org>, L<https://modelcontextprotocol.io>.
349  
350 =cut
« MCP/Server/Transport/HTTP.pm ↑ Summary MCP/Tool.pm »