bin/mcp-vim

filter: Statementstmt 74.4% 391 / 525 Branchbran 56.6% 137 / 242 Conditioncond 46.6% 76 / 163 MC/DCmcdc 23.7% 19 / 80 Subroutinesub 69.6% 55 / 79 Podpod 0.0% 0 / 1 totaltotal 62.2% 678 / 1090 CC 164 SCAR 31.9
CC
164
Cov
65%
_on_upload_done
182.0
__ANON__
67.0
send_data
56.0
CRAP 24.3
« bin/mcp-multibroker ↑ Summary blib/lib/AnyEvent/MCP/Server/Connect.pm »
1 #!/opt/bin/perl
2  
3 =head1 NAME
4  
5 mcp-vim - MCP server for live Vim editors
6  
7 =head1 SYNOPSIS
8  
9 mcp-vim [--name NAME] [--bind ADDRESS[:PORT]] [--stdio] [--print-url]
10  
11 =head1 DESCRIPTION
12  
13 C<mcp-vim> lets MCP clients read and edit buffers in running Vim editors,
14 including changes that have not been saved to disk. An assistant can work
15 with the same text you are editing, and its changes appear in Vim for you
16 to review and save.
17  
18 It runs as a broker daemon. Each Vim editor needs the supplied Vim plugin,
19 which connects the editor to the broker. Your MCP client connects to the
20 same broker, which forwards requests to the editor and returns its replies.
21 The client can use MCP over HTTP or stdin/stdout; Vim always connects over
22 TCP using the plugin's private protocol.
23  
24 One broker can serve several Vim editors. Each editor connects with a
25 target name, allowing the client to list the connected editors and choose
26 which one to work with. Buffer IDs belong to the selected editor.
27  
28 See L</VIM PLUGIN INSTALLATION> for installing and connecting the Vim
29 plugin, and L<AnyEvent::MCP::Intro> for configuring an MCP client.
30  
31 =head1 FIRST USE
32  
33 Install the companion Vim plugin described below. Configure the MCP
34 client to launch:
35  
36 mcp-vim --stdio --name editor
37  
38 In another terminal, under the same user and configuration directory,
39 retrieve the listener's credential-bearing URL:
40  
41 mcp-vim --name editor --print-url
42  
43 Append a target name and enter the resulting command in Vim:
44  
45 :Mcp http://HOST:PORT/TOKEN/my-editor
46  
47 Then ask the assistant to call C<targets>, C<state>, and C<read-lines>
48 for a buffer in C<my-editor>. C<targets> shows whether Vim connected;
49 C<state> supplies buffer IDs and changedticks. Reads include unsaved text.
50  
51 Through a multibroker, tools have a prefix such as C<vim.targets>.
52 Start its mcp-vim child with C<--eager> so the listener exists before
53 the first tool call. Starting the broker alone does not connect Vim:
54 each editor must run C<:Mcp>. If connecting fails, check the broker's
55 C<--name>, bind address, token and configuration environment.
56 Edits require a current C<expected_changedtick>; they do not save files
57 until the separate C<save> tool or a writing Ex command is used.
58  
59 =head1 TOOLS
60  
61 C<targets> lists connected Vim sessions, and C<state> reports their buffers
62 and current cursor. C<read-lines> and C<grep> operate on live Vim buffers,
63 B<not> saved disk files. C<apply-diff> and C<substitute> edit buffers;
64 C<set-cursor> deliberately changes the visible editor position.
65 Use C<targets> first, then C<state> to obtain buffer IDs and changedticks.
66 A target identifies one connected editor; a buffer ID is local to that editor.
67  
68 Editing operations require the buffer's C<expected_changedtick> from a
69 recent state or read. A changed tick rejects stale edits instead of silently
70 applying them to a buffer that has moved on. Diff context must also match.
71 Explicitly addressed unloaded buffers can be loaded on demand, so reads
72 and edits are not necessarily free of editor side effects. A buffer edit
73 does not save the file to disk; the user remains in control of that step.
74  
75 =head2 Patch text and buffer lines
76  
77 C<apply-diff> accepts Unicode text. The private JSON protocol decodes it
78 into a Vim String; the plugin writes buffer lines in Vim's internal
79 C<&encoding> and sends the patch String to GNU patch. C<&fileencoding>
80 and C<&fileformat> govern saving the buffer, not these temporary files.
81 The UTF-8 path has been checked with non-ASCII text.
82  
83 Patching operates on complete logical lines, with a final newline,
84 independently of C<&endofline>. Nonempty output without that final newline
85 is rejected. Vim represents an embedded NUL in a buffer line as NL inside
86 the corresponding String; C<writefile>/C<readfile> preserve such bytes in
87 untouched lines.
88  
89 NUL-containing diffs are rejected by the broker before permission prompting
90 or forwarding: Vim's C<json_decode> would drop C<\u0000> from Strings.
91 There is no raw-byte diff transport for Vim yet. This differs from the
92 byte-oriented shared helper and the filesystem tool's raw-byte base64 form.
93  
94 =head2 Undo and redo
95  
96 C<undo> and C<redo> each move one step through the selected buffer's normal
97 Vim undo tree. Both require C<target>, C<buffer> and C<expected_changedtick>,
98 and use the C<write> permission. The tick is checked after loading and
99 entering that buffer. A stale tick or an unmodifiable buffer rejects the
100 operation. Neither tool saves the buffer.
101  
102 The result includes C<buffer>, the new C<changedtick>, C<changed>,
103 C<seq_cur> (the reached undo sequence), C<seq_last> (the latest allocated
104 sequence) and C<modified>. At the oldest/newest reachable state, the operation
105 succeeds with C<changed> false. Redo follows Vim's selected branch; it does
106 not switch to another branch or select an arbitrary historical sequence.
107  
108 When another buffer is selected, the caller's original buffer and view are
109 restored. In the current buffer, Vim's normal undo/redo cursor adjustment
110 is retained. Undo acts on ordinary buffer history, including human edits;
111 it does not identify or group changes made by an assistant.
112  
113 =head2 Open a file
114  
115 C<open> accepts C<target> and a nonempty C<path> without NUL. It adds the
116 pathname to Vim's buffer list and loads it without selecting it. Relative
117 paths use Vim's current effective directory at execution time. The pathname
118 is passed to C<bufadd>, not an Ex command or shell; wildcard and command
119 characters are literal. A missing file becomes an empty named buffer.
120  
121 An existing buffer is reused. Loaded contents, including unsaved edits,
122 are not reread from disk. The result reports C<buffer>, C<filename>,
123 C<changedtick>, C<line_count> and C<modified>, ready for subsequent tools.
124 No file is saved. Use C<set-cursor> separately to display the buffer.
125  
126 This requires the separate C<open> action. Loading can run normal Vim
127 autocommands and modelines, which can change editor state or fail after
128 side effects. An error does not undo buffer creation or those effects.
129 Permission scopes still cover an editor, not an individual pathname.
130  
131 =head2 Save modified buffers
132  
133 C<save> accepts C<target>, C<buffer> and C<expected_changedtick>. It runs
134 Vim's C<:update> in that buffer: an unmodified buffer needs no write; a
135 modified buffer is saved to its current filename. There is no filename
136 argument, save-as or force option. A stale tick rejects the operation.
137  
138 Saving requires the separate C<save> permission. A C<write> grant for
139 editing does not authorize saving. The result reports C<buffer>,
140 C<changedtick>, C<modified> and C<filename> after the command. Inspect
141 C<modified>: write autocommands can leave or make the buffer modified.
142  
143 Normal Vim write checks and autocommands apply. They can change text,
144 rename or remove buffers, write other files, or fail after side effects.
145 The tick guard checks the buffer before the command; it does not constrain
146 autocommands or detect external changes to the disk file. A removed or
147 unloaded target after the command produces an error even if a write occurred.
148 The caller's original buffer and view are restored when possible.
149  
150 =head2 Unrestricted Ex commands
151  
152 C<ex> accepts C<target> and C<command>. Without C<buffer>, it executes the
153 command text in that editor's current buffer, window and directory.
154 An optional C<buffer> makes that buffer current first and leaves it current
155 unless the command changes it. C<expected_changedtick> requires C<buffer>
156 and is checked in Vim immediately before executing the command, after
157 entering the buffer. A stale tick prevents execution. Buffer loading and
158 entering can still have their normal Vim side effects.
159  
160 For example, C<command =E<gt> "update"> with a buffer id and its latest
161 changedtick saves that buffer only if its contents have not changed since
162 you inspected it. The tick does not describe the disk file or prevent
163 autocommands from running.
164  
165 The command can change the buffer, window and directory,
166 access files, invoke shell commands or configured functions, and exit Vim.
167 It is not restricted to the current buffer. Prefer the dedicated tools
168 when they express the requested operation.
169  
170 The permission prompt includes the command text. Persistent choices cover
171 this exact command in this editor, any Ex command in this editor, or any
172 Ex command in all current and future editors. Exact means the complete
173 command string, including whitespace and newlines. Such a rule applies to
174 all buffers in that editor: approving C<update> is not approval for only
175 the buffer used in the original request. Commands can invoke mappings,
176 functions and autocommands whose behaviour changes independently of the
177 command text.
178  
179 The result is C<{output: STRING}>, containing captured Vim messages.
180 An error is returned as a tool error; effects before that error remain.
181 Use noninteractive commands. Message capture suppresses ordinary message
182 display, but does not prevent commands from prompting or blocking Vim.
183 Request cancellation stops waiting for the reply, not a command already
184 running in Vim. If a command exits Vim, the connection can close before
185 a reply is delivered.
186  
187 =head1 VIM PLUGIN INSTALLATION
188  
189 The Vim plugin is included in the AnyEvent::MCP source distribution as
190 C<vim/plugin/mcp-vim.vim>. Installing the Perl distribution does not install
191 the Vim plugin. From the source distribution, install it yourself:
192  
193 mkdir -p ~/.vim/plugin
194 cp vim/plugin/mcp-vim.vim ~/.vim/plugin/mcp-vim.vim
195  
196 Alternatively, download the published plugin:
197  
198 mkdir -p ~/.vim/plugin
199 wget -O ~/.vim/plugin/mcp-vim.vim \
200 https://dist.schmorp.de/mcp-vim/1/mcp-vim.vim
201  
202 The C</1/> is the major version of the private Vim/broker protocol, not
203 the MCP protocol or the Perl distribution. Restart Vim after installing
204 or updating the plugin.
205  
206 Connect a Vim instance with C<:Mcp URL>, appending the desired target name
207 to the broker URL (which C<mcp-vim --print-url> can show):
208  
209 :Mcp http://HOST:PORT/TOKEN/TARGET
210  
211 To avoid typing the URL prefix repeatedly, configure
212 C<g:mcp_broker_url> in your vimrc:
213  
214 let g:mcp_broker_url = 'http://HOST:PORT/TOKEN/'
215  
216 Then use C<:Mcp TARGET>, with the target name alone.
217  
218 Distinct Vim instances requesting the same target name receive suffixes
219 such as C< #2>. Reconnecting the same instance replaces its connection and
220 keeps its assigned name. Use C<targets> to obtain the actual names.
221  
222 The Vim plugin uses a private protocol, not MCP. Its initial raw JSON line is
223 C<["mcp-vim", cookie, major, minor, target, instance_id]>; subsequent messages
224 use Vim's ordinary JSON channel envelope. The broker accepts clients with the
225 same major version and a minor version no newer than its own. Keep the broker
226 and plugin versions compatible when updating them.
227  
228 The broker itself can connect to a multibroker using
229 C<--connect http://host:port/token/alias>. Its own TCP listener remains active
230 for Vim and browser connections. The multibroker URL and the Vim broker's own
231 listener URL have independent credentials.
232  
233 =head1 CONNECTIONS AND AUTHENTICATION
234  
235 By default, the broker derives a stable port in the 16384..32767 range
236 from its service-instance name, defaulting to C<default>. Managed users
237 have individually derived tokens. All enabled users may authenticate MCP
238 requests, but only C<connect_user> (default C<default>) may register Vim
239 editors or XPCSE WebSockets. Configured C<tokens> or repeated C<--token>
240 options replace managed credentials and admit those explicit tokens for all
241 connection types. Keep tokens private.
242  
243 By default the TCP listener binds IPv4 loopback on the name-derived port.
244 C<bind> in C<[instance NAME]> or C<--bind> overrides the address and port.
245  
246 C<--stdio>, or C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio>, additionally
247 serves MCP over stdin/stdout. The TCP listener remains active. In this mode
248 the process exits after stdio closes and pending responses have drained.
249  
250 C<--print-url> prints enabled user URLs, annotating the connect user;
251 C<--print-url=USER> selects one. Neither starts a listener. Normal startup does not print
252 the credential. Use the same C<HOME> and C<XDG_CONFIG_HOME> as the
253 running broker, for example when checking the URL of a systemd service
254 account. Changing the global master secret changes derived tokens and
255 invalidates URLs using those tokens. Explicitly configured tokens are
256 independent of the master secret.
257  
258 =head1 PERMISSIONS
259  
260 MCP tool calls require permission independently of connection authentication.
261 C<read> covers C<targets>, C<state>, C<read-lines> and C<grep>.
262 C<write> covers C<apply-diff>, C<substitute>, C<undo>, C<redo> and C<set-cursor>, including
263 changes to the visible editor position. C<save> authorizes the C<save> tool and is
264 independent of C<read> and C<write>. C<open> independently authorizes loading
265 files by pathname. C<exec> authorizes the unrestricted
266 C<ex> tool. Neither C<read> nor C<write> implies C<exec>, or each other.
267 Explicit all-action rules also match C<exec>. Dedicated
268 editing tools leave buffers unsaved; C<save> saves explicitly, and Ex
269 commands can save files or perform other arbitrary work.
270  
271 Permission prompts offer the selected editor (all its buffers), or all
272 editors including future connections. Listing target names has its own
273 scope. Rules identify editors by their assigned target names, not connection
274 IDs; a saved rule also applies to a later editor using that name.
275 Buffer filenames do not restrict these grants.
276  
277 C<apply-diff> attaches display-only C<View patch> details containing the
278 editor name, buffer number and supplied diff. YAD offers a separate viewer;
279 terminal and native MCP prompts show a bounded preview inline. These details
280 do not narrow a saved editor-wide write grant.
281  
282 Rules are stored in
283 C<$XDG_CONFIG_HOME/anyevent-mcp/rules/vim-NAME.ini>, or the corresponding
284 C<$HOME/.config> path. C<NAME> is the service-instance name. For example,
285 C<mcp-vim> uses C<rules/vim-default.ini>. Subjects are C<target:TARGET>
286 for read/write access to an editor and C<targets> for discovery. Ex subjects
287 are C<ex:JSON_TARGET:JSON_COMMAND>, where both JSON values are strings.
288 The helper offers exact and editor-wide matchers; there is no need to
289 write their quoting by hand. An omitted subject still matches all subjects.
290 An allow rule needs an empty C<sandbox-grants> value:
291  
292 [rule]
293 decision=allow
294 action=read
295 subject=target:my-editor
296 sandbox-grants=
297  
298 By default, questions go to the local permission helper. C<--ask tty> and
299 C<--ask yad> force the built-in terminal or YAD interface without fallback.
300 Use C<--ask mcp>
301 to ask through a client with form elicitation, or C<--ask auto> to use
302 elicitation when advertised and the helper otherwise. A declined elicitation
303 does not fall back to the helper. The environment variable
304 C<PERL_ANYEVENT_MCP_PERMISSION_ASK> supplies the default when C<--ask> is
305 omitted. See L<AnyEvent::MCP::Server::Permissions> for rule and prompt details.
306  
307 These checks apply to MCP tools over both HTTP and stdio. They do not change
308 the authenticated private Vim connection or the browser session protocol.
309 Reads can still load explicitly addressed buffers and trigger Vim's usual
310 loading behaviour; these permissions do not sandbox Vim.
311  
312 =head1 OPTIONS
313  
314 Shared switches are documented in
315 L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.
316 The following shared switch has editor-specific behavior.
317  
318 =over
319  
320 =item --ask MODE
321  
322 Permission prompts: C<helper> (default), C<tty>, C<yad>, C<mcp> or
323 C<auto>, or C<none>. tty/yad force local interface; mcp delegates to
324 client, auto prefers native elicitation when offered, and none denies
325 unmatched requests. See L</PERMISSIONS>.
326  
327 =back
328  
329 =head2 Shared-option behavior
330  
331 =over
332  
333 =item --bind ADDRESS[:PORT]
334  
335 Also selects the address and port for private Vim and browser WebSockets.
336  
337 =item --token TOKEN
338  
339 Also authenticates private Vim and browser WebSocket connections.
340  
341 =item --stdio
342  
343 The private Vim/WebSocket listener remains active while MCP uses stdio.
344  
345 =item --connect URL
346  
347 The private Vim/WebSocket listener remains active while MCP connects
348 outward to a multibroker.
349  
350 =item --print-url[=USER]
351  
352 Prints the credential-bearing URL prefix for Vim clients. Append a
353 Vim target as described in L</FIRST USE>.
354  
355 =item --auto-allow TOOL[,ACTION[,CAPABILITY]]
356  
357 For example, C<--auto-allow '*,write'> allows buffer edits, but not
358 C<save>, C<open> or unrestricted C<exec>.
359  
360 =back
361  
362 =head1 SYSTEMD
363  
364 A service can run C</path/to/mcp-vim> directly. Set its C<HOME> and, if
365 needed, C<XDG_CONFIG_HOME> so it uses the intended global secret.
366 Run C<mcp-vim --print-url> as the service user to obtain the connection URL;
367 there is no separate install-time cookie generation step.
368  
369 =cut
370  
371 7 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
372  
373 7 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
374 6 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
375 6 ▶use Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
376 6 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
377 6 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
378  
379 6 ▶use AnyEvent ();
Subroutine BEGIN: called CC=1 SCAR=0.0
380 6 ▶use AnyEvent::Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
381 6 ▶use AnyEvent::MCP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
382 6 ▶use AnyEvent::MCP::Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
383 6 ▶use AnyEvent::MCP::Extension ();
Subroutine BEGIN: called CC=1 SCAR=0.0
384 6 ▶use AnyEvent::MCP::Server::HTTP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
385 6 ▶use AnyEvent::MCP::Server::Toolset ();
Subroutine BEGIN: called CC=1 SCAR=0.0
386 6 ▶use AnyEvent::MCP::Server::Permissions ();
Subroutine BEGIN: called CC=1 SCAR=0.0
387  
388 6 ▶use AnyEvent::MCP::Server::Simple qw(mcp_getoptions mcp_tool_help mcp_log mcp_log_request);
Subroutine BEGIN: called CC=1 SCAR=0.0
389  
390 3 our $PORT;
391 3 our $NICK;
392  
393 3 my $usage = "Usage: mcp-vim [OPTION]...\n";
394 3 my $server_options = mcp_getoptions
395 {
396 usage => $usage,
397 path => "/",
398 description => "Bridge live Vim buffers to MCP and browser WebSocket clients.\n"
399 . "With --stdio, the broker also serves MCP on stdin/stdout; TCP stays active.",
400 examples => " mcp-vim --name editor --bind 127.0.0.1:20792\n"
401 . " mcp-vim --name editor --print-url\n"
402 . " mcp-vim --auto-allow '*,write'",
403 }
404 ;
405 3 ▶@ARGV and die $usage;
Branch: 1 branch
BranchTrueFalseTotal
@ARGV and die $usage 0 3 3
406  
407 3 my $ask = delete $server_options->{ask};
408 3 my $name = $server_options->{name};
409 3 my $bind = $server_options->{bind};
410 3 ▶my @tokens = @{$server_options->{tokens} || []};
Condition100%2/2
$server_options->{'tokens'} || []
l!l
12
MC/DC100%1/1
$server_options->{'tokens'} || []
$server_options->{'tokens'}
Truth table100%2/2
A
A= $server_options->{'tokens'}
Aresult
11
00
411 3 my $connect = $server_options->{connect};
412 3 ▶my $stdio = $server_options->{stdio} || !defined $connect && $ENV{PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL} eq "stdio";
Condition50%3/6
$server_options->{'stdio'} || !defined($connect) && $ENV{'PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL'} eq 'stdio'
l!l&&r!l&&!r
210
not defined $connect and $ENV{"PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL"} eq "stdio"
!ll&&!rl&&r
001
MC/DC0%0/3
$server_options->{'stdio'} || !defined($connect) && $ENV{'PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL'} eq 'stdio'
$server_options->{'stdio'} not defined $connect $ENV{"PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL"} eq "stdio"
Truth table50%2/4
A || not(B) and C
A= $server_options->{'stdio'}B= not defined $connectC= $ENV{"PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL"} eq "stdio"
ABCresult
1XX1
0111
00X0
0100
413 3 ▶!($stdio && defined $connect) or die "Cannot combine --stdio and --connect\n";
Branch: 1 branch
BranchTrueFalseTotal
($stdio and defined $connect) and die "Cannot combine --stdio and --connect\n" 0 3 3
Condition33%1/3
$stdio and defined $connect
!ll&&!rl&&r
030
MC/DC0%0/2
$stdio and defined $connect
$stdio defined $connect
Truth table33%1/3
A and B
A= $stdioB= defined $connect
ABresult
0X0
100
111
414  
415 # private Vim/broker wire protocol (separate from the browser protocol)
416 3 my $vim_prot_major = 1;
417 3 my $vim_prot_minor = 0;
418  
419 3 my $config = AnyEvent::MCP::Config::global_config ();
420 3 my %http = $config->http_settings ($name, $bind);
421 3 my $host = $http{host};
422 3 $PORT = $http{port};
423  
424 3 ▶$http{tokens} = \@tokens if @tokens;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens 1 2 3
425 3 ▶$http{connect_tokens} = \@tokens if @tokens;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens 1 2 3
426 3 ▶delete $http{token_users} if @tokens;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens 1 2 3
427 3 my @accepted_tokens = @{$http{tokens}};
428 3 my @connect_tokens = @{$http{connect_tokens}};
429 3 ▶/\A[A-Za-z0-9_.~-]+\z/ or die "Invalid mcp-vim token\n" for @accepted_tokens;
Branch: 1 branch
BranchTrueFalseTotal
/\A[A-Za-z0-9_.~-]+\z/u or die "Invalid mcp-vim token\n" 4 0 4
430 3 my %connect_token = map { $_ => 1 } @connect_tokens;
431  
432 3 ▶$NICK //= (POSIX::uname)[1] || die "cannot determine mcp-vim hostname\n";
Condition50%2/4
$main::NICK //= (POSIX::uname())[1] || die("cannot determine mcp-vim hostname\n")
l!l
03
(POSIX::uname())[1] || die("cannot determine mcp-vim hostname\n")
l!l
30
MC/DC0%0/1
$main::NICK //= (POSIX::uname())[1] || die("cannot determine mcp-vim hostname\n")
$main::NICK
Truth table50%1/2
A
A= $main::NICK
Aresult
11
00
433  
434 3 our $JSON_CODER = JSON::XS->new->utf8;
435  
436 #############################################################################
437  
438 3 my %xpcse;
439 my %vim;
440 3 my %target;
441  
442 5 ▶sub targets_changed {
Subroutine targets_changed: called CC=2 SCAR=6.9
443 6 $_->send_json ([targets => keys %target]) for values %xpcse;
444 }
445  
446 #############################################################################
447  
448 27 ▶sub base::emit {
Subroutine emit: called CC=2 SCAR=7.1
Pod undocumented
449 28 my ($self, $type, @args) = @_;
450  
451 30 eval {
452 28 $type =~ y/-/_/;
453 28 $type = "_on_$type";
454  
455 28 $self->$type (@args);
456 };
457 27 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 28 28
458 0 warn "error executing $type callback: $@";
459 }
460 }
461  
462 #############################################################################
463 # vim
464  
465 3 @vim::ISA = base::;
466  
467 2 ▶sub vim::new {
Subroutine new: called CC=8 SCAR=21.1
468 2 my ($class, $hdl, $hello) = @_;
469  
470 2 my ($requested, $instance_id) = @$hello[4, 5];
471  
472 (my $old) = grep
473 defined $instance_id
474 && defined $_->{instance_id}
475 && $_->{requested} eq $requested
476 2 ▶ && $_->{instance_id} eq $instance_id,
Condition66%6/9
defined $instance_id && defined $_->{'instance_id'} && $_->{'requested'} eq $requested && $_->{'instance_id'} eq $instance_id
!ll&&!rl&&r
110
defined $instance_id and defined $_->{"instance_id"} and $_->{"requested"} eq $requested
!ll&&!rl&&r
011
defined $instance_id and defined $_->{"instance_id"}
!ll&&!rl&&r
011
MC/DC0%0/4
defined $instance_id && defined $_->{'instance_id'} && $_->{'requested'} eq $requested && $_->{'instance_id'} eq $instance_id
defined $instance_id defined $_->{"instance_id"} $_->{"requested"} eq $requested $_->{'instance_id'} eq $instance_id
Truth table20%1/5
A and B and C && D
A= defined $instance_idB= defined $_->{"instance_id"}C= $_->{"requested"} eq $requestedD= $_->{'instance_id'} eq $instance_id
ABCDresult
0XXX0
10XX0
110X0
11100
11111
477 values %vim;
478  
479 2 ▶ my $name = $old ? $old->{target} : $requested;
Branch: 1 branch
BranchTrueFalseTotal
$old ? : 0 3 3
480 2 ▶ $old->destroy if $old;
Branch: 1 branch
BranchTrueFalseTotal
if $old 0 3 3
481  
482 2 ▶ unless ($old) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($old) 2 1 3
483 2 my $n = 2;
484 $name = "$requested #" . $n++
485 2 ▶ while exists $target{$name};
Branch: 1 branch
BranchTrueFalseTotal
exists $target{$name} and do { $name = "$requested #" . $n++ } 0 3 3
486 }
487  
488 2 my $self = bless {
489 ah => $hdl,
490 target => $name,
491 requested => $requested,
492 instance_id => $instance_id,
493 }, $class;
494  
495 2 $vim{$self+0} = $self;
496  
497 2 AE::log debug => "new vim connection\n";
498  
499 # the line-based hello reader leaves subsequent bytes in the handle.
500 2 $hdl->{json} = AnyEvent::MCP::json_class ()->new->utf8->max_depth (512);
501 2 $hdl->rtimeout (0);
502  
503 {
504 2 Scalar::Util::weaken (my $self = $self);
505  
506 2 ▶ $hdl->on_error (sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
507 2 $_[0]->destroy;
508 2 $self->destroy;
509 2 });
510 }
511  
512 2 mcp_log "vim <$self->{target}> connected";
513 2 $target{$self->{target}} = $self;
514 2 targets_changed;
515  
516 2 $self->read_json;
517 2 $self
518 }
519  
520 28 ▶sub vim::read_json {
Subroutine read_json: called CC=1 SCAR=0.0
521 28 my ($self) = @_;
522  
523 28 Scalar::Util::weaken (my $weak_self = $self);
524  
525 26 ▶ $self->{ah}->push_read (json => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
526 26 my (undef, $packet) = @_;
527  
528 26 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 27 0 27
529  
530 26 $self->emit (@{ $packet->[1] });
531 26 $self->read_json;
532 28 });
533 }
534  
535 2 ▶sub vim::destroy {
Subroutine destroy: called CC=5 SCAR=16.4
536 2 my ($self) = @_;
537  
538 2 ▶ delete $vim{$self+0}
Branch: 1 branch
BranchTrueFalseTotal
delete $vim{$self + 0} or return 2 1 3
539 or return;
540  
541 2 $self->{ah}->destroy;
542  
543 2 ▶ if (my $save = delete $self->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $save = delete $self->{"save"}) 1 4 5
544 0 $save->{xpcse}->cancel_save ($save);
545 }
546  
547 2 delete $target{$self->{target}};
548 2 targets_changed;
549  
550 $_->(0, "vim disconnected")
551 2 ▶ for values %{ delete $self->{rpccb} || {} };
Condition33%1/3
delete $self->{'rpccb'} || {}
l!l
300
MC/DC100%1/1
delete $self->{'rpccb'} || {}
delete $self->{'rpccb'}
Truth table100%2/2
A
A= delete $self->{'rpccb'}
Aresult
11
00
552  
553 2 mcp_log "vim <$self->{target}> disconnected";
554 }
555  
556 27 ▶sub vim::send_msg {
Subroutine send_msg: called CC=1 SCAR=0.0
557 27 my ($self, $msg) = @_;
558  
559 27 $self->{ah}->push_write (json => [0, $msg]);
560  
561 27 AE::log trace => "$self->{target} < @$msg";#d#
562 }
563  
564 27 ▶sub vim::rpc_ {
Subroutine rpc_: called CC=1 SCAR=0.0
565 27 my $cb = pop;
566 27 my ($self, $cmd, @args) = @_;
567  
568 27 my $id = ++$self->{rpcid};
569 27 $self->{rpccb}{$id} = $cb;
570  
571 27 $self->send_msg ([call => $id, $cmd, @args]);
572 }
573  
574 26 ▶sub vim::_on_reply {
Subroutine _on_reply: called CC=2 SCAR=6.9
575 26 my ($self, $id, $success, $result) = @_; # also backtrace, but we completely ignore that
576  
577 26 ▶ my $cb = delete $self->{rpccb}{$id}
Branch: 1 branch
BranchTrueFalseTotal
my $cb = delete $self->{"rpccb"}{$id} or die "reply for id $id has no callback\n" 27 2 29
578 or die "reply for id $id has no callback\n";
579  
580 26 $cb->($success, $result);
581 }
582  
583 # startup session info
584 0 ▶sub vim::_on_session {
Subroutine _on_session: not called CC=1 SCAR=6.9
585 0 my ($self, $id, $state) = @_;
586  
587 0 $self->{session}{$id} = $state;
588 }
589  
590 0 ▶sub vim::_on_ack {
Subroutine _on_ack: not called CC=1 SCAR=6.9
591 0 my ($self, $bytes) = @_;
592 }
593  
594 # end of session list
595 0 ▶sub vim::_on_sessions_done {
Subroutine _on_sessions_done: not called CC=1 SCAR=6.9
596 0 my ($self) = @_;
597  
598 0 $self->send_msg ([echo => "connected as '$self->{target}'"]);
599 }
600  
601 0 ▶sub vim::_on_save {
Subroutine _on_save: not called CC=4 SCAR=30.0
602 0 my ($self, $id, $force) = @_;
603  
604 # a save's input belongs to Vim until eof; the browser queue owns the upload.
605 0 ▶ if (my $old = delete $self->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $old = delete $self->{"save"}) 0 0 0
606 0 $old->{xpcse}->cancel_save ($old);
607 }
608  
609 0 ▶ my $hdrs = $self->{session}{$id}
Branch: 1 branch
BranchTrueFalseTotal
my $hdrs = $self->{"session"}{$id} or return $self->send_msg(["echo", "${id}: session not found"]) 0 0 0
610 or return $self->send_msg ([echo => "$id: session not found"]);
611  
612 0 my ($xpcse) = grep $_->{origin} eq $hdrs->{origin}, values %xpcse;
613  
614 0 ▶ $xpcse
Branch: 1 branch
BranchTrueFalseTotal
$xpcse or return $self->send_msg(["echo", qq[${id}: no origin found, connect a tab for $hdrs->{"origin"}]]) 0 0 0
615 or return $self->send_msg ([echo => "$id: no origin found, connect a tab for $hdrs->{origin}"]);
616  
617 0 AE::log info => "save $id $hdrs->{origin}";
618 0 $self->send_msg ([echo => "requesting save to $hdrs->{origin}..."]);
619  
620 0 $self->{save} = $xpcse->save ($self, $id, $hdrs, $force);
621 }
622  
623 0 ▶sub vim::_on_data {
Subroutine _on_data: not called CC=2 SCAR=17.9
624 0 my ($self, $encoded) = @_;
625  
626 0 my $data = MIME::Base64::decode_base64 $encoded;
627  
628 0 ▶ if (my $save = $self->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $save = $self->{'save'}) { } 0 0 0
629 0 push @{$save->{data}}, $data;
630 0 $save->{xpcse}->send_data;
631 } else {
632 # discard a rejected save's input without holding up its sender.
633 0 $self->send_msg ([ack => length $data]);
634 }
635 }
636  
637 0 ▶sub vim::_on_eof {
Subroutine _on_eof: not called CC=3 SCAR=24.8
638 0 my ($self, $success) = @_;
639  
640 my $save = delete $self->{save}
641 0 ▶ or return;
Branch: 1 branch
BranchTrueFalseTotal
my $save = delete $self->{"save"} or return 0 0 0
642  
643 0 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) { } 0 0 0
644 0 $save->{eof} = 1;
645 0 $save->{xpcse}->send_data;
646 } else {
647 0 $save->{xpcse}->cancel_save ($save);
648 }
649 }
650  
651 0 ▶sub vim::_on_close {
Subroutine _on_close: not called CC=2 SCAR=17.9
652 0 my ($self, $id) = @_;
653  
654 0 ▶ my $hdrs = $self->{session}{$id}
Branch: 1 branch
BranchTrueFalseTotal
my $hdrs = $self->{"session"}{$id} or return $self->send_msg(["echo", "${id}: session not found"]) 0 0 0
655 or return $self->send_msg ([echo => "$id: session not found"]);
656  
657 0 AE::log debug => "vim session close $id";
658  
659 0 unlink $hdrs->{path};
660 0 delete $self->{session}{$id};
661 }
662  
663 0 ▶sub vim::session_open {
Subroutine session_open: not called CC=2 SCAR=16.3
664 0 my ($self, $hdrs) = @_;
665  
666 0 my $id = "s" . substr rand, 2;
667 0 $self->{session}{$id} = $hdrs;
668  
669 0 AE::log debug => "vim session open: $id $hdrs->{path}";
670  
671 0 my $filename = $hdrs->{filename};
672  
673 0 $filename =~ s/->/âž”/g;
674 0 $filename =~ s/::/∷/g;
675 0 $filename =~ s/\//∕/g;
676 0 $filename =~ s/[\/<>:"\\|\?\*\x00-\x1f]/_/g;
677  
678 0 ▶ $self->send_msg ([open => "$id", $filename // "unknown", $hdrs->{extension}, $hdrs]);
Condition50%1/2
$filename // "unknown"
l!l
01
MC/DC0%0/1
$filename // "unknown"
$filename
Truth table50%1/2
A
A= $filename
Aresult
11
00
679 }
680  
681 0 ▶sub vim::_on_quit {
Subroutine _on_quit: not called CC=1 SCAR=6.9
682 0 my ($self) = @_;
683  
684 0 $self->destroy;
685 }
686  
687 #############################################################################
688  
689 3 @xpcse::ISA = base::;
690  
691 1 ▶sub xpcse::new {
Subroutine new: called CC=1 SCAR=0.3
692 1 my ($class, $self) = @_;
693  
694 1 bless $self, $class;
695  
696 {
697 1 Scalar::Util::weaken (my $self = $self);
698  
699 0 ▶ $self->{conn}->on (finish => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
700 #AE::log trace => "on finish";#d#
701 0 $self->finish;
702 1 });
703  
704 1 ▶ $self->{conn}->on (each_message => sub {
Subroutine __ANON__: called CC=3 SCAR=13.2
705 1 eval {
706 1 my $opcode = $_[1]->opcode;
707  
708 1 ▶ if ($opcode == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opcode == 1) { } 1 0 1
709 1 AE::log trace => "websocket recv: " . $_[1]->body;
710  
711 1 $self->emit (@{ $JSON_CODER->decode ($_[1]->body) });
712  
713 } else {
714 0 my $data = $_[1]->body;
715 0 $self->{ondata_cb}($self, $data);
716 0 $self->send_json ([ack => length $data]);
717 }
718 };
719 1 ▶ if ($@) { # AnyEvent::WebScoket simply eats errors and silently disconnects
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
720 0 warn $@;
721 0 exit 1;
722 }
723 1 });
724  
725 0 ▶ $self->{pinger} = AE::timer 5, 10 * 60, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
726 # send regular pong frames, to satisfy nginx and to probe the connection
727 0 $self->{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 10, body => ""));
728 1 };
729 }
730  
731 1 $xpcse{$self+0} = $self; # keep alive
732  
733 1 $self->send_json ([nick => $NICK]);
734  
735 1 targets_changed;
736  
737 1 $self
738 }
739  
740 1 ▶sub xpcse::_on_xpcse_client {
Subroutine _on_xpcse_client: called CC=2 SCAR=7.0
741 1 my ($self, $version) = @_;
742  
743 1 ▶ if ($version != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($version != 1) 1 0 1
744 1 AE::log warn => "ws xpcse client version mismatch (me 1, them $version)";
745 1 $self->destroy;
746 1 return;
747 }
748 }
749  
750 0 ▶sub xpcse::_on_open {
Subroutine _on_open: not called CC=2 SCAR=17.9
751 0 my ($self, $target, $hdrs) = @_;
752  
753 0 ▶ if (my $vim = $target{$target}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vim = $target{$target}) { } 0 0 0
754 0 $self->{upload_vim} = $vim;
755  
756 0 $vim->session_open ($hdrs);
757  
758 0 ▶ $self->{ondata_cb} = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
759 0 ▶ $vim->send_msg ([data => MIME::Base64::encode_base64 $_[1], ""]) if $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim{$vim + 0} 0 0 0
760 0 };
761 } else {
762 0 ▶ $self->{ondata_cb} = sub { };
Subroutine __ANON__: not called CC=1 SCAR=6.9
763 }
764 }
765  
766 1 ▶sub xpcse::_on_eof {
Subroutine _on_eof: called CC=3 SCAR=14.2
767 1 my ($self, $success) = @_;
768  
769 1 ▶ if (my $vim = delete $self->{upload_vim}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vim = delete $self->{"upload_vim"}) 0 1 1
770 0 ▶ $vim->send_msg ([eof => $success*1]) if $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim{$vim + 0} 0 0 0
771 }
772  
773 1 delete $self->{ondata_cb};
774 }
775  
776 2 ▶sub xpcse::send_json {
Subroutine send_json: called CC=1 SCAR=0.0
777 2 $_[0]{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 1, body => $JSON_CODER->encode ($_[1])));
778 }
779  
780 0 ▶sub xpcse::send_bin {
Subroutine send_bin: not called CC=1 SCAR=6.9
781 0 $_[0]{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 2, body => $_[1]));
782 }
783  
784 1 ▶sub xpcse::destroy {
Subroutine destroy: called CC=10 SCAR=31.1
785 1 my ($self, $code) = @_;
786  
787 1 ▶ delete $xpcse{$self+0}
Branch: 1 branch
BranchTrueFalseTotal
delete $xpcse{$self + 0} or return 1 0 1
788 or return;
789  
790 1 ▶ $code ||= 1002;
Condition100%2/2
$code ||= 1002
l!l
11
MC/DC0%0/1
$code ||= 1002
$code
Truth table50%1/2
A
A= $code
Aresult
11
00
791  
792 1 delete $self->{pinger};
793  
794 1 $self->_on_eof (0);
795 1 ▶ for my $save (@{delete $self->{saves} || []}) {
Condition50%1/2
delete $self->{'saves'} || []
l!l
02
MC/DC0%0/1
delete $self->{'saves'} || []
delete $self->{'saves'}
Truth table50%1/2
A
A= delete $self->{'saves'}
Aresult
11
00
796 0 ▶ if (my $vim = $save->{vim}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vim = $save->{"vim"}) 0 0 0
797 delete $vim->{save}
798 0 ▶ if $vim->{save} && $vim->{save} == $save;
Branch: 1 branch
BranchTrueFalseTotal
if $vim->{"save"} and $vim->{"save"} == $save 0 0 0
Condition0%0/3
$vim->{"save"} and $vim->{"save"} == $save
!ll&&!rl&&r
000
MC/DC0%0/2
$vim->{"save"} and $vim->{"save"} == $save
$vim->{"save"} $vim->{"save"} == $save
Truth table0%0/3
A and B
A= $vim->{"save"}B= $vim->{"save"} == $save
ABresult
0X0
100
111
799 0 ▶ $vim->send_msg ([echo => "$save->{session}: browser disconnected"]) if $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim{$vim + 0} 0 0 0
800 }
801 }
802  
803 1 my $conn = delete $self->{conn};
804  
805 1 ▶ $conn->close ($code) if $conn;
Branch: 1 branch
BranchTrueFalseTotal
if $conn 1 0 1
806  
807 1 AE::log debug => "websocket connection destroy $code";
808 }
809  
810 0 ▶sub xpcse::finish {
Subroutine finish: not called CC=1 SCAR=6.9
811 0 shift->destroy (@_);
812 }
813  
814 0 ▶sub xpcse::save {
Subroutine save: not called CC=2 SCAR=17.9
815 0 my ($self, $vim, $session, $hdrs, $force) = @_;
816  
817 0 ▶ my $save = {
Branch: 1 branch
BranchTrueFalseTotal
$force ? : 0 0 0
818 xpcse => $self,
819 vim => $vim,
820 session => $session,
821 hdrs => $hdrs,
822 force => $force ? 1 : 0,
823 data => [],
824 };
825  
826 # the queue and Vim input own the save; neither endpoint is kept alive by it.
827 0 Scalar::Util::weaken ($save->{xpcse});
828 0 Scalar::Util::weaken ($save->{vim});
829 0 push @{$self->{saves}}, $save;
830 0 $self->send_data;
831 0 $save
832 }
833  
834 0 ▶sub xpcse::send_data {
Subroutine send_data: not called CC=7 SCAR=40.3
835 0 my ($self) = @_;
836  
837 0 ▶ my $save = $self->{saves}[0]
Branch: 1 branch
BranchTrueFalseTotal
my $save = $self->{"saves"}[0] or return 0 0 0
838 or return;
839  
840 0 ▶ unless (exists $save->{credit}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $save->{"credit"}) 0 0 0
841 0 $save->{credit} = 10e6;
842 # trailing flag is ignored by current browser clients.
843 0 $self->send_json ([upload => $save->{hdrs}, $save->{force}]);
844 }
845  
846 # a positive credit admits one whole chunk, even if it exceeds the window.
847 0 ▶ while (@{$save->{data}} && $save->{credit} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$save->{"data"};} and $save->{"credit"} > 0) 0 0 0
Condition0%0/3
@{$save->{"data"};} and $save->{"credit"} > 0
!ll&&!rl&&r
000
MC/DC0%0/2
@{$save->{"data"};} and $save->{"credit"} > 0
@{$save->{"data"};} $save->{"credit"} > 0
Truth table0%0/3
A and B
A= @{$save->{"data"};}B= $save->{"credit"} > 0
ABresult
0X0
100
111
848 0 my $data = shift @{$save->{data}};
849 0 $save->{credit} -= length $data;
850 0 $self->send_bin ($data);
851 }
852  
853 # eof is 1 when Vim has finished, 2 once the browser has been told.
854 0 ▶ if ($save->{eof} == 1 && !@{$save->{data}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($save->{"eof"} == 1 and not @{$save->{"data"};}) 0 0 0
Condition0%0/3
$save->{"eof"} == 1 and not @{$save->{"data"};}
!ll&&!rl&&r
000
MC/DC0%0/2
$save->{"eof"} == 1 and not @{$save->{"data"};}
$save->{"eof"} == 1 not @{$save->{"data"};}
Truth table0%0/3
A and not(B)
A= $save->{"eof"} == 1B= not @{$save->{"data"};}
ABresult
0X0
100
111
855 0 $save->{eof} = 2;
856 0 $self->send_json (["upload-done"]);
857 }
858 }
859  
860 0 ▶sub xpcse::_on_ack {
Subroutine _on_ack: not called CC=6 SCAR=37.4
861 0 my ($self, $bytes) = @_;
862  
863 0 ▶ my $save = $self->{saves}[0]
Branch: 1 branch
BranchTrueFalseTotal
my $save = $self->{"saves"}[0] or return 0 0 0
864 or return;
865  
866 $bytes =~ /\A[0-9]+\z/ && $bytes <= 10e6 - $save->{credit}
867 0 ▶ or return $self->destroy;
Branch: 1 branch
BranchTrueFalseTotal
$bytes =~ /\A[0-9]+\z/u and $bytes <= 10000000 - $save->{"credit"} or return $self->destroy 0 0 0
Condition0%0/3
$bytes =~ /\A[0-9]+\z/u and $bytes <= 10000000 - $save->{"credit"}
!ll&&!rl&&r
000
MC/DC0%0/2
$bytes =~ /\A[0-9]+\z/u and $bytes <= 10000000 - $save->{"credit"}
$bytes =~ /\A[0-9]+\z/u $bytes <= 10000000 - $save->{"credit"}
Truth table0%0/3
A and B
A= $bytes =~ /\A[0-9]+\z/uB= $bytes <= 10000000 - $save->{"credit"}
ABresult
0X0
100
111
868  
869 0 $save->{credit} += $bytes;
870  
871 # ack means receipt by the browser, independently of the final save result.
872 0 my $vim = $save->{vim};
873 0 ▶ $vim->send_msg ([ack => $bytes]) if $vim && $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim and $vim{$vim + 0} 0 0 0
Condition0%0/3
$vim and $vim{$vim + 0}
!ll&&!rl&&r
000
MC/DC0%0/2
$vim and $vim{$vim + 0}
$vim $vim{$vim + 0}
Truth table0%0/3
A and B
A= $vimB= $vim{$vim + 0}
ABresult
0X0
100
111
874  
875 0 $self->send_data;
876 }
877  
878 0 ▶sub xpcse::_on_upload_done {
Subroutine _on_upload_done: not called CC=13 SCAR=52.0
879 0 my ($self, $status, $msg, $etag) = @_;
880  
881 0 ▶ my $save = $self->{saves}[0]
Branch: 1 branch
BranchTrueFalseTotal
my $save = $self->{"saves"}[0] or return 0 0 0
882 or return;
883  
884 0 ▶ $save->{eof} == 2
Branch: 1 branch
BranchTrueFalseTotal
$save->{"eof"} == 2 or return $self->destroy 0 0 0
885 or return $self->destroy;
886  
887 0 shift @{$self->{saves}};
888  
889 0 my $vim = $save->{vim};
890 0 ▶ if ($vim && $vim{$vim+0}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($vim and $vim{$vim + 0}) 0 0 0
Condition0%0/3
$vim and $vim{$vim + 0}
!ll&&!rl&&r
000
MC/DC0%0/2
$vim and $vim{$vim + 0}
$vim $vim{$vim + 0}
Truth table0%0/3
A and B
A= $vimB= $vim{$vim + 0}
ABresult
0X0
100
111
891 0 ▶ if ($status == 200 && defined $etag && $etag =~ /\A"sha256:[a-f0-9]{64}"\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 200 and defined $etag and $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u) 0 0 0
Condition0%0/6
$status == 200 and defined $etag and $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u
!ll&&!rl&&r
000
$status == 200 and defined $etag
!ll&&!rl&&r
000
MC/DC0%0/3
$status == 200 and defined $etag and $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u
$status == 200 defined $etag $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u
Truth table0%0/4
A and B and C
A= $status == 200B= defined $etagC= $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u
ABCresult
0XX0
10X0
1100
1111
892 0 ▶ if (my $state = $vim->{session}{$save->{session}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $state = $vim->{"session"}{$save->{"session"}}) 0 0 0
893 0 $state->{etag} = $etag;
894 0 $vim->send_msg (["update-metadata" => $save->{session}, { etag => $etag }]);
895 }
896 }
897 0 ▶ if ($status != 200 || $msg =~ /\n/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status != 200 or $msg =~ /\n/u) { } 0 0 0
Condition0%0/3
$status != 200 or $msg =~ /\n/u
l!l&&r!l&&!r
000
MC/DC0%0/2
$status != 200 or $msg =~ /\n/u
$status != 200 $msg =~ /\n/u
Truth table0%0/3
A or B
A= $status != 200B= $msg =~ /\n/u
ABresult
1X1
011
000
898 0 $msg =~ s/^upload ok, but.*:\n+//;
899 0 $msg =~ s/\n\n+/\n/g;
900 0 $msg =~ s/\n\z//;
901 0 ▶ $vim->send_msg ([error => "error: " . ($status == 200 ? "" : "HTTP $status: ") . $msg]);
Branch: 1 branch
BranchTrueFalseTotal
$status == 200 ? : 0 0 0
902  
903 0 ▶ if ($msg =~ / line ([0-9]+), /) {
Branch: 1 branch
BranchTrueFalseTotal
if ($msg =~ / line ([0-9]+), /u) 0 0 0
904 0 $vim->send_msg ([goto => $save->{session}, $1, 1]);
905 }
906  
907 0 AE::log warn => "upload error: $status $msg";
908 } else {
909 0 $vim->send_msg ([echo => "$status $msg"]);
910 }
911 }
912  
913 # the browser's reply, rather than sending eof, releases the next upload.
914 0 $self->send_data;
915 }
916  
917 0 ▶sub xpcse::cancel_save {
Subroutine cancel_save: not called CC=2 SCAR=17.9
918 0 my ($self, $save) = @_;
919  
920 0 ▶ if ($self->{saves}[0] == $save) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'saves'}[0] == $save) { } 0 0 0
921 # there is no upload-abort message; closing prevents a partial POST.
922 0 $self->destroy (1011);
923 } else {
924 0 @{$self->{saves}} = grep $_ != $save, @{$self->{saves}};
925 }
926 }
927  
928 #############################################################################
929  
930 my $permissions = AnyEvent::MCP::Server::Permissions->new (
931 name => "vim-$name",
932 actions => {
933 read => "Read Vim target names, editor state and buffer contents",
934 open => "Load a file into a Vim buffer; autocommands and modelines may run",
935 write => "Change Vim buffer contents or the editor position",
936 save => "Save a Vim buffer to its current filename if modified",
937 exec => "Execute arbitrary Vim commands with full host-user privileges",
938 },
939 (defined $ask ? (ask => $ask) : ()),
940 3 ▶ auto_rules => [@{$server_options->{auto_rules} || []},
Branch: 1 branch
BranchTrueFalseTotal
defined $ask ? : 1 2 3
Condition50%1/2
$server_options->{'auto_rules'} || []
l!l
03
MC/DC0%0/1
$server_options->{'auto_rules'} || []
$server_options->{'auto_rules'}
Truth table50%1/2
A
A= $server_options->{'auto_rules'}
Aresult
11
00
941 $config->auto_rules ($name)],
942 );
943  
944 59 ▶sub vim_permission {
Subroutine vim_permission: called CC=8 SCAR=20.8
945 59 my ($req, $action, $name, $command, $details, $reason) = @_;
946  
947 59 ▶ my $subject = defined $name ? "target:$name" : "targets";
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 51 8 59
948 59 ▶ my $label = defined $name ? "editor '$name' (all buffers)" : "the list of connected editors";
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 51 8 59
949 59 my @subjects = (
950 { label => $label, match => $subject },
951 { label => "all Vim editors, including future connections", match => "^" },
952 );
953  
954 59 ▶ if (defined $command) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $command) 14 45 59
955 14 my $json = JSON::XS->new->allow_nonref;
956 14 my $editor = "ex:" . $json->encode ($name) . ":";
957 14 $subject = $editor . $json->encode ($command);
958 14 @subjects = (
959 { label => "this exact command in editor '$name' (all buffers)", match => $subject },
960 { label => "any Ex command in editor '$name' (all buffers)", match => "^" . (quotemeta $editor) },
961 { label => "any Ex command in any Vim editor, including future connections", match => "^" },
962 );
963 }
964  
965 $req->require_permission ({
966 tool => $req->{tool},
967 59 ▶ action => $action,
Branch: 3 branches
BranchTrueFalseTotal
defined $name ? : 49 8 57
defined $command ? : 14 43 57
defined $details ? : 3 56 59
Condition100%2/2
$reason // qq[$req->{"tool"}: ] . (defined $name ? "Vim editor '${name}'" : "list connected Vim editors") . (defined $command ? "\n\n$command" : "")
l!l
257
MC/DC100%1/1
$reason // qq[$req->{"tool"}: ] . (defined $name ? "Vim editor '${name}'" : "list connected Vim editors") . (defined $command ? "\n\n$command" : "")
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
968 dimensions => { subject => { label => "Editor / command", value => $subject, choices => \@subjects } },
969 sandbox_grants => [],
970 reason => $reason // ("$req->{tool}: " . (defined $name ? "Vim editor '$name'" : "list connected Vim editors")
971 . (defined $command ? "\n\n$command" : "")),
972 (defined $details ? (details => $details) : ()),
973 });
974 }
975  
976 3 my $toolset = AnyEvent::MCP::Server::Toolset->new;
977 3 my $json = JSON::XS->new;
978  
979 25 ▶sub rpc_reply {
Subroutine rpc_reply: called CC=1 SCAR=0.0
980 25 my ($req, $format) = @_;
981  
982 25 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
983 25 my ($success, $result) = @_;
984  
985 25 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 1 24 25
986  
987 eval {
988 24 ▶ $success or die "$result\n";
Branch: 1 branch
BranchTrueFalseTotal
$success or die "$result\n" 19 5 24
989  
990 19 ▶ $req->reply ($format ? $format->($result) : {
Branch: 1 branch
BranchTrueFalseTotal
$format ? : 2 17 19
991 content => [{
992 type => "text",
993 text => $json->encode ($result),
994 }],
995 });
996 19 1
997 24 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $success or die "$result\n"; $req->reply($format ? &$format($result) : {"content", [{"type", "text", "text", $json->encode($result)}]}); 1 } } or do { my $error = $@; return if $req->{"cancelled"}; die $error if $req->{"finished"}; &AE::log("info", qq[mcp-tool $req->{"tool"}: $error]); $req->error($error) } 19 5 24
998 5 my $error = $@;
999  
1000 5 ▶ return if $req->{cancelled};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"cancelled"} 0 5 5
1001 5 ▶ die $error if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 0 5 5
1002  
1003 5 AE::log info => "mcp-tool $req->{tool}: $error";
1004 5 $req->error ($error);
1005 };
1006 }
1007 25 }
1008  
1009 $toolset->tool (targets =>
1010 "List connected Vim targets (human-readable editor/session IDs). Use if target unknown.",
1011 {
1012 type => "object",
1013 properties => {},
1014 },
1015 7 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1016 7 my ($req, $args) = @_;
1017  
1018 7 vim_permission $req, read => undef;
1019  
1020 5 AE::log debug => "vim targets";
1021  
1022 5 $req->reply ({
1023 content => [{
1024 type => "text",
1025 text => $json->encode ([sort keys %target]),
1026 }],
1027 });
1028 }
1029 3 );
1030  
1031 $toolset->tool (state =>
1032 "Get live Vim state; optional target selects one editor, omit for all. "
1033 . "Returns target => state: cwd, current buffer/cursor, buffer metadata. "
1034 . "Unloaded buffers have null changedtick/line_count; read/search before guarded edits. "
1035 . "Explicit buffer access loads on demand. "
1036 . "Call state each turn if current editor/buffer unknown. "
1037 . "Buffers are live editor state, not disk snapshots.",
1038 {
1039 type => "object",
1040 properties => {
1041 target => {
1042 type => "string",
1043 description => "Optional Vim target id from targets. Omit for all targets.",
1044 },
1045 },
1046 required => [],
1047 },
1048 9 ▶ sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
1049 9 my ($req, $args) = @_;
1050  
1051 9 ▶ my @log = length $args->{target} ? $args->{target} : ();
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'target'} ? : 3 6 9
1052  
1053 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1054 9 AE::log debug => join " ", "vim state", @log;
1055  
1056 my @targets = length $args->{target}
1057 ? $args->{target}
1058 9 ▶ : keys %target;
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'target'} ? : 3 6 9
1059  
1060 # permission retries must happen before any of the parallel RPCs start.
1061 9 vim_permission $req, read => $_ for @targets;
1062 5 ▶ vim_permission $req, read => undef unless @targets;
Branch: 1 branch
BranchTrueFalseTotal
unless @targets 1 4 5
1063  
1064 5 my %state;
1065 5 my $pending = @targets;
1066 5 my $reply = rpc_reply $req;
1067  
1068 5 ▶ return $reply->(1, \%state) unless $pending;
Branch: 1 branch
BranchTrueFalseTotal
unless $pending 1 4 5
1069  
1070 4 for my $name (@targets) {
1071 7 ▶ my $vim = $target{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $vim = $target{$name} or die "target does not exist: $name\n" 7 0 7
1072 or die "target does not exist: $name\n";
1073  
1074 7 ▶ $vim->rpc_ (state => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1075 7 my ($success, $result) = @_;
1076  
1077 7 ▶ return $reply->(0, $result) unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 1 6 7
1078  
1079 6 $state{$name} = $result;
1080 6 ▶ $reply->(1, \%state) unless --$pending;
Branch: 1 branch
BranchTrueFalseTotal
unless --$pending 3 3 6
1081 7 });
1082 }
1083 }
1084 3 );
1085  
1086 $toolset->tool (read_lines =>
1087 "linenums=true prefixes absolute line number and colon. " .
1088 "Read live Vim ranges; load explicit buffer on demand. Returns JSON changedtick/range metadata, then two MCP text items per range: [range=start,end], newline-terminated lines.",
1089 {
1090 type => "object",
1091 properties => {
1092 target => {
1093 type => "string",
1094 description => "Vim target id.",
1095 },
1096 buffer => {
1097 type => "integer",
1098 description => "Buffer id from state.",
1099 },
1100 ranges => {
1101 type => "array",
1102 description => "One or more restricted Vim Ex ranges: %, ., $, positive line numbers, +/- offsets, /regex/, ?regex?, and optional , or ; between two addresses.",
1103 minItems => 1,
1104 items => { type => "string" },
1105 },
1106 linenums => {
1107 type => "boolean",
1108 default => JSON::XS::false,
1109 description => "Prefix each line with its absolute line number and a colon.",
1110 },
1111 },
1112 required => ["target", "buffer", "ranges"],
1113 },
1114 3 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1115 3 my ($req, $args) = @_;
1116  
1117 3 vim_permission $req, read => $args->{target};
1118  
1119 2 my @log = ($args->{target}, $args->{buffer}, @{$args->{ranges}});
1120  
1121 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1122 2 AE::log debug => join " ", "vim read-lines", @log;
1123  
1124 $target{$args->{target}}->rpc_ (
1125 2 ▶ read_lines => $args->{buffer}, $args->{ranges}, rpc_reply ($req, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1126 2 my ($result) = @_;
1127  
1128 2 my @ranges = @{$result->{ranges}};
1129 my $metadata = {
1130 changedtick => $result->{changedtick},
1131 ranges => [map {
1132 2 +{
1133 range => $_->{range},
1134 start => $_->{start},
1135 end => $_->{end},
1136 }
1137 4 } @ranges],
1138 };
1139  
1140 +{
1141 content => [
1142 {
1143 type => "text",
1144 text => $json->encode ($metadata),
1145 },
1146 2 map {{
1147 type => "text",
1148 text => "[range=$_->{start},$_->{end}]",
1149 }, {
1150 type => "text",
1151 4 text => do {
1152 4 my $line = $_->{start};
1153 4 ▶ join "", map { ($args->{linenums} ? $line++ . ":" : "") . "$_\n" } @{$_->{lines}};
Branch: 1 branch
BranchTrueFalseTotal
$args->{'linenums'} ? : 3 4 7
1154 },
1155 }} @ranges,
1156 ],
1157 }
1158 })
1159 2 );
1160 }
1161 3 );
1162  
1163 $toolset->tool (grep =>
1164 "Search Vim buffers; load explicit IDs on demand; empty buffers = all loaded buffers. "
1165 . "mode=regex: native Vim regex; mode=word: literal whole word. "
1166 . "Returns buffer/tick/line/column/text matches, truncated flag.",
1167 {
1168 type => "object",
1169 properties => {
1170 target => {
1171 type => "string",
1172 description => "Vim target id.",
1173 },
1174 buffers => {
1175 type => "array",
1176 description => "Buffer IDs; explicit IDs load on demand; [] = all loaded buffers.",
1177 items => { type => "integer" },
1178 },
1179 pattern => {
1180 type => "string",
1181 description => "Native Vim regex (mode=regex) or literal word (mode=word).",
1182 },
1183 mode => {
1184 type => "string",
1185 enum => ["regex", "word"],
1186 description => "Search syntax.",
1187 },
1188 max_results => {
1189 type => "integer",
1190 minimum => 1,
1191 description => "Max matches.",
1192 },
1193 },
1194 required => ["target", "buffers", "pattern", "mode", "max_results"],
1195 },
1196 6 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1197 6 my ($req, $args) = @_;
1198  
1199 6 vim_permission $req, read => $args->{target};
1200  
1201 5 my @buffers = map 0 + $_, @{$args->{buffers}};
1202 5 ▶ my $log_buffers = @buffers ? (join ",", map 0 + $_, @buffers) : "*";
Branch: 1 branch
BranchTrueFalseTotal
@buffers ? : 5 0 5
1203 my @log = (
1204 $args->{target},
1205 $log_buffers,
1206 $args->{mode},
1207 5 (substr $args->{pattern}, 0, 20),
1208 );
1209  
1210 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1211 5 AE::log debug => join " ", "vim grep", @log;
1212  
1213 $target{$args->{target}}->rpc_ (
1214 5 grep => \@buffers, $args->{pattern}, $args->{mode}, $args->{max_results}, rpc_reply ($req)
1215 );
1216 }
1217 3 );
1218  
1219 1 ▶sub normalize_udiff {
Subroutine normalize_udiff: called CC=22 SCAR=34.9
1220 1 my $diff = shift;
1221 1 my @line = split /\n/, $diff, -1;
1222 1 my $delta = 0;
1223 1 my $hunks = 0;
1224 1 my @max_offset;
1225  
1226 1 ▶ pop @line while @line and !length $line[-1];
Branch: 1 branch
BranchTrueFalseTotal
@line and not length $line[-1] and do { pop @line } 1 1 2
Condition66%2/3
@line and not length $line[-1]
!ll&&!rl&&r
011
MC/DC50%1/2
@line and not length $line[-1]
@line not length $line[-1]
Truth table66%2/3
A and not(B)
A= @lineB= not length $line[-1]
ABresult
0X0
100
111
1227  
1228 1 ▶ for (my $i = 0; $i < @line; ++$i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @line) 1 1 2
1229 1 ▶ next unless $line[$i] =~ /^@@ /;
Branch: 1 branch
BranchTrueFalseTotal
unless $line[$i] =~ /^\@@ /u 0 1 1
1230  
1231 1 ▶ $line[$i] =~ /^@@ -(\d+)(?:,\d+)?(?: \+\d+(?:,\d+)?)? @@(.*)$/
Branch: 1 branch
BranchTrueFalseTotal
$line[$i] =~ /^\@@ -(\d+)(?:,\d+)?(?: \+\d+(?:,\d+)?)? \@@(.*)$/u or die "normalize_udiff: bad hunk header '$line[$i]'\n" 1 0 1
1232 or die "normalize_udiff: bad hunk header '$line[$i]'\n";
1233  
1234 1 my ($old_start, $suffix) = ($1, $2);
1235 1 my ($old_count, $new_count) = (0, 0);
1236 1 my %old_line;
1237 1 my $j = $i + 1;
1238  
1239 # GNU patch mishandles hunks with more prefix than suffix context.
1240 # make the first context line an identity change without losing it.
1241 # see https://unix.stackexchange.com/questions/414542/does-patch-work-with-asymmetric-context
1242 1 ▶ splice @line, $i + 1, 1, "-$1", "+$1"
Branch: 1 branch
BranchTrueFalseTotal
if $line[$i + 1] =~ /^ (.*)\z/u 0 1 1
1243 if $line[$i + 1] =~ /^ (.*)\z/;
1244  
1245 1 ▶ for (; $j < @line; ++$j) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @line) 2 1 3
1246 2 ▶ last if $line[$j] =~ /^@@ /;
Branch: 1 branch
BranchTrueFalseTotal
if $line[$j] =~ /^\@@ /u 0 2 2
1247  
1248 2 my $tag = substr $line[$j], 0, 1;
1249  
1250 2 ▶ if ($tag eq " ") {
Branch: 4 branches
BranchTrueFalseTotal
if ($tag eq ' ') { } 0 2 2
elsif ($tag eq '-') { } 1 1 2
elsif ($tag eq '+') { } 1 0 1
elsif ($line[$j] eq '\\ No newline at end of file') { } 0 0 0
1251 0 ++$old_count;
1252 0 ++$new_count;
1253 0 $old_line{substr $line[$j], 1} = 1;
1254 } elsif ($tag eq "-") {
1255 1 ++$old_count;
1256 1 $old_line{substr $line[$j], 1} = 1;
1257 } elsif ($tag eq "+") {
1258 1 ++$new_count;
1259 } elsif ($line[$j] eq "\\ No newline at end of file") {
1260 # marker belongs to the preceding body line and counts neither side.
1261 } else {
1262 0 die "normalize_udiff: bad hunk line '$line[$j]'\n";
1263 }
1264 }
1265  
1266 1 ▶ $old_count or $new_count
Branch: 1 branch
BranchTrueFalseTotal
$old_count or $new_count or die "normalize_udiff: empty hunk at old line $old_start\n" 1 0 1
Condition33%1/3
$old_count or $new_count
l!l&&r!l&&!r
100
MC/DC0%0/2
$old_count or $new_count
$old_count $new_count
Truth table33%1/3
A or B
A= $old_countB= $new_count
ABresult
1X1
011
000
1267 or die "normalize_udiff: empty hunk at old line $old_start\n";
1268  
1269 1 ▶ $old_count or !$old_start
Branch: 1 branch
BranchTrueFalseTotal
$old_count or not $old_start or die 'normalize_udiff: hunk ' . ($hunks + 1) . " needs old-side context for insertion after old line $old_start\n" 1 0 1
Condition33%1/3
$old_count or not $old_start
l!l&&r!l&&!r
100
MC/DC0%0/2
$old_count or not $old_start
$old_count not $old_start
Truth table33%1/3
A or not(B)
A= $old_countB= not $old_start
ABresult
1X1
011
000
1270 or die "normalize_udiff: hunk " . ($hunks + 1)
1271 . " needs old-side context for insertion after old line $old_start\n";
1272  
1273 1 my $new_start = $old_start + $delta;
1274 1 ▶ ++$new_start unless $old_count;
Branch: 1 branch
BranchTrueFalseTotal
unless $old_count 0 1 1
1275 1 ▶ --$new_start unless $new_count;
Branch: 1 branch
BranchTrueFalseTotal
unless $new_count 0 1 1
1276  
1277 1 ▶ $new_start >= 0
Branch: 1 branch
BranchTrueFalseTotal
$new_start >= 0 or die "normalize_udiff: invalid new line $new_start\n" 1 0 1
1278 or die "normalize_udiff: invalid new line $new_start\n";
1279  
1280 1 $line[$i] = sprintf "@@ -%d,%d +%d,%d @@%s",
1281 $old_start, $old_count, $new_start, $new_count, $suffix;
1282  
1283 1 $delta += $new_count - $old_count;
1284 1 ++$hunks;
1285 1 my $max_offset = keys %old_line;
1286 1 ▶ --$max_offset
Branch: 1 branch
BranchTrueFalseTotal
if $max_offset 1 0 1
1287 if $max_offset;
1288 1 push @max_offset, $max_offset;
1289 1 $i = $j - 1;
1290 }
1291  
1292 1 ▶ $hunks
Branch: 1 branch
BranchTrueFalseTotal
$hunks or die "normalize_udiff: no hunks\n" 1 0 1
1293 or die "normalize_udiff: no hunks\n";
1294  
1295 1 ((join "\n", @line, ""), \@max_offset)
1296 }
1297  
1298 $toolset->tool (open =>
1299 "Load pathname into Vim buffer without selecting; reuse existing buffer without rereading. "
1300 . "Requires separate open permission. Relative paths use Vim's current directory. "
1301 . "No shell/wildcard/Ex parsing. Missing files create empty named buffers; no save. "
1302 . "Load autocommands/modelines run: may change editor or fail after side effects. "
1303 . "Returns buffer, filename, changedtick, line_count, modified.",
1304 {
1305 type => "object",
1306 properties => {
1307 target => { type => "string", description => "Vim target id." },
1308 path => { type => "string", minLength => 1, description => "File pathname, without NUL." },
1309 },
1310 required => ["target", "path"],
1311 additionalProperties => JSON::XS::false,
1312 },
1313 5 ▶ sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
1314 5 my ($req, $args) = @_;
1315  
1316 5 ▶ defined $args->{path} && !ref $args->{path} && length $args->{path} && $args->{path} !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"path"} and not ref $args->{"path"} and length $args->{"path"} and not $args->{"path"} =~ /\0/u or die "path must be a nonempty string without NUL\n" 2 3 5
Condition88%8/9
defined $args->{"path"} and not ref $args->{"path"} and length $args->{"path"} and not $args->{"path"} =~ /\0/u
!ll&&!rl&&r
212
defined $args->{"path"} and not ref $args->{"path"} and length $args->{"path"}
!ll&&!rl&&r
113
defined $args->{"path"} and not ref $args->{"path"}
!ll&&!rl&&r
014
MC/DC75%3/4
defined $args->{"path"} and not ref $args->{"path"} and length $args->{"path"} and not $args->{"path"} =~ /\0/u
defined $args->{"path"} not ref $args->{"path"} length $args->{"path"} not $args->{"path"} =~ /\0/u
Truth table80%4/5
A and not(B) and C and not(D)
A= defined $args->{"path"}B= not ref $args->{"path"}C= length $args->{"path"}D= not $args->{"path"} =~ /\0/u
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1317 or die "path must be a nonempty string without NUL\n";
1318 my $vim = $target{$args->{target}}
1319 2 ▶ or die "target does not exist: $args->{target}\n";
Branch: 1 branch
BranchTrueFalseTotal
my $vim = $target{$args->{"target"}} or die qq[target does not exist: $args->{"target"}\n] 2 0 2
1320  
1321 vim_permission $req, open => $args->{target}, undef, undef,
1322 2 "Open file in Vim editor '$args->{target}'\nPath: " . JSON::XS->new->allow_nonref->encode ($args->{path});
1323  
1324 1 AE::log debug => "vim open $args->{target} " . $json->encode (substr $args->{path}, 0, 80);
1325  
1326 1 $vim->rpc_ (open => $args->{path}, rpc_reply ($req));
1327 }
1328 3 );
1329  
1330 $toolset->tool (apply_diff =>
1331 "Apply relaxed unified diff to live Vim buffer; reject NUL. In @@ headers only old start (-N) matters: first hunk body line, including context; "
1332 . "other numbers ignored/recomputed (may be 0); '\@\@ -N \@\@' valid. "
1333 . "Requires current expected_changedtick and exact context (fuzz=0). Hunk relocation bounded by distinct old-side lines per hunk. Pure insertion only at buffer start; elsewhere include old-side context.",
1334 {
1335 type => "object",
1336 properties => {
1337 target => {
1338 type => "string",
1339 description => "Vim target id.",
1340 },
1341 buffer => {
1342 type => "integer",
1343 description => "Buffer id from current Vim state.",
1344 },
1345 diff => {
1346 type => "string",
1347 minLength => 1,
1348 description => "Unified diff: \@\@ old start (-N) is first hunk body line including context; other counts ignored (may be 0); \@\@ -N \@\@ valid. Pure insertion only at start; elsewhere old-side context required. Hunk relocation bound derived from distinct old-side lines.",
1349 },
1350 expected_changedtick => {
1351 type => "integer",
1352 description => "changedtick from latest state/read of this buffer.",
1353 },
1354 },
1355 required => ["target", "buffer", "diff", "expected_changedtick"],
1356 },
1357 4 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.8
1358 4 my ($req, $args) = @_;
1359  
1360 4 ▶ defined $args->{diff} && !ref $args->{diff} && $args->{diff} !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"diff"} and not ref $args->{"diff"} and not $args->{"diff"} =~ /\0/u or die "diff must be text without NUL\n" 3 1 4
Condition50%3/6
defined $args->{"diff"} and not ref $args->{"diff"} and not $args->{"diff"} =~ /\0/u
!ll&&!rl&&r
013
defined $args->{"diff"} and not ref $args->{"diff"}
!ll&&!rl&&r
004
MC/DC33%1/3
defined $args->{"diff"} and not ref $args->{"diff"} and not $args->{"diff"} =~ /\0/u
defined $args->{"diff"} not ref $args->{"diff"} not $args->{"diff"} =~ /\0/u
Truth table50%2/4
A and not(B) and not(C)
A= defined $args->{"diff"}B= not ref $args->{"diff"}C= not $args->{"diff"} =~ /\0/u
ABCresult
0XX0
10X0
1100
1111
1361 or die "diff must be text without NUL\n";
1362  
1363 3 my $buffer = $args->{buffer};
1364 vim_permission $req, write => $args->{target}, undef, {
1365 3 "View patch" => "Editor: $args->{target}\nBuffer: $buffer\n\n$args->{diff}",
1366 };
1367  
1368 1 my ($hunk, $body);
1369  
1370 1 for (split /\n/, $args->{diff}) {
1371 3 ▶ if (/^@@ /) {
Branch: 2 branches
BranchTrueFalseTotal
if (/^\@@ /u) { } 1 2 3
elsif ($hunk) { } 2 0 2
1372 1 ++$hunk;
1373 } elsif ($hunk) {
1374 2 ++$body;
1375 }
1376 }
1377  
1378 1 my @log = ($args->{target}, $args->{buffer}, $body);
1379  
1380 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1381 1 AE::log debug => join " ", "vim apply-diff", @log;
1382  
1383 $target{$args->{target}}->rpc_ (
1384 apply_patch =>
1385 $args->{buffer},
1386 (normalize_udiff $args->{diff}),
1387 1 $args->{expected_changedtick}, rpc_reply ($req)
1388 );
1389 }
1390 3 );
1391  
1392 $toolset->tool (substitute =>
1393 "Guarded Vim :substitute over live buffer range; for mechanical regex replacements. "
1394 . "Prefer apply-diff for structural/multiline edits. Native Vim regex pattern. "
1395 . "Native Vim :substitute replacement/flags. "
1396 . q{To clear the whole buffer, use range %, pattern \%^\_.*\%$, replacement empty, flags empty; Vim leaves one empty line. }
1397 . "expected_changedtick must match; otherwise stale error.",
1398 {
1399 type => "object",
1400 properties => {
1401 target => {
1402 type => "string",
1403 description => "Vim target id.",
1404 },
1405 buffer => {
1406 type => "integer",
1407 description => "Buffer id.",
1408 },
1409 range => {
1410 type => "string",
1411 description => "Restricted Vim Ex range: %, ., $, positive line numbers, +/- offsets, /regex/, ?regex?, and optional , or ; between two addresses.",
1412 },
1413 pattern => {
1414 type => "string",
1415 description => "Native Vim regex.",
1416 },
1417 replacement => {
1418 type => "string",
1419 description => "Native Vim :substitute replacement.",
1420 },
1421 flags => {
1422 type => "string",
1423 description => "Vim substitute flags; allowed: egiInp#lr.",
1424 pattern => "^[egiInp#lr]*\$",
1425 },
1426 expected_changedtick => {
1427 type => "integer",
1428 description => "changedtick from latest read/state.",
1429 },
1430 },
1431 required => [
1432 "target", "buffer", "range", "pattern", "replacement", "flags", "expected_changedtick"
1433 ],
1434 },
1435 2 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1436 2 my ($req, $args) = @_;
1437  
1438 2 vim_permission $req, write => $args->{target};
1439  
1440 my @log = (
1441 $args->{target}, $args->{buffer}, $args->{range},
1442 (substr $args->{pattern}, 0, 20),
1443 "=>",
1444 (substr $args->{replacement}, 0, 20),
1445 $args->{flags},
1446 1 );
1447  
1448 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1449 1 AE::log debug => join " ", "vim substitute", @log;
1450  
1451 $target{$args->{target}}->rpc_ (
1452 substitute => $args->{buffer}, $args->{range}, $args->{pattern},
1453 1 $args->{replacement}, $args->{flags}, $args->{expected_changedtick}, rpc_reply ($req)
1454 );
1455 }
1456 3 );
1457  
1458 3 for my $operation (qw(undo redo update)) {
1459 $toolset->tool (($operation eq "update" ? "save" : $operation) =>
1460 $operation eq "update"
1461 ? "Run Vim :update: save selected buffer to current filename only if modified. "
1462 . "Requires save permission and current expected_changedtick; no filename/force option. "
1463 . "Write autocommands run; failure may leave side effects (no rollback). "
1464 . "Returns buffer, changedtick, modified, filename. "
1465 . "Preserves caller's current buffer/view when possible."
1466 : ucfirst ($operation) . " one change in selected Vim buffer via undo tree. "
1467 . "Requires write permission and latest expected_changedtick. "
1468 . "Leaves edits unsaved; preserves caller's current buffer when editing another. "
1469 . "At history boundary: changed=false. "
1470 . "Returns buffer, changedtick, changed, seq_cur (reached undo sequence), seq_last, modified.",
1471 {
1472 type => "object",
1473 properties => {
1474 target => { type => "string", description => "Vim target id." },
1475 buffer => { type => "integer", minimum => 1, description => "Buffer id from current Vim state." },
1476 expected_changedtick => {
1477 type => "integer", minimum => 0,
1478 description => "changedtick from latest read/state of this buffer.",
1479 },
1480 },
1481 required => ["target", "buffer", "expected_changedtick"],
1482 additionalProperties => JSON::XS::false,
1483 },
1484 16 ▶ sub {
Subroutine __ANON__: called CC=10 SCAR=23.5
1485 16 my ($req, $args) = @_;
1486  
1487 16 ▶ defined $args->{buffer} && !ref $args->{buffer} && $args->{buffer} =~ /\A[1-9][0-9]*\z/
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"buffer"} and not ref $args->{"buffer"} and $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u or die "buffer must be a positive integer\n" 13 3 16
Condition50%3/6
defined $args->{"buffer"} and not ref $args->{"buffer"} and $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u
!ll&&!rl&&r
0313
defined $args->{"buffer"} and not ref $args->{"buffer"}
!ll&&!rl&&r
0016
MC/DC33%1/3
defined $args->{"buffer"} and not ref $args->{"buffer"} and $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u
defined $args->{"buffer"} not ref $args->{"buffer"} $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u
Truth table50%2/4
A and not(B) and C
A= defined $args->{"buffer"}B= not ref $args->{"buffer"}C= $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u
ABCresult
0XX0
10X0
1100
1111
1488 or die "buffer must be a positive integer\n";
1489 defined $args->{expected_changedtick} && !ref $args->{expected_changedtick}
1490 13 ▶ && $args->{expected_changedtick} =~ /\A[0-9]+\z/
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"expected_changedtick"} and not ref $args->{"expected_changedtick"} and $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u or die "expected_changedtick must be a nonnegative integer\n" 7 6 13
Condition83%5/6
defined $args->{"expected_changedtick"} and not ref $args->{"expected_changedtick"} and $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u
!ll&&!rl&&r
337
defined $args->{"expected_changedtick"} and not ref $args->{"expected_changedtick"}
!ll&&!rl&&r
3010
MC/DC66%2/3
defined $args->{"expected_changedtick"} and not ref $args->{"expected_changedtick"} and $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u
defined $args->{"expected_changedtick"} not ref $args->{"expected_changedtick"} $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u
Truth table75%3/4
A and not(B) and C
A= defined $args->{"expected_changedtick"}B= not ref $args->{"expected_changedtick"}C= $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u
ABCresult
0XX0
10X0
1100
1111
1491 or die "expected_changedtick must be a nonnegative integer\n";
1492  
1493 my $vim = $target{$args->{target}}
1494 7 ▶ or die "target does not exist: $args->{target}\n";
Branch: 1 branch
BranchTrueFalseTotal
my $vim = $target{$args->{"target"}} or die qq[target does not exist: $args->{"target"}\n] 7 0 7
1495  
1496 7 ▶ vim_permission $req, ($operation eq "update" ? "save" : "write") => $args->{target};
Branch: 1 branch
BranchTrueFalseTotal
$operation eq 'update' ? : 3 4 7
1497  
1498 AE::log debug => join " ", "vim", ($operation eq "update" ? "save" : $operation),
1499 4 ▶ $args->{target}, $args->{buffer};
Branch: 1 branch
BranchTrueFalseTotal
$operation eq 'update' ? : 2 2 4
1500 4 $vim->rpc_ ($operation => 0 + $args->{buffer}, 0 + $args->{expected_changedtick}, rpc_reply ($req));
1501 }
1502 9 ▶ );
Branch: 2 branches
BranchTrueFalseTotal
$operation eq 'update' ? : 3 6 9
$operation eq 'update' ? : 3 6 9
1503 }
1504  
1505 $toolset->tool (set_cursor =>
1506 "Show/select buffer and position Vim cursor. Unlike read/edit, intentionally changes user's "
1507 . "editor position. Optional expected_changedtick rejects stale buffer. "
1508 . "After edits in user's current buffer, move cursor to changed region so user sees it. "
1509 . "Avoid cursor movement for exploratory reads/searches unless useful.",
1510 {
1511 type => "object",
1512 properties => {
1513 target => {
1514 type => "string",
1515 description => "Vim target id.",
1516 },
1517 buffer => {
1518 type => "integer",
1519 description => "Buffer id.",
1520 },
1521 line => {
1522 type => "integer",
1523 minimum => 1,
1524 description => "1-based line.",
1525 },
1526 column => {
1527 type => "integer",
1528 minimum => 1,
1529 description => "1-based byte column as used by Vim col().",
1530 },
1531 expected_changedtick => {
1532 type => "integer",
1533 description => "Optional buffer changedtick guard.",
1534 },
1535 },
1536 required => ["target", "buffer", "line", "column"],
1537 },
1538 3 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1539 3 my ($req, $args) = @_;
1540  
1541 3 vim_permission $req, write => $args->{target};
1542  
1543 2 my @log = ($args->{target}, $args->{buffer}, $args->{line}, $args->{column});
1544  
1545 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1546 2 AE::log debug => join " ", "vim set-cursor", @log;
1547  
1548 $target{$args->{target}}->rpc_ (
1549 2 ▶ set_cursor => @{$args}{qw(buffer line column)},
Branch: 1 branch
BranchTrueFalseTotal
exists $args->{'expected_changedtick'} ? : 1 1 2
1550 2 (exists $args->{expected_changedtick} ? $args->{expected_changedtick} : ()), rpc_reply ($req)
1551 );
1552 }
1553 3 );
1554  
1555 $toolset->tool (ex =>
1556 "Execute unrestricted Vim Ex in current editor context; needs separate exec permission. "
1557 . "Can run shell, read/write files, invoke code, exit Vim with user's privileges. "
1558 . "Prefer dedicated read/edit/navigation tools. "
1559 . "command: Ex text, including separators/newlines; keep reviewable. "
1560 . "Optional buffer becomes current; expected_changedtick requires buffer, checked just before execution. "
1561 . "Persistent grants may cover exact command, any command in this editor, or all editors. "
1562 . "Returns {output: Vim messages} or Vim error; no rollback of earlier effects. "
1563 . "Use noninteractive commands; prompts/long runs block Vim; cancellation cannot undo execution.",
1564 {
1565 type => "object",
1566 properties => {
1567 target => { type => "string", description => "Vim target id." },
1568 command => { type => "string", minLength => 1, description => "Unrestricted Ex command text, without NUL." },
1569 buffer => { type => "integer", minimum => 1, description => "Optional buffer to make current before execution." },
1570 expected_changedtick => {
1571 type => "integer", minimum => 0,
1572 description => "Optional changedtick guard for buffer; requires buffer. A stale tick prevents execution.",
1573 },
1574 },
1575 required => ["target", "command"],
1576 },
1577 18 ▶ sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
1578 18 my ($req, $args) = @_;
1579  
1580 18 my $command = $args->{command};
1581 18 ▶ defined $command && !ref $command && length $command && $command !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
defined $command and not ref $command and length $command and not $command =~ /\0/u or die "command must be a nonempty string without NUL\n" 15 3 18
Condition88%8/9
defined $command and not ref $command and length $command and not $command =~ /\0/u
!ll&&!rl&&r
2115
defined $command and not ref $command and length $command
!ll&&!rl&&r
1116
defined $command and not ref $command
!ll&&!rl&&r
0117
MC/DC75%3/4
defined $command and not ref $command and length $command and not $command =~ /\0/u
defined $command not ref $command length $command not $command =~ /\0/u
Truth table80%4/5
A and not(B) and C and not(D)
A= defined $commandB= not ref $commandC= length $commandD= not $command =~ /\0/u
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1582 or die "command must be a nonempty string without NUL\n";
1583  
1584 !exists $args->{expected_changedtick} || exists $args->{buffer}
1585 15 ▶ or die "expected_changedtick requires buffer\n";
Branch: 1 branch
BranchTrueFalseTotal
not exists $args->{"expected_changedtick"} or exists $args->{"buffer"} or die "expected_changedtick requires buffer\n" 14 1 15
Condition100%3/3
not exists $args->{"expected_changedtick"} or exists $args->{"buffer"}
l!l&&r!l&&!r
1311
MC/DC100%2/2
not exists $args->{"expected_changedtick"} or exists $args->{"buffer"}
not exists $args->{"expected_changedtick"} exists $args->{"buffer"}
Truth table100%3/3
not(A) or B
A= not exists $args->{"expected_changedtick"}B= exists $args->{"buffer"}
ABresult
1X1
011
000
1586  
1587 my $vim = $target{$args->{target}}
1588 14 ▶ or die "target does not exist: $args->{target}\n";
Branch: 1 branch
BranchTrueFalseTotal
my $vim = $target{$args->{"target"}} or die qq[target does not exist: $args->{"target"}\n] 14 0 14
1589  
1590 14 vim_permission $req, exec => $args->{target}, $command;
1591  
1592 4 $vim->rpc_ (ex => $command, @{$args}{qw(buffer expected_changedtick)}, rpc_reply ($req));
1593 }
1594 3 );
1595  
1596 3 mcp_tool_help ($server_options->{tool_help}, $toolset);
1597  
1598 3 my $instructions = <<'EOF';
1599 Live Vim buffers, not disk snapshots. Use targets for editors, state for buffer IDs/changedticks.
1600 Read via read-lines/grep; explicit access may load unloaded buffers.
1601 open loads pathname without selecting; requires separate open permission.
1602 apply-diff/substitute/undo/redo modify live buffers; require current expected_changedtick; leave unsaved.
1603 save writes current filename only if modified; needs save permission and current expected_changedtick.
1604 set-cursor moves visible editor cursor; use to show edits or navigate.
1605 ex runs unrestricted Ex with full Vim privileges; requires separate exec permission. Prefer narrow tools.
1606 EOF
1607  
1608 my $custom_instructions = $server_options->{custom_instructions}
1609 // $config->{section}{"instance $name"}{custom_instructions}
1610 3 ▶ // $config->{section}{"program " . AnyEvent::MCP::Config::program_name ()}{custom_instructions};
Condition33%2/6
($server_options->{"custom_instructions"} // $config->{"section"}{"instance $name"}{"custom_instructions"}) // $config->{"section"}{'program ' . AnyEvent::MCP::Config::program_name()}{"custom_instructions"}
l!l&&r!l&&!r
003
$server_options->{"custom_instructions"} // $config->{"section"}{"instance $name"}{"custom_instructions"}
l!l&&r!l&&!r
003
MC/DC0%0/3
($server_options->{"custom_instructions"} // $config->{"section"}{"instance $name"}{"custom_instructions"}) // $config->{"section"}{'program ' . AnyEvent::MCP::Config::program_name()}{"custom_instructions"}
$server_options->{"custom_instructions"} $config->{"section"}{"instance $name"}{"custom_instructions"} $config->{"section"}{'program ' . AnyEvent::MCP::Config::program_name()}{"custom_instructions"}
Truth table25%1/4
A // B // C
A= $server_options->{"custom_instructions"}B= $config->{"section"}{"instance $name"}{"custom_instructions"}C= $config->{"section"}{'program ' . AnyEvent::MCP::Config::program_name()}{"custom_instructions"}
ABCresult
1XX1
01X1
0011
0000
1611 3 ▶my %guidance = (
Branch: 1 branch
BranchTrueFalseTotal
defined $custom_instructions ? : 0 3 3
1612 instructions => $instructions,
1613 short_instructions => "Live Vim buffers: inspect, edit with changedtick guards (unsaved), navigate. Discover tools.",
1614 auto_instructions => 1,
1615 on_request => \&mcp_log_request,
1616 (defined $custom_instructions ? (custom_instructions => $custom_instructions) : ()),
1617 );
1618  
1619 my $mcp = AnyEvent::MCP::Server::HTTP->new (
1620 server_info => { name => "mcp-vim", version => "0" },
1621 %guidance,
1622 toolsets => [$toolset],
1623 permissions => $permissions,
1624 path => "/",
1625 tokens => \@accepted_tokens,
1626 token_users => $http{token_users},
1627 3 max_size => 100e6,
1628 origins => ["*"],
1629 connection_close => 1,
1630 );
1631  
1632 3 my $done = AE::cv;
1633 3 my $stdio_mcp;
1634  
1635 3 ▶if (defined $connect) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $connect) { } 0 3 3
elsif ($stdio) { } 3 0 3
1636 0 require AnyEvent::MCP::Server::Connect;
1637 $stdio_mcp = AnyEvent::MCP::Server::Connect->new (
1638 server_info => $mcp->{server_info},
1639 %guidance,
1640 toolsets => [$toolset],
1641 permissions => $permissions,
1642 max_size => 100e6,
1643 connect => $connect,
1644 0 ▶ on_close => sub { $done->send },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1645 0 );
1646 0 $stdio_mcp->start;
1647 } elsif ($stdio) {
1648 3 require AnyEvent::MCP::Server::JSONL;
1649  
1650 3 binmode STDIN;
1651 3 binmode STDOUT;
1652  
1653 $stdio_mcp = AnyEvent::MCP::Server::JSONL->new (
1654 server_info => $mcp->{server_info},
1655 %guidance,
1656 toolsets => [$toolset],
1657 permissions => $permissions,
1658 max_size => 100e6,
1659 3 ▶ on_connection_close => sub { $done->send },
Subroutine __ANON__: called CC=1 SCAR=0.0
1660 3 );
1661  
1662 3 $stdio_mcp->accept (\*STDIN, \*STDOUT);
1663 }
1664  
1665 #############################################################################
1666  
1667 3 ▶sub accept_json {
Subroutine accept_json: called CC=1 SCAR=1.9
1668 3 my ($fh) = @_;
1669  
1670 my $hdl = AnyEvent::Handle->new (
1671 fh => $fh,
1672 0 ▶ on_error => sub { $_[0]->destroy },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1673 0 ▶ on_eof => sub { $_[0]->destroy },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1674 3 );
1675  
1676 2 ▶ AnyEvent::MCP::Extension::accept ($hdl, \@connect_tokens, sub {
Subroutine __ANON__: called CC=15 SCAR=42.0
1677 2 my ($hdl, $hello) = @_;
1678  
1679 2 ▶ @$hello == 6 && $hello->[0] eq "mcp-vim"
Branch: 1 branch
BranchTrueFalseTotal
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4] and defined $hello->[5] and not ref $hello->[5] or die "Invalid private Vim hello\n" 2 0 2
Condition33%13/39
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4] and defined $hello->[5] and not ref $hello->[5]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4] and defined $hello->[5]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim"
!ll&&!rl&&r
002
MC/DC0%0/14
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4] and defined $hello->[5] and not ref $hello->[5]
@$hello == 6 $hello->[0] eq "mcp-vim" defined $hello->[2] not ref $hello->[2] $hello->[2] =~ /\A[0-9]+\z/u defined $hello->[3] not ref $hello->[3] $hello->[3] =~ /\A[0-9]+\z/u $hello->[2] == $vim_prot_major $hello->[3] <= $vim_prot_minor defined $hello->[4] not ref $hello->[4] defined $hello->[5] not ref $hello->[5]
Truth table6%1/15
A and B and C and not(D) and E and F and not(G) and H and I and J and K and not(L) and M and not(N)
A= @$hello == 6B= $hello->[0] eq "mcp-vim"C= defined $hello->[2]D= not ref $hello->[2]E= $hello->[2] =~ /\A[0-9]+\z/uF= defined $hello->[3]G= not ref $hello->[3]H= $hello->[3] =~ /\A[0-9]+\z/uI= $hello->[2] == $vim_prot_majorJ= $hello->[3] <= $vim_prot_minorK= defined $hello->[4]L= not ref $hello->[4]M= defined $hello->[5]N= not ref $hello->[5]
ABCDEFGHIJKLMNresult
0XXXXXXXXXXXXX0
10XXXXXXXXXXXX0
110XXXXXXXXXXX0
1110XXXXXXXXXX0
11110XXXXXXXXX0
111110XXXXXXXX0
1111110XXXXXXX0
11111110XXXXXX0
111111110XXXXX0
1111111110XXXX0
11111111110XXX0
111111111110XX0
1111111111110X0
111111111111100
111111111111111
1680 && defined $hello->[2] && !ref $hello->[2] && $hello->[2] =~ /\A[0-9]+\z/
1681 && defined $hello->[3] && !ref $hello->[3] && $hello->[3] =~ /\A[0-9]+\z/
1682 && $hello->[2] == $vim_prot_major && $hello->[3] <= $vim_prot_minor
1683 && defined $hello->[4] && !ref $hello->[4]
1684 && defined $hello->[5] && !ref $hello->[5]
1685 or die "Invalid private Vim hello\n";
1686  
1687 2 vim->new ($hdl, $hello);
1688 3 });
1689 }
1690  
1691 #############################################################################
1692  
1693 3 ▶sub accept_ws {
Subroutine accept_ws: called CC=2 SCAR=6.9
1694 3 my ($fh, $peer_host, $peer_port) = @_;
1695  
1696 3 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require AnyEvent::WebSocket::Server; require AnyEvent::WebSocket::Message; 1 } } or return &AE::log("warn", "WebSocket support unavailable: $@") 3 0 3
1697 3 require AnyEvent::WebSocket::Server;
1698 3 require AnyEvent::WebSocket::Message;
1699 3 1
1700 } or return AE::log warn => "WebSocket support unavailable: $@";
1701  
1702 # tcp_server has already formatted the numeric address for us.
1703 3 my $peer = AnyEvent::Socket::format_hostport $peer_host, $peer_port;
1704  
1705 3 my ($origin, $rejection);
1706  
1707 my $ws_server = new AnyEvent::WebSocket::Server
1708 max_payload_size => 1000e6,
1709 3 ▶ handshake => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1710 3 my ($req, $res) = @_;
1711  
1712 3 my ($cookie, $target) = $req->{resource_name} =~ m%^/([^/]+)/+(.+)\z%s;
1713 3 ▶ unless (defined $cookie && $connect_token{$cookie}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cookie and $connect_token{$cookie}) 2 1 3
Condition100%3/3
defined $cookie and $connect_token{$cookie}
!ll&&!rl&&r
111
MC/DC100%2/2
defined $cookie and $connect_token{$cookie}
defined $cookie $connect_token{$cookie}
Truth table100%3/3
A and B
A= defined $cookieB= $connect_token{$cookie}
ABresult
0X0
100
111
1714 2 ▶ $rejection = defined $cookie ? "invalid token" : "invalid path";
Branch: 1 branch
BranchTrueFalseTotal
defined $cookie ? : 1 1 2
1715 2 die "Vim WebSocket handshake rejected\n";
1716 }
1717  
1718 1 $origin = $target;
1719  
1720 1 AE::log info => "websocket connect for $origin";
1721 #$res->subprotocol ($prot);
1722  
1723 #$res->{subprotocol}
1724 # or return AE::log info => "no matching subprotocol";
1725  
1726 1 $res
1727 },
1728 3 ;
1729  
1730 3 ▶ $ws_server->establish ($fh)->cb (sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
1731 3 ▶ if (my $conn = eval { $_[0]->recv }) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $conn = eval { do { $_[0]->recv } }) { } 1 2 3
elsif ($rejection) { } 2 0 2
1732 1 xpcse->new ({ conn => $conn, origin => $origin });
1733 } elsif ($rejection) {
1734 2 AE::log warn => "Vim WebSocket rejected: $rejection ($peer)";
1735 } else {
1736 0 AE::log warn => "Vim WebSocket establishment failed from $peer: $@";
1737 }
1738 3 });
1739 }
1740  
1741 #############################################################################
1742  
1743 11 ▶AnyEvent::Socket::tcp_server $host, $PORT, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1744 11 ▶ my ($fh, $peer_host, $peer_port) = @_
Branch: 1 branch
BranchTrueFalseTotal
my($fh, $peer_host, $peer_port) = or return 11 0 11
1745 or return;
1746  
1747 11 ▶ my $watcher; $watcher = AE::io $fh, 0, sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
1748 11 undef $watcher;
1749  
1750 11 ▶ defined recv $fh, my $magic, 1, Socket::MSG_PEEK
Branch: 1 branch
BranchTrueFalseTotal
defined recv($fh, my $magic, 1, 2) or return 11 0 11
1751 or return;
1752  
1753 11 ▶ if ($magic eq "[") { # json
Branch: 3 branches
BranchTrueFalseTotal
if ($magic eq '[') { } 3 8 11
elsif ($magic eq 'P' or $magic eq 'O') { } 4 4 8
elsif ($magic eq 'G') { } 3 1 4
1754 3 accept_json $fh;
1755 ▶ } elsif ($magic eq "P" or $magic eq "O") { # HTTP POST/OPTIONS / MCP JSON-RPC 2.0
Condition66%2/3
$magic eq "P" or $magic eq "O"
l!l&&r!l&&!r
404
MC/DC50%1/2
$magic eq "P" or $magic eq "O"
$magic eq "P" $magic eq "O"
Truth table66%2/3
A or B
A= $magic eq "P"B= $magic eq "O"
ABresult
1X1
011
000
1756 4 $mcp->accept ($fh);
1757 } elsif ($magic eq "G") {
1758 3 accept_ws $fh, $peer_host, $peer_port;
1759 }
1760 11 };
1761 3 };
1762  
1763 3 $done->recv;
1764  
« bin/mcp-multibroker ↑ Summary blib/lib/AnyEvent/MCP/Server/Connect.pm »