bin/mcp-vim

filter: Statementstmt 71.8% 378 / 526 Branchbran 52.0% 127 / 244 Conditioncond 41.3% 67 / 162 MC/DCmcdc 21.2% 17 / 80 Subroutinesub 69.6% 55 / 79 Podpod 0.0% 0 / 1 totaltotal 58.9% 644 / 1092 CC 164 SCAR 32.0
CC
164
Cov
61%
_on_upload_done
182.0
__ANON__
67.0
send_data
56.0
CRAP 24.4
« bin/mcp-http ↑ Summary bin/anyevent-mcp »
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 switch is specific to C<mcp-vim>.
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>. tty/yad force local interface; mcp delegates to client,
324 auto prefers native elicitation when offered. See L</PERMISSIONS>.
325  
326 =back
327  
328 =head2 Shared-option behavior
329  
330 =over
331  
332 =item --bind ADDRESS[:PORT]
333  
334 Also selects the address and port for private Vim and browser WebSockets.
335  
336 =item --token TOKEN
337  
338 Also authenticates private Vim and browser WebSocket connections.
339  
340 =item --stdio
341  
342 The private Vim/WebSocket listener remains active while MCP uses stdio.
343  
344 =item --connect URL
345  
346 The private Vim/WebSocket listener remains active while MCP connects
347 outward to a multibroker.
348  
349 =item --print-url[=USER]
350  
351 Prints the credential-bearing URL prefix for Vim clients. Append a
352 Vim target as described in L</FIRST USE>.
353  
354 =item --auto-allow TOOL[,ACTION[,CAPABILITY]]
355  
356 For example, C<--auto-allow '*,write'> allows buffer edits, but not
357 C<save>, C<open> or unrestricted C<exec>.
358  
359 =back
360  
361 =head1 SYSTEMD
362  
363 A service can run C</path/to/mcp-vim> directly. Set its C<HOME> and, if
364 needed, C<XDG_CONFIG_HOME> so it uses the intended global secret.
365 Run C<mcp-vim --print-url> as the service user to obtain the connection URL;
366 there is no separate install-time cookie generation step.
367  
368 =cut
369  
370 19 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
371  
372 19 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
373 19 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
374 19 ▶use Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
375 19 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
376 19 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
377  
378 19 ▶use AnyEvent ();
Subroutine BEGIN: called CC=1 SCAR=0.0
379 19 ▶use AnyEvent::Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
380 19 ▶use AnyEvent::MCP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
381 19 ▶use AnyEvent::MCP::Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
382 19 ▶use AnyEvent::MCP::Extension ();
Subroutine BEGIN: called CC=1 SCAR=0.0
383 19 ▶use AnyEvent::MCP::Server::HTTP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
384 19 ▶use AnyEvent::MCP::Server::Toolset ();
Subroutine BEGIN: called CC=1 SCAR=0.0
385 19 ▶use AnyEvent::MCP::Server::Permissions ();
Subroutine BEGIN: called CC=1 SCAR=0.0
386  
387 19 ▶use AnyEvent::MCP::Server::Simple qw(mcp_getoptions mcp_tool_help mcp_log mcp_log_request);
Subroutine BEGIN: called CC=1 SCAR=0.0
388  
389 16 our $PORT;
390 16 our $NICK;
391  
392 16 my $usage = "Usage: mcp-vim [OPTION]...\n";
393 16 my $server_options = mcp_getoptions ({
394 usage => $usage,
395 path => "/",
396 description => "Bridge live Vim buffers to MCP and browser WebSocket clients.\n"
397 . "With --stdio, the broker also serves MCP on stdin/stdout; TCP stays active.",
398 options => [["--ask MODE", "Ask for permission via helper (default), tty, yad, mcp, or auto"]],
399 examples => " mcp-vim --name editor --bind 127.0.0.1:20792\n"
400 . " mcp-vim --name editor --print-url\n"
401 . " mcp-vim --auto-allow '*,write'",
402 }, "ask=s" => \my $ask);
403 1 ▶@ARGV and die $usage;
Branch: 1 branch
BranchTrueFalseTotal
@ARGV and die $usage 0 1 1
404  
405 1 my $name = $server_options->{name};
406 1 my $bind = $server_options->{bind};
407 1 ▶my @tokens = @{$server_options->{tokens} || []};
Condition50%1/2
$server_options->{'tokens'} || []
l!l
01
MC/DC0%0/1
$server_options->{'tokens'} || []
$server_options->{'tokens'}
Truth table50%1/2
A
A= $server_options->{'tokens'}
Aresult
11
00
408 1 my $connect = $server_options->{connect};
409 1 ▶my $stdio = $server_options->{stdio} || !defined $connect && $ENV{PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL} eq "stdio";
Condition33%2/6
$server_options->{'stdio'} || !defined($connect) && $ENV{'PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL'} eq 'stdio'
l!l&&r!l&&!r
001
not defined $connect and $ENV{"PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL"} eq "stdio"
!ll&&!rl&&r
010
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 table25%1/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
410 1 ▶!($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 1 1
Condition33%1/3
$stdio and defined $connect
!ll&&!rl&&r
100
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
411  
412 # private Vim/broker wire protocol (separate from the browser protocol)
413 1 my $vim_prot_major = 1;
414 1 my $vim_prot_minor = 0;
415  
416 1 my $config = AnyEvent::MCP::Config->global;
417 1 my %http = $config->http_settings ($name, $bind);
418 1 my $host = $http{host};
419 1 $PORT = $http{port};
420  
421 # A URL credential must survive service restarts and --print-url.
422 1 my $stored = AnyEvent::MCP::Config->new (file => $config->{file});
423 $stored->{section}{global}{secret} eq $config->{section}{global}{secret}
424 1 ▶ or die "mcp-vim: MCP master secret is not persistently stored in $config->{file}\n";
Branch: 1 branch
BranchTrueFalseTotal
$stored->{"section"}{"global"}{"secret"} eq $config->{"section"}{"global"}{"secret"} or die qq[mcp-vim: MCP master secret is not persistently stored in $config->{"file"}\n] 1 0 1
425  
426 1 ▶$http{tokens} = \@tokens if @tokens;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens 0 1 1
427 1 ▶$http{connect_tokens} = \@tokens if @tokens;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens 0 1 1
428 1 ▶delete $http{token_users} if @tokens;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens 0 1 1
429 1 my @accepted_tokens = @{$http{tokens}};
430 1 my @connect_tokens = @{$http{connect_tokens}};
431 1 ▶/\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" 1 0 1
432 1 my %connect_token = map { $_ => 1 } @connect_tokens;
433  
434 1 ▶$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
01
(POSIX::uname())[1] || die("cannot determine mcp-vim hostname\n")
l!l
10
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
435  
436  
437 1 our $JSON_CODER = JSON::XS->new->utf8;
438  
439 #############################################################################
440  
441 1 my %xpcse;
442 my %vim;
443 1 my %target;
444  
445 5 ▶sub targets_changed {
Subroutine targets_changed: called CC=2 SCAR=6.9
446 5 $_->send_json ([targets => keys %target]) for values %xpcse;
447 }
448  
449 #############################################################################
450  
451 27 ▶sub base::emit {
Subroutine emit: called CC=2 SCAR=7.1
Pod undocumented
452 27 my ($self, $type, @args) = @_;
453  
454 27 eval {
455 27 $type =~ y/-/_/;
456 27 $type = "_on_$type";
457  
458 27 $self->$type (@args);
459 };
460 27 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 27 27
461 0 warn "error executing $type callback: $@";
462 }
463 }
464  
465 #############################################################################
466 # vim
467  
468 1 @vim::ISA = base::;
469  
470 2 ▶sub vim::new {
Subroutine new: called CC=8 SCAR=22.0
471 2 my ($class, $hdl, $hello) = @_;
472  
473 2 my ($requested, $instance_id) = @$hello[4, 5];
474  
475 (my $old) = grep
476 defined $instance_id
477 && defined $_->{instance_id}
478 && $_->{requested} eq $requested
479 2 ▶ && $_->{instance_id} eq $instance_id,
Condition33%3/9
defined $instance_id && defined $_->{'instance_id'} && $_->{'requested'} eq $requested && $_->{'instance_id'} eq $instance_id
!ll&&!rl&&r
100
defined $instance_id and defined $_->{"instance_id"} and $_->{"requested"} eq $requested
!ll&&!rl&&r
010
defined $instance_id and defined $_->{"instance_id"}
!ll&&!rl&&r
001
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
480 values %vim;
481  
482 2 ▶ my $name = $old ? $old->{target} : $requested;
Branch: 1 branch
BranchTrueFalseTotal
$old ? : 0 2 2
483 2 ▶ $old->destroy if $old;
Branch: 1 branch
BranchTrueFalseTotal
if $old 0 2 2
484  
485 2 ▶ unless ($old) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($old) 2 0 2
486 2 my $n = 2;
487 $name = "$requested #" . $n++
488 2 ▶ while exists $target{$name};
Branch: 1 branch
BranchTrueFalseTotal
exists $target{$name} and do { $name = "$requested #" . $n++ } 0 2 2
489 }
490  
491 2 my $self = bless {
492 ah => $hdl,
493 target => $name,
494 requested => $requested,
495 instance_id => $instance_id,
496 }, $class;
497  
498 2 $vim{$self+0} = $self;
499  
500 2 AE::log debug => "new vim connection\n";
501  
502 # the line-based hello reader leaves subsequent bytes in the handle.
503 2 $hdl->{json} = AnyEvent::MCP::json_class ()->new->utf8->max_depth (512);
504 2 $hdl->rtimeout (0);
505  
506 {
507 2 Scalar::Util::weaken (my $self = $self);
508  
509 2 ▶ $hdl->on_error (sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
510 2 $_[0]->destroy;
511 2 $self->destroy;
512 2 });
513 }
514  
515 2 mcp_log "vim <$self->{target}> connected";
516 2 $target{$self->{target}} = $self;
517 2 targets_changed;
518  
519 2 $self->read_json;
520 2 $self
521 }
522  
523 28 ▶sub vim::read_json {
Subroutine read_json: called CC=1 SCAR=0.0
524 28 my ($self) = @_;
525  
526 28 Scalar::Util::weaken (my $weak_self = $self);
527  
528 26 ▶ $self->{ah}->push_read (json => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
529 26 my (undef, $packet) = @_;
530  
531 26 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 26 0 26
532  
533 26 $self->emit (@{ $packet->[1] });
534 26 $self->read_json;
535 28 });
536 }
537  
538 2 ▶sub vim::destroy {
Subroutine destroy: called CC=5 SCAR=16.8
539 2 my ($self) = @_;
540  
541 2 ▶ delete $vim{$self+0}
Branch: 1 branch
BranchTrueFalseTotal
delete $vim{$self + 0} or return 2 0 2
542 or return;
543  
544 2 $self->{ah}->destroy;
545  
546 2 ▶ if (my $save = delete $self->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $save = delete $self->{"save"}) 0 2 2
547 0 $save->{xpcse}->cancel_save ($save);
548 }
549  
550 2 delete $target{$self->{target}};
551 2 targets_changed;
552  
553 $_->(0, "vim disconnected")
554 2 ▶ for values %{ delete $self->{rpccb} || {} };
Condition50%1/2
delete $self->{'rpccb'} || {}
l!l
20
MC/DC0%0/1
delete $self->{'rpccb'} || {}
delete $self->{'rpccb'}
Truth table50%1/2
A
A= delete $self->{'rpccb'}
Aresult
11
00
555  
556 2 mcp_log "vim <$self->{target}> disconnected";
557 }
558  
559 27 ▶sub vim::send_msg {
Subroutine send_msg: called CC=1 SCAR=0.0
560 27 my ($self, $msg) = @_;
561  
562 27 $self->{ah}->push_write (json => [0, $msg]);
563  
564 27 AE::log trace => "$self->{target} < @$msg";#d#
565 }
566  
567 27 ▶sub vim::rpc_ {
Subroutine rpc_: called CC=1 SCAR=0.0
568 27 my $cb = pop;
569 27 my ($self, $cmd, @args) = @_;
570  
571 27 my $id = ++$self->{rpcid};
572 27 $self->{rpccb}{$id} = $cb;
573  
574 27 $self->send_msg ([call => $id, $cmd, @args]);
575 }
576  
577 26 ▶sub vim::_on_reply {
Subroutine _on_reply: called CC=2 SCAR=7.1
578 26 my ($self, $id, $success, $result) = @_; # also backtrace, but we completelky ignore that
579  
580 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" 26 0 26
581 or die "reply for id $id has no callback\n";
582  
583 26 $cb->($success, $result);
584 }
585  
586 # startup session info
587 0 ▶sub vim::_on_session {
Subroutine _on_session: not called CC=1 SCAR=6.9
588 0 my ($self, $id, $state) = @_;
589  
590 0 $self->{session}{$id} = $state;
591 }
592  
593 0 ▶sub vim::_on_ack {
Subroutine _on_ack: not called CC=1 SCAR=6.9
594 0 my ($self, $bytes) = @_;
595 }
596  
597 # end of session list
598 0 ▶sub vim::_on_sessions_done {
Subroutine _on_sessions_done: not called CC=1 SCAR=6.9
599 0 my ($self) = @_;
600  
601 0 $self->send_msg ([echo => "connected as '$self->{target}'"]);
602 }
603  
604 0 ▶sub vim::_on_save {
Subroutine _on_save: not called CC=4 SCAR=30.0
605 0 my ($self, $id, $force) = @_;
606  
607 # a save's input belongs to Vim until eof; the browser queue owns the upload.
608 0 ▶ if (my $old = delete $self->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $old = delete $self->{"save"}) 0 0 0
609 0 $old->{xpcse}->cancel_save ($old);
610 }
611  
612 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
613 or return $self->send_msg ([echo => "$id: session not found"]);
614  
615 0 my ($xpcse) = grep $_->{origin} eq $hdrs->{origin}, values %xpcse;
616  
617 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
618 or return $self->send_msg ([echo => "$id: no origin found, connect a tab for $hdrs->{origin}"]);
619  
620 0 AE::log info => "save $id $hdrs->{origin}";
621 0 $self->send_msg ([echo => "requesting save to $hdrs->{origin}..."]);
622  
623 0 $self->{save} = $xpcse->save ($self, $id, $hdrs, $force);
624 }
625  
626 0 ▶sub vim::_on_data {
Subroutine _on_data: not called CC=2 SCAR=17.9
627 0 my ($self, $encoded) = @_;
628  
629 0 my $data = MIME::Base64::decode_base64 $encoded;
630  
631 0 ▶ if (my $save = $self->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $save = $self->{'save'}) { } 0 0 0
632 0 push @{$save->{data}}, $data;
633 0 $save->{xpcse}->send_data;
634 } else {
635 # discard a rejected save's input without holding up its sender.
636 0 $self->send_msg ([ack => length $data]);
637 }
638 }
639  
640 0 ▶sub vim::_on_eof {
Subroutine _on_eof: not called CC=3 SCAR=24.8
641 0 my ($self, $success) = @_;
642  
643 my $save = delete $self->{save}
644 0 ▶ or return;
Branch: 1 branch
BranchTrueFalseTotal
my $save = delete $self->{"save"} or return 0 0 0
645  
646 0 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) { } 0 0 0
647 0 $save->{eof} = 1;
648 0 $save->{xpcse}->send_data;
649 } else {
650 0 $save->{xpcse}->cancel_save ($save);
651 }
652 }
653  
654 0 ▶sub vim::_on_close {
Subroutine _on_close: not called CC=2 SCAR=17.9
655 0 my ($self, $id) = @_;
656  
657 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
658 or return $self->send_msg ([echo => "$id: session not found"]);
659  
660 0 AE::log debug => "vim session close $id";
661  
662 0 unlink $hdrs->{path};
663 0 delete $self->{session}{$id};
664 }
665  
666 0 ▶sub vim::session_open {
Subroutine session_open: not called CC=2 SCAR=17.9
667 0 my ($self, $hdrs) = @_;
668  
669 0 my $id = "s" . substr rand, 2;
670 0 $self->{session}{$id} = $hdrs;
671  
672 0 AE::log debug => "vim session open: $id $hdrs->{path}";
673  
674 0 my $filename = $hdrs->{filename};
675  
676 0 $filename =~ s/->/âž”/g;
677 0 $filename =~ s/::/∷/g;
678 0 $filename =~ s/\//∕/g;
679 0 $filename =~ s/[\/<>:"\\|\?\*\x00-\x1f]/_/g;
680  
681 0 ▶ $self->send_msg ([open => "$id", $filename // "unknown", $hdrs->{extension}, $hdrs]);
Condition0%0/2
$filename // "unknown"
l!l
00
MC/DC0%0/1
$filename // "unknown"
$filename
Truth table0%0/2
A
A= $filename
Aresult
11
00
682 }
683  
684 0 ▶sub vim::_on_quit {
Subroutine _on_quit: not called CC=1 SCAR=6.9
685 0 my ($self) = @_;
686  
687 0 $self->destroy;
688 }
689  
690 #############################################################################
691  
692 1 @xpcse::ISA = base::;
693  
694 1 ▶sub xpcse::new {
Subroutine new: called CC=1 SCAR=0.3
695 1 my ($class, $self) = @_;
696  
697 1 bless $self, $class;
698  
699 {
700 1 Scalar::Util::weaken (my $self = $self);
701  
702 0 ▶ $self->{conn}->on (finish => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
703 #AE::log trace => "on finish";#d#
704 0 $self->finish;
705 1 });
706  
707 1 ▶ $self->{conn}->on (each_message => sub {
Subroutine __ANON__: called CC=3 SCAR=13.2
708 1 eval {
709 1 my $opcode = $_[1]->opcode;
710  
711 1 ▶ if ($opcode == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opcode == 1) { } 1 0 1
712 1 AE::log trace => "websocket recv: " . $_[1]->body;
713  
714 1 $self->emit (@{ $JSON_CODER->decode ($_[1]->body) });
715  
716 } else {
717 0 my $data = $_[1]->body;
718 0 $self->{ondata_cb}($self, $data);
719 0 $self->send_json ([ack => length $data]);
720 }
721 };
722 1 ▶ if ($@) { # AnyEvent::WebScoket simply eats errors and silently disconnects
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
723 0 warn $@;
724 0 exit 1;
725 }
726 1 });
727  
728 0 ▶ $self->{pinger} = AE::timer 5, 10 * 60, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
729 # send regular pong frames, to satisfy nginx and to probe the connection
730 0 $self->{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 10, body => ""));
731 1 };
732 }
733  
734 1 $xpcse{$self+0} = $self; # keep alive
735  
736 1 $self->send_json ([nick => $NICK]);
737  
738 1 targets_changed;
739  
740 1 $self
741 }
742  
743 1 ▶sub xpcse::_on_xpcse_client {
Subroutine _on_xpcse_client: called CC=2 SCAR=7.0
744 1 my ($self, $version) = @_;
745  
746 1 ▶ if ($version != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($version != 1) 1 0 1
747 1 AE::log warn => "ws xpcse client version mismatch (me 1, them $version)";
748 1 $self->destroy;
749 1 return;
750 }
751 }
752  
753 0 ▶sub xpcse::_on_open {
Subroutine _on_open: not called CC=2 SCAR=17.9
754 0 my ($self, $target, $hdrs) = @_;
755  
756 0 ▶ if (my $vim = $target{$target}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vim = $target{$target}) { } 0 0 0
757 0 $self->{upload_vim} = $vim;
758  
759 0 $vim->session_open ($hdrs);
760  
761 0 ▶ $self->{ondata_cb} = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
762 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
763 0 };
764 } else {
765 0 ▶ $self->{ondata_cb} = sub { };
Subroutine __ANON__: not called CC=1 SCAR=6.9
766 }
767 }
768  
769 1 ▶sub xpcse::_on_eof {
Subroutine _on_eof: called CC=3 SCAR=14.2
770 1 my ($self, $success) = @_;
771  
772 1 ▶ if (my $vim = delete $self->{upload_vim}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vim = delete $self->{"upload_vim"}) 0 1 1
773 0 ▶ $vim->send_msg ([eof => $success*1]) if $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim{$vim + 0} 0 0 0
774 }
775  
776 1 delete $self->{ondata_cb};
777 }
778  
779 2 ▶sub xpcse::send_json {
Subroutine send_json: called CC=1 SCAR=0.0
780 2 $_[0]{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 1, body => $JSON_CODER->encode ($_[1])));
781 }
782  
783 0 ▶sub xpcse::send_bin {
Subroutine send_bin: not called CC=1 SCAR=6.9
784 0 $_[0]{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 2, body => $_[1]));
785 }
786  
787 1 ▶sub xpcse::destroy {
Subroutine destroy: called CC=10 SCAR=32.3
788 1 my ($self, $code) = @_;
789  
790 1 ▶ delete $xpcse{$self+0}
Branch: 1 branch
BranchTrueFalseTotal
delete $xpcse{$self + 0} or return 1 0 1
791 or return;
792  
793 1 ▶ $code ||= 1002;
Condition50%1/2
$code ||= 1002
l!l
01
MC/DC0%0/1
$code ||= 1002
$code
Truth table50%1/2
A
A= $code
Aresult
11
00
794  
795 1 delete $self->{pinger};
796  
797 1 $self->_on_eof (0);
798 1 ▶ for my $save (@{delete $self->{saves} || []}) {
Condition50%1/2
delete $self->{'saves'} || []
l!l
01
MC/DC0%0/1
delete $self->{'saves'} || []
delete $self->{'saves'}
Truth table50%1/2
A
A= delete $self->{'saves'}
Aresult
11
00
799 0 ▶ if (my $vim = $save->{vim}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vim = $save->{"vim"}) 0 0 0
800 delete $vim->{save}
801 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
802 0 ▶ $vim->send_msg ([echo => "$save->{session}: browser disconnected"]) if $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim{$vim + 0} 0 0 0
803 }
804 }
805  
806 1 my $conn = delete $self->{conn};
807  
808 1 ▶ $conn->close ($code) if $conn;
Branch: 1 branch
BranchTrueFalseTotal
if $conn 1 0 1
809  
810 1 AE::log debug => "websocket connection destroy $code";
811 }
812  
813 0 ▶sub xpcse::finish {
Subroutine finish: not called CC=1 SCAR=6.9
814 0 shift->destroy (@_);
815 }
816  
817 0 ▶sub xpcse::save {
Subroutine save: not called CC=2 SCAR=17.9
818 0 my ($self, $vim, $session, $hdrs, $force) = @_;
819  
820 0 ▶ my $save = {
Branch: 1 branch
BranchTrueFalseTotal
$force ? : 0 0 0
821 xpcse => $self,
822 vim => $vim,
823 session => $session,
824 hdrs => $hdrs,
825 force => $force ? 1 : 0,
826 data => [],
827 };
828  
829 # the queue and Vim input own the save; neither endpoint is kept alive by it.
830 0 Scalar::Util::weaken ($save->{xpcse});
831 0 Scalar::Util::weaken ($save->{vim});
832 0 push @{$self->{saves}}, $save;
833 0 $self->send_data;
834 0 $save
835 }
836  
837 0 ▶sub xpcse::send_data {
Subroutine send_data: not called CC=7 SCAR=40.3
838 0 my ($self) = @_;
839  
840 0 ▶ my $save = $self->{saves}[0]
Branch: 1 branch
BranchTrueFalseTotal
my $save = $self->{"saves"}[0] or return 0 0 0
841 or return;
842  
843 0 ▶ unless (exists $save->{credit}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $save->{"credit"}) 0 0 0
844 0 $save->{credit} = 10e6;
845 # trailing flag is ignored by current browser clients.
846 0 $self->send_json ([upload => $save->{hdrs}, $save->{force}]);
847 }
848  
849 # a positive credit admits one whole chunk, even if it exceeds the window.
850 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
851 0 my $data = shift @{$save->{data}};
852 0 $save->{credit} -= length $data;
853 0 $self->send_bin ($data);
854 }
855  
856 # eof is 1 when Vim has finished, 2 once the browser has been told.
857 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
858 0 $save->{eof} = 2;
859 0 $self->send_json (["upload-done"]);
860 }
861 }
862  
863 0 ▶sub xpcse::_on_ack {
Subroutine _on_ack: not called CC=6 SCAR=37.4
864 0 my ($self, $bytes) = @_;
865  
866 0 ▶ my $save = $self->{saves}[0]
Branch: 1 branch
BranchTrueFalseTotal
my $save = $self->{"saves"}[0] or return 0 0 0
867 or return;
868  
869 $bytes =~ /\A[0-9]+\z/ && $bytes <= 10e6 - $save->{credit}
870 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
871  
872 0 $save->{credit} += $bytes;
873  
874 # ack means receipt by the browser, independently of the final save result.
875 0 my $vim = $save->{vim};
876 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
877  
878 0 $self->send_data;
879 }
880  
881 0 ▶sub xpcse::_on_upload_done {
Subroutine _on_upload_done: not called CC=13 SCAR=52.0
882 0 my ($self, $status, $msg, $etag) = @_;
883  
884 0 ▶ my $save = $self->{saves}[0]
Branch: 1 branch
BranchTrueFalseTotal
my $save = $self->{"saves"}[0] or return 0 0 0
885 or return;
886  
887 0 ▶ $save->{eof} == 2
Branch: 1 branch
BranchTrueFalseTotal
$save->{"eof"} == 2 or return $self->destroy 0 0 0
888 or return $self->destroy;
889  
890 0 shift @{$self->{saves}};
891  
892 0 my $vim = $save->{vim};
893 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
894 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
895 0 ▶ if (my $state = $vim->{session}{$save->{session}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $state = $vim->{"session"}{$save->{"session"}}) 0 0 0
896 0 $state->{etag} = $etag;
897 0 $vim->send_msg (["update-metadata" => $save->{session}, { etag => $etag }]);
898 }
899 }
900 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
901 0 $msg =~ s/^upload ok, but.*:\n+//;
902 0 $msg =~ s/\n\n+/\n/g;
903 0 $msg =~ s/\n\z//;
904 0 ▶ $vim->send_msg ([error => "error: " . ($status == 200 ? "" : "HTTP $status: ") . $msg]);
Branch: 1 branch
BranchTrueFalseTotal
$status == 200 ? : 0 0 0
905  
906 0 ▶ if ($msg =~ / line ([0-9]+), /) {
Branch: 1 branch
BranchTrueFalseTotal
if ($msg =~ / line ([0-9]+), /u) 0 0 0
907 0 $vim->send_msg ([goto => $save->{session}, $1, 1]);
908 }
909  
910 0 AE::log warn => "upload error: $status $msg";
911 } else {
912 0 $vim->send_msg ([echo => "$status $msg"]);
913 }
914 }
915  
916 # the browser's reply, rather than sending eof, releases the next upload.
917 0 $self->send_data;
918 }
919  
920 0 ▶sub xpcse::cancel_save {
Subroutine cancel_save: not called CC=2 SCAR=17.9
921 0 my ($self, $save) = @_;
922  
923 0 ▶ if ($self->{saves}[0] == $save) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'saves'}[0] == $save) { } 0 0 0
924 # there is no upload-abort message; closing prevents a partial POST.
925 0 $self->destroy (1011);
926 } else {
927 0 @{$self->{saves}} = grep $_ != $save, @{$self->{saves}};
928 }
929 }
930  
931 #############################################################################
932  
933 my $permissions = AnyEvent::MCP::Server::Permissions->new (
934 name => "vim-$name",
935 actions => {
936 read => "Read Vim target names, editor state and buffer contents",
937 open => "Load a file into a Vim buffer; autocommands and modelines may run",
938 write => "Change Vim buffer contents or the editor position",
939 save => "Save a Vim buffer to its current filename if modified",
940 exec => "Execute arbitrary Vim commands with full host-user privileges",
941 },
942 (defined $ask ? (ask => $ask) : ()),
943 1 ▶ auto_rules => [@{$server_options->{auto_rules} || []},
Branch: 1 branch
BranchTrueFalseTotal
defined $ask ? : 0 1 1
Condition50%1/2
$server_options->{'auto_rules'} || []
l!l
01
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
944 $config->auto_rules ($name)],
945 );
946  
947 61 ▶sub vim_permission {
Subroutine vim_permission: called CC=8 SCAR=20.8
948 61 my ($req, $action, $name, $command, $details, $reason) = @_;
949  
950 61 ▶ my $subject = defined $name ? "target:$name" : "targets";
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 53 8 61
951 61 ▶ my $label = defined $name ? "editor '$name' (all buffers)" : "the list of connected editors";
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 53 8 61
952 61 my @subjects = (
953 { label => $label, match => $subject },
954 { label => "all Vim editors, including future connections", match => "^" },
955 );
956  
957 61 ▶ if (defined $command) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $command) 14 47 61
958 14 my $json = JSON::XS->new->allow_nonref;
959 14 my $editor = "ex:" . $json->encode ($name) . ":";
960 14 $subject = $editor . $json->encode ($command);
961 14 @subjects = (
962 { label => "this exact command in editor '$name' (all buffers)", match => $subject },
963 { label => "any Ex command in editor '$name' (all buffers)", match => "^" . (quotemeta $editor) },
964 { label => "any Ex command in any Vim editor, including future connections", match => "^" },
965 );
966 }
967  
968 $req->require_permission ({
969 tool => $req->{tool},
970 61 ▶ action => $action,
Branch: 3 branches
BranchTrueFalseTotal
defined $name ? : 51 8 59
defined $command ? : 14 45 59
defined $details ? : 3 58 61
Condition100%2/2
$reason // qq[$req->{"tool"}: ] . (defined $name ? "Vim editor '${name}'" : "list connected Vim editors") . (defined $command ? "\n\n$command" : "")
l!l
259
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
971 dimensions => { subject => { label => "Editor / command", value => $subject, choices => \@subjects } },
972 sandbox_grants => [],
973 reason => $reason // ("$req->{tool}: " . (defined $name ? "Vim editor '$name'" : "list connected Vim editors")
974 . (defined $command ? "\n\n$command" : "")),
975 (defined $details ? (details => $details) : ()),
976 });
977 }
978  
979 1 my $toolset = AnyEvent::MCP::Server::Toolset->new;
980 1 my $json = JSON::XS->new;
981  
982 25 ▶sub rpc_reply {
Subroutine rpc_reply: called CC=1 SCAR=0.0
983 25 my ($req, $format) = @_;
984  
985 25 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
986 25 my ($success, $result) = @_;
987  
988 25 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 1 24 25
989  
990 eval {
991 24 ▶ $success or die "$result\n";
Branch: 1 branch
BranchTrueFalseTotal
$success or die "$result\n" 19 5 24
992  
993 19 ▶ $req->reply ($format ? $format->($result) : {
Branch: 1 branch
BranchTrueFalseTotal
$format ? : 2 17 19
994 content => [{
995 type => "text",
996 text => $json->encode ($result),
997 }],
998 });
999 19 1
1000 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
1001 5 my $error = $@;
1002  
1003 5 ▶ return if $req->{cancelled};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"cancelled"} 0 5 5
1004 5 ▶ die $error if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 0 5 5
1005  
1006 5 AE::log info => "mcp-tool $req->{tool}: $error";
1007 5 $req->error ($error);
1008 };
1009 }
1010 25 }
1011  
1012 $toolset->tool (targets =>
1013 "List connected Vim targets (human-readable editor/session IDs). Use if target unknown.",
1014 {
1015 type => "object",
1016 properties => {},
1017 },
1018 7 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1019 7 my ($req, $args) = @_;
1020  
1021 7 vim_permission $req, read => undef;
1022  
1023 5 AE::log debug => "vim targets";
1024  
1025 5 $req->reply ({
1026 content => [{
1027 type => "text",
1028 text => $json->encode ([sort keys %target]),
1029 }],
1030 });
1031 }
1032 1 );
1033  
1034 $toolset->tool (state =>
1035 "Get live Vim state; optional target selects one editor, omit for all. "
1036 . "Returns target => state: cwd, current buffer/cursor, buffer metadata. "
1037 . "Unloaded buffers have null changedtick/line_count; read/search before guarded edits. "
1038 . "Explicit buffer access loads on demand. "
1039 . "Call state each turn if current editor/buffer unknown. "
1040 . "Buffers are live editor state, not disk snapshots.",
1041 {
1042 type => "object",
1043 properties => {
1044 target => {
1045 type => "string",
1046 description => "Optional Vim target id from targets. Omit for all targets.",
1047 },
1048 },
1049 required => [],
1050 },
1051 9 ▶ sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
1052 9 my ($req, $args) = @_;
1053  
1054 9 ▶ my @log = length $args->{target} ? $args->{target} : ();
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'target'} ? : 3 6 9
1055  
1056 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1057 9 AE::log debug => join " ", "vim state", @log;
1058  
1059 my @targets = length $args->{target}
1060 ? $args->{target}
1061 9 ▶ : keys %target;
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'target'} ? : 3 6 9
1062  
1063 # permission retries must happen before any of the parallel RPCs start.
1064 9 vim_permission $req, read => $_ for @targets;
1065 5 ▶ vim_permission $req, read => undef unless @targets;
Branch: 1 branch
BranchTrueFalseTotal
unless @targets 1 4 5
1066  
1067 5 my %state;
1068 5 my $pending = @targets;
1069 5 my $reply = rpc_reply $req;
1070  
1071 5 ▶ return $reply->(1, \%state) unless $pending;
Branch: 1 branch
BranchTrueFalseTotal
unless $pending 1 4 5
1072  
1073 4 for my $name (@targets) {
1074 7 ▶ my $vim = $target{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $vim = $target{$name} or die "target does not exist: $name\n" 7 0 7
1075 or die "target does not exist: $name\n";
1076  
1077 7 ▶ $vim->rpc_ (state => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1078 7 my ($success, $result) = @_;
1079  
1080 7 ▶ return $reply->(0, $result) unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 1 6 7
1081  
1082 6 $state{$name} = $result;
1083 6 ▶ $reply->(1, \%state) unless --$pending;
Branch: 1 branch
BranchTrueFalseTotal
unless --$pending 3 3 6
1084 7 });
1085 }
1086 }
1087 1 );
1088  
1089 $toolset->tool (read_lines =>
1090 "linenums=true prefixes absolute line number and colon. " .
1091 "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.",
1092 {
1093 type => "object",
1094 properties => {
1095 target => {
1096 type => "string",
1097 description => "Vim target id.",
1098 },
1099 buffer => {
1100 type => "integer",
1101 description => "Buffer id from state.",
1102 },
1103 ranges => {
1104 type => "array",
1105 description => "One or more restricted Vim Ex ranges: %, ., $, positive line numbers, +/- offsets, /regex/, ?regex?, and optional , or ; between two addresses.",
1106 minItems => 1,
1107 items => { type => "string" },
1108 },
1109 linenums => {
1110 type => "boolean",
1111 default => JSON::XS::false,
1112 description => "Prefix each line with its absolute line number and a colon.",
1113 },
1114 },
1115 required => ["target", "buffer", "ranges"],
1116 },
1117 3 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1118 3 my ($req, $args) = @_;
1119  
1120 3 vim_permission $req, read => $args->{target};
1121  
1122 2 my @log = ($args->{target}, $args->{buffer}, @{$args->{ranges}});
1123  
1124 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1125 2 AE::log debug => join " ", "vim read-lines", @log;
1126  
1127 $target{$args->{target}}->rpc_ (
1128 2 ▶ read_lines => $args->{buffer}, $args->{ranges}, rpc_reply ($req, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1129 2 my ($result) = @_;
1130  
1131 2 my @ranges = @{$result->{ranges}};
1132 my $metadata = {
1133 changedtick => $result->{changedtick},
1134 ranges => [map {
1135 2 +{
1136 range => $_->{range},
1137 start => $_->{start},
1138 end => $_->{end},
1139 }
1140 4 } @ranges],
1141 };
1142  
1143 +{
1144 content => [
1145 {
1146 type => "text",
1147 text => $json->encode ($metadata),
1148 },
1149 2 map {{
1150 type => "text",
1151 text => "[range=$_->{start},$_->{end}]",
1152 }, {
1153 type => "text",
1154 4 text => do {
1155 4 my $line = $_->{start};
1156 4 ▶ join "", map { ($args->{linenums} ? $line++ . ":" : "") . "$_\n" } @{$_->{lines}};
Branch: 1 branch
BranchTrueFalseTotal
$args->{'linenums'} ? : 3 4 7
1157 },
1158 }} @ranges,
1159 ],
1160 }
1161 })
1162 2 );
1163 }
1164 1 );
1165  
1166 $toolset->tool (grep =>
1167 "Search Vim buffers; load explicit IDs on demand; empty buffers = all loaded buffers. "
1168 . "mode=regex: native Vim regex; mode=word: literal whole word. "
1169 . "Returns buffer/tick/line/column/text matches, truncated flag.",
1170 {
1171 type => "object",
1172 properties => {
1173 target => {
1174 type => "string",
1175 description => "Vim target id.",
1176 },
1177 buffers => {
1178 type => "array",
1179 description => "Buffer IDs; explicit IDs load on demand; [] = all loaded buffers.",
1180 items => { type => "integer" },
1181 },
1182 pattern => {
1183 type => "string",
1184 description => "Native Vim regex (mode=regex) or literal word (mode=word).",
1185 },
1186 mode => {
1187 type => "string",
1188 enum => ["regex", "word"],
1189 description => "Search syntax.",
1190 },
1191 max_results => {
1192 type => "integer",
1193 minimum => 1,
1194 description => "Max matches.",
1195 },
1196 },
1197 required => ["target", "buffers", "pattern", "mode", "max_results"],
1198 },
1199 6 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1200 6 my ($req, $args) = @_;
1201  
1202 6 vim_permission $req, read => $args->{target};
1203  
1204 5 my @buffers = map 0 + $_, @{$args->{buffers}};
1205 5 ▶ my $log_buffers = @buffers ? (join ",", map 0 + $_, @buffers) : "*";
Branch: 1 branch
BranchTrueFalseTotal
@buffers ? : 5 0 5
1206 my @log = (
1207 $args->{target},
1208 $log_buffers,
1209 $args->{mode},
1210 5 (substr $args->{pattern}, 0, 20),
1211 );
1212  
1213 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1214 5 AE::log debug => join " ", "vim grep", @log;
1215  
1216 $target{$args->{target}}->rpc_ (
1217 5 grep => \@buffers, $args->{pattern}, $args->{mode}, $args->{max_results}, rpc_reply ($req)
1218 );
1219 }
1220 1 );
1221  
1222 1 ▶sub normalize_udiff {
Subroutine normalize_udiff: called CC=22 SCAR=34.9
1223 1 my $diff = shift;
1224 1 my @line = split /\n/, $diff, -1;
1225 1 my $delta = 0;
1226 1 my $hunks = 0;
1227 1 my @max_offset;
1228  
1229 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
1230  
1231 1 ▶ for (my $i = 0; $i < @line; ++$i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @line) 1 1 2
1232 1 ▶ next unless $line[$i] =~ /^@@ /;
Branch: 1 branch
BranchTrueFalseTotal
unless $line[$i] =~ /^\@@ /u 0 1 1
1233  
1234 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
1235 or die "normalize_udiff: bad hunk header '$line[$i]'\n";
1236  
1237 1 my ($old_start, $suffix) = ($1, $2);
1238 1 my ($old_count, $new_count) = (0, 0);
1239 1 my %old_line;
1240 1 my $j = $i + 1;
1241  
1242 # GNU patch mishandles hunks with more prefix than suffix context.
1243 # make the first context line an identity change without losing it.
1244 # see https://unix.stackexchange.com/questions/414542/does-patch-work-with-asymmetric-context
1245 1 ▶ splice @line, $i + 1, 1, "-$1", "+$1"
Branch: 1 branch
BranchTrueFalseTotal
if $line[$i + 1] =~ /^ (.*)\z/u 0 1 1
1246 if $line[$i + 1] =~ /^ (.*)\z/;
1247  
1248 1 ▶ for (; $j < @line; ++$j) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @line) 2 1 3
1249 2 ▶ last if $line[$j] =~ /^@@ /;
Branch: 1 branch
BranchTrueFalseTotal
if $line[$j] =~ /^\@@ /u 0 2 2
1250  
1251 2 my $tag = substr $line[$j], 0, 1;
1252  
1253 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
1254 0 ++$old_count;
1255 0 ++$new_count;
1256 0 $old_line{substr $line[$j], 1} = 1;
1257 } elsif ($tag eq "-") {
1258 1 ++$old_count;
1259 1 $old_line{substr $line[$j], 1} = 1;
1260 } elsif ($tag eq "+") {
1261 1 ++$new_count;
1262 } elsif ($line[$j] eq "\\ No newline at end of file") {
1263 # marker belongs to the preceding body line and counts neither side.
1264 } else {
1265 0 die "normalize_udiff: bad hunk line '$line[$j]'\n";
1266 }
1267 }
1268  
1269 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
1270 or die "normalize_udiff: empty hunk at old line $old_start\n";
1271  
1272 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
1273 or die "normalize_udiff: hunk " . ($hunks + 1)
1274 . " needs old-side context for insertion after old line $old_start\n";
1275  
1276 1 my $new_start = $old_start + $delta;
1277 1 ▶ ++$new_start unless $old_count;
Branch: 1 branch
BranchTrueFalseTotal
unless $old_count 0 1 1
1278 1 ▶ --$new_start unless $new_count;
Branch: 1 branch
BranchTrueFalseTotal
unless $new_count 0 1 1
1279  
1280 1 ▶ $new_start >= 0
Branch: 1 branch
BranchTrueFalseTotal
$new_start >= 0 or die "normalize_udiff: invalid new line $new_start\n" 1 0 1
1281 or die "normalize_udiff: invalid new line $new_start\n";
1282  
1283 1 $line[$i] = sprintf "@@ -%d,%d +%d,%d @@%s",
1284 $old_start, $old_count, $new_start, $new_count, $suffix;
1285  
1286 1 $delta += $new_count - $old_count;
1287 1 ++$hunks;
1288 1 my $max_offset = keys %old_line;
1289 1 ▶ --$max_offset
Branch: 1 branch
BranchTrueFalseTotal
if $max_offset 1 0 1
1290 if $max_offset;
1291 1 push @max_offset, $max_offset;
1292 1 $i = $j - 1;
1293 }
1294  
1295 1 ▶ $hunks
Branch: 1 branch
BranchTrueFalseTotal
$hunks or die "normalize_udiff: no hunks\n" 1 0 1
1296 or die "normalize_udiff: no hunks\n";
1297  
1298 1 ((join "\n", @line, ""), \@max_offset)
1299 }
1300  
1301 $toolset->tool (open =>
1302 "Load pathname into Vim buffer without selecting; reuse existing buffer without rereading. "
1303 . "Requires separate open permission. Relative paths use Vim's current directory. "
1304 . "No shell/wildcard/Ex parsing. Missing files create empty named buffers; no save. "
1305 . "Load autocommands/modelines run: may change editor or fail after side effects. "
1306 . "Returns buffer, filename, changedtick, line_count, modified.",
1307 {
1308 type => "object",
1309 properties => {
1310 target => { type => "string", description => "Vim target id." },
1311 path => { type => "string", minLength => 1, description => "File pathname, without NUL." },
1312 },
1313 required => ["target", "path"],
1314 additionalProperties => JSON::XS::false,
1315 },
1316 5 ▶ sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
1317 5 my ($req, $args) = @_;
1318  
1319 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
1320 or die "path must be a nonempty string without NUL\n";
1321 my $vim = $target{$args->{target}}
1322 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
1323  
1324 vim_permission $req, open => $args->{target}, undef, undef,
1325 2 "Open file in Vim editor '$args->{target}'\nPath: " . JSON::XS->new->allow_nonref->encode ($args->{path});
1326  
1327 1 AE::log debug => "vim open $args->{target} " . $json->encode (substr $args->{path}, 0, 80);
1328  
1329 1 $vim->rpc_ (open => $args->{path}, rpc_reply ($req));
1330 }
1331 1 );
1332  
1333 $toolset->tool (apply_diff =>
1334 "Apply relaxed unified diff to live Vim buffer; reject NUL. In @@ headers only old start (-N) matters: first hunk body line, including context; "
1335 . "other numbers ignored/recomputed (may be 0); '\@\@ -N \@\@' valid. "
1336 . "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.",
1337 {
1338 type => "object",
1339 properties => {
1340 target => {
1341 type => "string",
1342 description => "Vim target id.",
1343 },
1344 buffer => {
1345 type => "integer",
1346 description => "Buffer id from current Vim state.",
1347 },
1348 diff => {
1349 type => "string",
1350 minLength => 1,
1351 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.",
1352 },
1353 expected_changedtick => {
1354 type => "integer",
1355 description => "changedtick from latest state/read of this buffer.",
1356 },
1357 },
1358 required => ["target", "buffer", "diff", "expected_changedtick"],
1359 },
1360 4 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.8
1361 4 my ($req, $args) = @_;
1362  
1363 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
1364 or die "diff must be text without NUL\n";
1365  
1366 3 my $buffer = $args->{buffer};
1367 vim_permission $req, write => $args->{target}, undef, {
1368 3 "View patch" => "Editor: $args->{target}\nBuffer: $buffer\n\n$args->{diff}",
1369 };
1370  
1371 1 my ($hunk, $body);
1372  
1373 1 for (split /\n/, $args->{diff}) {
1374 3 ▶ if (/^@@ /) {
Branch: 2 branches
BranchTrueFalseTotal
if (/^\@@ /u) { } 1 2 3
elsif ($hunk) { } 2 0 2
1375 1 ++$hunk;
1376 } elsif ($hunk) {
1377 2 ++$body;
1378 }
1379 }
1380  
1381 1 my @log = ($args->{target}, $args->{buffer}, $body);
1382  
1383 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1384 1 AE::log debug => join " ", "vim apply-diff", @log;
1385  
1386 $target{$args->{target}}->rpc_ (
1387 apply_patch =>
1388 $args->{buffer},
1389 (normalize_udiff $args->{diff}),
1390 1 $args->{expected_changedtick}, rpc_reply ($req)
1391 );
1392 }
1393 1 );
1394  
1395 $toolset->tool (substitute =>
1396 "Guarded Vim :substitute over live buffer range; for mechanical regex replacements. "
1397 . "Prefer apply-diff for structural/multiline edits. Native Vim regex pattern. "
1398 . "Native Vim :substitute replacement/flags. "
1399 . q{To clear the whole buffer, use range %, pattern \%^\_.*\%$, replacement empty, flags empty; Vim leaves one empty line. }
1400 . "expected_changedtick must match; otherwise stale error.",
1401 {
1402 type => "object",
1403 properties => {
1404 target => {
1405 type => "string",
1406 description => "Vim target id.",
1407 },
1408 buffer => {
1409 type => "integer",
1410 description => "Buffer id.",
1411 },
1412 range => {
1413 type => "string",
1414 description => "Restricted Vim Ex range: %, ., $, positive line numbers, +/- offsets, /regex/, ?regex?, and optional , or ; between two addresses.",
1415 },
1416 pattern => {
1417 type => "string",
1418 description => "Native Vim regex.",
1419 },
1420 replacement => {
1421 type => "string",
1422 description => "Native Vim :substitute replacement.",
1423 },
1424 flags => {
1425 type => "string",
1426 description => "Vim substitute flags; allowed: egiInp#lr.",
1427 pattern => "^[egiInp#lr]*\$",
1428 },
1429 expected_changedtick => {
1430 type => "integer",
1431 description => "changedtick from latest read/state.",
1432 },
1433 },
1434 required => [
1435 "target", "buffer", "range", "pattern", "replacement", "flags", "expected_changedtick"
1436 ],
1437 },
1438 2 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1439 2 my ($req, $args) = @_;
1440  
1441 2 vim_permission $req, write => $args->{target};
1442  
1443 my @log = (
1444 $args->{target}, $args->{buffer}, $args->{range},
1445 (substr $args->{pattern}, 0, 20),
1446 "=>",
1447 (substr $args->{replacement}, 0, 20),
1448 $args->{flags},
1449 1 );
1450  
1451 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1452 1 AE::log debug => join " ", "vim substitute", @log;
1453  
1454 $target{$args->{target}}->rpc_ (
1455 substitute => $args->{buffer}, $args->{range}, $args->{pattern},
1456 1 $args->{replacement}, $args->{flags}, $args->{expected_changedtick}, rpc_reply ($req)
1457 );
1458 }
1459 1 );
1460  
1461 1 for my $operation (qw(undo redo update)) {
1462 $toolset->tool (($operation eq "update" ? "save" : $operation) =>
1463 $operation eq "update"
1464 ? "Run Vim :update: save selected buffer to current filename only if modified. "
1465 . "Requires save permission and current expected_changedtick; no filename/force option. "
1466 . "Write autocommands run; failure may leave side effects (no rollback). "
1467 . "Returns buffer, changedtick, modified, filename. "
1468 . "Preserves caller's current buffer/view when possible."
1469 : ucfirst ($operation) . " one change in selected Vim buffer via undo tree. "
1470 . "Requires write permission and latest expected_changedtick. "
1471 . "Leaves edits unsaved; preserves caller's current buffer when editing another. "
1472 . "At history boundary: changed=false. "
1473 . "Returns buffer, changedtick, changed, seq_cur (reached undo sequence), seq_last, modified.",
1474 {
1475 type => "object",
1476 properties => {
1477 target => { type => "string", description => "Vim target id." },
1478 buffer => { type => "integer", minimum => 1, description => "Buffer id from current Vim state." },
1479 expected_changedtick => {
1480 type => "integer", minimum => 0,
1481 description => "changedtick from latest read/state of this buffer.",
1482 },
1483 },
1484 required => ["target", "buffer", "expected_changedtick"],
1485 additionalProperties => JSON::XS::false,
1486 },
1487 16 ▶ sub {
Subroutine __ANON__: called CC=10 SCAR=23.5
1488 16 my ($req, $args) = @_;
1489  
1490 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
1491 or die "buffer must be a positive integer\n";
1492 defined $args->{expected_changedtick} && !ref $args->{expected_changedtick}
1493 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
1494 or die "expected_changedtick must be a nonnegative integer\n";
1495  
1496 my $vim = $target{$args->{target}}
1497 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
1498  
1499 7 ▶ vim_permission $req, ($operation eq "update" ? "save" : "write") => $args->{target};
Branch: 1 branch
BranchTrueFalseTotal
$operation eq 'update' ? : 3 4 7
1500  
1501 AE::log debug => join " ", "vim", ($operation eq "update" ? "save" : $operation),
1502 4 ▶ $args->{target}, $args->{buffer};
Branch: 1 branch
BranchTrueFalseTotal
$operation eq 'update' ? : 2 2 4
1503 4 $vim->rpc_ ($operation => 0 + $args->{buffer}, 0 + $args->{expected_changedtick}, rpc_reply ($req));
1504 }
1505 3 ▶ );
Branch: 2 branches
BranchTrueFalseTotal
$operation eq 'update' ? : 1 2 3
$operation eq 'update' ? : 1 2 3
1506 }
1507  
1508 $toolset->tool (set_cursor =>
1509 "Show/select buffer and position Vim cursor. Unlike read/edit, intentionally changes user's "
1510 . "editor position. Optional expected_changedtick rejects stale buffer. "
1511 . "After edits in user's current buffer, move cursor to changed region so user sees it. "
1512 . "Avoid cursor movement for exploratory reads/searches unless useful.",
1513 {
1514 type => "object",
1515 properties => {
1516 target => {
1517 type => "string",
1518 description => "Vim target id.",
1519 },
1520 buffer => {
1521 type => "integer",
1522 description => "Buffer id.",
1523 },
1524 line => {
1525 type => "integer",
1526 minimum => 1,
1527 description => "1-based line.",
1528 },
1529 column => {
1530 type => "integer",
1531 minimum => 1,
1532 description => "1-based byte column as used by Vim col().",
1533 },
1534 expected_changedtick => {
1535 type => "integer",
1536 description => "Optional buffer changedtick guard.",
1537 },
1538 },
1539 required => ["target", "buffer", "line", "column"],
1540 },
1541 3 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1542 3 my ($req, $args) = @_;
1543  
1544 3 vim_permission $req, write => $args->{target};
1545  
1546 2 my @log = ($args->{target}, $args->{buffer}, $args->{line}, $args->{column});
1547  
1548 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1549 2 AE::log debug => join " ", "vim set-cursor", @log;
1550  
1551 $target{$args->{target}}->rpc_ (
1552 2 ▶ set_cursor => @{$args}{qw(buffer line column)},
Branch: 1 branch
BranchTrueFalseTotal
exists $args->{'expected_changedtick'} ? : 1 1 2
1553 2 (exists $args->{expected_changedtick} ? $args->{expected_changedtick} : ()), rpc_reply ($req)
1554 );
1555 }
1556 1 );
1557  
1558 $toolset->tool (ex =>
1559 "Execute unrestricted Vim Ex in current editor context; needs separate exec permission. "
1560 . "Can run shell, read/write files, invoke code, exit Vim with user's privileges. "
1561 . "Prefer dedicated read/edit/navigation tools. "
1562 . "command: Ex text, including separators/newlines; keep reviewable. "
1563 . "Optional buffer becomes current; expected_changedtick requires buffer, checked just before execution. "
1564 . "Persistent grants may cover exact command, any command in this editor, or all editors. "
1565 . "Returns {output: Vim messages} or Vim error; no rollback of earlier effects. "
1566 . "Use noninteractive commands; prompts/long runs block Vim; cancellation cannot undo execution.",
1567 {
1568 type => "object",
1569 properties => {
1570 target => { type => "string", description => "Vim target id." },
1571 command => { type => "string", minLength => 1, description => "Unrestricted Ex command text, without NUL." },
1572 buffer => { type => "integer", minimum => 1, description => "Optional buffer to make current before execution." },
1573 expected_changedtick => {
1574 type => "integer", minimum => 0,
1575 description => "Optional changedtick guard for buffer; requires buffer. A stale tick prevents execution.",
1576 },
1577 },
1578 required => ["target", "command"],
1579 },
1580 18 ▶ sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
1581 18 my ($req, $args) = @_;
1582  
1583 18 my $command = $args->{command};
1584 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
1585 or die "command must be a nonempty string without NUL\n";
1586  
1587 !exists $args->{expected_changedtick} || exists $args->{buffer}
1588 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
1589  
1590 my $vim = $target{$args->{target}}
1591 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
1592  
1593 14 vim_permission $req, exec => $args->{target}, $command;
1594  
1595 4 $vim->rpc_ (ex => $command, @{$args}{qw(buffer expected_changedtick)}, rpc_reply ($req));
1596 }
1597 1 );
1598  
1599 1 mcp_tool_help ($server_options->{tool_help}, $toolset);
1600  
1601 0 my $instructions = <<'EOF';
1602 Live Vim buffers, not disk snapshots. Use targets for editors, state for buffer IDs/changedticks.
1603 Read via read-lines/grep; explicit access may load unloaded buffers.
1604 open loads pathname without selecting; requires separate open permission.
1605 apply-diff/substitute/undo/redo modify live buffers; require current expected_changedtick; leave unsaved.
1606 save writes current filename only if modified; needs save permission and current expected_changedtick.
1607 set-cursor moves visible editor cursor; use to show edits or navigate.
1608 ex runs unrestricted Ex with full Vim privileges; requires separate exec permission. Prefer narrow tools.
1609 EOF
1610  
1611 my $custom_instructions = $server_options->{custom_instructions}
1612 // $config->{section}{"instance $name"}{custom_instructions}
1613 0 ▶ // $config->{section}{"program " . AnyEvent::MCP::Config::program_name ()}{custom_instructions};
Condition0%0/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
000
$server_options->{"custom_instructions"} // $config->{"section"}{"instance $name"}{"custom_instructions"}
l!l&&r!l&&!r
000
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 table0%0/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
1614 0 ▶my %guidance = (
Branch: 1 branch
BranchTrueFalseTotal
defined $custom_instructions ? : 0 0 0
1615 instructions => $instructions,
1616 short_instructions => "Live Vim buffers: inspect, edit with changedtick guards (unsaved), navigate. Discover tools.",
1617 auto_instructions => 1,
1618 on_request => \&mcp_log_request,
1619 (defined $custom_instructions ? (custom_instructions => $custom_instructions) : ()),
1620 );
1621  
1622 my $mcp = AnyEvent::MCP::Server::HTTP->new (
1623 server_info => { name => "mcp-vim", version => "0" },
1624 %guidance,
1625 toolsets => [$toolset],
1626 permissions => $permissions,
1627 path => "/",
1628 tokens => \@accepted_tokens,
1629 token_users => $http{token_users},
1630 0 max_size => 100e6,
1631 origins => ["*"],
1632 connection_close => 1,
1633 );
1634  
1635 0 my $done = AE::cv;
1636 0 my $stdio_mcp;
1637  
1638 0 ▶if (defined $connect) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $connect) { } 0 0 0
elsif ($stdio) { } 0 0 0
1639 0 require AnyEvent::MCP::Server::Connect;
1640 $stdio_mcp = AnyEvent::MCP::Server::Connect->new (
1641 server_info => $mcp->{server_info},
1642 %guidance,
1643 toolsets => [$toolset],
1644 permissions => $permissions,
1645 max_size => 100e6,
1646 connect => $connect,
1647 0 ▶ on_close => sub { $done->send },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1648 0 );
1649 0 $stdio_mcp->start;
1650 } elsif ($stdio) {
1651 0 require AnyEvent::MCP::Server::JSONL;
1652  
1653 0 binmode STDIN;
1654 0 binmode STDOUT;
1655  
1656 $stdio_mcp = AnyEvent::MCP::Server::JSONL->new (
1657 server_info => $mcp->{server_info},
1658 %guidance,
1659 toolsets => [$toolset],
1660 permissions => $permissions,
1661 max_size => 100e6,
1662 3 ▶ on_connection_close => sub { $done->send },
Subroutine __ANON__: called CC=1 SCAR=0.0
1663 0 );
1664  
1665 0 $stdio_mcp->accept (\*STDIN, \*STDOUT);
1666 }
1667  
1668 #############################################################################
1669  
1670 3 ▶sub accept_json {
Subroutine accept_json: called CC=1 SCAR=1.9
1671 3 my ($fh) = @_;
1672  
1673 my $hdl = AnyEvent::Handle->new (
1674 fh => $fh,
1675 0 ▶ on_error => sub { $_[0]->destroy },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1676 0 ▶ on_eof => sub { $_[0]->destroy },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1677 3 );
1678  
1679 2 ▶ AnyEvent::MCP::Extension::accept ($hdl, \@connect_tokens, sub {
Subroutine __ANON__: called CC=15 SCAR=42.0
1680 2 my ($hdl, $hello) = @_;
1681  
1682 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
1683 && defined $hello->[2] && !ref $hello->[2] && $hello->[2] =~ /\A[0-9]+\z/
1684 && defined $hello->[3] && !ref $hello->[3] && $hello->[3] =~ /\A[0-9]+\z/
1685 && $hello->[2] == $vim_prot_major && $hello->[3] <= $vim_prot_minor
1686 && defined $hello->[4] && !ref $hello->[4]
1687 && defined $hello->[5] && !ref $hello->[5]
1688 or die "Invalid private Vim hello\n";
1689  
1690 2 vim->new ($hdl, $hello);
1691 3 });
1692 }
1693  
1694 #############################################################################
1695  
1696 3 ▶sub accept_ws {
Subroutine accept_ws: called CC=2 SCAR=6.9
1697 3 my ($fh, $peer_host, $peer_port) = @_;
1698  
1699 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
1700 3 require AnyEvent::WebSocket::Server;
1701 3 require AnyEvent::WebSocket::Message;
1702 3 1
1703 } or return AE::log warn => "WebSocket support unavailable: $@";
1704  
1705 # tcp_server has already formatted the numeric address for us.
1706 3 my $peer = AnyEvent::Socket::format_hostport $peer_host, $peer_port;
1707  
1708 3 my ($origin, $rejection);
1709  
1710 my $ws_server = new AnyEvent::WebSocket::Server
1711 max_payload_size => 1000e6,
1712 3 ▶ handshake => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1713 3 my ($req, $res) = @_;
1714  
1715 3 my ($cookie, $target) = $req->{resource_name} =~ m%^/([^/]+)/+(.+)\z%s;
1716 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
1717 2 ▶ $rejection = defined $cookie ? "invalid token" : "invalid path";
Branch: 1 branch
BranchTrueFalseTotal
defined $cookie ? : 1 1 2
1718 2 die "Vim WebSocket handshake rejected\n";
1719 }
1720  
1721 1 $origin = $target;
1722  
1723 1 AE::log info => "websocket connect for $origin";
1724 #$res->subprotocol ($prot);
1725  
1726 #$res->{subprotocol}
1727 # or return AE::log info => "no matching subprotocol";
1728  
1729 1 $res
1730 },
1731 3 ;
1732  
1733 3 ▶ $ws_server->establish ($fh)->cb (sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
1734 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
1735 1 xpcse->new ({ conn => $conn, origin => $origin });
1736 } elsif ($rejection) {
1737 2 AE::log warn => "Vim WebSocket rejected: $rejection ($peer)";
1738 } else {
1739 0 AE::log warn => "Vim WebSocket establishment failed from $peer: $@";
1740 }
1741 3 });
1742 }
1743  
1744 #############################################################################
1745  
1746 11 ▶AnyEvent::Socket::tcp_server $host, $PORT, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1747 11 ▶ my ($fh, $peer_host, $peer_port) = @_
Branch: 1 branch
BranchTrueFalseTotal
my($fh, $peer_host, $peer_port) = or return 11 0 11
1748 or return;
1749  
1750 11 ▶ my $watcher; $watcher = AE::io $fh, 0, sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
1751 11 undef $watcher;
1752  
1753 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
1754 or return;
1755  
1756 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
1757 3 accept_json $fh;
1758 ▶ } 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
1759 4 $mcp->accept ($fh);
1760 } elsif ($magic eq "G") {
1761 3 accept_ws $fh, $peer_host, $peer_port;
1762 }
1763 11 };
1764 0 };
1765  
1766 0 $done->recv;
1767  
« bin/mcp-http ↑ Summary bin/anyevent-mcp »