Files
ipal-kit/test/mcp.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 6b2c9b3cc6 Search leaves out the 404 page: searchContent, the search route, MCP search_content
searchContent / listContent read Site settings once (depth 0, homepage + notFound)
and skip unlistedPageIds; createSearchRoute and the MCP route pass settingsSlug.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:31:43 +01:00

140 lines
6.3 KiB
TypeScript

import type { BasePayload } from 'payload'
import { afterEach, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { createSearchRoute } from '../src/modules/content/createSearchRoute.js'
import { createMcpRoute } from '../src/modules/mcp/createMcpRoute.js'
const config: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const pages = [
{ id: 1, slug: 'o-nas', _status: 'published', meta: { description: 'Kim jesteśmy' }, title: 'O nas' },
{ id: 2, slug: 'szkic', _status: 'draft', title: 'Szkic' },
{ id: 3, slug: 'ukryta', _status: 'published', noindex: true, title: 'Ukryta' },
{ id: 4, slug: 'strona-glowna', _status: 'published', title: 'Start' },
]
const payload = {
find: vi.fn(async () => ({ docs: pages })),
findGlobal: vi.fn(async () => ({
homepage: { id: 4, slug: 'strona-glowna' },
siteDescription: 'Usługi IT',
siteName: 'Acme',
})),
} as unknown as BasePayload
let n = 0
const mcp = createMcpRoute({ baseUrl: 'https://acme.pl/', config, getCachedPayload: async () => payload })
async function rpc(body: unknown, ip = `10.1.0.${++n}`) {
const res = await mcp.POST(
new Request('https://acme.pl/api/mcp', {
body: JSON.stringify(body),
headers: { 'content-type': 'application/json', 'x-real-ip': ip },
method: 'POST',
}),
)
return { body: res.status === 202 ? null : await res.json(), status: res.status }
}
const call = async (name: string, args: Record<string, unknown> = {}) => {
const { body } = await rpc({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name, arguments: args } })
return (body as { result: { content: { text: string }[]; isError?: boolean } }).result
}
describe('createMcpRoute', () => {
afterEach(() => vi.clearAllMocks())
test('initialize + tools/list advertise the four read-only tools', async () => {
const init = await rpc({ id: 1, jsonrpc: '2.0', method: 'initialize', params: { protocolVersion: '2025-06-18' } })
expect(init.body.result.capabilities.tools).toBeDefined()
const list = await rpc({ id: 2, jsonrpc: '2.0', method: 'tools/list' })
expect(list.body.result.tools.map((t: { name: string }) => t.name)).toEqual([
'get_site_info',
'list_pages',
'search_content',
'get_page',
])
})
test('get_site_info: name, description, languages, home URL', async () => {
const text = (await call('get_site_info')).content[0].text
expect(text).toContain('Site: Acme')
expect(text).toContain('Description: Usługi IT')
expect(text).toContain('pl (Polski), en (English) — default pl')
expect(text).toContain('Home: https://acme.pl/pl')
expect(text).toContain('Sitemap: https://acme.pl/sitemap.xml')
})
test('list_pages: only published, indexable pages; home collapses to the root', async () => {
const text = (await call('list_pages')).content[0].text
expect(text).toContain('- O nas (https://acme.pl/pl/o-nas) — Kim jesteśmy')
expect(text).toContain('- Start (https://acme.pl/pl)')
expect(text).not.toContain('Szkic')
expect(text).not.toContain('Ukryta')
})
test('search_content needs a query', async () => {
expect((await call('search_content')).content[0].text).toBe('No query provided.')
expect((await call('search_content', { query: 'nas' })).content[0].text).toContain('O nas')
})
test('search_content and the search route leave out the page assigned as the 404 page', async () => {
const withNotFound = [...pages, { id: 5, slug: 'nie-znaleziono', _status: 'published', title: 'Nie znaleziono nas' }]
;(payload.find as ReturnType<typeof vi.fn>).mockResolvedValue({ docs: withNotFound })
;(payload.findGlobal as ReturnType<typeof vi.fn>).mockResolvedValue({ homepage: 4, notFound: 5, siteName: 'Acme' })
const text = (await call('search_content', { query: 'nas' })).content[0].text
expect(text).toContain('O nas')
expect(text).not.toContain('nie-znaleziono')
// The site search route uses the same searchContent.
const search = createSearchRoute({ config, getCachedPayload: async () => payload, rateLimit: false })
const body = (await (await search(new Request('https://acme.pl/api/search?q=nas'))).json()) as { results: { slug: string }[] }
// (the fake find ignores the query, so every published page comes back — except the 404 page)
expect(body.results.map((r) => r.slug)).toEqual(['o-nas', 'strona-glowna'])
;(payload.find as ReturnType<typeof vi.fn>).mockResolvedValue({ docs: pages })
})
test('tool errors stay generic (no internals leak)', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
;(payload.find as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('ECONNREFUSED db:5432'))
const res = await call('get_page', { path: '/pl/o-nas' })
expect(res.isError).toBe(true)
expect(res.content[0].text).toBe('Tool execution failed.')
})
test('protocol edges: notifications, unknown method, parse error, batch cap', async () => {
expect((await rpc({ jsonrpc: '2.0', method: 'notifications/initialized' })).status).toBe(202)
expect((await rpc({ id: 9, jsonrpc: '2.0', method: 'nope' })).body.error.code).toBe(-32601)
const bad = await mcp.POST(new Request('https://acme.pl/api/mcp', { body: '{', method: 'POST' }))
expect(bad.status).toBe(400)
const batch = Array.from({ length: 11 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'ping' }))
expect((await rpc(batch)).status).toBe(400)
expect((await mcp.GET()).status).toBe(405)
})
test('a null, number or string message gets Invalid Request, not a 500', async () => {
for (const body of [null, 42, 'x']) {
const res = await rpc(body)
expect(res.status).toBe(200)
expect(res.body.error.code).toBe(-32600)
}
const batch = await rpc([null, { id: 2, jsonrpc: '2.0', method: 'ping' }])
expect(batch.body.map((m: { error?: { code: number } }) => m.error?.code ?? 'ok')).toEqual([-32600, 'ok'])
})
test('rate limit counts every message in a batch', async () => {
const ip = '10.9.9.9'
const batch = Array.from({ length: 10 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'ping' }))
for (let i = 0; i < 6; i++) {expect((await rpc(batch, ip)).status).toBe(200)}
expect((await rpc(batch, ip)).status).toBe(429)
})
})