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:
batmanisko committed 2026-11-12 10:27:48 +01:00
1 parent 3c08f71f63
commit ccc19e5ff4
9 files changed
+575 -5

No files matched your search

+7
View File
@@ -32,6 +32,7 @@ import butterflyRoutes from "./routes/butterflyRoutes";
import { getConfettiCharacters, getConfettiImage, getHellGirlImages } from "./confetti";
import { getTrustedRemoteUser, parseTrustedIps } from "./trustedHeaders";
import { getGroupLimits } from "./limits";
import { assertMcpConfig, handleMcpRequest, mcpMethodNotAllowed } from "./mcp";
const ENVIRONMENT = process.env.NODE_ENV ?? 'production';
dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });
@@ -39,6 +40,7 @@ dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });
if (!process.env.JWT_SECRET) {
throw new Error("Není vyplněna proměnná prostředí JWT_SECRET");
}
assertMcpConfig();
const app = express();
const server = require("http").createServer(app);
@@ -242,6 +244,11 @@ app.get("/api/confetti/image/:id", async (req, res, next) => {
} catch (e: any) { next(e); }
});
// ─── MCP pro AI agenty — vlastní token (MCP_TOKEN), nezávislý na JWT i hlavičkách z proxy ───
app.post("/mcp", handleMcpRequest);
app.all("/mcp", mcpMethodNotAllowed);
// ─── Auth middleware ──────────────────────────────────────────────────────────
app.use("/api/", (req, res, next) => {
+165
View File
@@ -0,0 +1,165 @@
import crypto from "crypto";
import type { NextFunction, Request, Response } from "express";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";
import { Restaurant, RestaurantDayMenu } from "../../types/gen/types.gen";
import { getActiveRestaurants, getDateForWeekIndex, getRestaurantMenu, getToday } from "./service";
import { CHOICE_NAMES } from "./userExport";
import { formatDate, getHumanDate, getIsWeekend } from "./utils";
/**
* MCP server pro AI agenty (např. Claude Code) — jen čtení menu.
*
* Agent je samostatný klient: ověřuje se vlastním tokenem z MCP_TOKEN, ne JWT webové aplikace
* ani hlavičkou z proxy. Token proto nefunguje na /api a webový JWT nefunguje na /mcp.
* Endpoint je bezstavový (nový server pro každý požadavek), takže nevadí více replik.
*/
const MIN_TOKEN_LENGTH = 32;
/** Ověří konfiguraci MCP při startu serveru. Krátký token je chyba konfigurace — server nenaběhne. */
export function assertMcpConfig() {
const token = process.env.MCP_TOKEN;
if (token && token.length < MIN_TOKEN_LENGTH) {
throw new Error(`Proměnná prostředí MCP_TOKEN musí být minimálně ${MIN_TOKEN_LENGTH} znaků`);
}
}
/** Vrátí token MCP klienta, nebo undefined, pokud MCP není zapnuté (nebo je token příliš krátký). */
function getMcpToken(): string | undefined {
const token = process.env.MCP_TOKEN;
return token && token.length >= MIN_TOKEN_LENGTH ? token : undefined;
}
/** Porovná Bearer token z požadavku s MCP_TOKEN v konstantním čase (hashe mají stejnou délku). */
function isAuthorized(req: Request, expected: string): boolean {
const header = req.headers.authorization;
if (!header?.startsWith('Bearer ')) return false;
const sha256 = (value: string) => crypto.createHash('sha256').update(value).digest();
return crypto.timingSafeEqual(sha256(header.slice('Bearer '.length)), sha256(expected));
}
/**
* Určí den pro výpis menu — stejná pravidla jako GET /api/data: konkrétní datum má přednost
* a budoucnost se ořízne na dnešek, index dne se bere v aktuálním týdnu, o víkendu bez parametrů pátek.
*/
function resolveDate(date?: string, dayIndex?: number): Date {
if (date) {
const parsed = new Date(`${date}T00:00:00`);
if (isNaN(parsed.getTime())) {
throw new Error('Neplatné datum');
}
return parsed.getTime() > getToday().getTime() ? getToday() : parsed;
}
if (dayIndex != null) {
return getDateForWeekIndex(dayIndex);
}
return getIsWeekend(getToday()) ? getDateForWeekIndex(4) : getToday();
}
/** Zformátuje menu jednoho podniku do čitelného textu pro agenta. */
function formatRestaurantMenu(restaurant: Restaurant, menu?: RestaurantDayMenu): string {
const heading = `## ${CHOICE_NAMES[restaurant]} (${restaurant})`;
if (!menu) {
return `${heading}\nMenu se nepodařilo načíst.`;
}
if (menu.closed) {
return `${heading}\nZavřeno.`;
}
if (!menu.food?.length) {
return `${heading}\nMenu zatím není k dispozici.`;
}
const lines = menu.food.map(food => {
const parts = [food.isSoup ? `[polévka] ${food.name}` : food.name];
if (food.amount && food.amount !== '-') parts.push(food.amount);
if (food.price) parts.push(food.price);
const allergens = food.allergens?.length ? ` (alergeny: ${food.allergens.join(', ')})` : '';
return `- ${parts.join(' — ')}${allergens}`;
});
if (menu.isStale) {
lines.push('Pozor: menu může pocházet z jiného týdne.');
}
for (const warning of menu.warnings ?? []) {
lines.push(`Upozornění: ${warning}`);
}
return [heading, ...lines].join('\n');
}
/** Vytvoří MCP server s nástroji pro čtení menu. */
export function createMcpServer(): McpServer {
const server = new McpServer({ name: 'luncher', version: '1.0.0' });
const activeRestaurants = getActiveRestaurants();
server.registerTool('list_restaurants', {
title: 'Seznam podniků',
description: 'Vrátí podniky, pro které Luncher stahuje denní obědová menu (identifikátor a název).',
annotations: { readOnlyHint: true, openWorldHint: false },
}, async () => ({
content: [{
type: 'text',
text: activeRestaurants.map(r => `- ${r}: ${CHOICE_NAMES[r]}`).join('\n'),
}],
}));
server.registerTool('get_menus', {
title: 'Denní menu',
description: 'Vrátí obědová menu podniků pro daný den (jídla, gramáž, ceny, alergeny). '
+ 'Bez parametrů vrátí dnešek (o víkendu pátek). Budoucí datum se ořízne na dnešek.',
inputSchema: {
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()
.describe('Konkrétní den ve formátu YYYY-MM-DD; má přednost před dayIndex'),
dayIndex: z.number().int().min(0).max(4).optional()
.describe('Den v aktuálním týdnu: 0 = pondělí … 4 = pátek'),
restaurant: z.enum(activeRestaurants as [Restaurant, ...Restaurant[]]).optional()
.describe('Jen jeden podnik (identifikátor z list_restaurants); bez něj všechny'),
},
annotations: { readOnlyHint: true, openWorldHint: false },
}, async ({ date, dayIndex, restaurant }) => {
const usedDate = resolveDate(date, dayIndex);
const sections = [`# Menu na ${getHumanDate(usedDate)} (${formatDate(usedDate)})`];
// Postupně, ne paralelně — getRestaurantMenu zapisuje do sdíleného týdenního záznamu
for (const r of restaurant ? [restaurant] : activeRestaurants) {
const menu = await getRestaurantMenu(r, usedDate).catch((e: any) => {
console.error(`MCP: nepodařilo se načíst menu ${r}`, e);
return undefined;
});
sections.push(formatRestaurantMenu(r, menu));
}
return { content: [{ type: 'text', text: sections.join('\n\n') }] };
});
return server;
}
/** POST /mcp — ověří MCP klienta a obslouží JSON-RPC požadavek v bezstavovém režimu. */
export async function handleMcpRequest(req: Request, res: Response, next: NextFunction) {
const token = getMcpToken();
if (!token) {
return res.status(404).json({ error: 'MCP není na tomto serveru zapnuté' });
}
if (!isAuthorized(req, token)) {
return res.status(401).json({ error: 'Neplatný MCP token' });
}
const server = createMcpServer();
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
res.on('close', () => {
transport.close();
server.close();
});
try {
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
} catch (e: any) {
next(e);
}
}
/** Ostatní metody na /mcp — bezstavový server nenabízí SSE stream (GET) ani ukončení session (DELETE). */
export function mcpMethodNotAllowed(_req: Request, res: Response) {
res.status(405).set('Allow', 'POST').json({
jsonrpc: '2.0',
error: { code: -32000, message: 'Metoda není povolena' },
id: null,
});
}
+153
View File
@@ -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();
});
});
+1 -1
View File
@@ -9,7 +9,7 @@ const storage = getStorage();
const DAY_OF_WEEK_FORMAT = new Intl.DateTimeFormat('cs-CZ', { weekday: 'long' });
/** Lidsky čitelné názvy voleb stravování (serverová obdoba klientského enums.ts). */
const CHOICE_NAMES: Record<LunchChoice, string> = {
export const CHOICE_NAMES: Record<LunchChoice, string> = {
SLADOVNICKA: 'Sladovnická',
TECHTOWER: 'TechTower',
ZASTAVKAUMICHALA: 'Zastávka u Michala',