-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathserver_test.go
More file actions
358 lines (299 loc) · 10.2 KB
/
Copy pathserver_test.go
File metadata and controls
358 lines (299 loc) · 10.2 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
// Tencent is pleased to support the open source community by making trpc-mcp-go available.
//
// Copyright (C) 2025 Tencent. All rights reserved.
//
// trpc-mcp-go is licensed under the Apache License Version 2.0.
package mcp
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Create test server
func createTestServer() (*Server, *httptest.Server) {
// Create MCP server
mcpServer := NewServer(
"Test-Server", // Server name
"1.0.0", // Server version
WithServerAddress(":3000"), // Server address
WithServerPath("/mcp"), // Set API path
)
// Create HTTP test server
httpServer := httptest.NewServer(mcpServer.HTTPHandler())
return mcpServer, httpServer
}
func TestNewServer(t *testing.T) {
// Create server
server := NewServer(
"Test-Server", // Server name
"1.0.0", // Server version
WithServerAddress(":3000"), // Server address
)
// Verify object creation is successful
assert.NotNil(t, server)
assert.Equal(t, ":3000", server.config.addr)
assert.Equal(t, "/mcp", server.config.path) // Default prefix
assert.NotNil(t, server.httpHandler)
assert.NotNil(t, server.mcpHandler)
assert.NotNil(t, server.toolManager)
}
func TestServer_WithPathPrefix(t *testing.T) {
// Create server with custom path prefix
server := NewServer(
"Test-Server", // Server name
"1.0.0", // Server version
WithServerAddress(":3000"), // Server address
WithServerPath("/custom-api"), // Custom path prefix
)
// Verify path prefix
assert.Equal(t, "/custom-api", server.config.path)
}
func TestServer_WithoutSession(t *testing.T) {
// Create server with sessions disabled
server := NewServer(
"Test-Server", // Server name
"1.0.0", // Server version
WithServerAddress(":3000"), // Server address
WithoutSession(), // Disable sessions
)
// Verify server created successfully
assert.NotNil(t, server)
assert.NotNil(t, server.httpHandler)
}
func TestServer_RegisterTool(t *testing.T) {
// Create server
server := NewServer(
"Test-Server", // Server name
"1.0.0", // Server version
WithServerAddress(":3000"), // Server address
)
// Register tool
tool := NewTool("mock-tool",
WithDescription("Mock Tool"),
)
server.RegisterTool(tool, func(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) {
return NewTextResult("Mock Response"), nil
})
// Verify tool was registered
registeredTool, exists := server.toolManager.getTool("mock-tool")
assert.True(t, exists)
assert.NotNil(t, registeredTool)
assert.Equal(t, "mock-tool", registeredTool.Name)
assert.Equal(t, "Mock Tool", registeredTool.Description)
}
func TestServer_HTTPHandler(t *testing.T) {
// Create server
server, httpServer := createTestServer()
defer httpServer.Close()
// Verify HTTP handler
assert.NotNil(t, server.HTTPHandler())
assert.Equal(t, server.httpHandler, server.HTTPHandler())
// Send HTTP request
resp, err := http.Get(httpServer.URL + "/mcp")
// Verify response
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode) // Server now returns 400 Bad Request instead of 405 Method Not Allowed
}
func TestServer_MCPHandler(t *testing.T) {
// Create server
server := NewServer(
"Test-Server", // Server name
"1.0.0", // Server version
WithServerAddress(":3000"), // Server address
)
// Verify MCP handler
assert.NotNil(t, server.MCPHandler())
assert.Equal(t, server.mcpHandler, server.MCPHandler())
}
// Test HTTP context function registration
func TestServer_WithHTTPContextFunc(t *testing.T) {
// Define context keys
type contextKey string
const authTokenKey contextKey = "auth_token"
// Define HTTP context function
extractAuthToken := func(ctx context.Context, r *http.Request) context.Context {
if authHeader := r.Header.Get("Authorization"); authHeader != "" {
return context.WithValue(ctx, authTokenKey, authHeader)
}
return ctx
}
// Create server with HTTP context function
server := NewServer(
"Test-Server",
"1.0.0",
WithServerAddress(":3000"),
WithHTTPContextFunc(extractAuthToken),
)
// Verify server created successfully
assert.NotNil(t, server)
assert.NotNil(t, server.config.httpContextFuncs)
assert.Len(t, server.config.httpContextFuncs, 1)
}
// Test multiple HTTP context functions
func TestServer_WithMultipleHTTPContextFuncs(t *testing.T) {
// Define context keys
type contextKey string
const (
authTokenKey contextKey = "auth_token"
userAgentKey contextKey = "user_agent"
)
// Define HTTP context functions
extractAuthToken := func(ctx context.Context, r *http.Request) context.Context {
if authHeader := r.Header.Get("Authorization"); authHeader != "" {
return context.WithValue(ctx, authTokenKey, authHeader)
}
return ctx
}
extractUserAgent := func(ctx context.Context, r *http.Request) context.Context {
if userAgent := r.Header.Get("User-Agent"); userAgent != "" {
return context.WithValue(ctx, userAgentKey, userAgent)
}
return ctx
}
// Create server with multiple HTTP context functions
server := NewServer(
"Test-Server",
"1.0.0",
WithServerAddress(":3000"),
WithHTTPContextFunc(extractAuthToken),
WithHTTPContextFunc(extractUserAgent),
)
// Verify server created successfully
assert.NotNil(t, server)
assert.NotNil(t, server.config.httpContextFuncs)
assert.Len(t, server.config.httpContextFuncs, 2)
}
// Test tool handler accessing headers via context
func TestServer_ToolHandlerWithHeaders(t *testing.T) {
// Define context keys
type contextKey string
const authTokenKey contextKey = "auth_token"
// Define HTTP context function
extractAuthToken := func(ctx context.Context, r *http.Request) context.Context {
if authHeader := r.Header.Get("Authorization"); authHeader != "" {
return context.WithValue(ctx, authTokenKey, authHeader)
}
return ctx
}
// Create server with HTTP context function
server := NewServer(
"Test-Server",
"1.0.0",
WithServerPath("/mcp"),
WithHTTPContextFunc(extractAuthToken),
)
// Define tool handler that accesses headers
headerTool := func(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) {
authToken, _ := ctx.Value(authTokenKey).(string)
return NewTextResult("Auth: " + authToken), nil
}
// Register tool
tool := NewTool("header-tool", WithDescription("Tool that uses headers"))
server.RegisterTool(tool, headerTool)
// Create HTTP test server
httpServer := httptest.NewServer(server.HTTPHandler())
defer httpServer.Close()
// Create client
client, err := NewClient(httpServer.URL+"/mcp", Implementation{
Name: "Test-Client",
Version: "1.0.0",
})
require.NoError(t, err)
defer client.Close()
// Initialize client
ctx := context.Background()
_, err = client.Initialize(ctx, &InitializeRequest{})
require.NoError(t, err)
// Call tool without headers
result, err := client.CallTool(ctx, &CallToolRequest{
Params: CallToolParams{
Name: "header-tool",
Arguments: map[string]interface{}{},
},
})
require.NoError(t, err)
textContent, ok := result.Content[0].(TextContent)
require.True(t, ok)
assert.Equal(t, "Auth: ", textContent.Text) // Empty auth token
// Create client with headers
headers := make(http.Header)
headers.Set("Authorization", "Bearer test-token")
clientWithHeaders, err := NewClient(httpServer.URL+"/mcp", Implementation{
Name: "Test-Client-With-Headers",
Version: "1.0.0",
}, WithHTTPHeaders(headers))
require.NoError(t, err)
defer clientWithHeaders.Close()
// Initialize client with headers
_, err = clientWithHeaders.Initialize(ctx, &InitializeRequest{})
require.NoError(t, err)
// Call tool with headers
result, err = clientWithHeaders.CallTool(ctx, &CallToolRequest{
Params: CallToolParams{
Name: "header-tool",
Arguments: map[string]interface{}{},
},
})
require.NoError(t, err)
textContent, ok = result.Content[0].(TextContent)
require.True(t, ok)
assert.Equal(t, "Auth: Bearer test-token", textContent.Text) // Header extracted successfully
}
func TestServer_GetServerInfo(t *testing.T) {
serverName := "Test-Server-GetInfo"
serverVersion := "2.0.0"
server := NewServer(
serverName,
serverVersion,
WithServerAddress(":3000"),
)
info := server.GetServerInfo()
assert.Equal(t, serverName, info.Name)
assert.Equal(t, serverVersion, info.Version)
}
func TestServer_UnregisterTools(t *testing.T) {
server := NewServer("Test-Server", "1.0.0")
// Create and register multiple tools
tool1 := NewTool("test-tool-1", WithDescription("Test Tool 1"))
tool2 := NewTool("test-tool-2", WithDescription("Test Tool 2"))
tool3 := NewTool("test-tool-3", WithDescription("Test Tool 3"))
handler := func(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) {
return NewTextResult("Mock result"), nil
}
server.RegisterTool(tool1, handler)
server.RegisterTool(tool2, handler)
server.RegisterTool(tool3, handler)
// Verify all tools are registered
tools := server.toolManager.getTools()
assert.Len(t, tools, 3)
// Test unregistering multiple existing tools
err := server.UnregisterTools("test-tool-1", "test-tool-3")
assert.NoError(t, err)
tools = server.toolManager.getTools()
assert.Len(t, tools, 1)
// Check that only tool2 remains
_, exists := server.toolManager.getTool("test-tool-1")
assert.False(t, exists)
_, exists = server.toolManager.getTool("test-tool-2")
assert.True(t, exists)
_, exists = server.toolManager.getTool("test-tool-3")
assert.False(t, exists)
// Test unregistering non-existent tools
err = server.UnregisterTools("non-existent-1", "non-existent-2")
assert.Error(t, err)
assert.Contains(t, err.Error(), "none of the specified tools were found")
// Test unregistering with no names provided
err = server.UnregisterTools()
assert.Error(t, err)
assert.Contains(t, err.Error(), "no tool names provided")
// Test unregistering mix of existing and non-existent tools
server.RegisterTool(tool1, handler)
err = server.UnregisterTools("test-tool-1", "non-existent", "test-tool-2")
assert.NoError(t, err) // Should succeed if at least one tool is unregistered
tools = server.toolManager.getTools()
assert.Len(t, tools, 0)
}