feat: MCP server pro AI agenty (čtení menu)
POST /mcp (bezstavový Streamable HTTP) s nástroji list_restaurants a get_menus. Agent je samostatný klient: ověřuje se jen tokenem MCP_TOKEN, ne webovým JWT ani hlavičkou z proxy; token nefunguje na /api. Bez MCP_TOKEN je MCP vypnuté, kratší token než 32 znaků = server nenaběhne.
This commit is contained in:
9 files changed
+575
-5
No files matched your search
@@ -0,0 +1,153 @@
|
||||
const mockGetRestaurantMenu = jest.fn();
|
||||
jest.mock('../service', () => ({
|
||||
...jest.requireActual('../service'),
|
||||
getRestaurantMenu: (...args: any[]) => mockGetRestaurantMenu(...args),
|
||||
}));
|
||||
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
import bodyParser from 'body-parser';
|
||||
import { generateToken, verify } from '../auth';
|
||||
import { assertMcpConfig, handleMcpRequest, mcpMethodNotAllowed } from '../mcp';
|
||||
import { formatDate } from '../utils';
|
||||
|
||||
const MCP_TOKEN = 'mcp-token-ktery-ma-taky-alespon-32-znaku';
|
||||
|
||||
function buildApp() {
|
||||
const app = express();
|
||||
app.use(bodyParser.json());
|
||||
app.post('/mcp', handleMcpRequest);
|
||||
app.all('/mcp', mcpMethodNotAllowed);
|
||||
return app;
|
||||
}
|
||||
|
||||
/** Odešle JSON-RPC požadavek na /mcp s předaným tokenem. */
|
||||
function rpc(method: string, params: object = {}, token: string | null = MCP_TOKEN) {
|
||||
const req = request(buildApp())
|
||||
.post('/mcp')
|
||||
.set('Accept', 'application/json, text/event-stream')
|
||||
.set('Content-Type', 'application/json');
|
||||
if (token) req.set('Authorization', `Bearer ${token}`);
|
||||
return req.send({ jsonrpc: '2.0', id: 1, method, params });
|
||||
}
|
||||
|
||||
const callTool = (name: string, args: object = {}) => rpc('tools/call', { name, arguments: args });
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.MCP_TOKEN = MCP_TOKEN;
|
||||
mockGetRestaurantMenu.mockReset();
|
||||
mockGetRestaurantMenu.mockResolvedValue({
|
||||
lastUpdate: Date.now(),
|
||||
closed: false,
|
||||
food: [
|
||||
{ amount: '0,33l', name: 'Hovězí vývar', price: '35 Kč', isSoup: true, allergens: [1, 9] },
|
||||
{ amount: '150g', name: 'Svíčková na smetaně', price: '169 Kč', isSoup: false },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
delete process.env.MCP_TOKEN;
|
||||
});
|
||||
|
||||
describe('ověření MCP klienta', () => {
|
||||
test('bez MCP_TOKEN je MCP vypnuté (404)', async () => {
|
||||
delete process.env.MCP_TOKEN;
|
||||
const res = await rpc('tools/list');
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
test('požadavek bez tokenu vrátí 401', async () => {
|
||||
const res = await rpc('tools/list', {}, null);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
test('špatný token vrátí 401', async () => {
|
||||
const res = await rpc('tools/list', {}, 'x'.repeat(40));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
test('webový JWT na /mcp nefunguje', async () => {
|
||||
const res = await rpc('tools/list', {}, generateToken('testuser'));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
test('MCP token není platný webový JWT (na /api nefunguje)', () => {
|
||||
expect(verify(MCP_TOKEN)).toBe(false);
|
||||
});
|
||||
|
||||
test('příliš krátký MCP_TOKEN je chyba konfigurace', () => {
|
||||
process.env.MCP_TOKEN = 'kratky';
|
||||
expect(() => assertMcpConfig()).toThrow();
|
||||
});
|
||||
|
||||
test('GET /mcp vrátí 405', async () => {
|
||||
const res = await request(buildApp())
|
||||
.get('/mcp')
|
||||
.set('Authorization', `Bearer ${MCP_TOKEN}`);
|
||||
expect(res.status).toBe(405);
|
||||
});
|
||||
});
|
||||
|
||||
describe('nástroje', () => {
|
||||
test('tools/list nabízí jen čtecí nástroje', async () => {
|
||||
const res = await rpc('tools/list');
|
||||
expect(res.status).toBe(200);
|
||||
const tools = res.body.result.tools;
|
||||
expect(tools.map((t: any) => t.name).sort()).toEqual(['get_menus', 'list_restaurants']);
|
||||
expect(tools.every((t: any) => t.annotations?.readOnlyHint === true)).toBe(true);
|
||||
});
|
||||
|
||||
test('list_restaurants vrátí aktivní podniky', async () => {
|
||||
const res = await callTool('list_restaurants');
|
||||
const text = res.body.result.content[0].text;
|
||||
expect(text).toContain('SLADOVNICKA: Sladovnická');
|
||||
// Dočasně vyřazený podnik se nenabízí
|
||||
expect(text).not.toContain('SENKSERIKOVA');
|
||||
});
|
||||
|
||||
test('get_menus pro konkrétní den vrátí menu všech aktivních podniků', async () => {
|
||||
const res = await callTool('get_menus', { date: '2025-01-08' });
|
||||
expect(res.status).toBe(200);
|
||||
const text = res.body.result.content[0].text;
|
||||
expect(text).toContain('(2025-01-08)');
|
||||
expect(text).toContain('## Sladovnická (SLADOVNICKA)');
|
||||
expect(text).toContain('- [polévka] Hovězí vývar — 0,33l — 35 Kč (alergeny: 1, 9)');
|
||||
expect(text).toContain('- Svíčková na smetaně — 150g — 169 Kč');
|
||||
expect(mockGetRestaurantMenu).toHaveBeenCalledTimes(3);
|
||||
expect(formatDate(mockGetRestaurantMenu.mock.calls[0][1])).toBe('2025-01-08');
|
||||
});
|
||||
|
||||
test('get_menus s filtrem podniku načte jen ten podnik', async () => {
|
||||
const res = await callTool('get_menus', { date: '2025-01-08', restaurant: 'TECHTOWER' });
|
||||
const text = res.body.result.content[0].text;
|
||||
expect(text).toContain('## TechTower (TECHTOWER)');
|
||||
expect(text).not.toContain('Sladovnická');
|
||||
expect(mockGetRestaurantMenu).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('budoucí datum se ořízne na dnešek', async () => {
|
||||
await callTool('get_menus', { date: '2099-01-01', restaurant: 'TECHTOWER' });
|
||||
expect(formatDate(mockGetRestaurantMenu.mock.calls[0][1])).toBe(formatDate(new Date()));
|
||||
});
|
||||
|
||||
test('zavřený podnik a chybějící menu se vypíšou srozumitelně', async () => {
|
||||
mockGetRestaurantMenu
|
||||
.mockResolvedValueOnce({ lastUpdate: 0, closed: true, food: [] })
|
||||
.mockResolvedValueOnce({ lastUpdate: 0, closed: false, food: [] })
|
||||
.mockRejectedValueOnce(new Error('scraper spadl'));
|
||||
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });
|
||||
const res = await callTool('get_menus', { date: '2025-01-08' });
|
||||
errorSpy.mockRestore();
|
||||
const text = res.body.result.content[0].text;
|
||||
expect(text).toContain('Zavřeno.');
|
||||
expect(text).toContain('Menu zatím není k dispozici.');
|
||||
expect(text).toContain('Menu se nepodařilo načíst.');
|
||||
});
|
||||
|
||||
test('neznámý podnik je chyba vstupu', async () => {
|
||||
const res = await callTool('get_menus', { restaurant: 'NEEXISTUJE' });
|
||||
expect(res.body.result.isError).toBe(true);
|
||||
expect(mockGetRestaurantMenu).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user