11# frozen_string_literal: true
22
3+ require "socket"
4+ require "timeout"
5+
36class TestServerManager
47 SERVERS = {
58 stdio : {
@@ -10,18 +13,21 @@ class TestServerManager
1013 http : {
1114 command : "bun" ,
1215 args : [ "spec/fixtures/typescript-mcp/index.ts" , "--" , "--silent" ] ,
13- pid_accessor : :http_server_pid
16+ pid_accessor : :http_server_pid ,
17+ port : 3005
1418 } ,
1519 pagination : {
1620 command : "bun" ,
1721 args : [ "spec/fixtures/pagination-server/index.ts" , "--" , "--silent" ] ,
18- pid_accessor : :pagination_server_pid
22+ pid_accessor : :pagination_server_pid ,
23+ port : 3007
1924 } ,
2025 sse : {
2126 command : "ruby" ,
2227 args : [ "lib/app.rb" , "--silent" ] ,
2328 chdir : "spec/fixtures/fast-mcp-ruby" ,
24- pid_accessor : :sse_server_pid
29+ pid_accessor : :sse_server_pid ,
30+ port : 3006
2531 }
2632 } . freeze
2733
@@ -35,9 +41,6 @@ def start_server
3541 start_server_type ( :stdio )
3642 start_server_type ( :http )
3743 start_server_type ( :pagination )
38-
39- # Give servers time to start
40- sleep 1.0
4144 rescue StandardError => e
4245 puts "Failed to start test server: #{ e . message } "
4346 stop_server
@@ -97,6 +100,9 @@ def start_server_type(server_type)
97100 pid = spawn ( config [ :command ] , *config [ :args ] , **spawn_options )
98101 Process . detach ( pid )
99102 send ( "#{ pid_accessor } =" , pid )
103+
104+ # Wait for the server to start, ensure they are ready to start
105+ wait_for_port ( config [ :port ] ) if config [ :port ]
100106 end
101107
102108 def stop_server_type ( server_type )
@@ -118,6 +124,17 @@ def stop_server_type(server_type)
118124 end
119125 end
120126
127+ def wait_for_port ( port , host = "127.0.0.1" , timeout = 15 )
128+ Timeout . timeout ( timeout ) do
129+ loop do
130+ Socket . tcp ( host , port , connect_timeout : 1 ) . close
131+ break
132+ rescue Errno ::ECONNREFUSED , Errno ::EHOSTUNREACH
133+ sleep 0.1
134+ end
135+ end
136+ end
137+
121138 def process_exists? ( pid )
122139 Process . kill ( 0 , pid )
123140 true
0 commit comments