-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathindex.ts
More file actions
374 lines (331 loc) · 12.2 KB
/
index.ts
File metadata and controls
374 lines (331 loc) · 12.2 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
// Copyright (c) Mapbox, Inc.
// Licensed under the MIT License.
// Load environment variables from .env file if present
// Use Node.js built-in util.parseEnv() and manually apply to override existing vars
import { parseEnv } from 'node:util';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { existsSync } from 'node:fs';
import { SpanStatusCode } from '@opentelemetry/api';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
registerAppResource,
RESOURCE_MIME_TYPE
} from '@modelcontextprotocol/ext-apps/server';
import { z } from 'zod';
import { parseToolConfigFromArgs, filterTools } from './config/toolConfig.js';
import {
getCoreTools,
getElicitationTools,
getResourceFallbackTools
} from './tools/toolRegistry.js';
import { getAllResources } from './resources/resourceRegistry.js';
import { getAllPrompts } from './prompts/promptRegistry.js';
import { getVersionInfo } from './utils/versionUtils.js';
import {
initializeTracing,
shutdownTracing,
isTracingInitialized,
getTracer
} from './utils/tracing.js';
// Load .env from current working directory (where npm run is executed)
// This happens before tracing is initialized, but we'll add a span when tracing is ready
const envPath = join(process.cwd(), '.env');
let envLoadError: Error | null = null;
let envLoadedCount = 0;
if (existsSync(envPath)) {
try {
// Read and parse .env file using Node.js built-in parseEnv
const envFile = readFileSync(envPath, 'utf-8');
const parsed = parseEnv(envFile);
// Apply parsed values to process.env (with override)
// Note: process.loadEnvFile() doesn't override, so we use parseEnv + manual assignment
for (const [key, value] of Object.entries(parsed)) {
process.env[key] = value;
envLoadedCount++;
}
} catch (error) {
envLoadError = error instanceof Error ? error : new Error(String(error));
// Error will be logged via MCP logging messages and traced if tracing is enabled
}
}
const versionInfo = getVersionInfo();
// Parse configuration from command-line arguments
const config = parseToolConfigFromArgs();
// Get and filter tools based on configuration
// Split into categories for capability-aware registration
const coreTools = getCoreTools();
const elicitationTools = getElicitationTools();
const resourceFallbackTools = getResourceFallbackTools();
const enabledCoreTools = filterTools(coreTools, config);
const enabledElicitationTools = filterTools(elicitationTools, config);
const enabledResourceFallbackTools = filterTools(resourceFallbackTools, config);
// Create an MCP server
const server = new McpServer(
{
name: versionInfo.name,
version: versionInfo.version
},
{
capabilities: {
tools: {
listChanged: true // Advertise support for dynamic tool registration
},
resources: {},
prompts: {}
}
}
);
// Register only core tools before connection
// Capability-dependent tools will be registered dynamically after connection
enabledCoreTools.forEach((tool) => {
tool.installTo(server);
});
// Register resources to the server
const resources = getAllResources();
// Separate MCP Apps UI resources from regular resources
const uiResources = resources.filter((r) => r.uri.startsWith('ui://'));
const regularResources = resources.filter((r) => !r.uri.startsWith('ui://'));
// Register MCP Apps UI resources using registerAppResource
// IMPORTANT: Use RESOURCE_MIME_TYPE which is "text/html;profile=mcp-app"
// This tells clients (like Claude Desktop) that this is an MCP App
uiResources.forEach((resource) => {
registerAppResource(
server as any,
resource.name,
resource.uri,
{ mimeType: RESOURCE_MIME_TYPE, description: resource.description },
async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return await resource.readCallback(new URL(resource.uri), {} as any);
}
);
});
// Register regular resources using standard registration
regularResources.forEach((resource) => {
resource.installTo(server);
});
// Register prompts to the server
const prompts = getAllPrompts();
prompts.forEach((prompt) => {
const argsSchema: Record<string, z.ZodString | z.ZodOptional<z.ZodString>> =
{};
// Convert prompt arguments to Zod schema format
prompt.arguments.forEach((arg) => {
const zodString = z.string().describe(arg.description);
argsSchema[arg.name] = arg.required ? zodString : zodString.optional();
});
server.registerPrompt(
prompt.name,
{
description: prompt.description,
argsSchema: argsSchema
},
async (args) => {
// Filter out undefined values from optional arguments
const filteredArgs: Record<string, string> = {};
for (const [key, value] of Object.entries(args || {})) {
if (value !== undefined) {
filteredArgs[key] = value;
}
}
return prompt.execute(filteredArgs);
}
);
});
async function main() {
// Send MCP logging messages about .env loading
if (envLoadError) {
server.server.sendLoggingMessage({
level: 'warning',
data: `Failed to load .env file: ${envLoadError.message}`
});
} else if (envLoadedCount > 0) {
server.server.sendLoggingMessage({
level: 'info',
data: `Loaded ${envLoadedCount} environment variables from ${envPath}`
});
} else {
server.server.sendLoggingMessage({
level: 'debug',
data: 'No .env file found or file was empty'
});
}
// Initialize OpenTelemetry tracing if not in test mode
if (process.env.NODE_ENV !== 'test' && !process.env.VITEST) {
try {
await initializeTracing();
// Send MCP logging message about tracing status
if (isTracingInitialized()) {
server.server.sendLoggingMessage({
level: 'info',
data: 'OpenTelemetry tracing enabled'
});
} else {
server.server.sendLoggingMessage({
level: 'debug',
data: 'OpenTelemetry tracing disabled (no OTLP endpoint configured)'
});
}
// Record .env loading as a span (retrospectively since it happened before tracing init)
if (isTracingInitialized()) {
const tracer = getTracer();
const span = tracer.startSpan('config.load_env', {
attributes: {
'config.file.path': envPath,
'config.file.exists': existsSync(envPath),
'config.vars.loaded': envLoadedCount,
'operation.type': 'config_load'
}
});
if (envLoadError) {
span.recordException(envLoadError);
span.setStatus({
code: SpanStatusCode.ERROR,
message: envLoadError.message
});
span.setAttribute('error.type', envLoadError.name);
span.setAttribute('error.message', envLoadError.message);
} else if (envLoadedCount > 0) {
span.setStatus({ code: SpanStatusCode.OK });
span.setAttribute('config.load.success', true);
} else {
// No error, but no variables loaded either (file might be empty or not exist)
span.setStatus({ code: SpanStatusCode.OK });
span.setAttribute('config.load.success', true);
span.setAttribute('config.load.empty', true);
}
span.end();
}
} catch (error) {
// Log tracing initialization failure
server.server.sendLoggingMessage({
level: 'warning',
data: `Failed to initialize tracing: ${error instanceof Error ? error.message : String(error)}`
});
}
}
const relevantEnvVars = Object.freeze({
MAPBOX_ACCESS_TOKEN: process.env.MAPBOX_ACCESS_TOKEN ? '***' : undefined,
MAPBOX_API_ENDPOINT: process.env.MAPBOX_API_ENDPOINT,
OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME,
OTEL_EXPORTER_OTLP_ENDPOINT: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
OTEL_TRACING_ENABLED: process.env.OTEL_TRACING_ENABLED,
OTEL_LOG_LEVEL: process.env.OTEL_LOG_LEVEL,
NODE_ENV: process.env.NODE_ENV
});
server.server.sendLoggingMessage({
level: 'debug',
data: JSON.stringify(relevantEnvVars, null, 2)
});
// Start receiving messages on stdin and sending messages on stdout
const transport = new StdioServerTransport();
await server.connect(transport);
// After connection, dynamically register capability-dependent tools
const clientCapabilities = server.server.getClientCapabilities();
// Debug: Log what capabilities we detected
server.server.sendLoggingMessage({
level: 'info',
data: `Client capabilities detected: ${JSON.stringify(clientCapabilities, null, 2)}`
});
let toolsAdded = false;
// Register elicitation tools if client supports elicitation
if (clientCapabilities?.elicitation && enabledElicitationTools.length > 0) {
server.server.sendLoggingMessage({
level: 'info',
data: `Client supports elicitation. Registering ${enabledElicitationTools.length} elicitation-dependent tools`
});
enabledElicitationTools.forEach((tool) => {
tool.installTo(server);
});
toolsAdded = true;
} else if (enabledElicitationTools.length > 0) {
server.server.sendLoggingMessage({
level: 'debug',
data: `Client does not support elicitation. Skipping ${enabledElicitationTools.length} elicitation-dependent tools`
});
}
// Register resource fallback tools for clients that don't support resources
// Note: Resources are a core MCP feature supported by most clients.
// However, some clients (like smolagents) don't support resources at all.
// These fallback tools provide the same content as resources but via tool calls instead.
//
// Configuration via CLIENT_NEEDS_RESOURCE_FALLBACK environment variable:
// - unset (default) = Skip fallback tools (assume client supports resources)
// - "true" = Provide fallback tools (client does NOT support resources)
const clientNeedsResourceFallback =
process.env.CLIENT_NEEDS_RESOURCE_FALLBACK?.toLowerCase() === 'true';
if (clientNeedsResourceFallback && enabledResourceFallbackTools.length > 0) {
server.server.sendLoggingMessage({
level: 'info',
data: `CLIENT_NEEDS_RESOURCE_FALLBACK=true. Registering ${enabledResourceFallbackTools.length} resource fallback tools`
});
enabledResourceFallbackTools.forEach((tool) => {
tool.installTo(server);
});
toolsAdded = true;
} else if (enabledResourceFallbackTools.length > 0) {
server.server.sendLoggingMessage({
level: 'debug',
data: `CLIENT_NEEDS_RESOURCE_FALLBACK not set or false. Skipping ${enabledResourceFallbackTools.length} resource fallback tools (client supports resources)`
});
}
// Notify client about tool list changes if any tools were added
if (toolsAdded) {
try {
server.sendToolListChanged();
server.server.sendLoggingMessage({
level: 'debug',
data: 'Sent notifications/tools/list_changed to client'
});
} catch (error) {
server.server.sendLoggingMessage({
level: 'warning',
data: `Failed to send tool list change notification: ${error instanceof Error ? error.message : String(error)}`
});
}
}
}
// Ensure cleanup interval is cleared when the process exits
async function shutdown() {
// Shutdown tracing
try {
await shutdownTracing();
server.server.sendLoggingMessage({
level: 'info',
data: 'Server shutting down gracefully'
});
} catch (error) {
server.server.sendLoggingMessage({
level: 'warning',
data: `Error during shutdown: ${error instanceof Error ? error.message : String(error)}`
});
}
process.exit(0);
}
function exitWithError(error: unknown, code = 1) {
// Use MCP logging for fatal errors
try {
server.server.sendLoggingMessage({
level: 'error',
data: `Fatal error: ${error instanceof Error ? error.message : String(error)}`
});
} catch {
// If MCP logging fails, we have no choice but to use console
console.error('Fatal error:', error);
}
process.exit(code);
}
['SIGINT', 'SIGTERM'].forEach((signal) => {
process.on(signal, async () => {
try {
await shutdown();
} finally {
process.exit(0);
}
});
});
process.on('uncaughtException', (err) => exitWithError(err));
process.on('unhandledRejection', (reason) => exitWithError(reason));
main().catch((error) => exitWithError(error));