@@ -48,4 +48,89 @@ struct ServerTests {
4848 await server. stop ( )
4949 await transport. disconnect ( )
5050 }
51+
52+ @Test ( " Initialize hook - successful " )
53+ func testInitializeHookSuccess( ) async throws {
54+ let transport = MockTransport ( )
55+
56+ actor TestState {
57+ var hookCalled = false
58+ func setHookCalled( ) { hookCalled = true }
59+ func wasHookCalled( ) -> Bool { hookCalled }
60+ }
61+
62+ let state = TestState ( )
63+ let server = Server ( name: " TestServer " , version: " 1.0 " )
64+
65+ // Start with the hook directly
66+ try await server. start ( transport: transport) { clientInfo, capabilities in
67+ #expect( clientInfo. name == " TestClient " )
68+ #expect( clientInfo. version == " 1.0 " )
69+ await state. setHookCalled ( )
70+ }
71+
72+ // Wait for server to initialize
73+ try await Task . sleep ( nanoseconds: 10_000_000 ) // 10ms
74+
75+ // Queue an initialize request
76+ try await transport. queueRequest (
77+ Initialize . request (
78+ . init(
79+ protocolVersion: Version . latest,
80+ capabilities: . init( ) ,
81+ clientInfo: . init( name: " TestClient " , version: " 1.0 " )
82+ )
83+ ) )
84+
85+ // Wait for message processing and hook execution
86+ try await Task . sleep ( nanoseconds: 200_000_000 ) // 200ms
87+
88+ #expect( await state. wasHookCalled ( ) == true )
89+ #expect( await transport. sentMessages. count >= 1 )
90+
91+ let messages = await transport. sentMessages
92+ if let response = messages. first {
93+ #expect( response. contains ( " serverInfo " ) )
94+ }
95+
96+ await server. stop ( )
97+ }
98+
99+ @Test ( " Initialize hook - rejection " )
100+ func testInitializeHookRejection( ) async throws {
101+ let transport = MockTransport ( )
102+
103+ let server = Server ( name: " TestServer " , version: " 1.0 " )
104+
105+ try await server. start ( transport: transport) { clientInfo, _ in
106+ if clientInfo. name == " BlockedClient " {
107+ throw Error . invalidRequest ( " Client not allowed " )
108+ }
109+ }
110+
111+ // Wait for server to initialize
112+ try await Task . sleep ( nanoseconds: 10_000_000 ) // 10ms
113+
114+ // Queue an initialize request from blocked client
115+ try await transport. queueRequest (
116+ Initialize . request (
117+ . init(
118+ protocolVersion: Version . latest,
119+ capabilities: . init( ) ,
120+ clientInfo: . init( name: " BlockedClient " , version: " 1.0 " )
121+ )
122+ ) )
123+
124+ // Wait for message processing
125+ try await Task . sleep ( nanoseconds: 200_000_000 ) // 200ms
126+
127+ #expect( await transport. sentMessages. count >= 2 )
128+
129+ let messages = await transport. sentMessages
130+ if let response = messages. first {
131+ #expect( response. contains ( " error " ) )
132+ #expect( response. contains ( " Client not allowed " ) )
133+ }
134+ await server. stop ( )
135+ }
51136}
0 commit comments