tools_test.go 14 KB

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