ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/lib/AnyEvent/MCP/Server.pm
Revision: 1.8
Committed: Sun Oct 18 10:19:43 2026 UTC (3 weeks, 3 days ago) by root
Branch: MAIN
Changes since 1.7: +47 -0 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3     AnyEvent::MCP::Server - MCP request dispatch and JSON-RPC framing
4    
5     =head1 DESCRIPTION
6    
7     An MCP server needs to understand requests, but it does not necessarily need
8     to own a listening socket. This class handles the protocol: it accepts decoded
9     JSON-RPC objects (or UTF-8 JSON), dispatches requests and delivers responses
10     through callbacks. Its subclasses L<AnyEvent::MCP::Server::JSONL> and
11     L<AnyEvent::MCP::Server::HTTP> handle the actual connections. If you are
12     writing a standalone server, L<AnyEvent::MCP::Server::Simple> is usually
13     the easier starting point.
14    
15     The server implements discovery, initialization, ping and tool listing/calls.
16     The 2025 compatibility path supports ordinary requests and responses, but
17     not server-initiated requests. Permission asking supports modern input
18     challenges as well as local helpers. SSE, subscriptions and schema validation
19     are not implemented yet.
20    
21     =head1 METHODS
22    
23 root 1.5 =over
24 root 1.1
25 root 1.5 =item $server = AnyEvent::MCP::Server->new (%config)
26 root 1.1
27 root 1.5 Creates the protocol object without opening a listener or starting an
28     event loop. Options are:
29 root 1.1
30 root 1.5 =over
31    
32     =item toolsets => [$toolset...]
33    
34     L<AnyEvent::MCP::Server::Toolset> objects searched in order, defaulting to
35     an empty array. The first Toolset containing a called tool handles it.
36    
37     =item server_info => { name => $name, version => $version }
38    
39     Advertised server identity, defaulting to C<AnyEvent::MCP> and this
40     distribution's version.
41    
42     =item instructions => $text
43    
44     Optional human-readable guidance. Surrounding whitespace and common
45     indentation are stripped. Empty instructions are omitted from discovery
46     and initialization results.
47    
48 root 1.8 =item short_instructions => $text
49    
50     Optional condensed guidance for deciding when to discover this server's tools.
51     Used instead of C<instructions> in discovery when C<auto_instructions> is true.
52     Without either short or custom instructions, the full instructions remain
53     advertised.
54    
55     =item custom_instructions => $text
56    
57     Instance-specific purpose, prepended to the advertised instructions.
58    
59     =item auto_instructions => $boolean
60    
61     When true, expose full C<instructions>, prefixed by any custom instance
62     purpose, in a C<meta-instructions> tool's description and call result.
63     Advertise C<short_instructions> instead, when provided. Defaults to false;
64     a conflicting tool name is an error.
65    
66 root 1.5 =item capabilities => { %capabilities }
67    
68     Advertised server capabilities, defaulting to C<{ tools =E<gt> {} }>.
69     Declaring a capability does not implement it.
70    
71     =item versions => [$version...]
72    
73     Supported revisions in preference order. Defaults to C<2026-07-28>,
74     C<2025-11-25>, C<2025-06-18> and C<2025-03-26>. The 2026 protocol uses
75     discovery and per-request metadata; the 2025 protocol uses initialization.
76    
77     =item permissions => $permissions
78    
79     L<AnyEvent::MCP::Server::Permissions> object used by
80     C<< $req->require_permission >>. The server handles permission-needed
81     exceptions. The permission object's C<ask> setting chooses between modern
82     input challenges and local prompts; local asking retries the handler
83     internally. Checks must precede side effects.
84    
85     =back
86    
87     Event callbacks are also constructor options; see L</EVENTS>.
88    
89     =item $req = $server->rpc ($message, $reply->($message), %context)
90 root 1.1
91     Accepts the decoded JSON-RPC hash reference C<$message>. C<$reply> receives
92 root 1.6 the decoded response, or undef when a notification is accepted or a request
93     is cancelled. Undef completes transport bookkeeping without a JSON-RPC
94     response. Returns the Request object for a request, or undef for
95     notifications and rejected messages.
96 root 1.1 C<$reply> can be called before this method returns, or later.
97    
98     C<peer> in C<%context> is a hash reference shared by messages on one connection.
99     It holds legacy initialization state and weak references to outstanding
100     requests for cancellation. Embedders supply a different peer for each
101     independent connection. Modern request metadata takes precedence over legacy
102     peer state.
103    
104     C<protocol_version> supplies the legacy HTTP protocol version.
105     C<on_notify> is an optional C<$callback->($req, $message)> receiving decoded
106     outgoing notifications. Without it, notifications are dropped.
107    
108 root 1.5 =item $req = $server->json_rpc ($json, $reply->($json), %context)
109 root 1.1
110     Like C<rpc>, but C<$json> and the response are UTF-8 encoded JSON strings.
111     The notification callback still receives decoded objects. Parse errors are
112     returned as JSON-RPC errors.
113    
114 root 1.5 =item $server->dispatch ($req)
115 root 1.1
116     Dispatches an already constructed Request. Normally called by C<rpc>.
117     Subclasses can override this method while retaining JSON-RPC handling.
118    
119 root 1.5 =back
120    
121 root 1.1 =head1 EVENTS
122    
123 root 1.5 =over
124    
125     =item on_request => $callback->($server, $req)
126 root 1.1
127     Called before each dispatch attempt, including permission retries. This
128     synchronous hook can inspect the request or refresh application state.
129     It does not replace dispatch; avoid side effects that must happen only once.
130    
131 root 1.5 =item on_tools_list => $callback->($server, $req)
132 root 1.1
133     Replaces the default Toolset listing. C<$callback> completes C<$req>.
134    
135 root 1.5 =item on_tools_call => $callback->($server, $req, $args)
136 root 1.1
137     Replaces the default Toolset lookup and invocation. C<$args> is also available
138     as C<< $req->{args} >>. C<$callback> completes C<$req>.
139    
140 root 1.5 =item on_error => $callback->($server, $req, $error)
141 root 1.1
142     Reports an exception caught during synchronous dispatch. A tool exception
143     becomes a text tool-error result; other exceptions become internal JSON-RPC
144     errors. Exceptions after a reply are propagated, as are exceptions from
145     asynchronous application callbacks.
146    
147 root 1.5 =back
148    
149 root 1.1 =cut
150    
151     package AnyEvent::MCP::Server;
152    
153     use common::sense;
154     use AnyEvent::MCP ();
155     use AnyEvent::MCP::Server::Request ();
156     use JSON::XS ();
157     use Scalar::Util qw(weaken);
158    
159     our @ISA = qw(AnyEvent::MCP::Base);
160    
161     sub new {
162     my $class = shift;
163    
164     my $self = $class->SUPER::new (
165     toolsets => [],
166     server_info => { name => "AnyEvent::MCP", version => $AnyEvent::MCP::VERSION },
167     capabilities => { tools => {} },
168     versions => [qw(2026-07-28 2025-11-25 2025-06-18 2025-03-26)],
169     @_,
170     );
171    
172     $self->{instructions} = AnyEvent::MCP::_clean_text $self->{instructions}
173     if exists $self->{instructions};
174    
175 root 1.8 my $instructions = $self->{instructions};
176     my $custom = exists $self->{custom_instructions}
177     ? AnyEvent::MCP::_clean_text $self->{custom_instructions} : "";
178    
179     if ($self->{auto_instructions} && length $instructions) {
180     require AnyEvent::MCP::Server::Toolset;
181    
182     my $name = "meta-instructions";
183     !grep (exists $_->{tool}{$name}, @{$self->{toolsets}})
184     or die "duplicate MCP tool '$name'\n";
185    
186     my $full = join "\n\n", grep length, $custom, $instructions;
187     my $toolset = AnyEvent::MCP::Server::Toolset->new;
188     $toolset->tool (meta_instructions =>
189     "Server instructions. Call for full text if truncated.\n\n$full",
190     { type => "object", properties => {} },
191     sub { $_[0]->reply ({ content => [{ type => "text", text => $full }] }) },
192     );
193     $self->{toolsets} = [@{$self->{toolsets}}, $toolset];
194    
195     my $short = exists $self->{short_instructions}
196     ? AnyEvent::MCP::_clean_text $self->{short_instructions} : "";
197     $short ||= $instructions unless length $custom;
198     $self->{instructions} = join "\n\n", grep length, $custom, $short;
199    
200     } elsif (length $custom) {
201     $self->{instructions} = join "\n\n", grep length, $custom, $instructions;
202     }
203    
204 root 1.1 $self
205     }
206    
207     sub _rpc_error {
208     my ($self, $reply, $id, $code, $message, $data) = @_;
209    
210     my $error = { code => $code, message => $message };
211     $error->{data} = $data if defined $data;
212    
213     $reply->({ jsonrpc => "2.0", id => $id, error => $error });
214     undef
215     }
216    
217     sub json_rpc {
218     my ($self, $json, $reply, @context) = @_;
219    
220     my $send = sub { $reply->(defined $_[0] ? JSON::XS::encode_json $_[0] : undef) };
221     my $message = eval { JSON::XS::decode_json $json };
222    
223     return $self->_rpc_error ($send, undef, -32700, "Parse error")
224     if $@;
225    
226     $self->rpc ($message, $send, @context)
227     }
228    
229     sub rpc {
230     my ($self, $message, $reply, %context) = @_;
231    
232     return $self->_rpc_error ($reply, undef, -32600, "Invalid request")
233     unless ref $message eq "HASH"
234     && $message->{jsonrpc} eq "2.0"
235     && defined $message->{method} && !ref $message->{method}
236     && (!exists $message->{id} || defined $message->{id} && !ref $message->{id});
237    
238     my $id = $message->{id};
239     my $key = $id; # Hash lookups must not stringify the wire ID.
240     my $method = $message->{method};
241     my $params = exists $message->{params} ? $message->{params} : {};
242     my $peer = $context{peer} || {};
243    
244     unless (exists $message->{id}) {
245     if ($method eq "notifications/cancelled" && ref $params eq "HASH" && defined $params->{requestId}) {
246     my $req = delete $peer->{requests}{$params->{requestId}};
247     $req->cancel ($params->{reason}) if $req;
248     }
249    
250     $reply->(undef);
251     return
252     }
253    
254     return $self->_rpc_error ($reply, $id, -32602, "Invalid params")
255     unless ref $params eq "HASH"
256     && (!exists $params->{_meta} || ref $params->{_meta} eq "HASH");
257    
258     my $meta = $params->{_meta} || {};
259     my $version = $meta->{"io.modelcontextprotocol/protocolVersion"}
260     || $context{protocol_version} || $peer->{protocol_version};
261    
262     if ($method eq "initialize") {
263     $version = $params->{protocolVersion};
264    
265     return $self->_rpc_error ($reply, $id, -32602, "Invalid initialize params")
266     unless defined $version && !ref $version
267     && ref $params->{capabilities} eq "HASH"
268     && ref $params->{clientInfo} eq "HASH";
269    
270     unless (grep $_ eq $version && $_ lt "2026", @{$self->{versions}}) {
271     ($version) = grep $_ lt "2026", @{$self->{versions}};
272     return $self->_rpc_error ($reply, $id, -32601, "Legacy initialization is not supported")
273     unless defined $version;
274     }
275     } else {
276     return $self->_rpc_error ($reply, $id, -32602, "Missing protocol version")
277     unless defined $version && !ref $version;
278    
279     return $self->_rpc_error ($reply, $id, -32022, "Unsupported protocol version", {
280     requested => $version,
281     supported => $self->{versions},
282     }) unless grep $_ eq $version, @{$self->{versions}};
283    
284     if ($version ge "2026") {
285     return $self->_rpc_error ($reply, $id, -32602, "Missing per-request metadata")
286     unless $meta->{"io.modelcontextprotocol/protocolVersion"} eq $version
287     && ref $meta->{"io.modelcontextprotocol/clientCapabilities"} eq "HASH";
288     }
289     }
290    
291     return $self->_rpc_error ($reply, $id, -32600, "Request id already outstanding")
292     if $peer->{requests}{$key};
293    
294 root 1.4 # the private multibroker protocol uses the normal MCP capability handshake.
295     # keep the negotiated version on this stream's peer, not on the server.
296 root 1.3 my $capabilities = $method eq "initialize"
297     ? $params->{capabilities} : $meta->{"io.modelcontextprotocol/clientCapabilities"};
298     if (ref $capabilities eq "HASH") {
299     my $extensions = $capabilities->{extensions};
300     if (ref $extensions eq "HASH") {
301     my $extension = $extensions->{"anyevent-mcp/multibroker"};
302     $peer->{aemcp_multibroker} = 1
303     if ref $extension eq "HASH" && ($extension->{version} || 0) eq "1";
304     }
305     }
306    
307 root 1.1 my $req = AnyEvent::MCP::Server::Request->new (
308 root 1.4 server => $self,
309     peer => $peer,
310     id => $id,
311     method => $method,
312     params => $params,
313 root 1.1 protocol_version => $version,
314 root 1.4 on_reply => sub {
315 root 1.1 my ($req, $result) = @_;
316    
317     delete $peer->{requests}{$key};
318    
319     if ($req->{protocol_version} ge "2026") {
320     $result = {
321     resultType => "complete",
322     %$result,
323     _meta => {
324     "io.modelcontextprotocol/serverInfo" => $self->{server_info},
325     %{$result->{_meta} || {}},
326     },
327     };
328     }
329    
330     $reply->({ jsonrpc => "2.0", id => $id, result => $result });
331     },
332     );
333    
334     if (my $notify = $context{on_notify}) {
335     $req->{on_notify} = sub {
336     my ($req, $method, $params) = @_;
337    
338     $notify->($req, { jsonrpc => "2.0", method => $method, params => $params });
339     };
340     }
341    
342     $peer->{requests}{$key} = $req;
343     weaken $peer->{requests}{$key};
344    
345     if ($method eq "tools/call") {
346     unless (defined $params->{name} && !ref $params->{name}
347     && (!exists $params->{arguments} || ref $params->{arguments} eq "HASH")) {
348     $self->_reject ($req, $reply, -32602, "Invalid tool call");
349     return $req
350     }
351    
352     $req->{tool} = $params->{name};
353     $req->{args} = exists $params->{arguments} ? $params->{arguments} : {};
354     }
355    
356     $req->{_reply} = $reply;
357    
358     $self->_dispatch ($req);
359    
360     $req
361     }
362    
363     sub _dispatch {
364     my ($self, $req) = @_;
365    
366     eval {
367 root 1.7 if ($self->{permissions} && $req->{method} eq "tools/call"
368     && $self->{permissions}->auto_decision ($req->{tool}) eq "deny") {
369     die "Permission denied by --auto-deny\n";
370     }
371    
372 root 1.1 $self->{permissions}->_resume ($req)
373     if $self->{permissions} && $req->{method} eq "tools/call";
374     $self->event (request => $req);
375     $self->dispatch ($req) unless $req->{finished};
376     1
377     } or do {
378     my $error = $@;
379     die $error if $req->{finished};
380    
381     if (ref $error eq "AnyEvent::MCP::Server::Permissions::Required" && $self->{permissions}) {
382     eval {
383     $self->{permissions}->require ($req, $error->{request}, sub {
384     my ($success, $grant) = @_;
385 root 1.4
386 root 1.1 return if $req->{finished};
387     return $req->error ($grant) unless $success;
388    
389     $self->{permissions}->_remember ($req, $error->{request}, $grant);
390     $self->_dispatch ($req);
391     });
392     1
393     } or do {
394     my $failure = $@;
395     die $failure if $req->{finished};
396     $self->event (error => $req, $failure);
397     $req->error ($failure);
398     };
399     } else {
400     $self->event (error => $req, $error);
401    
402     if ($req->{method} eq "tools/call") {
403     $req->error ($error);
404     } else {
405     $self->_reject ($req, $req->{_reply}, -32603, "Internal error");
406     }
407     }
408     };
409     }
410    
411     sub _reject {
412     my ($self, $req, $reply, $code, $message) = @_;
413    
414     $req->{finished} = 1;
415     my $key = $req->{id};
416     delete $req->{peer}{requests}{$key};
417     delete @$req{qw(on_reply on_notify on_cancel _reply)};
418    
419     $self->_rpc_error ($reply, $req->{id}, $code, $message)
420     }
421    
422     sub dispatch {
423     my ($self, $req) = @_;
424 root 1.4
425 root 1.1 my $method = $req->{method};
426    
427     if ($method eq "initialize") {
428     $req->{peer}{protocol_version} = $req->{protocol_version};
429     $req->{peer}{client_info} = $req->{params}{clientInfo};
430     $req->{peer}{client_capabilities} = $req->{params}{capabilities};
431    
432     my $result = {
433     protocolVersion => $req->{protocol_version},
434     serverInfo => $self->{server_info},
435     capabilities => $self->{capabilities},
436     };
437 root 1.2 $result->{instructions} = $self->{instructions} if length $self->{instructions};
438 root 1.1
439     $req->reply ($result);
440    
441     } elsif ($method eq "server/discover") {
442     my $result = {
443     supportedVersions => $self->{versions},
444     capabilities => $self->{capabilities},
445     };
446 root 1.2 $result->{instructions} = $self->{instructions} if length $self->{instructions};
447 root 1.1
448     $req->reply ($result);
449    
450     } elsif ($method eq "ping") {
451     $req->reply ({});
452    
453     } elsif ($method eq "tools/list") {
454     if ($self->{on_tools_list}) {
455     $self->event (tools_list => $req);
456     } else {
457     $req->reply ({ tools => [map @{$_->list}, @{$self->{toolsets}}] });
458     }
459    
460     } elsif ($method eq "tools/call") {
461     if ($self->{on_tools_call}) {
462     $self->event (tools_call => $req, $req->{args});
463     } else {
464     my ($toolset) = grep exists $_->{tool}{$req->{tool}}, @{$self->{toolsets}};
465    
466     if ($toolset) {
467     $toolset->call ($req);
468     } else {
469     $self->_reject ($req, $req->{_reply}, -32602, "Unknown tool '$req->{tool}'");
470     }
471     }
472    
473     } else {
474     $self->_reject ($req, $req->{_reply}, -32601, "Method not found");
475     }
476     }
477    
478     1