Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
434 lines (390 loc) · 15.7 KB
/
Copy pathserver.js
File metadata and controls
434 lines (390 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
const express = require("express");
const cors = require("cors");
const app = express();
const PORT = Number(process.env.PORT || 10000);
const MCP_SERVER_NAME = process.env.MCP_SERVER_NAME || "bitespy-main-mcp";
const MCP_SERVER_VERSION = process.env.MCP_SERVER_VERSION || "1.0.0";
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const MCP_ALLOWED_ORIGIN = process.env.MCP_ALLOWED_ORIGIN || "*";
const MCP_MODEL = process.env.MCP_MODEL || "gemini-2.5-flash-lite";
const TOOL_NAMES = [
"scan_product",
"ingredient_extractor",
"question_generator",
"analyze_claims",
"verdict_engine",
"alternate_products",
"generate_json",
];
const TOOL_POLICIES = {
ingredient_extractor: {
denyWhen: (args) => Boolean(args?.dbWrite || args?.persist || args?.rawSql || args?.rawQuery),
denyReason: "ingredient_extractor is extraction-only and cannot write to DB or run raw queries.",
},
verdict_engine: {
denyWhen: (args) => Boolean(args?.dbWrite || args?.persistVerdict || args?.storeVerdict),
denyReason: "verdict_engine cannot persist misconception flags yet; DB write path is disabled for now.",
},
alternate_products: {
denyWhen: (args) => Boolean(args?.dbWrite || args?.persistRecommendations),
denyReason: "alternate_products is read/generation only and cannot persist recommendations yet.",
},
};
app.use(cors({ origin: MCP_ALLOWED_ORIGIN === "*" ? true : MCP_ALLOWED_ORIGIN }));
app.use(express.json({ limit: "12mb" }));
function sseSend(res, payload) {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.status(200).write(`event: message\ndata: ${JSON.stringify(payload)}\n\n`);
res.end();
}
function jsonRpcError(id, code, message, data) {
return {
jsonrpc: "2.0",
id: id ?? null,
error: {
code,
message,
data: data || null,
},
};
}
function jsonRpcResult(id, result) {
return {
jsonrpc: "2.0",
id,
result,
};
}
function extractJsonPayload(raw) {
const fenced = raw.match(/```json\s*([\s\S]*?)```/i);
if (fenced && fenced[1]) {
return fenced[1].trim();
}
const firstBrace = raw.indexOf("{");
const lastBrace = raw.lastIndexOf("}");
if (firstBrace >= 0 && lastBrace > firstBrace) {
return raw.slice(firstBrace, lastBrace + 1);
}
throw new Error("Model response did not include valid JSON.");
}
async function callGeminiJson(prompt, inlineData, model) {
if (!GEMINI_API_KEY) {
throw new Error("Missing GEMINI_API_KEY in MCP server environment.");
}
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/${model || MCP_MODEL}:generateContent?key=${GEMINI_API_KEY}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
contents: [
{
role: "user",
parts: inlineData
? [
{ text: prompt },
{
inlineData: {
mimeType: inlineData.mimeType,
data: inlineData.data,
},
},
]
: [{ text: prompt }],
},
],
generationConfig: {
temperature: 0.2,
responseMimeType: "application/json",
},
}),
}
);
if (!response.ok) {
const body = await response.text();
throw new Error(`Gemini request failed (${response.status}): ${body}`);
}
const payload = await response.json();
const rawText = (payload.candidates || [])
.flatMap((candidate) => ((candidate.content && candidate.content.parts) || []))
.map((part) => part.text || "")
.join("\n")
.trim();
if (!rawText) {
throw new Error("Gemini returned empty content.");
}
const jsonText = extractJsonPayload(rawText);
return JSON.parse(jsonText);
}
function toolsList() {
return {
tools: [
{
name: "scan_product",
description: "Analyze product image or product prompt and return structured product JSON for scan flow.",
inputSchema: {
type: "object",
properties: {
prompt: { type: "string", description: "Detailed task prompt for product scan." },
model: { type: "string", description: "Model identifier." },
inlineData: {
type: "object",
description: "Optional image payload for visual analysis.",
properties: {
mimeType: { type: "string" },
data: { type: "string" },
},
},
},
required: ["prompt"],
},
},
{
name: "ingredient_extractor",
description: "Extract structured ingredients, additives, and allergy signals from product evidence.",
inputSchema: {
type: "object",
properties: {
prompt: { type: "string", description: "Prompt asking for ingredient extraction JSON." },
ingredientText: { type: "string", description: "Optional raw ingredient string if available." },
model: { type: "string", description: "Model identifier." },
inlineData: {
type: "object",
description: "Optional image payload when extracting from image directly.",
properties: {
mimeType: { type: "string" },
data: { type: "string" },
},
},
},
required: ["prompt"],
},
},
{
name: "question_generator",
description: "Generate concise health, allergy, and preference questions from ingredient context.",
inputSchema: {
type: "object",
properties: {
prompt: { type: "string", description: "Prompt requesting question generation JSON." },
productContext: {
type: "object",
description: "Optional product context to steer question quality.",
},
model: { type: "string", description: "Model identifier." },
},
required: ["prompt"],
},
},
{
name: "analyze_claims",
description: "Analyze product claims and output structured JSON with rating, risks, and alternatives.",
inputSchema: {
type: "object",
properties: {
prompt: { type: "string", description: "Detailed analysis prompt with scan and answer context." },
model: { type: "string", description: "Model identifier." },
inlineData: {
type: "object",
properties: {
mimeType: { type: "string" },
data: { type: "string" },
},
},
},
required: ["prompt"],
},
},
{
name: "verdict_engine",
description: "Create deterministic-style verdict payload and misconception flags (generation only, no DB writes).",
inputSchema: {
type: "object",
properties: {
prompt: { type: "string", description: "Prompt requesting verdict output JSON." },
scoreCard: { type: "object", description: "Optional score context for verdict composition." },
model: { type: "string", description: "Model identifier." },
},
required: ["prompt"],
},
},
{
name: "alternate_products",
description: "Generate relevant alternatives using product context, user profile, and recent conversation context.",
inputSchema: {
type: "object",
properties: {
prompt: { type: "string", description: "Prompt requesting alternatives JSON." },
userProfile: { type: "object", description: "User preferences/allergies/health goals." },
recentConversation: {
type: "array",
description: "Recent conversation snippets to avoid irrelevant alternatives.",
},
model: { type: "string", description: "Model identifier." },
},
required: ["prompt"],
},
},
{
name: "generate_json",
description: "Generic JSON generator tool for fallback or extension use.",
inputSchema: {
type: "object",
properties: {
prompt: { type: "string", description: "Prompt requesting JSON output." },
model: { type: "string", description: "Model identifier." },
inlineData: {
type: "object",
properties: {
mimeType: { type: "string" },
data: { type: "string" },
},
},
},
required: ["prompt"],
},
},
],
};
}
function applyToolPolicy(name, args) {
const policy = TOOL_POLICIES[name];
if (!policy) {
return;
}
if (policy.denyWhen(args)) {
throw new Error(policy.denyReason);
}
}
function toolSpecificPrompt(name, prompt, args) {
if (name === "ingredient_extractor") {
const ingredientText = typeof args.ingredientText === "string" ? args.ingredientText.trim() : "";
return [
"Return strict JSON only. Extract ingredients, additive flags, allergy signals, and confidence notes.",
ingredientText ? `Ingredient text input:\n${ingredientText}` : "",
prompt,
].filter(Boolean).join("\n\n");
}
if (name === "question_generator") {
const productContext = args.productContext ? JSON.stringify(args.productContext) : "";
return [
"Return strict JSON only. Questions must be concise, non-repetitive, and useful for health/allergy/preference decisions.",
productContext ? `Product context:\n${productContext}` : "",
prompt,
].filter(Boolean).join("\n\n");
}
if (name === "verdict_engine") {
const scoreCard = args.scoreCard ? JSON.stringify(args.scoreCard) : "";
return [
"Return strict JSON only. Include verdict, misconception flags, reasons, and confidence. Do not include DB operations.",
scoreCard ? `Score context:\n${scoreCard}` : "",
prompt,
].filter(Boolean).join("\n\n");
}
if (name === "alternate_products") {
const profile = args.userProfile ? JSON.stringify(args.userProfile) : "{}";
const recentConversation = Array.isArray(args.recentConversation)
? JSON.stringify(args.recentConversation.slice(-8))
: "[]";
return [
"Return strict JSON only. Provide meaningful alternatives based on user profile and recent conversation. Avoid generic or irrelevant suggestions.",
`User profile:\n${profile}`,
`Recent conversation:\n${recentConversation}`,
prompt,
].join("\n\n");
}
return prompt;
}
async function executeTool(name, args) {
if (!TOOL_NAMES.includes(name)) {
throw new Error(`Unknown tool: ${name}`);
}
applyToolPolicy(name, args || {});
const prompt = typeof args.prompt === "string" ? args.prompt : "";
if (!prompt.trim()) {
throw new Error("Missing required argument: prompt");
}
const model = typeof args.model === "string" && args.model.trim() ? args.model.trim() : MCP_MODEL;
const inlineData = args.inlineData && args.inlineData.mimeType && args.inlineData.data
? {
mimeType: String(args.inlineData.mimeType),
data: String(args.inlineData.data),
}
: undefined;
const enrichedPrompt = toolSpecificPrompt(name, prompt, args || {});
const result = await callGeminiJson(enrichedPrompt, inlineData, model);
return result;
}
app.get("/health", (_req, res) => {
res.status(200).json({
ok: true,
service: MCP_SERVER_NAME,
version: MCP_SERVER_VERSION,
});
});
app.get("/mcp", (_req, res) => {
res.status(200).json({
ok: true,
message: "MCP endpoint is alive. Use POST /mcp with JSON-RPC 2.0.",
supportedMethods: ["initialize", "tools/list", "tools/call"],
example: {
jsonrpc: "2.0",
id: 1,
method: "tools/list",
},
});
});
app.post("/mcp", async (req, res) => {
const body = req.body || {};
const id = body.id ?? null;
const method = body.method;
try {
if (method === "initialize") {
return sseSend(
res,
jsonRpcResult(id, {
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: {
name: MCP_SERVER_NAME,
version: MCP_SERVER_VERSION,
},
})
);
}
if (method === "tools/list") {
return sseSend(res, jsonRpcResult(id, toolsList()));
}
if (method === "tools/call") {
const params = body.params || {};
const toolName = params.name;
const toolArgs = params.arguments || {};
if (!toolName || typeof toolName !== "string") {
return sseSend(res, jsonRpcError(id, -32602, "Invalid params: missing tool name"));
}
const result = await executeTool(toolName, toolArgs);
return sseSend(
res,
jsonRpcResult(id, {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
})
);
}
return sseSend(res, jsonRpcError(id, -32601, `Method not found: ${method}`));
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return sseSend(res, jsonRpcError(id, -32000, message));
}
});
app.listen(PORT, () => {
console.log(`[MCP] ${MCP_SERVER_NAME} listening on port ${PORT}`);
});