-
Notifications
You must be signed in to change notification settings - Fork 272
Expand file tree
/
Copy pathmcp_test.go
More file actions
347 lines (312 loc) · 10.6 KB
/
Copy pathmcp_test.go
File metadata and controls
347 lines (312 loc) · 10.6 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
package mcp
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/sipcapture/homer-core/src/config"
)
func newTestModule(t *testing.T) *Module {
t.Helper()
mod, err := New(&config.MCPConfig{
Mode: "hybrid",
HomerBaseURL: "http://127.0.0.1:8080",
HomerToken: "token",
DefaultLimit: 100,
SQLDefaultLimit: 100,
})
if err != nil {
t.Fatalf("New() error: %v", err)
}
return mod
}
func TestBuildStructuredPayloadInviteLastHour(t *testing.T) {
mod := newTestModule(t)
now := int64(1740656400000)
payload, normalized := mod.buildStructuredPayload("find INVITE in the last hour src ip 10.1.2.3", now, 200)
if payload.Filter.Method != "INVITE" {
t.Fatalf("expected method INVITE, got %q", payload.Filter.Method)
}
if payload.Filter.SrcIP != "10.1.2.3" {
t.Fatalf("expected src_ip 10.1.2.3, got %q", payload.Filter.SrcIP)
}
if payload.Timestamp.From != now-60*60*1000 {
t.Fatalf("unexpected timestamp.from: %d", payload.Timestamp.From)
}
if payload.Timestamp.To != now {
t.Fatalf("unexpected timestamp.to: %d", payload.Timestamp.To)
}
if payload.Param.Limit != 200 {
t.Fatalf("expected limit 200, got %d", payload.Param.Limit)
}
if normalized["time_range"] != "last_hour" {
t.Fatalf("expected time_range=last_hour, got %#v", normalized["time_range"])
}
}
func TestValidateSQLAllowsCallTableName(t *testing.T) {
sql := "SELECT * FROM homer_lake.main.hep_proto_1_call WHERE method = 'INVITE' ORDER BY timestamp DESC LIMIT 10"
if err := validateSQL(sql); err != nil {
t.Fatalf("expected SQL to be valid, got error: %v", err)
}
}
func TestValidateSQLAllowsForbiddenWordsInLiterals(t *testing.T) {
sql := "SELECT * FROM homer_lake.main.hep_proto_1_call WHERE session_id = 'foo-call-bar' OR note = 'drop table'"
if err := validateSQL(sql); err != nil {
t.Fatalf("expected keywords inside string literals to be allowed, got: %v", err)
}
}
func TestValidateSQLRejectsSemicolon(t *testing.T) {
sql := "SELECT * FROM homer_lake.main.hep_proto_1_call WHERE method = 'INVITE';"
if err := validateSQL(sql); err == nil {
t.Fatalf("expected semicolon SQL to be rejected")
}
}
func TestValidateSQLRejectsDropToken(t *testing.T) {
// Bare DROP identifier must still be rejected; words inside string
// literals are allowed (see TestValidateSQLAllowsForbiddenWordsInLiterals).
sql := "SELECT * FROM homer_lake.main.hep_proto_1_call WHERE DROP"
if err := validateSQL(sql); err == nil {
t.Fatalf("expected DROP identifier SQL to be rejected")
}
}
func TestValidateSQLRejectsCallStatement(t *testing.T) {
sql := "SELECT * FROM homer_lake.main.hep_proto_1_call WHERE 1=1 CALL some_proc()"
if err := validateSQL(sql); err == nil {
t.Fatalf("expected CALL statement SQL to be rejected")
}
}
func TestValidateSQLRejectsForeignTable(t *testing.T) {
sql := "SELECT * FROM some_other.table WHERE method = 'INVITE'"
if err := validateSQL(sql); err == nil {
t.Fatalf("expected foreign table SQL to be rejected")
}
}
func TestRunHybridAutoModeRouting(t *testing.T) {
var (
mu sync.Mutex
visited []string
)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
visited = append(visited, r.URL.Path)
mu.Unlock()
if r.Header.Get("Authorization") != "Bearer token" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"items": []map[string]any{{"id": 1}},
"keys": []string{"id"},
},
"meta": map[string]any{"ok": true},
})
})
ts := httptest.NewServer(handler)
defer ts.Close()
mod, err := New(&config.MCPConfig{
Mode: "hybrid",
HomerBaseURL: ts.URL,
HomerToken: "token",
DefaultLimit: 100,
SQLDefaultLimit: 100,
})
if err != nil {
t.Fatalf("New() error: %v", err)
}
_, err = mod.runHybrid(context.Background(), hybridArgs{QueryText: "find INVITE in the last hour", Mode: "auto"})
if err != nil {
t.Fatalf("runHybrid structured error: %v", err)
}
_, err = mod.runHybrid(context.Background(), hybridArgs{QueryText: "show sql INVITE in the last hour", Mode: "auto"})
if err != nil {
t.Fatalf("runHybrid sql error: %v", err)
}
mu.Lock()
defer mu.Unlock()
if len(visited) != 2 {
t.Fatalf("expected 2 API calls, got %d", len(visited))
}
if visited[0] != "/api/v4/transactions/search" {
t.Fatalf("expected first call to /api/v4/transactions/search, got %s", visited[0])
}
if visited[1] != "/api/v4/query" {
t.Fatalf("expected second call to /api/v4/query, got %s", visited[1])
}
}
func TestParseQueryRegexOnlyWhenLLMDisabled(t *testing.T) {
mod := newTestModule(t)
if mod.llm != nil {
t.Fatalf("expected nil llm client, got %#v", mod.llm)
}
_, _, meta, err := mod.parseQuery(context.Background(), "find INVITE in the last hour", 1740656400000, 0, "auto")
if err != nil {
t.Fatalf("parseQuery error: %v", err)
}
if meta.Used != parserRegex {
t.Fatalf("expected parser_used=regex, got %q", meta.Used)
}
}
func TestParseQueryStrictLLMErrorsWhenDisabled(t *testing.T) {
mod := newTestModule(t)
_, _, _, err := mod.parseQuery(context.Background(), "show me bye", 1740656400000, 0, "llm")
if err == nil {
t.Fatal("expected error when parser=llm and LLM is disabled")
}
}
func newModuleWithLLM(t *testing.T, llmURL string) *Module {
t.Helper()
mod, err := New(&config.MCPConfig{
Mode: "hybrid",
HomerBaseURL: "http://127.0.0.1:8080",
HomerToken: "token",
DefaultLimit: 100,
SQLDefaultLimit: 100,
LLM: config.MCPLLMConfig{
Enable: true,
BaseURL: llmURL,
APIKey: "k",
Model: "test-model",
TimeoutSec: 5,
},
})
if err != nil {
t.Fatalf("New() error: %v", err)
}
if mod.llm == nil {
t.Fatal("expected non-nil llm client")
}
return mod
}
func TestParseQueryUsesLLMWhenAvailable(t *testing.T) {
llm := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, chatJSON(`{"method":"BYE","src_ip":"9.9.9.9"}`))
}))
defer llm.Close()
mod := newModuleWithLLM(t, llm.URL)
payload, normalized, meta, err := mod.parseQuery(context.Background(), "give me everything", 1740656400000, 0, "auto")
if err != nil {
t.Fatalf("parseQuery error: %v", err)
}
if meta.Used != parserLLM {
t.Fatalf("expected parser_used=llm, got %q", meta.Used)
}
if meta.Model != "test-model" {
t.Fatalf("expected model=test-model, got %q", meta.Model)
}
if payload.Filter.Method != "BYE" {
t.Fatalf("expected method=BYE, got %q", payload.Filter.Method)
}
if payload.Filter.SrcIP != "9.9.9.9" {
t.Fatalf("expected src_ip=9.9.9.9, got %q", payload.Filter.SrcIP)
}
if normalized["method"] != "BYE" {
t.Fatalf("expected normalized.method=BYE, got %#v", normalized["method"])
}
}
func TestParseQueryFallsBackOnLLMFailure(t *testing.T) {
llm := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "boom", http.StatusInternalServerError)
}))
defer llm.Close()
mod := newModuleWithLLM(t, llm.URL)
payload, _, meta, err := mod.parseQuery(context.Background(), "find INVITE in the last hour src ip 10.1.2.3", 1740656400000, 0, "auto")
if err != nil {
t.Fatalf("parseQuery error: %v", err)
}
if meta.Used != "regex_fallback" {
t.Fatalf("expected parser_used=regex_fallback, got %q", meta.Used)
}
if meta.Error == "" {
t.Fatal("expected non-empty meta.error after fallback")
}
if payload.Filter.Method != "INVITE" || payload.Filter.SrcIP != "10.1.2.3" {
t.Fatalf("regex fallback did not extract expected fields: %+v", payload.Filter)
}
}
func TestParseQueryRegexOverrideIgnoresLLM(t *testing.T) {
called := false
llm := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
called = true
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, chatJSON(`{"method":"BYE"}`))
}))
defer llm.Close()
mod := newModuleWithLLM(t, llm.URL)
payload, _, meta, err := mod.parseQuery(context.Background(), "find INVITE last hour", 1740656400000, 0, "regex")
if err != nil {
t.Fatalf("parseQuery error: %v", err)
}
if called {
t.Fatal("expected LLM to not be called when parser=regex")
}
if meta.Used != parserRegex {
t.Fatalf("expected parser_used=regex, got %q", meta.Used)
}
if payload.Filter.Method != "INVITE" {
t.Fatalf("expected method=INVITE from regex, got %q", payload.Filter.Method)
}
}
func TestParseQueryStrictLLMErrorsWhenLLMFails(t *testing.T) {
llm := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "nope", http.StatusBadGateway)
}))
defer llm.Close()
mod := newModuleWithLLM(t, llm.URL)
_, _, _, err := mod.parseQuery(context.Background(), "anything", 1740656400000, 0, "llm")
if err == nil {
t.Fatal("expected error when parser=llm and LLM fails")
}
}
func TestParseQueryLLMTimeRangeOverridesRegex(t *testing.T) {
llm := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, chatJSON(`{"method":"INVITE","from_ms":1000,"to_ms":5000,"time_range_label":"custom_range"}`))
}))
defer llm.Close()
mod := newModuleWithLLM(t, llm.URL)
payload, normalized, _, err := mod.parseQuery(context.Background(), "anything", 1740656400000, 0, "auto")
if err != nil {
t.Fatalf("parseQuery error: %v", err)
}
if payload.Timestamp.From != 1000 || payload.Timestamp.To != 5000 {
t.Fatalf("expected llm time range, got %d..%d", payload.Timestamp.From, payload.Timestamp.To)
}
if normalized["time_range"] != "custom_range" {
t.Fatalf("expected time_range=custom_range, got %#v", normalized["time_range"])
}
}
func TestRunHybridForcedStructuredIgnoresSQLRequest(t *testing.T) {
var visited string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
visited = r.URL.Path
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{"items": []map[string]any{}, "keys": []string{}},
"meta": map[string]any{},
})
}))
defer ts.Close()
mod, err := New(&config.MCPConfig{
Mode: "structured",
HomerBaseURL: ts.URL,
HomerToken: "token",
DefaultLimit: 100,
SQLDefaultLimit: 100,
})
if err != nil {
t.Fatalf("New() error: %v", err)
}
_, err = mod.runHybrid(context.Background(), hybridArgs{QueryText: "show sql INVITE", Mode: "sql"})
if err != nil {
t.Fatalf("runHybrid error: %v", err)
}
if visited != "/api/v4/transactions/search" {
t.Fatalf("expected forced structured route, got %s", visited)
}
}