-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalpha1.pl
More file actions
executable file
·1645 lines (1645 loc) · 52.7 KB
/
alpha1.pl
File metadata and controls
executable file
·1645 lines (1645 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Encode qw(decode_utf8 encode_utf8 FB_CROAK);
use JSON::PP qw(decode_json encode_json);
use IO::Socket::UNIX;
use IO::Socket::INET;
use IO::Pty;
use IO::Select;
use POSIX qw(:termios_h strftime WNOHANG setsid TCSANOW ECHO ECHOK ECHOE ICANON);
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
use IPC::Cmd qw(can_run);
use Errno qw(EAGAIN EWOULDBLOCK EINTR EPIPE);
use Getopt::Long;
use Time::HiRes qw(sleep time);
our %options;
GetOptions(\%options, 'socket=s', 'terminal=s') or exit 1;
if ($options{'socket'}) {
my $socket_path = $options{'socket'};
if (!$socket_path) {
print STDERR "Missing socket path\n";
exit 1;
}
run_unix_socket_client($socket_path);
exit 0;
}
our $VERSION = "1.2";
our $PROTOCOL_VERSION = "2025-06-18";
our $DEFAULT_VM_PORT = 4555;
our $RING_BUFFER_SIZE = 1000;
our $MAX_BUFFER_BYTES = 10 * 1024 * 1024;
our $CONSOLE_HISTORY_LINES = 60;
our $SIGTERM_TIMEOUT = 5;
our $SIGKILL_WAIT = 1;
our $RESTART_BACKOFF_INITIAL = 1.0;
our $RESTART_BACKOFF_MAX = 60;
our %restart_backoff;
our $CONSOLE_KILL_TIMEOUT = 60;
use constant {
MCP_PARSE_ERROR => -32700,
MCP_INVALID_REQUEST => -32600,
MCP_METHOD_NOT_FOUND => -32601,
MCP_INVALID_PARAMS => -32602,
MCP_INTERNAL_ERROR => -32603,
MCP_SERVER_ERROR => -32000,
};
our %LOG_LEVEL_PRIORITY = (
debug => 0,
info => 1,
error => 2,
);
our $current_log_level = 'debug';
our %bridges;
our %restart_guard;
our $running = 1;
our $PARENT_PID = $$;
our $IS_PARENT = 1;
our @created_socket_files = ();
our %write_buffers;
our $MAX_WRITE_BUFFER_BYTES = 1024 * 1024;
# Track resource subscriptions separately from progress subscriptions
our %resource_subscriptions; # uri => 1
our %progress_subscriptions; # progressToken => { vm_name => $vm_name, last_sent => $time }
if ($^O !~ /^(linux|darwin|freebsd|openbsd|netbsd|solaris|aix|cygwin|dragonfly|midnightbsd|gnu|haiku|hpux|irix|minix|qnx|sco|sysv|unix)/i) {
print encode_utf8(mcp_error(undef, MCP_SERVER_ERROR, "Unsupported Operating System: $^O. This server only runs on *nix-like systems.")) . "\n";
exit 1;
}
my $mcp_select = IO::Select->new(\*STDIN);
sub detect_terminal {
my $test_launch = sub {
my ($cmd) = @_;
my $MAX_TEST_TIME = 1;
return 0 unless @$cmd && can_run($cmd->[0]);
eval {
local $SIG{ALRM} = sub { die "TIMEOUT\n" };
alarm($MAX_TEST_TIME);
my @test_cmd = (@$cmd, 'true');
my $pid = fork();
return 0 unless defined $pid;
if ($pid == 0) {
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
exec(@test_cmd);
exit(1);
}
waitpid($pid, 0);
my $exit = $? >> 8;
alarm(0);
return 1 if $exit == 0 || $exit == 1;
return 0;
};
alarm(0);
return 0 if $@;
return 1;
};
my @priority_terminals = (
{ name => 'Ghostty.app', config => ['ghostty', '-e'], check => sub { can_run('ghostty') && $test_launch->($_[0]) } },
{ name => 'WezTerm.app', config => ['wezterm', 'start', '--'], check => sub { can_run('wezterm') && $test_launch->($_[0]) } },
{ name => 'iTerm.app', config => ['open', '-a', 'iTerm'], check => sub { -d "/Applications/iTerm.app" || -d "/Applications/iTerm2.app" } },
{ name => 'Terminal.app', config => ['open', '-a', 'Terminal'], check => sub { -d "/Applications/Terminal.app" } },
{ name => 'wezterm', config => ['wezterm', 'start', '--'], check => sub { can_run('wezterm') && $test_launch->($_[0]) } },
{ name => 'kitty', config => ['kitty', '--'], check => sub { can_run('kitty') && $test_launch->($_[0]) } },
{ name => 'alacritty', config => ['alacritty', '-e'], check => sub { can_run('alacritty') && $test_launch->($_[0]) } },
{ name => 'ghostty', config => ['ghostty', '-e'], check => sub { can_run('ghostty') && $test_launch->($_[0]) } },
{ name => 'foot', config => ['foot'], check => sub { can_run('foot') && $test_launch->($_[0]) } },
{ name => 'konsole', config => ['konsole', '-e'], check => sub { can_run('konsole') && $test_launch->($_[0]) } },
{ name => 'gnome-terminal', config => ['gnome-terminal', '--'], check => sub { can_run('gnome-terminal') && $test_launch->($_[0]) } },
{ name => 'tilix', config => ['tilix', '-e'], check => sub { can_run('tilix') && $test_launch->($_[0]) } },
{ name => 'terminator', config => ['terminator', '-x'], check => sub { can_run('terminator') && $test_launch->($_[0]) } },
{ name => 'xfce4-terminal', config => ['xfce4-terminal', '-x'], check => sub { can_run('xfce4-terminal') && $test_launch->($_[0]) } },
{ name => 'xterm', config => ['xterm', '-e'], check => sub { can_run('xterm') && $test_launch->($_[0]) } },
{ name => 'urxvt', config => ['urxvt', '-e'], check => sub { can_run('urxvt') && $test_launch->($_[0]) } },
);
if ($options{'terminal'}) {
my $user_terminal = $options{'terminal'};
my $cfg = [$user_terminal, '-e'];
if ($user_terminal eq 'wezterm') {
$cfg = [$user_terminal, 'start', '--'];
} elsif ($user_terminal eq 'xfce4-terminal') {
$cfg = [$user_terminal, '--command'];
} elsif ($user_terminal eq 'gnome-terminal') {
$cfg = [$user_terminal, '--'];
} elsif ($user_terminal eq 'kitty') {
$cfg = [$user_terminal];
}
if (can_run($user_terminal) && $test_launch->($cfg)) {
return $cfg;
}
}
if ($ENV{TERM_PROGRAM}) {
my %map = (
'iTerm.app' => ['open', '-a', 'iTerm'],
'iTerm2' => ['open', '-a', 'iTerm'],
'Apple_Terminal' => ['open', '-a', 'Terminal'],
'vscode' => ['code', '--wait'],
'vscode-insiders' => ['code-insiders', '--wait'],
'Warp' => ['warp'],
'Hyper' => ['hyper'],
);
if (my $cfg = $map{$ENV{TERM_PROGRAM}}) {
my $bin = $cfg->[0];
if ($bin eq 'open' || $test_launch->($cfg)) {
return $cfg;
}
}
}
if ($ENV{TERMINAL} && can_run($ENV{TERMINAL})) {
my $env_flag = ($ENV{TERMINAL} =~ /gnome-terminal/) ? '--' : '-e';
my $cfg = [$ENV{TERMINAL}, $env_flag];
if ($test_launch->($cfg)) {
return $cfg;
}
}
for my $entry (@priority_terminals) {
if ($entry->{check}($entry->{config})) {
return $entry->{config};
}
}
return;
}
my %TOOLS = (
start => {
description => "Start the bridge for VM serial console communication.",
inputSchema => {
type => "object",
properties => {
vm_name => { type => "string", description => "Name of the VM" },
port => { type => "integer", description => "Port number for VM serial console (default: 4555)" },
},
required => ["vm_name"],
},
handler => \&tool_start,
},
stop => {
description => "Stop the bridge.",
inputSchema => {
type => "object",
properties => { vm_name => { type => "string", description => "Name of the VM" } },
required => ["vm_name"],
},
handler => \&tool_stop,
},
status => {
description => "Check the status of the bridge.",
inputSchema => {
type => "object",
properties => { vm_name => { type => "string", description => "Name of the VM" } },
required => ["vm_name"],
},
handler => \&tool_status,
},
read => {
description => "Read buffered output from VM serial console.",
inputSchema => {
type => "object",
properties => { vm_name => { type => "string", description => "Name of the VM" } },
required => ["vm_name"],
},
handler => \&tool_read,
},
write => {
description => "Send a command to the VM serial console.",
inputSchema => {
type => "object",
properties => {
vm_name => { type => "string", description => "Name of the VM" },
text => { type => "string", description => "Command to send to the VM" },
},
required => ["vm_name", "text"],
},
handler => \&tool_write,
}
);
start_mcp_server() unless caller;
END {
return unless $IS_PARENT;
return unless $$ == $PARENT_PID;
cleanup();
}
sub should_log {
my ($level) = @_;
my $level_pri = $LOG_LEVEL_PRIORITY{$level} // 0;
my $min_pri = $LOG_LEVEL_PRIORITY{$current_log_level} // 0;
return $level_pri >= $min_pri;
}
sub debug {
my ($message) = @_;
return unless should_log('debug');
printf STDERR "[DEBUG %d] %s\n", $$, $message;
}
sub shell_quote {
my ($s) = @_;
$s = '' unless defined $s;
$s =~ s/'/'"'"'/g;
return "'$s'";
}
sub emit_json_line {
my ($obj) = @_;
return unless $$ == $PARENT_PID;
my $json = encode_json($obj);
my $bytes = encode_utf8($json . "\n");
return write_all_nonblocking(\*STDOUT, $bytes, 2.0);
}
sub send_progress_notification {
my ($progressToken, $progress, $total, $message) = @_;
return unless defined $progressToken;
return unless $$ == $PARENT_PID;
my $params = {
progressToken => $progressToken,
};
$params->{progress} = $progress if defined $progress;
$params->{total} = $total if defined $total;
$params->{message} = $message if defined $message;
emit_json_line({
jsonrpc => "2.0",
method => "notifications/progress",
params => $params,
});
}
sub send_resource_list_changed_notification {
return unless $$ == $PARENT_PID;
emit_json_line({
jsonrpc => "2.0",
method => "notifications/resources/list_changed",
});
}
sub send_resource_updated_notification {
my ($uri) = @_;
return unless $$ == $PARENT_PID;
return unless $resource_subscriptions{$uri};
emit_json_line({
jsonrpc => "2.0",
method => "notifications/resources/updated",
params => { uri => $uri },
});
}
sub mcp_error {
my ($id, $code, $message, $data) = @_;
my $error_response = {
jsonrpc => "2.0",
id => $id,
error => {
code => $code,
message => $message,
},
};
$error_response->{error}{data} = $data if defined $data;
return encode_json($error_response);
}
sub tool_exec_error {
my ($message) = @_;
return {
content => [{ type => "text", text => $message }],
isError => JSON::PP::true,
};
}
sub write_all_nonblocking {
my ($fh, $data, $timeout, $mode) = @_;
$timeout = 2.0 unless defined $timeout;
$mode = 2 unless defined $mode;
return 1 unless defined $fh;
return 1 unless defined $data;
return 1 unless length $data;
my $fd = fileno($fh);
return 0 unless defined $fd;
if ($mode == 2) {
return _write_all_timeout($fh, $data, $timeout) if $timeout > 0;
}
my $written = syswrite($fh, $data, length($data));
if (defined $written) {
return 1 if $written == length($data);
if ($mode == 0) {
return $written;
}
my $remaining = substr($data, $written);
return _queue_write_buffer($fh, $remaining, $fd);
}
if ($!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK}) {
if ($mode == 0) {
return 0;
}
return _queue_write_buffer($fh, $data, $fd);
}
return 0;
}
sub _write_all_timeout {
my ($fh, $data, $timeout) = @_;
return 1 unless defined $fh;
return 1 unless defined $data;
return 1 unless length $data;
my $fd = fileno($fh);
return 0 unless defined $fd;
my $sel = IO::Select->new();
$sel->add($fh);
my $offset = 0;
my $start = time();
while ($offset < length($data)) {
my $written = syswrite($fh, $data, length($data) - $offset, $offset);
if (defined $written) {
if ($written == 0) {
return 0 if time() - $start >= $timeout;
$sel->can_write(0.05);
next;
}
$offset += $written;
next;
}
if ($!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK}) {
return 0 if time() - $start >= $timeout;
$sel->can_write(0.05);
next;
}
return 0;
}
return 1;
}
sub _queue_write_buffer {
my ($fh, $data, $fd) = @_;
return 0 unless defined $data && length $data;
$fd = fileno($fh) unless defined $fd;
return 0 unless defined $fd;
if ($write_buffers{$fd}{buffer_bytes} && $write_buffers{$fd}{buffer_bytes} >= $MAX_WRITE_BUFFER_BYTES) {
warn "Write buffer full for fd $fd, dropping data" if should_log('debug');
return 0;
}
unless (exists $write_buffers{$fd}) {
$write_buffers{$fd} = {
fh => $fh,
buffer => [],
buffer_bytes => 0,
fileno => $fd,
};
}
push @{ $write_buffers{$fd}{buffer} }, $data;
$write_buffers{$fd}{buffer_bytes} += length($data);
return 1;
}
sub flush_write_buffers {
my ($fd) = @_;
my $total_written = 0;
my @fds_to_process = defined $fd ? ($fd) : keys %write_buffers;
for my $flush_fd (@fds_to_process) {
next unless exists $write_buffers{$flush_fd};
next unless @{ $write_buffers{$flush_fd}{buffer} };
my $buf_ref = $write_buffers{$flush_fd};
my $fh = $buf_ref->{fh};
while (@{ $buf_ref->{buffer} }) {
my $data = $buf_ref->{buffer}[0];
my $written = syswrite($fh, $data, length($data));
if (defined $written) {
if ($written == length($data)) {
shift @{ $buf_ref->{buffer} };
$buf_ref->{buffer_bytes} -= $written;
$total_written += $written;
} else {
$buf_ref->{buffer}[0] = substr($data, $written);
$buf_ref->{buffer_bytes} -= $written;
$total_written += $written;
last;
}
} elsif ($!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK}) {
last;
} else {
warn "Write error on fd $flush_fd: $!" if should_log('debug');
shift @{ $buf_ref->{buffer} };
$buf_ref->{buffer_bytes} -= length($data) if length($data) > 0;
last;
}
}
delete $write_buffers{$flush_fd} unless @{ $buf_ref->{buffer} };
}
return $total_written;
}
sub set_nonblocking {
my ($fh) = @_;
my $flags = fcntl($fh, F_GETFL, 0);
return unless defined $flags;
return fcntl($fh, F_SETFL, $flags | O_NONBLOCK);
}
sub start_mcp_server {
local $SIG{INT} = \&cleanup;
local $SIG{TERM} = \&cleanup;
local $SIG{HUP} = \&cleanup;
local $SIG{QUIT} = \&cleanup;
local $SIG{PIPE} = 'IGNORE';
local $SIG{CHLD} = sub {
while (waitpid(-1, WNOHANG) > 0) { }
};
binmode(STDIN, ':raw');
binmode(STDOUT, ':raw');
local $| = 1;
unless (set_nonblocking(\*STDIN)) {
print STDERR "Can't set STDIN nonblocking: $!\n";
print encode_utf8(mcp_error(undef, MCP_INTERNAL_ERROR, "Can't set STDIN nonblocking: $!")) . "\n";
exit 1;
}
set_nonblocking(\*STDOUT) or print STDERR "Warning: Can't set STDOUT nonblocking: $!\n";
printf STDERR "[DEBUG $$] Starting $0 MCP Server (protocol $PROTOCOL_VERSION)...\n" if should_log('debug');
my $stdin_buffer = '';
my $last_progress_time = 0;
while ($running) {
if ($mcp_select->count == 0 && !%bridges) {
printf STDERR "[DEBUG $$] No more inputs or active bridges. Shutting down...\n" if should_log('debug');
$running = 0;
last;
}
# Handle MCP messages
my @mcp_ready = $mcp_select->can_read(0.01);
for my $fh (@mcp_ready) {
next unless $fh == \*STDIN;
my $buffer;
my $bytes = sysread(STDIN, $buffer, 8192);
unless (defined $bytes) {
next if $!{EAGAIN} || $!{EWOULDBLOCK} || $!{EINTR};
debug("STDIN error: $!. Shutting down...");
$running = 0;
next;
}
if ($bytes == 0) {
if (%bridges) {
debug("STDIN closed (EOF) but keeping server alive for active bridges");
$mcp_select->remove(\*STDIN);
last;
} else {
debug("STDIN closed (EOF). No active bridges, shutting down...");
$running = 0;
next;
}
}
$stdin_buffer .= $buffer;
while ($stdin_buffer =~ s/^(.*?\n)//s) {
my $raw_line = $1;
$raw_line =~ s/\r?\n$//;
next unless length $raw_line;
$raw_line =~ s/^\s+|\s+$//g;
next unless length $raw_line;
debug("Received request bytes");
my $request;
eval {
my $decoded = decode_utf8($raw_line, FB_CROAK);
$request = decode_json($decoded);
1;
} or do {
my $err = $@ || "unknown parse error";
debug("Parse error: $err");
emit_json_line({
jsonrpc => "2.0",
id => undef,
error => {
code => MCP_PARSE_ERROR,
message => "Parse error",
data => "$err",
},
});
next;
};
my $response = eval { handle_request($request) };
if (my $err = $@) {
debug("Request handler error: $err");
if (ref($request) eq 'HASH' && exists $request->{id}) {
emit_json_line({
jsonrpc => "2.0",
id => $request->{id},
error => {
code => MCP_INTERNAL_ERROR,
message => "Internal error",
data => "$err",
},
});
}
next;
}
emit_json_line($response) if $response;
}
}
# Monitor bridge I/O
foreach my $vm_name (keys %bridges) {
my $bridge = $bridges{$vm_name};
next unless $bridge && $bridge->{select};
my @bridge_ready = $bridge->{select}->can_read(0.01);
for my $fh (@bridge_ready) {
monitor_bridge($vm_name, $fh);
}
}
# Send periodic progress notifications ONLY to clients that have explicitly subscribed
if (keys %progress_subscriptions && time() - $last_progress_time >= 0.5) {
$last_progress_time = time();
foreach my $progressToken (keys %progress_subscriptions) {
my $sub = $progress_subscriptions{$progressToken};
my $vm_name = $sub->{vm_name};
my $bridge = $bridges{$vm_name};
# Only send if bridge exists and has content
if ($bridge && @{ $bridge->{buffer} }) {
my $raw_bytes = join('', map { $$_ } @{ $bridge->{buffer} });
my $text;
eval { $text = decode_utf8($raw_bytes, 1); 1 } or do {
$text = $raw_bytes;
$text =~ s/([^\x20-\x7E\r\n\t])/sprintf("\\x{%02X}", ord($1))/ge;
};
send_progress_notification($progressToken, undef, undef, $text);
$sub->{last_sent} = time();
}
# Clean up stale subscriptions (no bridge, or bridge stopped)
unless ($bridge) {
debug("Cleaning up progress subscription for $vm_name (bridge gone)");
delete $progress_subscriptions{$progressToken};
}
}
}
flush_write_buffers() if %write_buffers;
sleep(0.001);
}
}
sub is_valid_jsonrpc_id {
my ($id) = @_;
return 1 if !ref($id);
return 0;
}
sub handle_request {
my ($request) = @_;
if (!$request || ref($request) ne 'HASH') {
return {
jsonrpc => "2.0",
id => undef,
error => {
code => MCP_INVALID_REQUEST,
message => "Invalid Request",
data => "Request must be a JSON object",
},
};
}
my $jsonrpc = $request->{jsonrpc};
my $method = $request->{method};
my $params = exists $request->{params} ? $request->{params} : {};
my $id = $request->{id};
my $is_notification = !exists $request->{id};
if (defined $jsonrpc && $jsonrpc ne '2.0') {
return if $is_notification;
return {
jsonrpc => "2.0",
id => is_valid_jsonrpc_id($id) ? $id : undef,
error => {
code => MCP_INVALID_REQUEST,
message => "Invalid Request",
data => "jsonrpc must be '2.0'",
},
};
}
if (!defined $method || ref($method) || $method eq '') {
return if $is_notification;
return {
jsonrpc => "2.0",
id => is_valid_jsonrpc_id($id) ? $id : undef,
error => {
code => MCP_INVALID_REQUEST,
message => "Invalid Request",
data => "method must be a non-empty string",
},
};
}
if (ref($params) && ref($params) ne 'HASH' && ref($params) ne 'ARRAY') {
return if $is_notification;
return {
jsonrpc => "2.0",
id => is_valid_jsonrpc_id($id) ? $id : undef,
error => {
code => MCP_INVALID_PARAMS,
message => "Invalid params",
},
};
}
# --- initialize ---
if ($method eq 'initialize') {
return if $is_notification;
return {
jsonrpc => "2.0",
id => is_valid_jsonrpc_id($id) ? $id : undef,
result => {
protocolVersion => $PROTOCOL_VERSION,
capabilities => {
logging => {},
resources => { subscribe => JSON::PP::true, listChanged => JSON::PP::true },
tools => { listChanged => JSON::PP::true },
},
serverInfo => {
name => "serencp",
version => $VERSION,
description => "MCP server for VM serial console communication via TCP/Unix sockets.",
},
},
};
}
# --- notifications/initialized (client notification, no response) ---
if ($method eq 'notifications/initialized') {
debug("Client initialized notification received");
return;
}
# --- ping ---
if ($method eq 'ping') {
return if $is_notification;
return { jsonrpc => "2.0", id => $id, result => {} };
}
# --- logging/setLevel ---
if ($method eq 'logging/setLevel') {
my $level = ref($params) eq 'HASH' ? $params->{level} : undef;
if ($level && exists $LOG_LEVEL_PRIORITY{$level}) {
$current_log_level = $level;
debug("Log level set to: $level");
return if $is_notification;
return { jsonrpc => "2.0", id => $id, result => {} };
}
return if $is_notification;
return {
jsonrpc => "2.0",
id => $id,
error => {
code => MCP_INVALID_PARAMS,
message => "Invalid log level: " . ($level // 'undef') . ". Valid: " . join(', ', sort keys %LOG_LEVEL_PRIORITY),
},
};
}
# --- resources/list ---
if ($method eq 'resources/list') {
return if $is_notification;
my @resources;
for my $vm_name (sort keys %bridges) {
push @resources, {
uri => "vm://$vm_name/output",
name => "VM Output: $vm_name",
description => "Buffered serial console output for $vm_name",
mimeType => "text/plain",
};
}
return { jsonrpc => "2.0", id => $id, result => { resources => \@resources } };
}
# --- resources/read ---
if ($method eq 'resources/read') {
return if $is_notification;
if (ref($params) ne 'HASH') {
return { jsonrpc => "2.0", id => $id, error => { code => MCP_INVALID_PARAMS, message => "Invalid params" } };
}
my $uri = $params->{uri};
if ($uri =~ m{^vm://([^/]+)/output$}) {
my $vm_name = $1;
my $bridge = $bridges{$vm_name};
if ($bridge) {
my $text = "";
if (@{ $bridge->{buffer} }) {
my $raw_bytes = join('', map { $$_ } @{ $bridge->{buffer} });
eval { $text = decode_utf8($raw_bytes, 1); 1 } or do {
$text = $raw_bytes;
$text =~ s/([^\x20-\x7E\r\n\t])/sprintf("\\x{%02X}", ord($1))/ge;
};
}
return {
jsonrpc => "2.0",
id => $id,
result => {
contents => [{
uri => $uri,
mimeType => "text/plain",
text => $text,
}],
},
};
}
}
return {
jsonrpc => "2.0",
id => $id,
error => { code => MCP_INVALID_REQUEST, message => "Resource not found or bridge not running" },
};
}
# --- resources/subscribe ---
if ($method eq 'resources/subscribe') {
return if $is_notification;
if (ref($params) ne 'HASH') {
return { jsonrpc => "2.0", id => $id, error => { code => MCP_INVALID_PARAMS, message => "Invalid params" } };
}
my $uri = $params->{uri};
unless (defined $uri && $uri =~ m{^vm://([^/]+)/output$}) {
return {
jsonrpc => "2.0",
id => $id,
error => { code => MCP_INVALID_PARAMS, message => "Invalid resource URI" },
};
}
$resource_subscriptions{$uri} = 1;
debug("Resource subscription added: $uri");
return { jsonrpc => "2.0", id => $id, result => {} };
}
# --- resources/unsubscribe ---
if ($method eq 'resources/unsubscribe') {
return if $is_notification;
if (ref($params) ne 'HASH') {
return { jsonrpc => "2.0", id => $id, error => { code => MCP_INVALID_PARAMS, message => "Invalid params" } };
}
my $uri = $params->{uri};
unless (defined $uri && $uri =~ m{^vm://([^/]+)/output$}) {
return {
jsonrpc => "2.0",
id => $id,
error => { code => MCP_INVALID_PARAMS, message => "Invalid resource URI" },
};
}
delete $resource_subscriptions{$uri};
debug("Resource subscription removed: $uri");
return { jsonrpc => "2.0", id => $id, result => {} };
}
# --- tools/list ---
if ($method eq 'tools/list') {
return if $is_notification;
my @list;
for my $name (sort keys %TOOLS) {
my %tool_def = (
name => $name,
description => $TOOLS{$name}{description},
inputSchema => $TOOLS{$name}{inputSchema},
);
$tool_def{annotations} = $TOOLS{$name}{annotations} if $TOOLS{$name}{annotations};
push @list, \%tool_def;
}
return { jsonrpc => "2.0", id => $id, result => { tools => \@list } };
}
# --- tools/call ---
if ($method eq 'tools/call') {
return if $is_notification;
if (ref($params) ne 'HASH') {
return {
jsonrpc => "2.0",
id => $id,
error => {
code => MCP_INVALID_PARAMS,
message => "Invalid params",
data => "tools/call params must be an object",
},
};
}
my $name = $params->{name};
my $args = $params->{arguments} || {};
# Pass _meta through for progress tokens
$args->{_meta} = $params->{_meta} if ref($params->{_meta}) eq 'HASH';
if (!defined $name || ref($name) || $name eq '') {
return {
jsonrpc => "2.0",
id => $id,
error => {
code => MCP_INVALID_PARAMS,
message => "Invalid params",
data => "Tool name must be a non-empty string",
},
};
}
if (my $tool = $TOOLS{$name}) {
my $res = $tool->{handler}->($args);
if (ref($res) eq 'HASH' && exists $res->{content} && exists $res->{isError}) {
return { jsonrpc => "2.0", id => $id, result => $res };
}
my $json_text = encode_json($res);
return {
jsonrpc => "2.0",
id => $id,
result => {
content => [{ type => "text", text => $json_text }],
isError => JSON::PP::false,
},
};
}
return {
jsonrpc => "2.0",
id => $id,
error => { code => MCP_METHOD_NOT_FOUND, message => "Tool not found: $name" },
};
}
return if $is_notification;
return {
jsonrpc => "2.0",
id => $id,
error => { code => MCP_METHOD_NOT_FOUND, message => "Method not found: $method" },
};
}
sub tool_start {
my ($params) = @_;
$params = {} unless ref($params) eq 'HASH';
$params = { map { lc($_) => $params->{$_} } keys %$params };
my $vm_name = $params->{vm_name};
my $port = defined($params->{port}) && length($params->{port}) ? $params->{port} : $DEFAULT_VM_PORT;
my $progressToken;
$progressToken = $params->{_meta}{progressToken} if ref($params->{_meta}) eq 'HASH';
return tool_exec_error("vm_name parameter is required") unless defined $vm_name && length $vm_name;
return tool_exec_error("port must be numeric") unless defined($port) && $port =~ /^\d+$/ && $port >= 1 && $port <= 65535;
debug("Starting bridge for VM: $vm_name on port: $port");
my $old_term_pid;
if (bridge_exists($vm_name)) {
debug("Stopping existing bridge for VM: $vm_name (fresh slate)");
$old_term_pid = stop_bridge($vm_name, 0);
}
my $result = start_bridge($vm_name, $port, $progressToken, $old_term_pid);
# Register progress subscription if token provided
if ($progressToken && ref($result) eq 'HASH' && $result->{success}) {
$progress_subscriptions{$progressToken} = {
vm_name => $vm_name,
last_sent => time(),
};
debug("Progress subscription registered for token: $progressToken (VM: $vm_name)");
}
return $result;
}
sub tool_stop {
my ($params) = @_;
$params = {} unless ref($params) eq 'HASH';
$params = { map { lc($_) => $params->{$_} } keys %$params };
my $vm_name = $params->{vm_name};
return tool_exec_error("vm_name parameter is required") unless defined $vm_name && length $vm_name;
if (!bridge_exists($vm_name)) {
return { success => 0, message => "No bridge running for VM: $vm_name" };
}
# Clean up resource subscription for this VM
delete $resource_subscriptions{"vm://$vm_name/output"};
# Clean up progress subscriptions for this VM
foreach my $token (keys %progress_subscriptions) {
if ($progress_subscriptions{$token}{vm_name} eq $vm_name) {
delete $progress_subscriptions{$token};
debug("Cleaned up progress subscription for VM: $vm_name (token: $token)");
}
}
stop_bridge($vm_name, 1);
send_resource_list_changed_notification();
return { success => 1, message => "Bridge stopped for VM: $vm_name" };
}
sub tool_status {
my ($params) = @_;
$params = {} unless ref($params) eq 'HASH';
$params = { map { lc($_) => $params->{$_} } keys %$params };
my $vm_name = $params->{vm_name};
return tool_exec_error("vm_name parameter is required") unless defined $vm_name && length $vm_name;
if (bridge_exists($vm_name)) {
my $bridge = $bridges{$vm_name};
my $uri = "vm://$vm_name/output";
return {
running => JSON::PP::true,
vm_name => $vm_name,
port => $bridge->{port},
buffer_size => scalar(@{ $bridge->{buffer} }),
buffer_bytes => $bridge->{buffer_bytes} || 0,
subscribed => $resource_subscriptions{$uri} ? JSON::PP::true : JSON::PP::false,
};
}
return {
running => JSON::PP::false,
vm_name => $vm_name,
port => undef,
buffer_size => 0,
buffer_bytes => 0,
subscribed => JSON::PP::false,
};
}
sub tool_read {
my ($params) = @_;
$params = {} unless ref($params) eq 'HASH';
$params = { map { lc($_) => $params->{$_} } keys %$params };
my $vm_name = $params->{vm_name};
return tool_exec_error("vm_name parameter is required") unless defined $vm_name && length $vm_name;
return tool_exec_error("Bridge not running for VM: $vm_name. Use start to start it.")
unless bridge_exists($vm_name);
debug("Read request for VM: $vm_name");
my $bridge = $bridges{$vm_name};
my $text = "";
my $total_bytes = 0;
if ($bridge && $bridge->{buffer} && @{ $bridge->{buffer} }) {
my $raw_bytes = join('', map { $$_ } @{ $bridge->{buffer} });
$total_bytes = length($raw_bytes);
eval { $text = decode_utf8($raw_bytes, 1); 1 } or do {
$text = $raw_bytes;
$text =~ s/([^\x20-\x7E\r\n\t])/sprintf("\\x{%02X}", ord($1))/ge;
};
}
# Clear buffer after read (destructive read)
@{ $bridge->{buffer} } = ();
$bridge->{buffer_bytes} = 0;
debug("Read completed: $total_bytes bytes from VM output");
return { success => JSON::PP::true, output => $text };
}
sub tool_write {
my ($params) = @_;
$params = {} unless ref($params) eq 'HASH';
$params = { map { lc($_) => $params->{$_} } keys %$params };
my $vm_name = $params->{vm_name};
my $text = $params->{text};
return tool_exec_error("vm_name and text parameters are required")
unless defined $vm_name && length($vm_name) && defined $text;
return tool_exec_error("Bridge not running for VM: $vm_name. Use start to start it.")
unless bridge_exists($vm_name);
debug("Write request for VM: $vm_name");
my $bridge = $bridges{$vm_name};
unless ($bridge && $bridge->{pty_in}) {
return { success => JSON::PP::false, message => "PTY not available" };
}
$text =~ s/\n+$//;
$text .= "\n";
my $bytes = encode_utf8($text);
debug("Writing to input PTY: " . length($bytes) . " bytes");
my $ok = write_all_nonblocking($bridge->{pty_in}, $bytes, 2.0);
return {
success => $ok ? JSON::PP::true : JSON::PP::false,
message => $ok ? "Command sent successfully" : "Failed to send command",
};
}
sub bridge_exists {
my ($vm_name) = @_;
return exists $bridges{$vm_name}
&& $bridges{$vm_name}{pty_in}
&& $bridges{$vm_name}{pty_out}
&& (!$bridges{$vm_name}{pid} || kill(0, $bridges{$vm_name}{pid}));
}
sub remove_socket_file {
my ($socket_path, $context) = @_;
$context ||= "general";
return unless -e $socket_path || -S $socket_path;
debug("Removing socket file ($context): $socket_path");
my $retry_count = 0;
while ($retry_count < 5) {
last if unlink($socket_path);
$retry_count++;
last unless -e $socket_path || -S $socket_path;
debug("Failed to unlink $socket_path ($context): $! (attempt $retry_count)");
sleep(0.1);
}
if (-e $socket_path || -S $socket_path) {
debug("Warning: Could not remove socket file $socket_path ($context) after retries");
return 0;
}
return 1;
}
sub start_bridge {
my ($vm_name, $port, $progressToken, $old_term_pid) = @_;
$port //= $DEFAULT_VM_PORT;
debug("Creating bridge for $vm_name on port $port");
send_progress_notification($progressToken, 0, 5, "Creating PTY pair") if $progressToken;
my $pty_in = IO::Pty->new();
my $pty_out = IO::Pty->new();
unless ($pty_in && $pty_out) {
debug("Failed to create PTYs");
return tool_exec_error("Failed to create PTYs for VM: $vm_name");
}
$pty_in->set_raw();
$pty_out->set_raw();
my ($read_pipe, $write_pipe);
unless (pipe($read_pipe, $write_pipe)) {
debug("Failed to create pipe: $!");
return tool_exec_error("Failed to create communication pipe for VM: $vm_name: $!");
}
send_progress_notification($progressToken, 1, 5, "Creating Unix sockets") if $progressToken;
my $session_id = sprintf("%s_%d", $vm_name, time());
my $socket_in_path = "/tmp/serial_${session_id}.in";
my $socket_out_path = "/tmp/serial_${session_id}.out";
remove_socket_file($socket_in_path, "bridge setup");
remove_socket_file($socket_out_path, "bridge setup");
my $socket_in = IO::Socket::UNIX->new(Type => SOCK_STREAM, Local => $socket_in_path, Listen => 8);