tools_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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
  25. uploadCalled bool
  26. }
  27. func (f *fakeWiki) handle(w http.ResponseWriter, r *http.Request) {
  28. f.t.Helper()
  29. if got, want := r.Header.Get("Authorization"), "Bearer test-key"; got != want {
  30. f.t.Errorf("Authorization = %q, want %q", got, want)
  31. }
  32. // The upload endpoint is multipart, not GraphQL JSON.
  33. if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") {
  34. f.mu.Lock()
  35. f.uploadCalled = true
  36. f.mu.Unlock()
  37. _, _ = w.Write([]byte("ok"))
  38. return
  39. }
  40. var req capturedRequest
  41. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  42. f.t.Errorf("decode request: %v", err)
  43. http.Error(w, "bad request", http.StatusBadRequest)
  44. return
  45. }
  46. f.mu.Lock()
  47. f.requests = append(f.requests, req)
  48. f.mu.Unlock()
  49. w.Header().Set("Content-Type", "application/json")
  50. switch {
  51. case strings.Contains(req.Query, "query SearchPages"):
  52. fmt.Fprint(w, `{"data":{"pages":{"search":{"results":[
  53. {"title":"MCP","description":"protocol","path":"/mcp","locale":"en"}
  54. ],"suggestions":["mcp"],"totalHits":1}}}}`)
  55. case strings.Contains(req.Query, "query GetPageById"):
  56. id, _ := req.Variables["id"].(float64)
  57. if id == 404 {
  58. fmt.Fprint(w, `{"data":{"pages":{"single":null}}}`)
  59. return
  60. }
  61. fmt.Fprintf(w, `{"data":{"pages":{"single":{
  62. "id":%d,"path":"/dev/go","title":"Go","description":"desc",
  63. "tags":[{"tag":"go","title":"Go"}],"content":"body",
  64. "createdAt":"c","updatedAt":"u","locale":"de"}}}}`, int(id))
  65. case strings.Contains(req.Query, "query GetPageByPath"):
  66. path, _ := req.Variables["path"].(string)
  67. locale, _ := req.Variables["locale"].(string)
  68. fmt.Fprintf(w, `{"data":{"pages":{"singleByPath":{
  69. "id":7,"path":%q,"title":"Start","description":"desc",
  70. "tags":[],"content":"body","createdAt":"c","updatedAt":"u","locale":%q}}}}`, path, locale)
  71. case strings.Contains(req.Query, "query GetAllPages"):
  72. if f.emptyList {
  73. fmt.Fprint(w, `{"data":{"pages":{"list":[]}}}`)
  74. return
  75. }
  76. fmt.Fprint(w, `{"data":{"pages":{"list":[
  77. {"id":1,"path":"/a","locale":"de","title":"A","description":"a",
  78. "createdAt":"c","updatedAt":"u","tags":["go"]}
  79. ]}}}`)
  80. case strings.Contains(req.Query, "mutation CreatePage"):
  81. title, _ := req.Variables["title"].(string)
  82. if title == "fail" {
  83. fmt.Fprint(w, `{"data":{"pages":{"create":{"responseResult":{
  84. "succeeded":false,"errorCode":6001,"slug":"","message":"Nope"}}}}}`)
  85. return
  86. }
  87. fmt.Fprint(w, `{"data":{"pages":{"create":{"responseResult":{
  88. "succeeded":true,"errorCode":0,"slug":"new","message":"Page created"}}}}}`)
  89. case strings.Contains(req.Query, "mutation UpdatePage"):
  90. id, _ := req.Variables["id"].(float64)
  91. if id == 404 {
  92. fmt.Fprint(w, `{"data":{"pages":{"update":{"responseResult":{
  93. "succeeded":false,"errorCode":6001,"slug":"","message":"Page not found"}}}}}`)
  94. return
  95. }
  96. fmt.Fprint(w, `{"data":{"pages":{"update":{"responseResult":{
  97. "succeeded":true,"errorCode":0,"slug":"","message":"Page updated"}}}}}`)
  98. case strings.Contains(req.Query, "query SiteConfig"):
  99. fmt.Fprint(w, `{"data":{"site":{"config":{"uploadMaxFileSize":5242880}}}}`)
  100. case strings.Contains(req.Query, "query ListAssetFolders"):
  101. parentID, _ := req.Variables["parentFolderId"].(float64)
  102. if parentID == 0 {
  103. fmt.Fprint(w, `{"data":{"assets":{"folders":[{"id":5,"slug":"images","name":"Images"}]}}}`)
  104. return
  105. }
  106. fmt.Fprint(w, `{"data":{"assets":{"folders":[{"id":9,"slug":"screens","name":"Screens"}]}}}`)
  107. case strings.Contains(req.Query, "query ListAssets"):
  108. fmt.Fprint(w, `{"data":{"assets":{"list":[
  109. {"id":1,"filename":"shot.png","ext":"png","kind":"IMAGE","mime":"image/png",
  110. "fileSize":12,"createdAt":"c","updatedAt":"u",
  111. "folder":{"id":9,"slug":"screens","name":"Screens"}},
  112. {"id":2,"filename":"manual.pdf","ext":"pdf","kind":"BINARY","mime":"application/pdf",
  113. "fileSize":2048,"createdAt":"c","updatedAt":"u",
  114. "folder":{"id":9,"slug":"screens","name":"Screens"}}
  115. ]}}}`)
  116. case strings.Contains(req.Query, "mutation CreateAssetFolder"):
  117. slug, _ := req.Variables["slug"].(string)
  118. if slug == "fail" {
  119. fmt.Fprint(w, `{"data":{"assets":{"createFolder":{"responseResult":{
  120. "succeeded":false,"errorCode":2002,"slug":"","message":"AssetFolderExists"}}}}}`)
  121. return
  122. }
  123. fmt.Fprint(w, `{"data":{"assets":{"createFolder":{"responseResult":{
  124. "succeeded":true,"errorCode":0,"slug":"new-folder","message":"Folder created"}}}}}`)
  125. default:
  126. f.t.Errorf("unexpected query: %s", req.Query)
  127. http.Error(w, "unknown operation", http.StatusBadRequest)
  128. }
  129. }
  130. func (f *fakeWiki) lastContaining(t *testing.T, fragment string) capturedRequest {
  131. t.Helper()
  132. f.mu.Lock()
  133. defer f.mu.Unlock()
  134. for i := len(f.requests) - 1; i >= 0; i-- {
  135. if strings.Contains(f.requests[i].Query, fragment) {
  136. return f.requests[i]
  137. }
  138. }
  139. t.Fatalf("no request containing %q", fragment)
  140. return capturedRequest{}
  141. }
  142. func newTestSession(t *testing.T, enableEdit bool) (*mcp.ClientSession, *fakeWiki) {
  143. t.Helper()
  144. fake := &fakeWiki{t: t}
  145. wikiSrv := httptest.NewServer(http.HandlerFunc(fake.handle))
  146. t.Cleanup(wikiSrv.Close)
  147. wikiClient, err := wikijs.New(wikiSrv.URL, "test-key")
  148. if err != nil {
  149. t.Fatalf("wikijs.New() error = %v", err)
  150. }
  151. srv := New(wikiClient, Options{
  152. Version: "test",
  153. EnableEdit: enableEdit,
  154. Logger: slog.New(slog.DiscardHandler),
  155. })
  156. st, ct := mcp.NewInMemoryTransports()
  157. ctx := context.Background()
  158. ss, err := srv.Connect(ctx, st, nil)
  159. if err != nil {
  160. t.Fatalf("server connect: %v", err)
  161. }
  162. t.Cleanup(func() { _ = ss.Close() })
  163. client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0"}, nil)
  164. cs, err := client.Connect(ctx, ct, nil)
  165. if err != nil {
  166. t.Fatalf("client connect: %v", err)
  167. }
  168. t.Cleanup(func() { _ = cs.Close() })
  169. return cs, fake
  170. }
  171. func callTool(t *testing.T, cs *mcp.ClientSession, name string, args map[string]any) *mcp.CallToolResult {
  172. t.Helper()
  173. res, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: name, Arguments: args})
  174. if err != nil {
  175. t.Fatalf("CallTool(%s) error = %v", name, err)
  176. }
  177. return res
  178. }
  179. func toolText(t *testing.T, res *mcp.CallToolResult) string {
  180. t.Helper()
  181. if len(res.Content) == 0 {
  182. t.Fatal("tool result has no content")
  183. }
  184. text, ok := res.Content[0].(*mcp.TextContent)
  185. if !ok {
  186. t.Fatalf("content type = %T, want *mcp.TextContent", res.Content[0])
  187. }
  188. return text.Text
  189. }
  190. func TestToolListWithoutEdit(t *testing.T) {
  191. cs, _ := newTestSession(t, false)
  192. res, err := cs.ListTools(context.Background(), nil)
  193. if err != nil {
  194. t.Fatalf("ListTools() error = %v", err)
  195. }
  196. got := toolNames(res.Tools)
  197. want := []string{"search_pages", "get_page_by_id", "get_page_by_path", "get_all_pages", "list_asset_folders", "list_assets"}
  198. if !equalNames(got, want) {
  199. t.Errorf("tools = %v, want %v", got, want)
  200. }
  201. }
  202. func TestToolListWithEdit(t *testing.T) {
  203. cs, _ := newTestSession(t, true)
  204. res, err := cs.ListTools(context.Background(), nil)
  205. if err != nil {
  206. t.Fatalf("ListTools() error = %v", err)
  207. }
  208. got := toolNames(res.Tools)
  209. want := []string{
  210. "search_pages", "get_page_by_id", "get_page_by_path", "get_all_pages",
  211. "list_asset_folders", "list_assets",
  212. "create_page", "edit_page", "upload_asset", "create_asset_folder",
  213. }
  214. if !equalNames(got, want) {
  215. t.Errorf("tools = %v, want %v", got, want)
  216. }
  217. }
  218. func toolNames(tools []*mcp.Tool) []string {
  219. names := make([]string, len(tools))
  220. for i, tool := range tools {
  221. names[i] = tool.Name
  222. }
  223. return names
  224. }
  225. func equalNames(got, want []string) bool {
  226. got = slices.Clone(got)
  227. want = slices.Clone(want)
  228. slices.Sort(got)
  229. slices.Sort(want)
  230. return slices.Equal(got, want)
  231. }
  232. func TestSearchPagesTool(t *testing.T) {
  233. cs, fake := newTestSession(t, false)
  234. res := callTool(t, cs, "search_pages", map[string]any{"query": "mcp"})
  235. if res.IsError {
  236. t.Fatalf("IsError = true: %s", toolText(t, res))
  237. }
  238. if res.StructuredContent == nil {
  239. t.Error("StructuredContent = nil")
  240. }
  241. var out wikijs.SearchResults
  242. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  243. t.Fatalf("decode result: %v", err)
  244. }
  245. if out.TotalHits != 1 || len(out.Results) != 1 {
  246. t.Fatalf("result = %+v", out)
  247. }
  248. if !strings.HasSuffix(out.Results[0].URL, "/mcp") {
  249. t.Errorf("URL = %q", out.Results[0].URL)
  250. }
  251. req := fake.lastContaining(t, "query SearchPages")
  252. if _, ok := req.Variables["path"]; ok {
  253. t.Errorf("path variable present: %v", req.Variables["path"])
  254. }
  255. }
  256. func TestSearchPagesValidation(t *testing.T) {
  257. cs, _ := newTestSession(t, false)
  258. tests := []struct {
  259. name string
  260. args map[string]any
  261. want string
  262. }{
  263. {name: "empty query", args: map[string]any{"query": " "}, want: "query must not be empty"},
  264. {name: "bad locale", args: map[string]any{"query": "x", "locale": "english"}, want: "invalid locale"},
  265. }
  266. for _, tt := range tests {
  267. t.Run(tt.name, func(t *testing.T) {
  268. res := callTool(t, cs, "search_pages", tt.args)
  269. if !res.IsError {
  270. t.Fatal("IsError = false, want true")
  271. }
  272. if got := toolText(t, res); !strings.Contains(got, tt.want) {
  273. t.Errorf("text = %q, want substring %q", got, tt.want)
  274. }
  275. })
  276. }
  277. }
  278. func TestGetPageByIDTool(t *testing.T) {
  279. cs, _ := newTestSession(t, false)
  280. res := callTool(t, cs, "get_page_by_id", map[string]any{"id": 42})
  281. if res.IsError {
  282. t.Fatalf("IsError = true: %s", toolText(t, res))
  283. }
  284. var page wikijs.Page
  285. if err := json.Unmarshal([]byte(toolText(t, res)), &page); err != nil {
  286. t.Fatalf("decode page: %v", err)
  287. }
  288. if page.ID != 42 || page.Title != "Go" {
  289. t.Errorf("page = %+v", page)
  290. }
  291. if !strings.HasSuffix(page.URL, "/de/dev/go") {
  292. t.Errorf("URL = %q", page.URL)
  293. }
  294. }
  295. func TestGetPageByIDNotFound(t *testing.T) {
  296. cs, _ := newTestSession(t, false)
  297. res := callTool(t, cs, "get_page_by_id", map[string]any{"id": 404})
  298. if res.IsError {
  299. t.Fatalf("IsError = true: %s", toolText(t, res))
  300. }
  301. if got := strings.TrimSpace(toolText(t, res)); got != "null" {
  302. t.Errorf("text = %q, want null", got)
  303. }
  304. }
  305. func TestGetPageByIDInvalid(t *testing.T) {
  306. cs, _ := newTestSession(t, false)
  307. res := callTool(t, cs, "get_page_by_id", map[string]any{"id": 0})
  308. if !res.IsError {
  309. t.Fatal("IsError = false, want true")
  310. }
  311. if got := toolText(t, res); !strings.Contains(got, "positive") {
  312. t.Errorf("text = %q", got)
  313. }
  314. }
  315. func TestGetPageByPathTool(t *testing.T) {
  316. cs, _ := newTestSession(t, false)
  317. res := callTool(t, cs, "get_page_by_path", map[string]any{"path": "/start", "locale": "de-DE"})
  318. if res.IsError {
  319. t.Fatalf("IsError = true: %s", toolText(t, res))
  320. }
  321. var page wikijs.Page
  322. if err := json.Unmarshal([]byte(toolText(t, res)), &page); err != nil {
  323. t.Fatalf("decode page: %v", err)
  324. }
  325. if page.ID != 7 {
  326. t.Errorf("page = %+v", page)
  327. }
  328. if !strings.HasSuffix(page.URL, "/de-DE/start") {
  329. t.Errorf("URL = %q", page.URL)
  330. }
  331. }
  332. func TestGetPageByPathRequiresLocale(t *testing.T) {
  333. cs, _ := newTestSession(t, false)
  334. res := callTool(t, cs, "get_page_by_path", map[string]any{"path": "/start"})
  335. if !res.IsError {
  336. t.Fatal("IsError = false, want true")
  337. }
  338. }
  339. func TestListPagesTool(t *testing.T) {
  340. cs, fake := newTestSession(t, false)
  341. res := callTool(t, cs, "get_all_pages", map[string]any{
  342. "limit": 10,
  343. "locale": "de",
  344. "tags": []string{"go"},
  345. })
  346. if res.IsError {
  347. t.Fatalf("IsError = true: %s", toolText(t, res))
  348. }
  349. var out struct {
  350. Pages []wikijs.PageListItem `json:"pages"`
  351. }
  352. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  353. t.Fatalf("decode pages: %v", err)
  354. }
  355. if len(out.Pages) != 1 || out.Pages[0].ID != 1 {
  356. t.Errorf("pages = %+v", out.Pages)
  357. }
  358. req := fake.lastContaining(t, "query GetAllPages")
  359. if got := req.Variables["limit"]; got != float64(10) {
  360. t.Errorf("variables[limit] = %v", got)
  361. }
  362. if got := req.Variables["locale"]; got != "de" {
  363. t.Errorf("variables[locale] = %v", got)
  364. }
  365. }
  366. func TestListPagesValidation(t *testing.T) {
  367. cs, _ := newTestSession(t, false)
  368. res := callTool(t, cs, "get_all_pages", map[string]any{"limit": 0})
  369. if !res.IsError {
  370. t.Fatal("IsError = false, want true")
  371. }
  372. if got := toolText(t, res); !strings.Contains(got, "limit must be a positive integer") {
  373. t.Errorf("text = %q", got)
  374. }
  375. }
  376. func TestCreatePageDefaults(t *testing.T) {
  377. cs, fake := newTestSession(t, true)
  378. res := callTool(t, cs, "create_page", map[string]any{
  379. "title": "New",
  380. "content": "body",
  381. "description": "desc",
  382. "path": "/new",
  383. })
  384. if res.IsError {
  385. t.Fatalf("IsError = true: %s", toolText(t, res))
  386. }
  387. var out mutationOutput
  388. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  389. t.Fatalf("decode output: %v", err)
  390. }
  391. if !out.Succeeded || out.Message != "Page created" {
  392. t.Errorf("output = %+v", out)
  393. }
  394. req := fake.lastContaining(t, "mutation CreatePage")
  395. want := map[string]any{
  396. "editor": "markdown",
  397. "isPublished": true,
  398. "isPrivate": false,
  399. "locale": "en",
  400. }
  401. for key, value := range want {
  402. if got := req.Variables[key]; got != value {
  403. t.Errorf("variables[%s] = %v, want %v", key, got, value)
  404. }
  405. }
  406. tags, ok := req.Variables["tags"].([]any)
  407. if !ok || len(tags) != 0 {
  408. t.Errorf("variables[tags] = %v, want []", req.Variables["tags"])
  409. }
  410. }
  411. func TestCreatePageFailure(t *testing.T) {
  412. cs, _ := newTestSession(t, true)
  413. res := callTool(t, cs, "create_page", map[string]any{
  414. "title": "fail",
  415. "content": "body",
  416. "description": "desc",
  417. "path": "/new",
  418. })
  419. if !res.IsError {
  420. t.Fatal("IsError = false, want true")
  421. }
  422. text := toolText(t, res)
  423. if !strings.Contains(text, "failed to create page") || !strings.Contains(text, "Nope") || !strings.Contains(text, "6001") {
  424. t.Errorf("text = %q", text)
  425. }
  426. }
  427. func TestEditPageDefaults(t *testing.T) {
  428. cs, fake := newTestSession(t, true)
  429. res := callTool(t, cs, "edit_page", map[string]any{
  430. "id": 7,
  431. "title": "Updated",
  432. "content": "body",
  433. "description": "desc",
  434. "path": "/start",
  435. })
  436. if res.IsError {
  437. t.Fatalf("IsError = true: %s", toolText(t, res))
  438. }
  439. var out mutationOutput
  440. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  441. t.Fatalf("decode output: %v", err)
  442. }
  443. if !out.Succeeded || out.Message != "Page updated" {
  444. t.Errorf("output = %+v", out)
  445. }
  446. req := fake.lastContaining(t, "mutation UpdatePage")
  447. if got := req.Variables["id"]; got != float64(7) {
  448. t.Errorf("variables[id] = %v", got)
  449. }
  450. if got := req.Variables["editor"]; got != "markdown" {
  451. t.Errorf("variables[editor] = %v", got)
  452. }
  453. }
  454. func TestEditPageNotFound(t *testing.T) {
  455. cs, _ := newTestSession(t, true)
  456. res := callTool(t, cs, "edit_page", map[string]any{
  457. "id": 404,
  458. "title": "Updated",
  459. "content": "body",
  460. "description": "desc",
  461. "path": "/start",
  462. })
  463. if !res.IsError {
  464. t.Fatal("IsError = false, want true")
  465. }
  466. text := toolText(t, res)
  467. if !strings.Contains(text, "failed to update page") || !strings.Contains(text, "Page not found") {
  468. t.Errorf("text = %q", text)
  469. }
  470. }
  471. func TestEditToolsHiddenWithoutEditMode(t *testing.T) {
  472. cs, _ := newTestSession(t, false)
  473. _, err := cs.CallTool(context.Background(), &mcp.CallToolParams{
  474. Name: "create_page",
  475. Arguments: map[string]any{"title": "x", "content": "", "description": "", "path": "/x"},
  476. })
  477. if err == nil {
  478. t.Fatal("CallTool(create_page) error = nil, want tool not found")
  479. }
  480. }
  481. func TestToolOutputIsJSON(t *testing.T) {
  482. cs, _ := newTestSession(t, false)
  483. res := callTool(t, cs, "get_all_pages", nil)
  484. var decoded any
  485. if err := json.Unmarshal([]byte(toolText(t, res)), &decoded); err != nil {
  486. t.Fatalf("output is not JSON: %v", err)
  487. }
  488. }
  489. func TestUploadAssetTool(t *testing.T) {
  490. cs, fake := newTestSession(t, true)
  491. res := callTool(t, cs, "upload_asset", map[string]any{
  492. "filename": "notes.txt",
  493. "content": "hello",
  494. "folder": "images",
  495. "contentB64": "",
  496. })
  497. if res.IsError {
  498. t.Fatalf("IsError = true: %s", toolText(t, res))
  499. }
  500. var out uploadAssetOutput
  501. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  502. t.Fatalf("decode result: %v", err)
  503. }
  504. if !out.Succeeded {
  505. t.Error("Succeeded = false, want true")
  506. }
  507. fake.mu.Lock()
  508. uploaded := fake.uploadCalled
  509. fake.mu.Unlock()
  510. if !uploaded {
  511. t.Error("upload never reached the fake WikiJS server")
  512. }
  513. }
  514. func TestUploadAssetToolValidation(t *testing.T) {
  515. cs, _ := newTestSession(t, true)
  516. tests := []struct {
  517. name string
  518. args map[string]any
  519. want string
  520. }{
  521. {name: "no content", args: map[string]any{"filename": "a.txt", "content": "", "contentB64": ""}, want: "exactly one"},
  522. {name: "both contents", args: map[string]any{"filename": "a.txt", "content": "a", "contentB64": "YQ=="}, want: "exactly one"},
  523. {name: "bad folder", args: map[string]any{"filename": "a.txt", "content": "a", "folder": "im ages/"}, want: "invalid asset folder"},
  524. }
  525. for _, tc := range tests {
  526. t.Run(tc.name, func(t *testing.T) {
  527. res := callTool(t, cs, "upload_asset", tc.args)
  528. if !res.IsError {
  529. t.Fatalf("IsError = false, want error containing %q", tc.want)
  530. }
  531. if !strings.Contains(toolText(t, res), tc.want) {
  532. t.Errorf("error text %q does not contain %q", toolText(t, res), tc.want)
  533. }
  534. })
  535. }
  536. }
  537. func TestListAssetsTool(t *testing.T) {
  538. cs, fake := newTestSession(t, false)
  539. res := callTool(t, cs, "list_assets", map[string]any{"folder": "images/screens"})
  540. if res.IsError {
  541. t.Fatalf("IsError = true: %s", toolText(t, res))
  542. }
  543. var out listAssetsOutput
  544. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  545. t.Fatalf("decode result: %v", err)
  546. }
  547. if len(out.Assets) != 2 {
  548. t.Fatalf("assets = %d, want 2", len(out.Assets))
  549. }
  550. if !strings.HasSuffix(out.Assets[0].URL, "/images/screens/shot.png") {
  551. t.Errorf("URL = %q", out.Assets[0].URL)
  552. }
  553. if out.Assets[0].Markdown == "" {
  554. t.Error("Markdown = empty, want a markdown reference")
  555. }
  556. req := fake.lastContaining(t, "query ListAssets")
  557. if got := req.Variables["folderId"]; got != float64(9) {
  558. t.Errorf("folderId = %v, want 9 (resolved from images/screens)", got)
  559. }
  560. }
  561. func TestListAssetsToolKindFilter(t *testing.T) {
  562. cs, _ := newTestSession(t, false)
  563. res := callTool(t, cs, "list_assets", map[string]any{"folder": "images/screens", "kind": "IMAGE"})
  564. if res.IsError {
  565. t.Fatalf("IsError = true: %s", toolText(t, res))
  566. }
  567. var out listAssetsOutput
  568. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  569. t.Fatalf("decode result: %v", err)
  570. }
  571. if len(out.Assets) != 1 || out.Assets[0].Kind != "IMAGE" {
  572. t.Fatalf("assets = %+v, want only the IMAGE asset", out.Assets)
  573. }
  574. }
  575. func TestListAssetsToolInvalidKind(t *testing.T) {
  576. cs, _ := newTestSession(t, false)
  577. res := callTool(t, cs, "list_assets", map[string]any{"kind": "VIDEO"})
  578. if !res.IsError {
  579. t.Fatal("IsError = false, want error")
  580. }
  581. if !strings.Contains(toolText(t, res), "invalid kind") {
  582. t.Errorf("error = %q", toolText(t, res))
  583. }
  584. }
  585. func TestListAssetFoldersTool(t *testing.T) {
  586. cs, fake := newTestSession(t, false)
  587. res := callTool(t, cs, "list_asset_folders", map[string]any{"parentFolder": "images"})
  588. if res.IsError {
  589. t.Fatalf("IsError = true: %s", toolText(t, res))
  590. }
  591. var out listAssetFoldersOutput
  592. if err := json.Unmarshal([]byte(toolText(t, res)), &out); err != nil {
  593. t.Fatalf("decode result: %v", err)
  594. }
  595. if len(out.Folders) != 1 || out.Folders[0].Slug != "screens" {
  596. t.Fatalf("folders = %+v", out.Folders)
  597. }
  598. if got, want := out.Folders[0].Path, "images/screens"; got != want {
  599. t.Errorf("Path = %q, want %q", got, want)
  600. }
  601. req := fake.lastContaining(t, "query ListAssetFolders")
  602. if got := req.Variables["parentFolderId"]; got != float64(5) {
  603. t.Errorf("parentFolderId = %v, want 5 (resolved from images)", got)
  604. }
  605. }
  606. func TestCreateAssetFolderTool(t *testing.T) {
  607. cs, fake := newTestSession(t, true)
  608. res := callTool(t, cs, "create_asset_folder", map[string]any{"name": "Vacation 2025"})
  609. if res.IsError {
  610. t.Fatalf("IsError = true: %s", toolText(t, res))
  611. }
  612. req := fake.lastContaining(t, "mutation CreateAssetFolder")
  613. if got, want := req.Variables["slug"], "vacation-2025"; got != want {
  614. t.Errorf("slug = %v, want %q", got, want)
  615. }
  616. }
  617. func TestCreateAssetFolderToolFailure(t *testing.T) {
  618. cs, _ := newTestSession(t, true)
  619. res := callTool(t, cs, "create_asset_folder", map[string]any{"name": "fail"})
  620. if !res.IsError {
  621. t.Fatal("IsError = false, want error")
  622. }
  623. if !strings.Contains(toolText(t, res), "AssetFolderExists") {
  624. t.Errorf("error = %q", toolText(t, res))
  625. }
  626. }
  627. func TestCreateAssetFolderToolValidation(t *testing.T) {
  628. cs, _ := newTestSession(t, true)
  629. tests := []struct {
  630. name string
  631. args map[string]any
  632. want string
  633. }{
  634. {name: "empty name", args: map[string]any{"name": " "}, want: "name must not be empty"},
  635. {name: "bad parent", args: map[string]any{"name": "x", "parentFolder": "im ages"}, want: "invalid asset folder"},
  636. }
  637. for _, tc := range tests {
  638. t.Run(tc.name, func(t *testing.T) {
  639. res := callTool(t, cs, "create_asset_folder", tc.args)
  640. if !res.IsError {
  641. t.Fatalf("IsError = false, want error containing %q", tc.want)
  642. }
  643. if !strings.Contains(toolText(t, res), tc.want) {
  644. t.Errorf("error text %q does not contain %q", toolText(t, res), tc.want)
  645. }
  646. })
  647. }
  648. }