tools_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "log/slog"
  7. "net/http"
  8. "net/http/httptest"
  9. "slices"
  10. "strings"
  11. "sync"
  12. "testing"
  13. "gogs.netdome.biz/paul/go-wikijs-mcp/internal/wikijs"
  14. "github.com/modelcontextprotocol/go-sdk/mcp"
  15. )
  16. type capturedRequest struct {
  17. Query string `json:"query"`
  18. Variables map[string]any `json:"variables"`
  19. }
  20. type fakeWiki struct {
  21. t *testing.T
  22. mu sync.Mutex
  23. requests []capturedRequest
  24. emptyList bool // GetAllPages returns an empty list
  25. }
  26. func (f *fakeWiki) handle(w http.ResponseWriter, r *http.Request) {
  27. f.t.Helper()
  28. if got, want := r.Header.Get("Authorization"), "Bearer test-key"; got != want {
  29. f.t.Errorf("Authorization = %q, want %q", got, want)
  30. }
  31. var req capturedRequest
  32. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  33. f.t.Errorf("decode request: %v", err)
  34. http.Error(w, "bad request", http.StatusBadRequest)
  35. return
  36. }
  37. f.mu.Lock()
  38. f.requests = append(f.requests, req)
  39. f.mu.Unlock()
  40. w.Header().Set("Content-Type", "application/json")
  41. switch {
  42. case strings.Contains(req.Query, "query SearchPages"):
  43. fmt.Fprint(w, `{"data":{"pages":{"search":{"results":[
  44. {"title":"MCP","description":"protocol","path":"/mcp","locale":"en"}
  45. ],"suggestions":["mcp"],"totalHits":1}}}}`)
  46. case strings.Contains(req.Query, "query GetPageById"):
  47. id, _ := req.Variables["id"].(float64)
  48. if id == 404 {
  49. fmt.Fprint(w, `{"data":{"pages":{"single":null}}}`)
  50. return
  51. }
  52. fmt.Fprintf(w, `{"data":{"pages":{"single":{
  53. "id":%d,"path":"/dev/go","title":"Go","description":"desc",
  54. "tags":[{"tag":"go","title":"Go"}],"content":"body",
  55. "createdAt":"c","updatedAt":"u","locale":"de"}}}}`, int(id))
  56. case strings.Contains(req.Query, "query GetPageByPath"):
  57. path, _ := req.Variables["path"].(string)
  58. locale, _ := req.Variables["locale"].(string)
  59. fmt.Fprintf(w, `{"data":{"pages":{"singleByPath":{
  60. "id":7,"path":%q,"title":"Start","description":"desc",
  61. "tags":[],"content":"body","createdAt":"c","updatedAt":"u","locale":%q}}}}`, path, locale)
  62. case strings.Contains(req.Query, "query GetAllPages"):
  63. if f.emptyList {
  64. fmt.Fprint(w, `{"data":{"pages":{"list":[]}}}`)
  65. return
  66. }
  67. fmt.Fprint(w, `{"data":{"pages":{"list":[
  68. {"id":1,"path":"/a","locale":"de","title":"A","description":"a",
  69. "createdAt":"c","updatedAt":"u","tags":["go"]}
  70. ]}}}`)
  71. case strings.Contains(req.Query, "mutation CreatePage"):
  72. title, _ := req.Variables["title"].(string)
  73. if title == "fail" {
  74. fmt.Fprint(w, `{"data":{"pages":{"create":{"responseResult":{
  75. "succeeded":false,"errorCode":6001,"slug":"","message":"Nope"}}}}}`)
  76. return
  77. }
  78. fmt.Fprint(w, `{"data":{"pages":{"create":{"responseResult":{
  79. "succeeded":true,"errorCode":0,"slug":"new","message":"Page created"}}}}}`)
  80. case strings.Contains(req.Query, "mutation UpdatePage"):
  81. id, _ := req.Variables["id"].(float64)
  82. if id == 404 {
  83. fmt.Fprint(w, `{"data":{"pages":{"update":{"responseResult":{
  84. "succeeded":false,"errorCode":6001,"slug":"","message":"Page not found"}}}}}`)
  85. return
  86. }
  87. fmt.Fprint(w, `{"data":{"pages":{"update":{"responseResult":{
  88. "succeeded":true,"errorCode":0,"slug":"","message":"Page updated"}}}}}`)
  89. default:
  90. f.t.Errorf("unexpected query: %s", req.Query)
  91. http.Error(w, "unknown operation", http.StatusBadRequest)
  92. }
  93. }
  94. func (f *fakeWiki) lastContaining(t *testing.T, fragment string) capturedRequest {
  95. t.Helper()
  96. f.mu.Lock()
  97. defer f.mu.Unlock()
  98. for i := len(f.requests) - 1; i >= 0; i-- {
  99. if strings.Contains(f.requests[i].Query, fragment) {
  100. return f.requests[i]
  101. }
  102. }
  103. t.Fatalf("no request containing %q", fragment)
  104. return capturedRequest{}
  105. }
  106. func newTestSession(t *testing.T, enableEdit bool) (*mcp.ClientSession, *fakeWiki) {
  107. t.Helper()
  108. fake := &fakeWiki{t: t}
  109. wikiSrv := httptest.NewServer(http.HandlerFunc(fake.handle))
  110. t.Cleanup(wikiSrv.Close)
  111. wikiClient, err := wikijs.New(wikiSrv.URL, "test-key")
  112. if err != nil {
  113. t.Fatalf("wikijs.New() error = %v", err)
  114. }
  115. srv := New(wikiClient, Options{
  116. Version: "test",
  117. EnableEdit: enableEdit,
  118. Logger: slog.New(slog.DiscardHandler),
  119. })
  120. st, ct := mcp.NewInMemoryTransports()
  121. ctx := context.Background()
  122. ss, err := srv.Connect(ctx, st, nil)
  123. if err != nil {
  124. t.Fatalf("server connect: %v", err)
  125. }
  126. t.Cleanup(func() { _ = ss.Close() })
  127. client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0"}, nil)
  128. cs, err := client.Connect(ctx, ct, nil)
  129. if err != nil {
  130. t.Fatalf("client connect: %v", err)
  131. }
  132. t.Cleanup(func() { _ = cs.Close() })
  133. return cs, fake
  134. }
  135. func callTool(t *testing.T, cs *mcp.ClientSession, name string, args map[string]any) *mcp.CallToolResult {
  136. t.Helper()
  137. res, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: name, Arguments: args})
  138. if err != nil {
  139. t.Fatalf("CallTool(%s) error = %v", name, err)
  140. }
  141. return res
  142. }
  143. func toolText(t *testing.T, res *mcp.CallToolResult) string {
  144. t.Helper()
  145. if len(res.Content) == 0 {
  146. t.Fatal("tool result has no content")
  147. }
  148. text, ok := res.Content[0].(*mcp.TextContent)
  149. if !ok {
  150. t.Fatalf("content type = %T, want *mcp.TextContent", res.Content[0])
  151. }
  152. return text.Text
  153. }
  154. func TestToolListWithoutEdit(t *testing.T) {
  155. cs, _ := newTestSession(t, false)
  156. res, err := cs.ListTools(context.Background(), nil)
  157. if err != nil {
  158. t.Fatalf("ListTools() error = %v", err)
  159. }
  160. got := toolNames(res.Tools)
  161. want := []string{"search_pages", "get_page_by_id", "get_page_by_path", "get_all_pages"}
  162. if !equalNames(got, want) {
  163. t.Errorf("tools = %v, want %v", got, want)
  164. }
  165. }
  166. func TestToolListWithEdit(t *testing.T) {
  167. cs, _ := newTestSession(t, true)
  168. res, err := cs.ListTools(context.Background(), nil)
  169. if err != nil {
  170. t.Fatalf("ListTools() error = %v", err)
  171. }
  172. got := toolNames(res.Tools)
  173. want := []string{"search_pages", "get_page_by_id", "get_page_by_path", "get_all_pages", "create_page", "edit_page"}
  174. if !equalNames(got, want) {
  175. t.Errorf("tools = %v, want %v", got, want)
  176. }
  177. }
  178. func toolNames(tools []*mcp.Tool) []string {
  179. names := make([]string, len(tools))
  180. for i, tool := range tools {
  181. names[i] = tool.Name
  182. }
  183. return names
  184. }
  185. func equalNames(got, want []string) bool {
  186. got = slices.Clone(got)
  187. want = slices.Clone(want)
  188. slices.Sort(got)
  189. slices.Sort(want)
  190. return slices.Equal(got, want)
  191. }
  192. func TestSearchPagesTool(t *testing.T) {
  193. cs, fake := newTestSession(t, false)
  194. res := callTool(t, cs, "search_pages", map[string]any{"query": "mcp"})
  195. if res.IsError {
  196. t.Fatalf("IsError = true: %s", toolText(t, res))
  197. }
  198. if res.StructuredContent == nil {
  199. t.Error("StructuredContent = nil")
  200. }
  201. var out wikijs.SearchResults
  202. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  203. t.Fatalf("decode result: %v", err)
  204. }
  205. if out.TotalHits != 1 || len(out.Results) != 1 {
  206. t.Fatalf("result = %+v", out)
  207. }
  208. if !strings.HasSuffix(out.Results[0].URL, "/mcp") {
  209. t.Errorf("URL = %q", out.Results[0].URL)
  210. }
  211. req := fake.lastContaining(t, "query SearchPages")
  212. if _, ok := req.Variables["path"]; ok {
  213. t.Errorf("path variable present: %v", req.Variables["path"])
  214. }
  215. }
  216. func TestSearchPagesValidation(t *testing.T) {
  217. cs, _ := newTestSession(t, false)
  218. tests := []struct {
  219. name string
  220. args map[string]any
  221. want string
  222. }{
  223. {name: "empty query", args: map[string]any{"query": " "}, want: "query must not be empty"},
  224. {name: "bad locale", args: map[string]any{"query": "x", "locale": "english"}, want: "invalid locale"},
  225. }
  226. for _, tt := range tests {
  227. t.Run(tt.name, func(t *testing.T) {
  228. res := callTool(t, cs, "search_pages", tt.args)
  229. if !res.IsError {
  230. t.Fatal("IsError = false, want true")
  231. }
  232. if got := toolText(t, res); !strings.Contains(got, tt.want) {
  233. t.Errorf("text = %q, want substring %q", got, tt.want)
  234. }
  235. })
  236. }
  237. }
  238. func TestGetPageByIDTool(t *testing.T) {
  239. cs, _ := newTestSession(t, false)
  240. res := callTool(t, cs, "get_page_by_id", map[string]any{"id": 42})
  241. if res.IsError {
  242. t.Fatalf("IsError = true: %s", toolText(t, res))
  243. }
  244. var page wikijs.Page
  245. if err := json.Unmarshal([]byte(toolText(t, res)), &page); err != nil {
  246. t.Fatalf("decode page: %v", err)
  247. }
  248. if page.ID != 42 || page.Title != "Go" {
  249. t.Errorf("page = %+v", page)
  250. }
  251. if !strings.HasSuffix(page.URL, "/de/dev/go") {
  252. t.Errorf("URL = %q", page.URL)
  253. }
  254. }
  255. func TestGetPageByIDNotFound(t *testing.T) {
  256. cs, _ := newTestSession(t, false)
  257. res := callTool(t, cs, "get_page_by_id", map[string]any{"id": 404})
  258. if res.IsError {
  259. t.Fatalf("IsError = true: %s", toolText(t, res))
  260. }
  261. if got := strings.TrimSpace(toolText(t, res)); got != "null" {
  262. t.Errorf("text = %q, want null", got)
  263. }
  264. }
  265. func TestGetPageByIDInvalid(t *testing.T) {
  266. cs, _ := newTestSession(t, false)
  267. res := callTool(t, cs, "get_page_by_id", map[string]any{"id": 0})
  268. if !res.IsError {
  269. t.Fatal("IsError = false, want true")
  270. }
  271. if got := toolText(t, res); !strings.Contains(got, "positive") {
  272. t.Errorf("text = %q", got)
  273. }
  274. }
  275. func TestGetPageByPathTool(t *testing.T) {
  276. cs, _ := newTestSession(t, false)
  277. res := callTool(t, cs, "get_page_by_path", map[string]any{"path": "/start", "locale": "de-DE"})
  278. if res.IsError {
  279. t.Fatalf("IsError = true: %s", toolText(t, res))
  280. }
  281. var page wikijs.Page
  282. if err := json.Unmarshal([]byte(toolText(t, res)), &page); err != nil {
  283. t.Fatalf("decode page: %v", err)
  284. }
  285. if page.ID != 7 {
  286. t.Errorf("page = %+v", page)
  287. }
  288. if !strings.HasSuffix(page.URL, "/de-DE/start") {
  289. t.Errorf("URL = %q", page.URL)
  290. }
  291. }
  292. func TestGetPageByPathRequiresLocale(t *testing.T) {
  293. cs, _ := newTestSession(t, false)
  294. res := callTool(t, cs, "get_page_by_path", map[string]any{"path": "/start"})
  295. if !res.IsError {
  296. t.Fatal("IsError = false, want true")
  297. }
  298. }
  299. func TestListPagesTool(t *testing.T) {
  300. cs, fake := newTestSession(t, false)
  301. res := callTool(t, cs, "get_all_pages", map[string]any{
  302. "limit": 10,
  303. "locale": "de",
  304. "tags": []string{"go"},
  305. })
  306. if res.IsError {
  307. t.Fatalf("IsError = true: %s", toolText(t, res))
  308. }
  309. var out struct {
  310. Pages []wikijs.PageListItem `json:"pages"`
  311. }
  312. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  313. t.Fatalf("decode pages: %v", err)
  314. }
  315. if len(out.Pages) != 1 || out.Pages[0].ID != 1 {
  316. t.Errorf("pages = %+v", out.Pages)
  317. }
  318. req := fake.lastContaining(t, "query GetAllPages")
  319. if got := req.Variables["limit"]; got != float64(10) {
  320. t.Errorf("variables[limit] = %v", got)
  321. }
  322. if got := req.Variables["locale"]; got != "de" {
  323. t.Errorf("variables[locale] = %v", got)
  324. }
  325. }
  326. func TestListPagesValidation(t *testing.T) {
  327. cs, _ := newTestSession(t, false)
  328. res := callTool(t, cs, "get_all_pages", map[string]any{"limit": 0})
  329. if !res.IsError {
  330. t.Fatal("IsError = false, want true")
  331. }
  332. if got := toolText(t, res); !strings.Contains(got, "limit must be a positive integer") {
  333. t.Errorf("text = %q", got)
  334. }
  335. }
  336. func TestCreatePageDefaults(t *testing.T) {
  337. cs, fake := newTestSession(t, true)
  338. res := callTool(t, cs, "create_page", map[string]any{
  339. "title": "New",
  340. "content": "body",
  341. "description": "desc",
  342. "path": "/new",
  343. })
  344. if res.IsError {
  345. t.Fatalf("IsError = true: %s", toolText(t, res))
  346. }
  347. var out mutationOutput
  348. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  349. t.Fatalf("decode output: %v", err)
  350. }
  351. if !out.Succeeded || out.Message != "Page created" {
  352. t.Errorf("output = %+v", out)
  353. }
  354. req := fake.lastContaining(t, "mutation CreatePage")
  355. want := map[string]any{
  356. "editor": "markdown",
  357. "isPublished": true,
  358. "isPrivate": false,
  359. "locale": "en",
  360. }
  361. for key, value := range want {
  362. if got := req.Variables[key]; got != value {
  363. t.Errorf("variables[%s] = %v, want %v", key, got, value)
  364. }
  365. }
  366. tags, ok := req.Variables["tags"].([]any)
  367. if !ok || len(tags) != 0 {
  368. t.Errorf("variables[tags] = %v, want []", req.Variables["tags"])
  369. }
  370. }
  371. func TestCreatePageFailure(t *testing.T) {
  372. cs, _ := newTestSession(t, true)
  373. res := callTool(t, cs, "create_page", map[string]any{
  374. "title": "fail",
  375. "content": "body",
  376. "description": "desc",
  377. "path": "/new",
  378. })
  379. if !res.IsError {
  380. t.Fatal("IsError = false, want true")
  381. }
  382. text := toolText(t, res)
  383. if !strings.Contains(text, "failed to create page") || !strings.Contains(text, "Nope") || !strings.Contains(text, "6001") {
  384. t.Errorf("text = %q", text)
  385. }
  386. }
  387. func TestEditPageDefaults(t *testing.T) {
  388. cs, fake := newTestSession(t, true)
  389. res := callTool(t, cs, "edit_page", map[string]any{
  390. "id": 7,
  391. "title": "Updated",
  392. "content": "body",
  393. "description": "desc",
  394. "path": "/start",
  395. })
  396. if res.IsError {
  397. t.Fatalf("IsError = true: %s", toolText(t, res))
  398. }
  399. var out mutationOutput
  400. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  401. t.Fatalf("decode output: %v", err)
  402. }
  403. if !out.Succeeded || out.Message != "Page updated" {
  404. t.Errorf("output = %+v", out)
  405. }
  406. req := fake.lastContaining(t, "mutation UpdatePage")
  407. if got := req.Variables["id"]; got != float64(7) {
  408. t.Errorf("variables[id] = %v", got)
  409. }
  410. if got := req.Variables["editor"]; got != "markdown" {
  411. t.Errorf("variables[editor] = %v", got)
  412. }
  413. }
  414. func TestEditPageNotFound(t *testing.T) {
  415. cs, _ := newTestSession(t, true)
  416. res := callTool(t, cs, "edit_page", map[string]any{
  417. "id": 404,
  418. "title": "Updated",
  419. "content": "body",
  420. "description": "desc",
  421. "path": "/start",
  422. })
  423. if !res.IsError {
  424. t.Fatal("IsError = false, want true")
  425. }
  426. text := toolText(t, res)
  427. if !strings.Contains(text, "failed to update page") || !strings.Contains(text, "Page not found") {
  428. t.Errorf("text = %q", text)
  429. }
  430. }
  431. func TestEditToolsHiddenWithoutEditMode(t *testing.T) {
  432. cs, _ := newTestSession(t, false)
  433. _, err := cs.CallTool(context.Background(), &mcp.CallToolParams{
  434. Name: "create_page",
  435. Arguments: map[string]any{"title": "x", "content": "", "description": "", "path": "/x"},
  436. })
  437. if err == nil {
  438. t.Fatal("CallTool(create_page) error = nil, want tool not found")
  439. }
  440. }
  441. func TestToolOutputIsJSON(t *testing.T) {
  442. cs, _ := newTestSession(t, false)
  443. res := callTool(t, cs, "get_all_pages", nil)
  444. var decoded any
  445. if err := json.Unmarshal([]byte(toolText(t, res)), &decoded); err != nil {
  446. t.Fatalf("output is not JSON: %v", err)
  447. }
  448. }