fodda-mcp 1.7.0 → 1.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +31 -0
- package/README.md +176 -18
- package/dist/a2aHandler.d.ts +20 -0
- package/dist/a2aHandler.d.ts.map +1 -0
- package/dist/a2aHandler.js +247 -0
- package/dist/a2aHandler.js.map +1 -0
- package/dist/agents/fodda-researcher/index.d.ts +35 -0
- package/dist/agents/fodda-researcher/index.d.ts.map +1 -0
- package/dist/agents/fodda-researcher/index.js +62 -0
- package/dist/agents/fodda-researcher/index.js.map +1 -0
- package/dist/agents/fodda-researcher/skills.d.ts +16 -0
- package/dist/agents/fodda-researcher/skills.d.ts.map +1 -0
- package/dist/agents/fodda-researcher/skills.js +163 -0
- package/dist/agents/fodda-researcher/skills.js.map +1 -0
- package/dist/brandTemplate.d.ts +14 -0
- package/dist/brandTemplate.d.ts.map +1 -0
- package/dist/brandTemplate.js +742 -0
- package/dist/brandTemplate.js.map +1 -0
- package/dist/catalogCache.d.ts +177 -0
- package/dist/catalogCache.d.ts.map +1 -0
- package/dist/catalogCache.js +708 -0
- package/dist/catalogCache.js.map +1 -0
- package/dist/editorialFill.d.ts +44 -0
- package/dist/editorialFill.d.ts.map +1 -0
- package/dist/editorialFill.js +377 -0
- package/dist/editorialFill.js.map +1 -0
- package/dist/enrichment.d.ts +74 -0
- package/dist/enrichment.d.ts.map +1 -0
- package/dist/enrichment.js +211 -0
- package/dist/enrichment.js.map +1 -0
- package/dist/errorHandling.d.ts +52 -0
- package/dist/errorHandling.d.ts.map +1 -0
- package/dist/errorHandling.js +327 -0
- package/dist/errorHandling.js.map +1 -0
- package/dist/index.d.ts +0 -1
- package/dist/index.js +595 -581
- package/dist/index.js.map +1 -1
- package/dist/pricingCache.d.ts +99 -0
- package/dist/pricingCache.d.ts.map +1 -0
- package/dist/pricingCache.js +414 -0
- package/dist/pricingCache.js.map +1 -0
- package/dist/queryCache.d.ts +25 -0
- package/dist/queryCache.d.ts.map +1 -0
- package/dist/queryCache.js +194 -0
- package/dist/queryCache.js.map +1 -0
- package/dist/searchTemplate.d.ts +16 -0
- package/dist/searchTemplate.d.ts.map +1 -0
- package/dist/searchTemplate.js +318 -0
- package/dist/searchTemplate.js.map +1 -0
- package/dist/sessionTracker.d.ts +39 -0
- package/dist/sessionTracker.d.ts.map +1 -0
- package/dist/sessionTracker.js +187 -0
- package/dist/sessionTracker.js.map +1 -0
- package/dist/skillClient.d.ts +142 -0
- package/dist/skillClient.d.ts.map +1 -0
- package/dist/skillClient.js +256 -0
- package/dist/skillClient.js.map +1 -0
- package/dist/svgVisuals.d.ts +77 -0
- package/dist/svgVisuals.d.ts.map +1 -0
- package/dist/svgVisuals.js +323 -0
- package/dist/svgVisuals.js.map +1 -0
- package/dist/systemPrompt.d.ts +26 -0
- package/dist/systemPrompt.d.ts.map +1 -0
- package/dist/systemPrompt.js +546 -0
- package/dist/systemPrompt.js.map +1 -0
- package/dist/test-waverunner-response.d.ts +2 -0
- package/dist/test-waverunner-response.d.ts.map +1 -0
- package/dist/test-waverunner-response.js +20 -0
- package/dist/test-waverunner-response.js.map +1 -0
- package/dist/test_analyst.d.ts +2 -0
- package/dist/test_analyst.d.ts.map +1 -0
- package/dist/test_analyst.js +39 -0
- package/dist/test_analyst.js.map +1 -0
- package/dist/test_analyst_local.d.ts +2 -0
- package/dist/test_analyst_local.d.ts.map +1 -0
- package/dist/test_analyst_local.js +51 -0
- package/dist/test_analyst_local.js.map +1 -0
- package/dist/test_live_mcp.js +1 -1
- package/dist/test_skills.d.ts +9 -0
- package/dist/test_skills.d.ts.map +1 -0
- package/dist/test_skills.js +267 -0
- package/dist/test_skills.js.map +1 -0
- package/dist/toolHandlers.d.ts +11 -0
- package/dist/toolHandlers.d.ts.map +1 -0
- package/dist/toolHandlers.js +2829 -0
- package/dist/toolHandlers.js.map +1 -0
- package/dist/tools.d.ts +78 -3
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +85 -292
- package/dist/tools.js.map +1 -1
- package/dist/trialTracker.d.ts +58 -0
- package/dist/trialTracker.d.ts.map +1 -0
- package/dist/trialTracker.js +179 -0
- package/dist/trialTracker.js.map +1 -0
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/verify_hmac.js +1 -1
- package/dist/verify_hmac.js.map +1 -1
- package/dist/verify_tools_endpoint.js +5 -5
- package/dist/verify_tools_endpoint.js.map +1 -1
- package/dist/widgetShell.d.ts +15 -0
- package/dist/widgetShell.d.ts.map +1 -0
- package/dist/widgetShell.js +151 -0
- package/dist/widgetShell.js.map +1 -0
- package/package.json +8 -4
- package/server.json +11 -2
package/dist/index.js
CHANGED
|
@@ -1,606 +1,620 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
3
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
-
import crypto from "crypto";
|
|
5
|
-
import { CallToolRequestSchema, ListToolsRequestSchema, isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
6
|
-
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
|
7
|
-
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
8
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
-
import express from "express";
|
|
10
|
-
import axios from "axios";
|
|
11
|
-
import * as dotenv from "dotenv";
|
|
12
|
-
import { TOOLS, MCP_SERVER_VERSION } from "./tools.js";
|
|
13
|
-
const requestContext = new AsyncLocalStorage();
|
|
14
|
-
dotenv.config();
|
|
15
|
-
const API_BASE_URL = process.env.FODDA_API_URL || "https://api.fodda.ai";
|
|
16
|
-
const IS_DEV = process.env.NODE_ENV === "development";
|
|
17
|
-
const DUMMY_API_KEY = "dummy-test-key";
|
|
18
|
-
const DUMMY_USER_ID = "dummy-test-user";
|
|
19
|
-
const server = new Server({
|
|
20
|
-
name: "fodda-mcp",
|
|
21
|
-
version: MCP_SERVER_VERSION,
|
|
22
|
-
}, {
|
|
23
|
-
capabilities: {
|
|
24
|
-
tools: {},
|
|
25
|
-
},
|
|
26
|
-
});
|
|
27
1
|
/**
|
|
28
|
-
*
|
|
2
|
+
* Fodda MCP Server — Clean Architecture
|
|
3
|
+
* Uses McpServer (high-level API) which is proven to work with Claude.
|
|
4
|
+
* NO middleware, NO AsyncLocalStorage, NO response interceptors.
|
|
5
|
+
* API key is extracted from URL query params and passed to tool handlers.
|
|
29
6
|
*/
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
7
|
+
import express from 'express';
|
|
8
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
9
|
+
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
|
|
10
|
+
import crypto from 'crypto';
|
|
11
|
+
import axios from 'axios';
|
|
12
|
+
import { initCatalogCache } from './catalogCache.js';
|
|
13
|
+
import { initPricingCache } from './pricingCache.js';
|
|
14
|
+
import { cacheGet, cacheSet, getCacheStats } from './queryCache.js';
|
|
15
|
+
import { MCP_SERVER_VERSION } from './tools.js';
|
|
16
|
+
import { createServer } from './toolHandlers.js';
|
|
17
|
+
import { checkTrialLimit, incrementTrialUsage } from './trialTracker.js';
|
|
18
|
+
import { registerA2ARoute } from './a2aHandler.js';
|
|
19
|
+
import * as dotenv from 'dotenv';
|
|
20
|
+
dotenv.config();
|
|
21
|
+
const API_BASE_URL = process.env.FODDA_API_URL || 'https://api.fodda.ai';
|
|
22
|
+
const app = express();
|
|
23
|
+
app.use(express.json({ limit: '512kb' }));
|
|
24
|
+
// CORS — minimal, matching test server
|
|
25
|
+
app.use((req, res, next) => {
|
|
26
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
27
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
|
|
28
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-API-Key, X-User-Id, Mcp-Session-Id, Accept');
|
|
29
|
+
res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id');
|
|
30
|
+
if (req.method === 'OPTIONS')
|
|
31
|
+
return res.status(204).end();
|
|
32
|
+
next();
|
|
34
33
|
});
|
|
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
|
-
const
|
|
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
|
-
isError: true,
|
|
90
|
-
content: [{ type: "text", text: JSON.stringify({ error: { code: "UNAUTHORIZED", message: "No Authorization metadata provided.", requestId } }) }],
|
|
91
|
-
};
|
|
92
|
-
}
|
|
34
|
+
// OAuth discovery endpoints — return 404 to indicate no OAuth support
|
|
35
|
+
app.get('/.well-known/oauth-protected-resource', (_req, res) => {
|
|
36
|
+
res.status(404).json({ error: 'OAuth not supported. Use API key auth via URL: ?api_key=YOUR_KEY' });
|
|
37
|
+
});
|
|
38
|
+
app.get('/.well-known/oauth-protected-resource/:path', (_req, res) => {
|
|
39
|
+
res.status(404).json({ error: 'OAuth not supported.' });
|
|
40
|
+
});
|
|
41
|
+
app.get('/.well-known/oauth-authorization-server', (_req, res) => {
|
|
42
|
+
res.status(404).json({ error: 'OAuth not supported.' });
|
|
43
|
+
});
|
|
44
|
+
app.post('/register', (_req, res) => {
|
|
45
|
+
res.status(404).json({ error: 'OAuth not supported.' });
|
|
46
|
+
});
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
// Widget cache — stores pre-rendered HTML for browser access
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
const widgetCache = new Map();
|
|
51
|
+
const WIDGET_TTL_MS = 30 * 60 * 1000; // 30 minutes
|
|
52
|
+
function storeWidget(html) {
|
|
53
|
+
const id = crypto.randomUUID();
|
|
54
|
+
widgetCache.set(id, { html, createdAt: Date.now() });
|
|
55
|
+
return id;
|
|
56
|
+
}
|
|
57
|
+
// Widget serving endpoint — returns cached pre-rendered HTML
|
|
58
|
+
app.get('/widget/:id', (req, res) => {
|
|
59
|
+
const entry = widgetCache.get(req.params.id);
|
|
60
|
+
if (!entry)
|
|
61
|
+
return res.status(404).send('<html><body><p>Widget expired or not found.</p></body></html>');
|
|
62
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
63
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
64
|
+
// Wrap in full HTML document for iframe rendering
|
|
65
|
+
res.send(`<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;}</style></head><body>${entry.html}</body></html>`);
|
|
66
|
+
});
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
// Session management
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
const transports = new Map();
|
|
71
|
+
const sessionApiKeys = new Map();
|
|
72
|
+
const sessionUserIds = new Map();
|
|
73
|
+
const sessionSources = new Map();
|
|
74
|
+
// Track session creation time in our own Map (transport._createdAt is a private
|
|
75
|
+
// field that is never set by the SDK — reading it always yields undefined).
|
|
76
|
+
const sessionCreatedAt = new Map();
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
// Periodic cleanup — prevent unbounded memory growth
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
const CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
|
|
81
|
+
const SESSION_MAX_AGE_MS = 60 * 60 * 1000; // 1 hour
|
|
82
|
+
setInterval(() => {
|
|
83
|
+
const now = Date.now();
|
|
84
|
+
// Sweep expired widgets
|
|
85
|
+
for (const [id, entry] of widgetCache) {
|
|
86
|
+
if (now - entry.createdAt > WIDGET_TTL_MS)
|
|
87
|
+
widgetCache.delete(id);
|
|
93
88
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
89
|
+
// Sweep stale sessions using our own creation-time Map
|
|
90
|
+
for (const [sid] of transports) {
|
|
91
|
+
const created = sessionCreatedAt.get(sid);
|
|
92
|
+
if (created && now - created > SESSION_MAX_AGE_MS) {
|
|
93
|
+
transports.delete(sid);
|
|
94
|
+
sessionApiKeys.delete(sid);
|
|
95
|
+
sessionUserIds.delete(sid);
|
|
96
|
+
sessionSources.delete(sid);
|
|
97
|
+
sessionCreatedAt.delete(sid);
|
|
103
98
|
}
|
|
104
99
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const isInternalKey = process.env.INTERNAL_TEST_KEYS?.split(',').includes(apiKey || "");
|
|
124
|
-
const isProduction = process.env.NODE_ENV === "production";
|
|
125
|
-
if (isProduction && !isInternalKey) {
|
|
126
|
-
// In production, matching keys are required to use simulation.
|
|
127
|
-
// If not internal key, we pretend simulation doesn't exist or return error?
|
|
128
|
-
// "Be ignored unless..." -> Proceed to normal execution path (which handles auth/tool call normally)
|
|
129
|
-
// But wait, if we proceed, it tries to execute the tool for real.
|
|
130
|
-
// If the intention is to SAFEGUARD against accidental real execution, we should probably BLOCK if test_mode is present but unauthorized.
|
|
131
|
-
// However, "Be ignored" implies falling back to normal behavior OR just doing nothing.
|
|
132
|
-
// Safest Enterprise approach: If you ASK for test_mode but aren't allowed, FAIL. Don't fall back to real execution which might cost money.
|
|
133
|
-
return {
|
|
134
|
-
isError: true,
|
|
135
|
-
content: [{ type: "text", text: JSON.stringify({ error: { code: "FORBIDDEN", message: "Error: Simulation mode not permitted in production without internal privileges.", requestId } }) }]
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
|
-
// 3. Structured Logging
|
|
139
|
-
console.error(JSON.stringify({
|
|
140
|
-
event: "mcp.tool_call.simulation",
|
|
141
|
-
simulation_mode: true,
|
|
142
|
-
simulation_type: "gemini_echo",
|
|
143
|
-
tool: name,
|
|
144
|
-
graphId,
|
|
145
|
-
userId
|
|
146
|
-
}));
|
|
147
|
-
// 4. Gemini Echo Response
|
|
148
|
-
return {
|
|
149
|
-
content: [{
|
|
150
|
-
type: "text",
|
|
151
|
-
text: JSON.stringify({
|
|
152
|
-
tool_calls: [{
|
|
153
|
-
name: name,
|
|
154
|
-
arguments: args
|
|
155
|
-
}]
|
|
156
|
-
}, null, 2)
|
|
157
|
-
}]
|
|
158
|
-
};
|
|
100
|
+
}, CLEANUP_INTERVAL_MS).unref();
|
|
101
|
+
// ---------------------------------------------------------------------------
|
|
102
|
+
// Service URL helper
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// M2: FODDA_SERVICE_URL must be set in Cloud Run env vars.
|
|
105
|
+
// Fallback to localhost for local dev only. The hardcoded project hash
|
|
106
|
+
// was removed — if it was being used, the URL was silently wrong.
|
|
107
|
+
function getServiceUrl() {
|
|
108
|
+
if (process.env.FODDA_SERVICE_URL)
|
|
109
|
+
return process.env.FODDA_SERVICE_URL;
|
|
110
|
+
if (process.env.K_SERVICE) {
|
|
111
|
+
// Derive from K_SERVICE + K_REVISION if FODDA_SERVICE_URL not set.
|
|
112
|
+
// Requires CLOUD_RUN_REGION env var (e.g. 'uk') to be set.
|
|
113
|
+
const region = process.env.CLOUD_RUN_REGION || 'uk';
|
|
114
|
+
const revHash = process.env.K_REVISION?.split('-').pop();
|
|
115
|
+
if (!revHash)
|
|
116
|
+
console.error('[getServiceUrl] WARNING: K_REVISION not set — widget URLs may be wrong');
|
|
117
|
+
return `https://${process.env.K_SERVICE}-${revHash || 'unknown'}-${region}.a.run.app`;
|
|
159
118
|
}
|
|
119
|
+
return `http://localhost:${process.env.PORT || 8080}`;
|
|
120
|
+
}
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
// Authenticated API caller — checks query cache first
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
/**
|
|
125
|
+
* Make an authenticated request to the Fodda API.
|
|
126
|
+
* Checks the query cache first; stores responses on cache miss.
|
|
127
|
+
*/
|
|
128
|
+
async function foddaRequest(method, path, apiKey, userId, body, requestId, source) {
|
|
129
|
+
// ── Cache check ──
|
|
130
|
+
const cached = cacheGet(method, path, body);
|
|
131
|
+
if (cached !== null)
|
|
132
|
+
return cached;
|
|
160
133
|
const timestamp = Date.now().toString();
|
|
161
134
|
const headers = {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
135
|
+
'X-API-Key': apiKey,
|
|
136
|
+
'X-User-Id': userId,
|
|
137
|
+
'X-Fodda-Timestamp': timestamp,
|
|
138
|
+
'X-Fodda-Billing': 'mcp-orchestrated', // Tells API to skip per-call billing — MCP charges lump sum via meter
|
|
139
|
+
'Content-Type': 'application/json',
|
|
167
140
|
};
|
|
168
|
-
if (
|
|
169
|
-
headers[
|
|
141
|
+
if (requestId)
|
|
142
|
+
headers['X-Request-Id'] = requestId;
|
|
143
|
+
if (source)
|
|
144
|
+
headers['X-Fodda-Source'] = source;
|
|
145
|
+
// HMAC sign the request
|
|
146
|
+
const secret = process.env.FODDA_MCP_SECRET;
|
|
147
|
+
if (secret) {
|
|
148
|
+
const payload = (method === 'POST' || method === 'PATCH') && body
|
|
149
|
+
? timestamp + '.' + JSON.stringify(body)
|
|
150
|
+
: timestamp + '.' + path;
|
|
151
|
+
const signature = crypto.createHmac('sha256', secret).update(payload).digest('hex');
|
|
152
|
+
headers['X-Fodda-Signature'] = signature;
|
|
170
153
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
case "search_graph": {
|
|
190
|
-
const limit = Math.min(Number(args?.limit) || 25, 50); // Defense in Depth: Cap results
|
|
191
|
-
const body = {
|
|
192
|
-
query: args?.query,
|
|
193
|
-
limit: limit,
|
|
194
|
-
use_semantic: args?.use_semantic !== false,
|
|
195
|
-
};
|
|
196
|
-
if (args?.filters)
|
|
197
|
-
body.filters = args.filters;
|
|
198
|
-
if (args?.include_evidence !== undefined) {
|
|
199
|
-
body.include_evidence = args.include_evidence;
|
|
200
|
-
}
|
|
201
|
-
else {
|
|
202
|
-
body.include_evidence = true; // Default to true — most agent use cases benefit from inline evidence
|
|
203
|
-
}
|
|
204
|
-
signRequest(body);
|
|
205
|
-
response = await axios.post(`${API_BASE_URL}/v1/graphs/${graphId}/search`, body, { headers });
|
|
206
|
-
break;
|
|
207
|
-
}
|
|
208
|
-
case "get_neighbors": {
|
|
209
|
-
const depth = Math.min(Number(args?.depth) || 1, 2); // Defense in Depth: Cap traversal depth
|
|
210
|
-
const limit = Math.min(Number(args?.limit) || 50, 50); // Defense in Depth: Cap results
|
|
211
|
-
const body = {
|
|
212
|
-
seed_node_ids: args?.seed_node_ids,
|
|
213
|
-
relationship_types: args?.relationship_types,
|
|
214
|
-
depth: depth,
|
|
215
|
-
limit: limit,
|
|
216
|
-
};
|
|
217
|
-
if (args?.direction)
|
|
218
|
-
body.direction = args.direction;
|
|
219
|
-
signRequest(body);
|
|
220
|
-
response = await axios.post(`${API_BASE_URL}/v1/graphs/${graphId}/neighbors`, body, { headers });
|
|
221
|
-
break;
|
|
222
|
-
}
|
|
223
|
-
case "get_evidence": {
|
|
224
|
-
const top_k = Math.min(Number(args?.top_k) || 5, 10); // Defense in Depth: Cap evidence sources
|
|
225
|
-
const body = {
|
|
226
|
-
for_node_id: args?.for_node_id,
|
|
227
|
-
top_k: top_k,
|
|
228
|
-
};
|
|
229
|
-
signRequest(body);
|
|
230
|
-
response = await axios.post(`${API_BASE_URL}/v1/graphs/${graphId}/evidence`, body, { headers });
|
|
231
|
-
break;
|
|
232
|
-
}
|
|
233
|
-
case "get_node": {
|
|
234
|
-
const getNodePath = `/v1/graphs/${graphId}/nodes/${args?.nodeId}`;
|
|
235
|
-
const getNodeSecret = process.env.FODDA_MCP_SECRET;
|
|
236
|
-
if (getNodeSecret) {
|
|
237
|
-
const payload = timestamp + "." + getNodePath;
|
|
238
|
-
const signature = crypto.createHmac("sha256", getNodeSecret).update(payload).digest("hex");
|
|
239
|
-
headers["X-Fodda-Signature"] = signature;
|
|
240
|
-
}
|
|
241
|
-
response = await axios.get(`${API_BASE_URL}${getNodePath}`, { headers });
|
|
242
|
-
break;
|
|
243
|
-
}
|
|
244
|
-
case "get_label_values": {
|
|
245
|
-
const propertyParam = args?.property ? `?property=${encodeURIComponent(String(args.property))}` : '';
|
|
246
|
-
const getLabelPath = `/v1/graphs/${graphId}/labels/${args?.label}/values${propertyParam}`;
|
|
247
|
-
const getLabelSecret = process.env.FODDA_MCP_SECRET;
|
|
248
|
-
if (getLabelSecret) {
|
|
249
|
-
const payload = timestamp + "." + getLabelPath;
|
|
250
|
-
const signature = crypto.createHmac("sha256", getLabelSecret).update(payload).digest("hex");
|
|
251
|
-
headers["X-Fodda-Signature"] = signature;
|
|
252
|
-
}
|
|
253
|
-
response = await axios.get(`${API_BASE_URL}${getLabelPath}`, { headers });
|
|
254
|
-
break;
|
|
255
|
-
}
|
|
256
|
-
case "psfk_overview": {
|
|
257
|
-
const industry = args?.industry;
|
|
258
|
-
const sector = args?.sector;
|
|
259
|
-
const body = {
|
|
260
|
-
industry,
|
|
261
|
-
sector,
|
|
262
|
-
region: args?.region,
|
|
263
|
-
timeframe: args?.timeframe,
|
|
264
|
-
};
|
|
265
|
-
signRequest(body);
|
|
266
|
-
response = await axios.post(`${API_BASE_URL}/v1/psfk/overview`, body, { headers });
|
|
267
|
-
break;
|
|
268
|
-
}
|
|
269
|
-
case "discover_adjacent_trends": {
|
|
270
|
-
const adjParams = new URLSearchParams({ node_id: String(args?.trend_id) });
|
|
271
|
-
if (args?.min_score !== undefined)
|
|
272
|
-
adjParams.set("min_score", String(args.min_score));
|
|
273
|
-
const adjLimit = Math.min(Number(args?.limit) || 10, 20); // Defense in Depth: Cap adjacent results
|
|
274
|
-
adjParams.set("limit", String(adjLimit));
|
|
275
|
-
if (args?.include_editorial !== undefined)
|
|
276
|
-
adjParams.set("include_editorial", String(args.include_editorial));
|
|
277
|
-
const adjPath = `/v1/graphs/${graphId}/adjacent?${adjParams.toString()}`;
|
|
278
|
-
const adjSecret = process.env.FODDA_MCP_SECRET;
|
|
279
|
-
if (adjSecret) {
|
|
280
|
-
const payload = timestamp + "." + adjPath;
|
|
281
|
-
const signature = crypto.createHmac("sha256", adjSecret).update(payload).digest("hex");
|
|
282
|
-
headers["X-Fodda-Signature"] = signature;
|
|
283
|
-
}
|
|
284
|
-
response = await axios.get(`${API_BASE_URL}${adjPath}`, { headers });
|
|
285
|
-
break;
|
|
286
|
-
}
|
|
287
|
-
case "list_graphs": {
|
|
288
|
-
const listGraphsPath = `/v1/graphs`;
|
|
289
|
-
const listGraphsSecret = process.env.FODDA_MCP_SECRET;
|
|
290
|
-
if (listGraphsSecret) {
|
|
291
|
-
const payload = timestamp + "." + listGraphsPath;
|
|
292
|
-
const signature = crypto.createHmac("sha256", listGraphsSecret).update(payload).digest("hex");
|
|
293
|
-
headers["X-Fodda-Signature"] = signature;
|
|
294
|
-
}
|
|
295
|
-
response = await axios.get(`${API_BASE_URL}${listGraphsPath}`, { headers });
|
|
296
|
-
break;
|
|
297
|
-
}
|
|
298
|
-
default:
|
|
299
|
-
throw new Error(`Unknown tool: ${name}`);
|
|
300
|
-
}
|
|
301
|
-
const durationMs = Date.now() - startTime;
|
|
302
|
-
const usage = response.data.usage || { total_billable_units: 0 };
|
|
303
|
-
// Structured Audit Log for Enterprise Traceability (Refined for Security Compliance)
|
|
304
|
-
console.error(JSON.stringify({
|
|
305
|
-
event: "mcp.tool_call",
|
|
306
|
-
tool: name,
|
|
307
|
-
graphId,
|
|
308
|
-
userId, // Corresponds to tenant/user identity
|
|
309
|
-
status: response.status,
|
|
310
|
-
durationMs,
|
|
311
|
-
billable_units: usage.total_billable_units,
|
|
312
|
-
deterministic: false,
|
|
313
|
-
layer: "mcp_proxy",
|
|
314
|
-
requestId,
|
|
315
|
-
traceId
|
|
316
|
-
}));
|
|
317
|
-
const resultData = { ...response.data, meta: { requestId } };
|
|
318
|
-
const resultString = JSON.stringify(resultData, null, 2);
|
|
319
|
-
const MAX_RESPONSE_BYTES = process.env.MAX_RESPONSE_BYTES ? parseInt(process.env.MAX_RESPONSE_BYTES, 10) : 2 * 1024 * 1024;
|
|
320
|
-
if (Buffer.byteLength(resultString, 'utf8') > MAX_RESPONSE_BYTES) {
|
|
321
|
-
console.error(JSON.stringify({
|
|
322
|
-
event: "mcp.tool_error",
|
|
323
|
-
tool: name,
|
|
324
|
-
graphId,
|
|
325
|
-
userId,
|
|
326
|
-
status: 413,
|
|
327
|
-
durationMs,
|
|
328
|
-
error: "Response exceeded maximum size limit",
|
|
329
|
-
requestId,
|
|
330
|
-
traceId
|
|
331
|
-
}));
|
|
332
|
-
return {
|
|
333
|
-
isError: true,
|
|
334
|
-
content: [{ type: "text", text: JSON.stringify({ error: { code: "PAYLOAD_TOO_LARGE", message: `Response exceeded maximum size of ${MAX_RESPONSE_BYTES} bytes.`, requestId } }) }]
|
|
335
|
-
};
|
|
336
|
-
}
|
|
337
|
-
return {
|
|
338
|
-
content: [{ type: "text", text: resultString }]
|
|
339
|
-
};
|
|
340
|
-
}
|
|
341
|
-
catch (error) {
|
|
342
|
-
const durationMs = Date.now() - startTime;
|
|
343
|
-
const status = error.status || error.response?.status || 500;
|
|
344
|
-
console.error(JSON.stringify({
|
|
345
|
-
event: "mcp.tool_error",
|
|
346
|
-
tool: name,
|
|
347
|
-
graphId,
|
|
348
|
-
userId,
|
|
349
|
-
status,
|
|
350
|
-
durationMs,
|
|
351
|
-
error: error.response?.data?.message || error.message,
|
|
352
|
-
requestId,
|
|
353
|
-
traceId
|
|
354
|
-
}));
|
|
355
|
-
let code = "UPSTREAM_ERROR";
|
|
356
|
-
if (status === 400)
|
|
357
|
-
code = "INVALID_PARAMS";
|
|
358
|
-
else if (status === 401)
|
|
359
|
-
code = "INVALID_AUTH";
|
|
360
|
-
else if (status === 403)
|
|
361
|
-
code = "FORBIDDEN";
|
|
362
|
-
else if (status === 404)
|
|
363
|
-
code = "GRAPH_NOT_FOUND";
|
|
364
|
-
else if (status === 429)
|
|
365
|
-
code = "RATE_LIMITED";
|
|
366
|
-
else if (status === 504)
|
|
367
|
-
code = "BACKEND_TIMEOUT";
|
|
368
|
-
else if (error.message && error.message.includes("Unknown tool"))
|
|
369
|
-
code = "UNKNOWN_TOOL";
|
|
370
|
-
return {
|
|
371
|
-
isError: true,
|
|
372
|
-
content: [{ type: "text", text: JSON.stringify({ error: { code, message: error.response?.data?.message || error.message, requestId } }) }],
|
|
154
|
+
const url = `${API_BASE_URL}${path}`;
|
|
155
|
+
// H3: 30s timeout — aligns with MCP client expectations.
|
|
156
|
+
// The previous 120s timeout held sessions open for 2 minutes on slow upstreams.
|
|
157
|
+
const AXIOS_TIMEOUT_MS = 30000;
|
|
158
|
+
const response = method === 'GET'
|
|
159
|
+
? await axios.get(url, { headers, timeout: AXIOS_TIMEOUT_MS })
|
|
160
|
+
: method === 'PATCH'
|
|
161
|
+
? await axios.patch(url, body, { headers, timeout: AXIOS_TIMEOUT_MS })
|
|
162
|
+
: await axios.post(url, body, { headers, timeout: AXIOS_TIMEOUT_MS });
|
|
163
|
+
// ── Cache store ──
|
|
164
|
+
cacheSet(method, path, body, response.data);
|
|
165
|
+
// ── Inject upstream usage warning headers into response data ──
|
|
166
|
+
// The app returns X-Usage-Warning / X-Usage-Percent / X-Usage-Overage-Tokens
|
|
167
|
+
// on successful responses to indicate approaching-limit or overage-active status.
|
|
168
|
+
const usageWarningHeader = response.headers?.['x-usage-warning'];
|
|
169
|
+
if (usageWarningHeader && response.data && typeof response.data === 'object') {
|
|
170
|
+
response.data._upstream_usage = {
|
|
171
|
+
warning: usageWarningHeader, // 'approaching-limit' or 'overage-active'
|
|
373
172
|
};
|
|
173
|
+
const pct = response.headers['x-usage-percent'];
|
|
174
|
+
if (pct)
|
|
175
|
+
response.data._upstream_usage.percent = parseInt(pct, 10);
|
|
176
|
+
const overageTokens = response.headers['x-usage-overage-tokens'];
|
|
177
|
+
if (overageTokens)
|
|
178
|
+
response.data._upstream_usage.overage_tokens = parseInt(overageTokens, 10);
|
|
374
179
|
}
|
|
375
|
-
|
|
180
|
+
return response.data;
|
|
181
|
+
}
|
|
182
|
+
// ---------------------------------------------------------------------------
|
|
183
|
+
// Waverunner (Gemini Interactions API) caller — parallel to foddaRequest()
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
376
185
|
/**
|
|
377
|
-
*
|
|
186
|
+
* Make an authenticated Waverunner call (Gemini Interactions API).
|
|
187
|
+
* This is NOT a Fodda API call — it goes directly to Google.
|
|
188
|
+
*
|
|
189
|
+
* Handles:
|
|
190
|
+
* - Pre-check trial credits (split pools: search / deep_dive / expert_agent)
|
|
191
|
+
* - Call Gemini via @google/genai SDK
|
|
192
|
+
* - Post-decrement trial credits, or fire-and-forget metering for paid accounts
|
|
193
|
+
* - NO caching (Waverunner calls are non-deterministic)
|
|
194
|
+
*
|
|
195
|
+
* When the Waverunner agent internally calls Fodda graph tools, it should
|
|
196
|
+
* use FODDA_INTERNAL_API_KEY so those calls skip billing.
|
|
378
197
|
*/
|
|
379
|
-
async function
|
|
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
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
198
|
+
async function waverunnerRequest(interactionType, tokenCost, userApiKey, userId, waverunnerPayload) {
|
|
199
|
+
const isTrial = false; // sk_trial_ keys retired — waverunner only used by paid/new-trial accounts
|
|
200
|
+
// ── Pre-check credits ──
|
|
201
|
+
// (sk_trial_ pre-check removed — new trial accounts are metered server-side by the API)
|
|
202
|
+
// ── Call Waverunner via Gemini SDK ──
|
|
203
|
+
const geminiKey = process.env.GEMINI_API_KEY;
|
|
204
|
+
if (!geminiKey) {
|
|
205
|
+
throw new Error('GEMINI_API_KEY environment variable is required for Waverunner calls.');
|
|
206
|
+
}
|
|
207
|
+
const { GoogleGenAI } = await import('@google/genai');
|
|
208
|
+
const ai = new GoogleGenAI({ apiKey: geminiKey });
|
|
209
|
+
const result = await ai.interactions.create(waverunnerPayload);
|
|
210
|
+
// ── Post-decrement (paid accounts) ──
|
|
211
|
+
foddaRequest('POST', '/v1/research/meter', userApiKey, userId, {
|
|
212
|
+
type: interactionType,
|
|
213
|
+
billable_units: tokenCost,
|
|
214
|
+
}).catch(err => console.error('[waverunnerRequest] Metering failed:', err.message));
|
|
215
|
+
return result;
|
|
216
|
+
}
|
|
217
|
+
// ---------------------------------------------------------------------------
|
|
218
|
+
// Browser Landing Page — catch humans who paste the MCP URL into a browser
|
|
219
|
+
// ---------------------------------------------------------------------------
|
|
220
|
+
app.get('/mcp', (req, res, next) => {
|
|
221
|
+
// Only intercept browser requests (Accept: text/html).
|
|
222
|
+
// MCP SDK clients send application/json or text/event-stream, so they
|
|
223
|
+
// fall through to the app.all('/mcp') transport handler below.
|
|
224
|
+
const accept = req.headers['accept'] || '';
|
|
225
|
+
if (!accept.includes('text/html'))
|
|
226
|
+
return next();
|
|
227
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
228
|
+
res.send(`<!DOCTYPE html>
|
|
229
|
+
<html lang="en">
|
|
230
|
+
<head>
|
|
231
|
+
<meta charset="utf-8">
|
|
232
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
233
|
+
<title>Fodda — This URL is for AI Systems</title>
|
|
234
|
+
<link rel="icon" type="image/png" href="${FAVICON_PNG}">
|
|
235
|
+
<link rel="icon" type="image/svg+xml" href="${FAVICON_SVG}">
|
|
236
|
+
<meta http-equiv="refresh" content="12;url=https://www.fodda.ai">
|
|
237
|
+
<style>
|
|
238
|
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');
|
|
239
|
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
240
|
+
body {
|
|
241
|
+
min-height: 100vh;
|
|
242
|
+
display: flex;
|
|
243
|
+
align-items: center;
|
|
244
|
+
justify-content: center;
|
|
245
|
+
background: #0D0A14;
|
|
246
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
247
|
+
color: #E8E2F0;
|
|
248
|
+
overflow: hidden;
|
|
249
|
+
}
|
|
250
|
+
/* Ambient background glow */
|
|
251
|
+
body::before {
|
|
252
|
+
content: '';
|
|
253
|
+
position: fixed;
|
|
254
|
+
top: -40%; left: -20%;
|
|
255
|
+
width: 140%; height: 140%;
|
|
256
|
+
background: radial-gradient(ellipse at 30% 50%, rgba(102,51,153,0.15) 0%, transparent 60%),
|
|
257
|
+
radial-gradient(ellipse at 70% 60%, rgba(74,36,112,0.10) 0%, transparent 50%);
|
|
258
|
+
pointer-events: none;
|
|
259
|
+
z-index: 0;
|
|
260
|
+
}
|
|
261
|
+
.card {
|
|
262
|
+
position: relative;
|
|
263
|
+
z-index: 1;
|
|
264
|
+
max-width: 520px;
|
|
265
|
+
width: 90%;
|
|
266
|
+
padding: 2.5rem 2.5rem 2rem;
|
|
267
|
+
border-radius: 20px;
|
|
268
|
+
background: rgba(22, 17, 32, 0.85);
|
|
269
|
+
border: 1px solid rgba(155, 114, 204, 0.25);
|
|
270
|
+
backdrop-filter: blur(24px);
|
|
271
|
+
-webkit-backdrop-filter: blur(24px);
|
|
272
|
+
box-shadow: 0 0 80px rgba(102, 51, 153, 0.12), 0 4px 32px rgba(0,0,0,0.4);
|
|
273
|
+
text-align: center;
|
|
274
|
+
animation: cardIn 0.6s ease-out;
|
|
275
|
+
}
|
|
276
|
+
@keyframes cardIn {
|
|
277
|
+
from { opacity: 0; transform: translateY(24px) scale(0.97); }
|
|
278
|
+
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
279
|
+
}
|
|
280
|
+
.logo-row {
|
|
281
|
+
display: flex;
|
|
282
|
+
align-items: center;
|
|
283
|
+
justify-content: center;
|
|
284
|
+
gap: 10px;
|
|
285
|
+
margin-bottom: 2rem;
|
|
286
|
+
}
|
|
287
|
+
.logo-mark {
|
|
288
|
+
width: 32px; height: 32px;
|
|
289
|
+
border-radius: 8px;
|
|
290
|
+
background: #663399;
|
|
291
|
+
display: flex;
|
|
292
|
+
align-items: center;
|
|
293
|
+
justify-content: center;
|
|
294
|
+
}
|
|
295
|
+
.logo-mark span {
|
|
296
|
+
color: #fff;
|
|
297
|
+
font-size: 17px;
|
|
298
|
+
font-weight: 600;
|
|
299
|
+
font-family: monospace;
|
|
300
|
+
}
|
|
301
|
+
.logo-text {
|
|
302
|
+
font-size: 20px;
|
|
303
|
+
font-weight: 600;
|
|
304
|
+
color: #E8E2F0;
|
|
305
|
+
letter-spacing: -0.5px;
|
|
306
|
+
}
|
|
307
|
+
.icon-row {
|
|
308
|
+
margin-bottom: 1.5rem;
|
|
309
|
+
}
|
|
310
|
+
.icon-row svg {
|
|
311
|
+
width: 56px; height: 56px;
|
|
312
|
+
color: #9B72CC;
|
|
313
|
+
animation: pulse 2.5s ease-in-out infinite;
|
|
314
|
+
}
|
|
315
|
+
@keyframes pulse {
|
|
316
|
+
0%, 100% { opacity: 0.7; transform: scale(1); }
|
|
317
|
+
50% { opacity: 1; transform: scale(1.06); }
|
|
318
|
+
}
|
|
319
|
+
h1 {
|
|
320
|
+
font-size: 1.35rem;
|
|
321
|
+
font-weight: 600;
|
|
322
|
+
color: #fff;
|
|
323
|
+
margin-bottom: 0.75rem;
|
|
324
|
+
line-height: 1.3;
|
|
325
|
+
}
|
|
326
|
+
.subtitle {
|
|
327
|
+
font-size: 0.95rem;
|
|
328
|
+
color: #A89BBE;
|
|
329
|
+
line-height: 1.6;
|
|
330
|
+
margin-bottom: 1.75rem;
|
|
331
|
+
}
|
|
332
|
+
.subtitle strong {
|
|
333
|
+
color: #C9B5E0;
|
|
334
|
+
font-weight: 500;
|
|
335
|
+
}
|
|
336
|
+
.url-preview {
|
|
337
|
+
display: inline-block;
|
|
338
|
+
padding: 0.45rem 1rem;
|
|
339
|
+
border-radius: 8px;
|
|
340
|
+
background: rgba(102, 51, 153, 0.12);
|
|
341
|
+
border: 1px solid rgba(155, 114, 204, 0.2);
|
|
342
|
+
font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
|
|
343
|
+
font-size: 0.72rem;
|
|
344
|
+
color: #9B72CC;
|
|
345
|
+
word-break: break-all;
|
|
346
|
+
margin-bottom: 1.75rem;
|
|
347
|
+
max-width: 100%;
|
|
348
|
+
}
|
|
349
|
+
.cta-btn {
|
|
350
|
+
display: inline-flex;
|
|
351
|
+
align-items: center;
|
|
352
|
+
gap: 8px;
|
|
353
|
+
padding: 0.75rem 1.75rem;
|
|
354
|
+
border-radius: 12px;
|
|
355
|
+
background: #663399;
|
|
356
|
+
color: #fff;
|
|
357
|
+
font-size: 0.95rem;
|
|
358
|
+
font-weight: 500;
|
|
359
|
+
text-decoration: none;
|
|
360
|
+
transition: background 0.2s, transform 0.2s, box-shadow 0.2s;
|
|
361
|
+
box-shadow: 0 0 0 0 rgba(102,51,153,0);
|
|
362
|
+
margin-bottom: 1rem;
|
|
363
|
+
}
|
|
364
|
+
.cta-btn:hover {
|
|
365
|
+
background: #7840B0;
|
|
366
|
+
transform: translateY(-1px);
|
|
367
|
+
box-shadow: 0 4px 20px rgba(102,51,153,0.35);
|
|
368
|
+
}
|
|
369
|
+
.cta-btn svg { width: 16px; height: 16px; }
|
|
370
|
+
.redirect-note {
|
|
371
|
+
font-size: 0.78rem;
|
|
372
|
+
color: #6B5A82;
|
|
373
|
+
margin-top: 0.5rem;
|
|
374
|
+
}
|
|
375
|
+
.steps {
|
|
376
|
+
margin-top: 1.5rem;
|
|
377
|
+
padding-top: 1.25rem;
|
|
378
|
+
border-top: 1px solid rgba(155, 114, 204, 0.12);
|
|
379
|
+
text-align: left;
|
|
380
|
+
}
|
|
381
|
+
.steps-title {
|
|
382
|
+
font-size: 0.75rem;
|
|
383
|
+
text-transform: uppercase;
|
|
384
|
+
letter-spacing: 1.2px;
|
|
385
|
+
color: #6B5A82;
|
|
386
|
+
margin-bottom: 0.85rem;
|
|
387
|
+
text-align: center;
|
|
388
|
+
}
|
|
389
|
+
.step {
|
|
390
|
+
display: flex;
|
|
391
|
+
align-items: flex-start;
|
|
392
|
+
gap: 12px;
|
|
393
|
+
margin-bottom: 0.65rem;
|
|
394
|
+
}
|
|
395
|
+
.step-num {
|
|
396
|
+
width: 22px; height: 22px;
|
|
397
|
+
border-radius: 50%;
|
|
398
|
+
background: rgba(102, 51, 153, 0.2);
|
|
399
|
+
color: #9B72CC;
|
|
400
|
+
font-size: 0.7rem;
|
|
401
|
+
font-weight: 600;
|
|
402
|
+
display: flex;
|
|
403
|
+
align-items: center;
|
|
404
|
+
justify-content: center;
|
|
405
|
+
flex-shrink: 0;
|
|
406
|
+
margin-top: 1px;
|
|
407
|
+
}
|
|
408
|
+
.step-text {
|
|
409
|
+
font-size: 0.82rem;
|
|
410
|
+
color: #A89BBE;
|
|
411
|
+
line-height: 1.5;
|
|
412
|
+
}
|
|
413
|
+
.step-text a {
|
|
414
|
+
color: #C9B5E0;
|
|
415
|
+
text-decoration: underline;
|
|
416
|
+
text-underline-offset: 2px;
|
|
417
|
+
}
|
|
418
|
+
.step-text a:hover { color: #fff; }
|
|
419
|
+
</style>
|
|
420
|
+
</head>
|
|
421
|
+
<body>
|
|
422
|
+
<div class="card">
|
|
423
|
+
<div class="logo-row">
|
|
424
|
+
<div class="logo-mark"><span>F</span></div>
|
|
425
|
+
<div class="logo-text">Fodda</div>
|
|
426
|
+
</div>
|
|
427
|
+
|
|
428
|
+
<div class="icon-row">
|
|
429
|
+
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
|
|
430
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M9.75 3.104v5.714a2.25 2.25 0 0 1-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 0 1 4.5 0m0 0v5.714a2.25 2.25 0 0 0 .659 1.591L19 14.5M14.25 3.104c.251.023.501.05.75.082M19 14.5l-1.482 4.17a2.25 2.25 0 0 1-2.133 1.58H8.615a2.25 2.25 0 0 1-2.133-1.58L5 14.5m14 0H5" />
|
|
431
|
+
</svg>
|
|
432
|
+
</div>
|
|
433
|
+
|
|
434
|
+
<h1>This URL is for AI systems,<br>not your browser</h1>
|
|
435
|
+
|
|
436
|
+
<p class="subtitle">
|
|
437
|
+
You've opened a <strong>Model Context Protocol (MCP)</strong> endpoint.
|
|
438
|
+
It's designed to be used by AI assistants like Claude, ChatGPT, Cursor, or the OpenAI Responses API —
|
|
439
|
+
not visited directly in a web browser.
|
|
440
|
+
</p>
|
|
441
|
+
|
|
442
|
+
<a href="https://www.fodda.ai" class="cta-btn">
|
|
443
|
+
Learn how to connect
|
|
444
|
+
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
|
|
445
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="m4.5 19.5 15-15m0 0H8.25m11.25 0v11.25" />
|
|
446
|
+
</svg>
|
|
447
|
+
</a>
|
|
448
|
+
|
|
449
|
+
<div class="redirect-note">Redirecting to fodda.ai in a few seconds…</div>
|
|
450
|
+
|
|
451
|
+
<div class="steps">
|
|
452
|
+
<div class="steps-title">How to use this URL</div>
|
|
453
|
+
<div class="step">
|
|
454
|
+
<div class="step-num">1</div>
|
|
455
|
+
<div class="step-text">Copy this MCP URL from your <a href="https://app.fodda.ai/settings" target="_blank">Fodda settings</a></div>
|
|
456
|
+
</div>
|
|
457
|
+
<div class="step">
|
|
458
|
+
<div class="step-num">2</div>
|
|
459
|
+
<div class="step-text">Paste it into the MCP settings of your AI tool (Claude, Cursor, Windsurf, etc.)</div>
|
|
460
|
+
</div>
|
|
461
|
+
<div class="step">
|
|
462
|
+
<div class="step-num">3</div>
|
|
463
|
+
<div class="step-text">Start asking questions — Fodda's knowledge graphs power your AI</div>
|
|
464
|
+
</div>
|
|
465
|
+
</div>
|
|
466
|
+
</div>
|
|
467
|
+
</body>
|
|
468
|
+
</html>`);
|
|
469
|
+
});
|
|
470
|
+
// ---------------------------------------------------------------------------
|
|
471
|
+
// MCP Transport Handler
|
|
472
|
+
// ---------------------------------------------------------------------------
|
|
473
|
+
app.all('/mcp', async (req, res) => {
|
|
474
|
+
try {
|
|
475
|
+
const sessionId = req.headers['mcp-session-id'];
|
|
476
|
+
let transport;
|
|
477
|
+
// Extract API key, userId, and entry ID from URL or headers
|
|
478
|
+
// Priority: query string (existing MCP clients) → X-API-Key header → Authorization Bearer (Remote MCP)
|
|
479
|
+
const apiKey = req.query.api_key
|
|
480
|
+
|| req.headers['x-api-key']
|
|
481
|
+
|| (req.headers['authorization']?.toString().replace(/^Bearer\s+/i, ''))
|
|
482
|
+
|| '';
|
|
483
|
+
const entryId = req.query.id || '';
|
|
484
|
+
// If id looks like an email and no explicit user_id, use it as userId for tracking + signup
|
|
485
|
+
const isEmailId = entryId.includes('@') && entryId.includes('.');
|
|
486
|
+
const userId = req.query.user_id
|
|
487
|
+
|| req.headers['x-user-id']
|
|
488
|
+
|| (isEmailId ? entryId : 'anonymous');
|
|
489
|
+
const source = req.query.source || '';
|
|
490
|
+
if (sessionId && transports.has(sessionId)) {
|
|
491
|
+
transport = transports.get(sessionId);
|
|
492
|
+
}
|
|
493
|
+
else if (!sessionId && req.method === 'POST') {
|
|
494
|
+
const body = req.body;
|
|
495
|
+
if (body?.method === 'initialize') {
|
|
496
|
+
// Store API key/userId for this session
|
|
497
|
+
// Wrap foddaRequest to bake in source attribution
|
|
498
|
+
const boundFoddaRequest = source
|
|
499
|
+
? ((m, p, k, u, b, r) => foddaRequest(m, p, k, u, b, r, source))
|
|
500
|
+
: foddaRequest;
|
|
501
|
+
const server = await createServer(apiKey, userId, boundFoddaRequest, waverunnerRequest, storeWidget, getServiceUrl, entryId);
|
|
502
|
+
transport = new StreamableHTTPServerTransport({
|
|
503
|
+
sessionIdGenerator: () => crypto.randomUUID(),
|
|
504
|
+
onsessioninitialized: (sid) => {
|
|
505
|
+
console.error(`Session created: ${sid}`);
|
|
506
|
+
transports.set(sid, transport);
|
|
507
|
+
sessionApiKeys.set(sid, apiKey);
|
|
508
|
+
sessionUserIds.set(sid, userId);
|
|
509
|
+
sessionCreatedAt.set(sid, Date.now()); // C2: track creation time
|
|
510
|
+
if (source)
|
|
511
|
+
sessionSources.set(sid, source);
|
|
512
|
+
}
|
|
513
|
+
});
|
|
514
|
+
transport.onclose = () => {
|
|
515
|
+
const sid = transport.sessionId;
|
|
516
|
+
if (sid) {
|
|
517
|
+
transports.delete(sid);
|
|
518
|
+
sessionApiKeys.delete(sid);
|
|
519
|
+
sessionUserIds.delete(sid);
|
|
520
|
+
sessionSources.delete(sid);
|
|
521
|
+
sessionCreatedAt.delete(sid); // C2: clean up creation time
|
|
488
522
|
}
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
transport = new StreamableHTTPServerTransport({
|
|
492
|
-
sessionIdGenerator: () => crypto.randomUUID(),
|
|
493
|
-
onsessioninitialized: (sid) => {
|
|
494
|
-
console.error(`StreamableHTTP session initialized: ${sid}`);
|
|
495
|
-
transports.set(sid, transport);
|
|
496
|
-
}
|
|
497
|
-
});
|
|
498
|
-
transport.onclose = () => {
|
|
499
|
-
const sid = transport.sessionId;
|
|
500
|
-
if (sid && transports.has(sid)) {
|
|
501
|
-
console.error(`StreamableHTTP session ${sid} disconnected`);
|
|
502
|
-
transports.delete(sid);
|
|
503
|
-
}
|
|
504
|
-
};
|
|
505
|
-
await server.connect(transport);
|
|
506
|
-
}
|
|
507
|
-
else {
|
|
508
|
-
return res.status(400).json({ error: 'No valid session ID provided' });
|
|
509
|
-
}
|
|
510
|
-
await transport.handleRequest(req, res, req.body);
|
|
523
|
+
};
|
|
524
|
+
await server.connect(transport);
|
|
511
525
|
}
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
526
|
+
else {
|
|
527
|
+
return res.status(400).json({
|
|
528
|
+
jsonrpc: '2.0',
|
|
529
|
+
error: { code: -32000, message: 'Bad Request: Session required' },
|
|
530
|
+
id: null
|
|
531
|
+
});
|
|
516
532
|
}
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
// Clean up on disconnect
|
|
524
|
-
res.on("close", () => {
|
|
525
|
-
transports.delete(sessionId);
|
|
526
|
-
console.error(`SSE session ${sessionId} disconnected (${transports.size} active)`);
|
|
533
|
+
}
|
|
534
|
+
else {
|
|
535
|
+
return res.status(404).json({
|
|
536
|
+
jsonrpc: '2.0',
|
|
537
|
+
error: { code: -32001, message: 'Session not found' },
|
|
538
|
+
id: null
|
|
527
539
|
});
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
else if (transports.size === 1) {
|
|
537
|
-
// Fallback: single-client mode
|
|
538
|
-
let transport;
|
|
539
|
-
transports.forEach((v) => { transport = v; });
|
|
540
|
-
await transport.handlePostMessage(req, res);
|
|
541
|
-
}
|
|
542
|
-
else if (transports.size === 0) {
|
|
543
|
-
res.status(400).send("No SSE connections established");
|
|
540
|
+
}
|
|
541
|
+
// Inject Accept: text/event-stream if missing (prevents SDK 406)
|
|
542
|
+
const accept = req.headers['accept'] || '';
|
|
543
|
+
if (!accept.includes('text/event-stream')) {
|
|
544
|
+
req.headers['accept'] = accept ? `${accept}, text/event-stream` : 'application/json, text/event-stream';
|
|
545
|
+
const idx = req.rawHeaders?.findIndex((h) => h.toLowerCase() === 'accept');
|
|
546
|
+
if (idx !== undefined && idx >= 0 && req.rawHeaders) {
|
|
547
|
+
req.rawHeaders[idx + 1] = req.headers['accept'];
|
|
544
548
|
}
|
|
545
|
-
else {
|
|
546
|
-
|
|
549
|
+
else if (req.rawHeaders) {
|
|
550
|
+
req.rawHeaders.push('Accept', req.headers['accept']);
|
|
547
551
|
}
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
app.get("/health", (req, res) => {
|
|
551
|
-
res.json({ status: "ok", version: MCP_SERVER_VERSION });
|
|
552
|
-
});
|
|
553
|
-
// Enterprise Transparency: Tool Capability Registry
|
|
554
|
-
app.get("/mcp/tools", (req, res) => {
|
|
555
|
-
res.json({
|
|
556
|
-
tools: TOOLS,
|
|
557
|
-
count: TOOLS.length,
|
|
558
|
-
version: MCP_SERVER_VERSION
|
|
559
|
-
});
|
|
560
|
-
});
|
|
561
|
-
// MCP Server Discovery (emerging .well-known standard)
|
|
562
|
-
app.get("/.well-known/mcp.json", (req, res) => {
|
|
563
|
-
res.json({
|
|
564
|
-
name: "ai.fodda/mcp-server",
|
|
565
|
-
title: "Fodda Knowledge Graphs",
|
|
566
|
-
description: "Fodda MCP — Expert-curated trend intelligence graphs exposed as structured context for AI agents.",
|
|
567
|
-
version: MCP_SERVER_VERSION,
|
|
568
|
-
transport: {
|
|
569
|
-
type: "streamable-http",
|
|
570
|
-
url: `${req.protocol}://${req.get("host")}/mcp`,
|
|
571
|
-
fallback: {
|
|
572
|
-
type: "sse",
|
|
573
|
-
url: `${req.protocol}://${req.get("host")}/sse`
|
|
574
|
-
}
|
|
575
|
-
},
|
|
576
|
-
tools_endpoint: `${req.protocol}://${req.get("host")}/mcp/tools`,
|
|
577
|
-
health_endpoint: `${req.protocol}://${req.get("host")}/health`
|
|
578
|
-
});
|
|
579
|
-
});
|
|
580
|
-
const httpServer = app.listen(port, () => {
|
|
581
|
-
console.error(`Fodda MCP server running on SSE at http://localhost:${port}/sse`);
|
|
582
|
-
});
|
|
583
|
-
// Graceful shutdown for Cloud Run
|
|
584
|
-
const shutdown = () => {
|
|
585
|
-
console.error("Shutting down gracefully...");
|
|
586
|
-
httpServer.close(() => {
|
|
587
|
-
console.error(`Closed ${transports.size} active SSE connections.`);
|
|
588
|
-
process.exit(0);
|
|
589
|
-
});
|
|
590
|
-
// Force exit after 10s if connections don't close
|
|
591
|
-
setTimeout(() => process.exit(1), 10000);
|
|
592
|
-
};
|
|
593
|
-
process.on("SIGTERM", shutdown);
|
|
594
|
-
process.on("SIGINT", shutdown);
|
|
552
|
+
}
|
|
553
|
+
await transport.handleRequest(req, res, req.body);
|
|
595
554
|
}
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
555
|
+
catch (error) {
|
|
556
|
+
console.error('Error:', error);
|
|
557
|
+
if (!res.headersSent)
|
|
558
|
+
res.status(500).json({ error: 'Internal server error' });
|
|
600
559
|
}
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
560
|
+
});
|
|
561
|
+
// Legacy SSE transport
|
|
562
|
+
app.get('/sse', async (req, res) => {
|
|
563
|
+
const apiKey = req.query.api_key || '';
|
|
564
|
+
const entryId = req.query.id || '';
|
|
565
|
+
const isEmailId = entryId.includes('@') && entryId.includes('.');
|
|
566
|
+
const userId = req.query.user_id
|
|
567
|
+
|| req.headers['x-user-id']
|
|
568
|
+
|| (isEmailId ? entryId : 'anonymous');
|
|
569
|
+
const source = req.query.source || '';
|
|
570
|
+
const sessionId = crypto.randomUUID();
|
|
571
|
+
const transport = new SSEServerTransport('/messages', res);
|
|
572
|
+
// Bind source parameter to foddaRequest to forward it upstream as X-Fodda-Source
|
|
573
|
+
const boundFoddaRequest = source
|
|
574
|
+
? ((m, p, k, u, b, r) => foddaRequest(m, p, k, u, b, r, source))
|
|
575
|
+
: foddaRequest;
|
|
576
|
+
const server = await createServer(apiKey, userId, boundFoddaRequest, waverunnerRequest, storeWidget, getServiceUrl);
|
|
577
|
+
await server.connect(transport);
|
|
578
|
+
console.error(`SSE session: ${sessionId}`);
|
|
579
|
+
});
|
|
580
|
+
app.post('/messages', async (req, res) => {
|
|
581
|
+
// SSE message handler would go here
|
|
582
|
+
res.status(404).json({ error: 'Use /mcp endpoint' });
|
|
583
|
+
});
|
|
584
|
+
// Favicon — required for Anthropic Connectors Directory (Google favicon API)
|
|
585
|
+
const FAVICON_SVG = 'https://ucarecdn.com/e3ce77f2-661e-48a1-a294-c7c01039aed4/foddaminilogo.svg';
|
|
586
|
+
const FAVICON_PNG = 'https://ucarecdn.com/6e7893d7-6b14-426b-83bc-574a3f72d6bc/foddafavicon.png';
|
|
587
|
+
app.get('/favicon.ico', (_req, res) => { res.redirect(301, FAVICON_PNG); });
|
|
588
|
+
app.get('/favicon.svg', (_req, res) => { res.redirect(301, FAVICON_SVG); });
|
|
589
|
+
// Root — minimal HTML so Google's favicon crawler can find the icon
|
|
590
|
+
app.get('/', (_req, res) => {
|
|
591
|
+
res.setHeader('Content-Type', 'text/html');
|
|
592
|
+
res.send(`<!DOCTYPE html>
|
|
593
|
+
<html><head>
|
|
594
|
+
<title>Fodda MCP Server</title>
|
|
595
|
+
<link rel="icon" type="image/png" href="${FAVICON_PNG}">
|
|
596
|
+
<link rel="icon" type="image/svg+xml" href="${FAVICON_SVG}">
|
|
597
|
+
</head><body>
|
|
598
|
+
<h1>Fodda MCP Server v${MCP_SERVER_VERSION}</h1>
|
|
599
|
+
<p>Expert-curated knowledge graphs for AI agents.</p>
|
|
600
|
+
<p>Connect via <a href="https://app.fodda.ai">app.fodda.ai</a></p>
|
|
601
|
+
</body></html>`);
|
|
602
|
+
});
|
|
603
|
+
app.get('/health', (_req, res) => res.json({ status: 'ok', version: MCP_SERVER_VERSION, queryCache: getCacheStats() }));
|
|
604
|
+
// ---------------------------------------------------------------------------
|
|
605
|
+
// A2A Protocol Endpoint — agent-to-agent task delegation
|
|
606
|
+
// ---------------------------------------------------------------------------
|
|
607
|
+
registerA2ARoute(app, foddaRequest);
|
|
608
|
+
const PORT = parseInt(process.env.PORT || '8080');
|
|
609
|
+
// Initialize catalog and pricing caches before accepting connections
|
|
610
|
+
Promise.all([
|
|
611
|
+
initCatalogCache(),
|
|
612
|
+
initPricingCache(),
|
|
613
|
+
]).then(() => {
|
|
614
|
+
app.listen(PORT, () => console.error(`Fodda MCP server v${MCP_SERVER_VERSION} on port ${PORT}`));
|
|
615
|
+
}).catch(() => {
|
|
616
|
+
// Start anyway with hardcoded fallbacks if cache init fails
|
|
617
|
+
console.error('[startup] Cache init failed — using hardcoded fallbacks');
|
|
618
|
+
app.listen(PORT, () => console.error(`Fodda MCP server v${MCP_SERVER_VERSION} on port ${PORT} (fallback mode)`));
|
|
605
619
|
});
|
|
606
620
|
//# sourceMappingURL=index.js.map
|