it-tools-mcp 4.1.8 → 4.1.14
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/README.md +91 -3
- package/build/index.js +513 -31
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
> **📝 Note**: A condensed version of this README is automatically synced to [Docker Hub](https://hub.docker.com/r/wrenchpilot/it-tools-mcp) due to character limits.
|
|
16
16
|
|
|
17
|
-
A comprehensive Model Context Protocol (MCP) server that provides access to over
|
|
17
|
+
A comprehensive Model Context Protocol (MCP) server that provides access to over 121 IT tools and utilities commonly used by developers, system administrators, and IT professionals. This server exposes a complete set of tools for encoding/decoding, text manipulation, hashing, network utilities, and many other common development and IT tasks.
|
|
18
18
|
|
|
19
19
|
## 📦 Installation & Setup
|
|
20
20
|
|
|
@@ -94,9 +94,97 @@ echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"encode_bas
|
|
|
94
94
|
docker run -i --rm wrenchpilot/it-tools-mcp:latest
|
|
95
95
|
```
|
|
96
96
|
|
|
97
|
-
##
|
|
97
|
+
## � MCP Logging Capabilities
|
|
98
98
|
|
|
99
|
-
This
|
|
99
|
+
This server includes full MCP logging support with the following features:
|
|
100
|
+
|
|
101
|
+
### Log Levels
|
|
102
|
+
|
|
103
|
+
- **debug** (0): Detailed debug information
|
|
104
|
+
- **info** (1): General information messages
|
|
105
|
+
- **notice** (2): Normal but significant events
|
|
106
|
+
- **warning** (3): Warning conditions
|
|
107
|
+
- **error** (4): Error conditions
|
|
108
|
+
- **critical** (5): Critical conditions
|
|
109
|
+
- **alert** (6): Action must be taken immediately
|
|
110
|
+
- **emergency** (7): System is unusable
|
|
111
|
+
|
|
112
|
+
### Logging Tools
|
|
113
|
+
|
|
114
|
+
- **`logging_setLevel`**: Change the minimum logging level at runtime
|
|
115
|
+
- **`logging_status`**: View current logging configuration and available levels
|
|
116
|
+
|
|
117
|
+
### Environment-Aware Behavior
|
|
118
|
+
|
|
119
|
+
- **Development Mode**: Debug level by default, enhanced console output
|
|
120
|
+
- **Production Mode**: Info level by default, clean output for MCP compliance
|
|
121
|
+
- **Automatic Fallback**: Console logging when MCP transport isn't ready
|
|
122
|
+
|
|
123
|
+
### Usage Examples
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
# Check current logging status
|
|
127
|
+
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"logging_status","arguments":{}}}' | npx it-tools-mcp
|
|
128
|
+
|
|
129
|
+
# Change log level to debug
|
|
130
|
+
echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"logging_setLevel","arguments":{"level":"debug"}}}' | npx it-tools-mcp
|
|
131
|
+
|
|
132
|
+
# Change log level to error (only show errors and above)
|
|
133
|
+
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"logging_setLevel","arguments":{"level":"error"}}}' | npx it-tools-mcp
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## 🔧 MCP Protocol Utilities
|
|
137
|
+
|
|
138
|
+
This server implements the complete MCP 2025-06-18 specification including advanced utilities:
|
|
139
|
+
|
|
140
|
+
### Ping Utility
|
|
141
|
+
|
|
142
|
+
- **Health Checking**: Use `ping` requests to verify connection status
|
|
143
|
+
- **Automatic Response**: Server responds promptly with empty result per MCP spec
|
|
144
|
+
- **Connection Monitoring**: Implement periodic health checks
|
|
145
|
+
|
|
146
|
+
### Progress Tracking
|
|
147
|
+
|
|
148
|
+
- **Long-Running Operations**: Receive progress updates for time-consuming tasks
|
|
149
|
+
- **Progress Tokens**: Include `_meta.progressToken` in requests to enable progress notifications
|
|
150
|
+
- **Notifications**: Server sends `notifications/progress` with current status
|
|
151
|
+
|
|
152
|
+
### Request Cancellation
|
|
153
|
+
|
|
154
|
+
- **Graceful Cancellation**: Send `notifications/cancelled` to abort in-progress requests
|
|
155
|
+
- **Resource Cleanup**: Server properly frees resources when requests are cancelled
|
|
156
|
+
- **Race Condition Handling**: Robust handling of timing edge cases
|
|
157
|
+
|
|
158
|
+
### Sampling Support
|
|
159
|
+
|
|
160
|
+
- **LLM Integration**: Server can request LLM completions from clients using `sampling/createMessage`
|
|
161
|
+
- **Model Preferences**: Support for model selection hints and capability priorities (cost, speed, intelligence)
|
|
162
|
+
- **Content Types**: Support for text, image, and audio content in sampling requests
|
|
163
|
+
- **Agentic Workflows**: Enable AI-powered tool operations through nested LLM calls
|
|
164
|
+
- **Client Control**: Clients maintain full control over model access and user approval
|
|
165
|
+
|
|
166
|
+
### Protocol Examples
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
# Test connection health with ping
|
|
170
|
+
echo '{"jsonrpc":"2.0","id":1,"method":"ping"}' | npx it-tools-mcp
|
|
171
|
+
|
|
172
|
+
# Request with progress tracking
|
|
173
|
+
echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"some_tool","arguments":{},"_meta":{"progressToken":"track123"}}}' | npx it-tools-mcp
|
|
174
|
+
|
|
175
|
+
# Cancel a request (send as notification)
|
|
176
|
+
echo '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"2","reason":"User cancelled"}}' | npx it-tools-mcp
|
|
177
|
+
|
|
178
|
+
# Test sampling capabilities
|
|
179
|
+
echo '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"mcp_sampling_demo","arguments":{"message":"What is the capital of France?","modelPreference":"claude","systemPrompt":"You are a helpful assistant.","maxTokens":100}}}' | npx it-tools-mcp
|
|
180
|
+
|
|
181
|
+
# Demo MCP utilities
|
|
182
|
+
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"mcp_utilities_demo","arguments":{"operation":"ping"}}}' | npx it-tools-mcp
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## �🛠️ Tool Categories
|
|
186
|
+
|
|
187
|
+
This MCP server provides over **121 tools** across **14 categories**:
|
|
100
188
|
|
|
101
189
|
- **� Ansible Tools** (5 tools): Vault encryption/decryption, inventory parser, playbook validator, reference
|
|
102
190
|
- **🎨 Color Tools** (2 tools): Hex ↔ RGB conversion
|
package/build/index.js
CHANGED
|
@@ -6,8 +6,6 @@ import { z } from "zod";
|
|
|
6
6
|
import fs from 'fs';
|
|
7
7
|
import path from 'path';
|
|
8
8
|
import { fileURLToPath } from 'url';
|
|
9
|
-
import { exec } from 'child_process';
|
|
10
|
-
import { promisify } from 'util';
|
|
11
9
|
const __filename = fileURLToPath(import.meta.url);
|
|
12
10
|
const __dirname = path.dirname(__filename);
|
|
13
11
|
/**
|
|
@@ -110,7 +108,7 @@ export function secureToolHandler(handler, identifier = 'default') {
|
|
|
110
108
|
}
|
|
111
109
|
catch (error) {
|
|
112
110
|
// Log error without exposing sensitive information
|
|
113
|
-
|
|
111
|
+
mcpLog('error', `Tool error for ${identifier}`, error instanceof Error ? error.message : 'Unknown error');
|
|
114
112
|
// Return safe error message
|
|
115
113
|
throw new Error('Tool execution failed. Please check your input and try again.');
|
|
116
114
|
}
|
|
@@ -223,10 +221,27 @@ function getPackageMetadata() {
|
|
|
223
221
|
}
|
|
224
222
|
// Create server instance with enhanced metadata and VS Code compliance features
|
|
225
223
|
const packageInfo = getPackageMetadata();
|
|
226
|
-
const execAsync = promisify(exec);
|
|
227
224
|
// Environment detection
|
|
228
225
|
const isDevelopment = process.env.NODE_ENV === 'development' || process.env.MCP_DEV_MODE === 'true';
|
|
229
226
|
const isTest = process.env.NODE_ENV === 'test';
|
|
227
|
+
// MCP Logging Implementation
|
|
228
|
+
const LOG_LEVELS = {
|
|
229
|
+
debug: 0,
|
|
230
|
+
info: 1,
|
|
231
|
+
notice: 2,
|
|
232
|
+
warning: 3,
|
|
233
|
+
error: 4,
|
|
234
|
+
critical: 5,
|
|
235
|
+
alert: 6,
|
|
236
|
+
emergency: 7
|
|
237
|
+
};
|
|
238
|
+
// Current minimum log level (default to info in production, debug in development)
|
|
239
|
+
let currentLogLevel = isDevelopment ? LOG_LEVELS.debug : LOG_LEVELS.info;
|
|
240
|
+
let mcpTransportReady = false;
|
|
241
|
+
// Progress tracking
|
|
242
|
+
const activeProgressTokens = new Map();
|
|
243
|
+
// Request cancellation tracking
|
|
244
|
+
const activeRequests = new Map();
|
|
230
245
|
const server = new McpServer({
|
|
231
246
|
name: "it-tools-mcp",
|
|
232
247
|
version: packageInfo.version,
|
|
@@ -243,8 +258,459 @@ const server = new McpServer({
|
|
|
243
258
|
sampling: {},
|
|
244
259
|
roots: {
|
|
245
260
|
listChanged: true
|
|
261
|
+
},
|
|
262
|
+
logging: {}
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
// MCP Logging Functions
|
|
266
|
+
function mcpLog(level, message, data) {
|
|
267
|
+
const levelValue = LOG_LEVELS[level];
|
|
268
|
+
// Only send if level meets minimum threshold
|
|
269
|
+
if (levelValue >= currentLogLevel && mcpTransportReady) {
|
|
270
|
+
try {
|
|
271
|
+
// Send MCP logging notification (using the transport directly)
|
|
272
|
+
// Note: The MCP SDK may handle this differently - this is a placeholder for the proper implementation
|
|
273
|
+
}
|
|
274
|
+
catch (error) {
|
|
275
|
+
// Fallback to console if MCP notification fails
|
|
276
|
+
console.error(`[${level.toUpperCase()}] ${message}`, data || '');
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
// Also log to console for development/debugging
|
|
280
|
+
if (isDevelopment || level === 'error' || level === 'critical' || level === 'emergency') {
|
|
281
|
+
console.error(`[${level.toUpperCase()}] ${message}`, data || '');
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
// Register logging/setLevel handler using the tool registration pattern
|
|
285
|
+
server.registerTool("logging_setLevel", {
|
|
286
|
+
description: "Set the minimum logging level for MCP logging notifications. Available levels: debug, info, notice, warning, error, critical, alert, emergency",
|
|
287
|
+
inputSchema: {
|
|
288
|
+
level: z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']).describe("The minimum log level to report")
|
|
289
|
+
}
|
|
290
|
+
}, async (args) => {
|
|
291
|
+
const { level } = args;
|
|
292
|
+
const oldLevelName = Object.keys(LOG_LEVELS).find(k => LOG_LEVELS[k] === currentLogLevel);
|
|
293
|
+
currentLogLevel = LOG_LEVELS[level];
|
|
294
|
+
mcpLog('info', `Log level changed from ${oldLevelName} to ${level}`);
|
|
295
|
+
return {
|
|
296
|
+
content: [{
|
|
297
|
+
type: "text",
|
|
298
|
+
text: JSON.stringify({
|
|
299
|
+
success: true,
|
|
300
|
+
previousLevel: oldLevelName,
|
|
301
|
+
newLevel: level,
|
|
302
|
+
message: `Logging level set to ${level}`,
|
|
303
|
+
availableLevels: Object.keys(LOG_LEVELS),
|
|
304
|
+
currentLevelValue: currentLogLevel
|
|
305
|
+
}, null, 2)
|
|
306
|
+
}]
|
|
307
|
+
};
|
|
308
|
+
});
|
|
309
|
+
// Add logging status tool
|
|
310
|
+
server.registerTool("logging_status", {
|
|
311
|
+
description: "Get current MCP logging configuration and status",
|
|
312
|
+
inputSchema: {}
|
|
313
|
+
}, async (args) => {
|
|
314
|
+
const currentLevelName = Object.keys(LOG_LEVELS).find(k => LOG_LEVELS[k] === currentLogLevel);
|
|
315
|
+
return {
|
|
316
|
+
content: [{
|
|
317
|
+
type: "text",
|
|
318
|
+
text: JSON.stringify({
|
|
319
|
+
currentLevel: currentLevelName,
|
|
320
|
+
currentLevelValue: currentLogLevel,
|
|
321
|
+
transportReady: mcpTransportReady,
|
|
322
|
+
environment: isDevelopment ? 'development' : 'production',
|
|
323
|
+
availableLevels: Object.entries(LOG_LEVELS).map(([name, value]) => ({
|
|
324
|
+
name,
|
|
325
|
+
value,
|
|
326
|
+
active: value >= currentLogLevel
|
|
327
|
+
})),
|
|
328
|
+
logLevelDescriptions: {
|
|
329
|
+
debug: "Detailed debug information (level 0)",
|
|
330
|
+
info: "General information messages (level 1)",
|
|
331
|
+
notice: "Normal but significant events (level 2)",
|
|
332
|
+
warning: "Warning conditions (level 3)",
|
|
333
|
+
error: "Error conditions (level 4)",
|
|
334
|
+
critical: "Critical conditions (level 5)",
|
|
335
|
+
alert: "Action must be taken immediately (level 6)",
|
|
336
|
+
emergency: "System is unusable (level 7)"
|
|
337
|
+
}
|
|
338
|
+
}, null, 2)
|
|
339
|
+
}]
|
|
340
|
+
};
|
|
341
|
+
});
|
|
342
|
+
// MCP Utilities Implementation
|
|
343
|
+
// Ping utility - connection health check
|
|
344
|
+
server.server.setRequestHandler(z.object({ method: z.literal("ping") }), async () => {
|
|
345
|
+
mcpLog('debug', 'Ping request received');
|
|
346
|
+
return {}; // Empty response as per spec
|
|
347
|
+
});
|
|
348
|
+
// Progress notification function
|
|
349
|
+
function sendProgressNotification(progressToken, progress, total, message) {
|
|
350
|
+
if (!mcpTransportReady || !activeProgressTokens.has(progressToken)) {
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
try {
|
|
354
|
+
server.server.notification({
|
|
355
|
+
method: "notifications/progress",
|
|
356
|
+
params: {
|
|
357
|
+
progressToken,
|
|
358
|
+
progress,
|
|
359
|
+
...(total !== undefined && { total }),
|
|
360
|
+
...(message && { message })
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
mcpLog('debug', `Progress notification sent for token ${progressToken}: ${progress}${total ? `/${total}` : ''}`);
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
mcpLog('warning', `Failed to send progress notification for token ${progressToken}`, error instanceof Error ? error.message : 'Unknown error');
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
// Cancellation notification handler
|
|
370
|
+
server.server.setNotificationHandler(z.object({
|
|
371
|
+
method: z.literal("notifications/cancelled"),
|
|
372
|
+
params: z.object({
|
|
373
|
+
requestId: z.union([z.string(), z.number()]),
|
|
374
|
+
reason: z.string().optional()
|
|
375
|
+
})
|
|
376
|
+
}), async (notification) => {
|
|
377
|
+
const { requestId, reason } = notification.params;
|
|
378
|
+
mcpLog('info', `Cancellation requested for request ${requestId}`, reason ? { reason } : undefined);
|
|
379
|
+
const activeRequest = activeRequests.get(requestId);
|
|
380
|
+
if (activeRequest) {
|
|
381
|
+
// Cancel the request using AbortController
|
|
382
|
+
activeRequest.abortController.abort(reason || 'Request cancelled');
|
|
383
|
+
activeRequests.delete(requestId);
|
|
384
|
+
mcpLog('info', `Request ${requestId} cancelled successfully`);
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
mcpLog('debug', `Cancellation notification for unknown or completed request: ${requestId}`);
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
// Helper function to extract progress token from request metadata
|
|
391
|
+
function extractProgressToken(params) {
|
|
392
|
+
return params?._meta?.progressToken;
|
|
393
|
+
}
|
|
394
|
+
// Helper function to register active request for cancellation support
|
|
395
|
+
function registerActiveRequest(requestId) {
|
|
396
|
+
const abortController = new AbortController();
|
|
397
|
+
activeRequests.set(requestId, {
|
|
398
|
+
abortController,
|
|
399
|
+
startTime: Date.now()
|
|
400
|
+
});
|
|
401
|
+
return abortController;
|
|
402
|
+
}
|
|
403
|
+
// Helper function to unregister active request
|
|
404
|
+
function unregisterActiveRequest(requestId) {
|
|
405
|
+
activeRequests.delete(requestId);
|
|
406
|
+
}
|
|
407
|
+
// Enhanced tool handler with cancellation and progress support
|
|
408
|
+
export function mcpToolHandler(handler, identifier = 'default') {
|
|
409
|
+
return async (params, extra) => {
|
|
410
|
+
// Rate limiting check
|
|
411
|
+
if (!rateLimiter.isAllowed(identifier)) {
|
|
412
|
+
throw new Error('Rate limit exceeded. Please try again later.');
|
|
413
|
+
}
|
|
414
|
+
// Extract progress token if provided
|
|
415
|
+
const progressToken = extractProgressToken(params);
|
|
416
|
+
if (progressToken) {
|
|
417
|
+
activeProgressTokens.set(progressToken, true);
|
|
418
|
+
}
|
|
419
|
+
// Register request for cancellation if requestId provided
|
|
420
|
+
let abortController;
|
|
421
|
+
if (extra?.requestId) {
|
|
422
|
+
abortController = registerActiveRequest(extra.requestId);
|
|
423
|
+
}
|
|
424
|
+
// Create combined abort signal
|
|
425
|
+
const signals = [extra?.signal, abortController?.signal].filter(Boolean);
|
|
426
|
+
let combinedSignal;
|
|
427
|
+
if (signals.length > 0) {
|
|
428
|
+
const combinedController = new AbortController();
|
|
429
|
+
combinedSignal = combinedController.signal;
|
|
430
|
+
signals.forEach(signal => {
|
|
431
|
+
if (signal.aborted) {
|
|
432
|
+
combinedController.abort(signal.reason);
|
|
433
|
+
}
|
|
434
|
+
else {
|
|
435
|
+
signal.addEventListener('abort', () => {
|
|
436
|
+
combinedController.abort(signal.reason);
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
// Progress callback
|
|
442
|
+
const progressCallback = progressToken
|
|
443
|
+
? (progress, total, message) => {
|
|
444
|
+
sendProgressNotification(progressToken, progress, total, message);
|
|
445
|
+
}
|
|
446
|
+
: undefined;
|
|
447
|
+
try {
|
|
448
|
+
const result = await handler(params, {
|
|
449
|
+
signal: combinedSignal,
|
|
450
|
+
progressCallback
|
|
451
|
+
});
|
|
452
|
+
return result;
|
|
453
|
+
}
|
|
454
|
+
catch (error) {
|
|
455
|
+
// Log error without exposing sensitive information
|
|
456
|
+
mcpLog('error', `Tool error for ${identifier}`, error instanceof Error ? error.message : 'Unknown error');
|
|
457
|
+
// Return safe error message
|
|
458
|
+
throw new Error('Tool execution failed. Please check your input and try again.');
|
|
246
459
|
}
|
|
460
|
+
finally {
|
|
461
|
+
// Cleanup
|
|
462
|
+
if (progressToken) {
|
|
463
|
+
activeProgressTokens.delete(progressToken);
|
|
464
|
+
}
|
|
465
|
+
if (extra?.requestId) {
|
|
466
|
+
unregisterActiveRequest(extra.requestId);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
// Demo tools for MCP utilities
|
|
472
|
+
server.registerTool("mcp_utilities_demo", {
|
|
473
|
+
description: "Demonstrate MCP utilities: ping, progress tracking, and cancellation support",
|
|
474
|
+
inputSchema: {
|
|
475
|
+
operation: z.enum(['ping', 'long_task', 'cancellable_task']).describe("The MCP utility operation to demonstrate"),
|
|
476
|
+
duration: z.number().optional().describe("Duration in seconds for long-running tasks (default: 10)"),
|
|
477
|
+
steps: z.number().optional().describe("Number of progress steps for demonstrating progress tracking (default: 5)")
|
|
478
|
+
}
|
|
479
|
+
}, async (args) => {
|
|
480
|
+
const { operation, duration = 10, steps = 5 } = args;
|
|
481
|
+
if (operation === 'ping') {
|
|
482
|
+
return {
|
|
483
|
+
content: [{
|
|
484
|
+
type: "text",
|
|
485
|
+
text: JSON.stringify({
|
|
486
|
+
operation: 'ping',
|
|
487
|
+
status: 'success',
|
|
488
|
+
message: 'MCP ping utility is working correctly',
|
|
489
|
+
timestamp: new Date().toISOString(),
|
|
490
|
+
usage: 'Send a "ping" request to test connection health'
|
|
491
|
+
}, null, 2)
|
|
492
|
+
}]
|
|
493
|
+
};
|
|
247
494
|
}
|
|
495
|
+
if (operation === 'long_task') {
|
|
496
|
+
// Simulate a long-running task with progress updates
|
|
497
|
+
const totalMs = duration * 1000;
|
|
498
|
+
const stepMs = totalMs / steps;
|
|
499
|
+
return {
|
|
500
|
+
content: [{
|
|
501
|
+
type: "text",
|
|
502
|
+
text: JSON.stringify({
|
|
503
|
+
operation: 'long_task',
|
|
504
|
+
status: 'completed',
|
|
505
|
+
message: `Simulated ${duration}s task with ${steps} progress updates`,
|
|
506
|
+
note: 'Use _meta.progressToken in your request to receive progress notifications',
|
|
507
|
+
example: {
|
|
508
|
+
request: {
|
|
509
|
+
jsonrpc: "2.0",
|
|
510
|
+
id: 1,
|
|
511
|
+
method: "tools/call",
|
|
512
|
+
params: {
|
|
513
|
+
name: "mcp_utilities_demo",
|
|
514
|
+
arguments: { operation: "long_task", duration: 5, steps: 3 },
|
|
515
|
+
_meta: { progressToken: "demo123" }
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}, null, 2)
|
|
520
|
+
}]
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
if (operation === 'cancellable_task') {
|
|
524
|
+
return {
|
|
525
|
+
content: [{
|
|
526
|
+
type: "text",
|
|
527
|
+
text: JSON.stringify({
|
|
528
|
+
operation: 'cancellable_task',
|
|
529
|
+
status: 'completed',
|
|
530
|
+
message: 'Simulated cancellable task',
|
|
531
|
+
note: 'Send a notifications/cancelled message to cancel in-progress requests',
|
|
532
|
+
example: {
|
|
533
|
+
cancel_notification: {
|
|
534
|
+
jsonrpc: "2.0",
|
|
535
|
+
method: "notifications/cancelled",
|
|
536
|
+
params: {
|
|
537
|
+
requestId: "your_request_id",
|
|
538
|
+
reason: "User requested cancellation"
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}, null, 2)
|
|
543
|
+
}]
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
return {
|
|
547
|
+
content: [{
|
|
548
|
+
type: "text",
|
|
549
|
+
text: JSON.stringify({ error: 'Unknown operation' }, null, 2)
|
|
550
|
+
}]
|
|
551
|
+
};
|
|
552
|
+
});
|
|
553
|
+
// Sampling demo tool
|
|
554
|
+
server.registerTool("mcp_sampling_demo", {
|
|
555
|
+
description: "Demonstrate MCP sampling capabilities and test sampling/createMessage requests",
|
|
556
|
+
inputSchema: {
|
|
557
|
+
message: z.string().describe("The message to send in the sampling request"),
|
|
558
|
+
modelPreference: z.enum(['claude', 'gpt', 'gemini', 'generic']).optional().describe("Preferred model family for demonstration"),
|
|
559
|
+
systemPrompt: z.string().optional().describe("System prompt to include in the sampling request"),
|
|
560
|
+
maxTokens: z.number().positive().optional().describe("Maximum tokens for the response (default: 100)"),
|
|
561
|
+
intelligence: z.number().min(0).max(1).optional().describe("Intelligence priority (0-1, higher = more capable models)"),
|
|
562
|
+
speed: z.number().min(0).max(1).optional().describe("Speed priority (0-1, higher = faster models)"),
|
|
563
|
+
cost: z.number().min(0).max(1).optional().describe("Cost priority (0-1, higher = cheaper models)")
|
|
564
|
+
}
|
|
565
|
+
}, async (args) => {
|
|
566
|
+
const { message, modelPreference, systemPrompt, maxTokens = 100, intelligence = 0.7, speed = 0.5, cost = 0.3 } = args;
|
|
567
|
+
// Build model preferences based on user input
|
|
568
|
+
const modelPreferences = {
|
|
569
|
+
intelligencePriority: intelligence,
|
|
570
|
+
speedPriority: speed,
|
|
571
|
+
costPriority: cost
|
|
572
|
+
};
|
|
573
|
+
// Add model hints based on preference
|
|
574
|
+
if (modelPreference) {
|
|
575
|
+
const hintMap = {
|
|
576
|
+
'claude': [{ name: 'claude-4-sonnet' }, { name: 'claude' }],
|
|
577
|
+
'gpt': [{ name: 'gpt-4' }, { name: 'gpt' }],
|
|
578
|
+
'gemini': [{ name: 'gemini-1.5-pro' }, { name: 'gemini' }],
|
|
579
|
+
'generic': [{ name: 'general-purpose' }]
|
|
580
|
+
};
|
|
581
|
+
modelPreferences.hints = hintMap[modelPreference];
|
|
582
|
+
}
|
|
583
|
+
// Create the sampling request
|
|
584
|
+
const samplingRequest = {
|
|
585
|
+
method: "sampling/createMessage",
|
|
586
|
+
params: {
|
|
587
|
+
messages: [
|
|
588
|
+
{
|
|
589
|
+
role: "user",
|
|
590
|
+
content: {
|
|
591
|
+
type: "text",
|
|
592
|
+
text: message
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
],
|
|
596
|
+
modelPreferences,
|
|
597
|
+
...(systemPrompt && { systemPrompt }),
|
|
598
|
+
maxTokens
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
return {
|
|
602
|
+
content: [{
|
|
603
|
+
type: "text",
|
|
604
|
+
text: JSON.stringify({
|
|
605
|
+
demo: 'MCP Sampling Protocol Demonstration',
|
|
606
|
+
status: 'request_prepared',
|
|
607
|
+
message: 'Here is the sampling request that would be sent to the MCP client',
|
|
608
|
+
request: samplingRequest,
|
|
609
|
+
explanation: {
|
|
610
|
+
protocol: 'MCP 2025-06-18 sampling/createMessage',
|
|
611
|
+
purpose: 'This demonstrates how servers can request LLM completions from clients',
|
|
612
|
+
modelSelection: modelPreferences.hints ?
|
|
613
|
+
`Prefers ${modelPreference} models with intelligence=${intelligence}, speed=${speed}, cost=${cost}` :
|
|
614
|
+
`No specific model preference, using priorities: intelligence=${intelligence}, speed=${speed}, cost=${cost}`,
|
|
615
|
+
flow: [
|
|
616
|
+
'1. Server sends sampling/createMessage request to client',
|
|
617
|
+
'2. Client selects appropriate model based on preferences',
|
|
618
|
+
'3. Client processes the message through the selected LLM',
|
|
619
|
+
'4. Client returns the LLM response to the server',
|
|
620
|
+
'5. Server can use the response for its tool operations'
|
|
621
|
+
],
|
|
622
|
+
security: 'Clients SHOULD implement user approval controls for sampling requests'
|
|
623
|
+
},
|
|
624
|
+
nextSteps: 'In production, this request would be sent to the MCP client for actual LLM processing'
|
|
625
|
+
}, null, 2)
|
|
626
|
+
}]
|
|
627
|
+
};
|
|
628
|
+
});
|
|
629
|
+
// MCP Sampling Implementation - Server-side LLM request handling
|
|
630
|
+
server.server.setRequestHandler(z.object({
|
|
631
|
+
method: z.literal("sampling/createMessage"),
|
|
632
|
+
params: z.object({
|
|
633
|
+
messages: z.array(z.object({
|
|
634
|
+
role: z.enum(["user", "assistant", "system"]),
|
|
635
|
+
content: z.union([
|
|
636
|
+
z.object({
|
|
637
|
+
type: z.literal("text"),
|
|
638
|
+
text: z.string()
|
|
639
|
+
}),
|
|
640
|
+
z.object({
|
|
641
|
+
type: z.literal("image"),
|
|
642
|
+
data: z.string(),
|
|
643
|
+
mimeType: z.string()
|
|
644
|
+
}),
|
|
645
|
+
z.object({
|
|
646
|
+
type: z.literal("audio"),
|
|
647
|
+
data: z.string(),
|
|
648
|
+
mimeType: z.string()
|
|
649
|
+
})
|
|
650
|
+
])
|
|
651
|
+
})),
|
|
652
|
+
modelPreferences: z.object({
|
|
653
|
+
hints: z.array(z.object({
|
|
654
|
+
name: z.string()
|
|
655
|
+
})).optional(),
|
|
656
|
+
costPriority: z.number().min(0).max(1).optional(),
|
|
657
|
+
speedPriority: z.number().min(0).max(1).optional(),
|
|
658
|
+
intelligencePriority: z.number().min(0).max(1).optional()
|
|
659
|
+
}).optional(),
|
|
660
|
+
systemPrompt: z.string().optional(),
|
|
661
|
+
maxTokens: z.number().positive().optional(),
|
|
662
|
+
temperature: z.number().min(0).max(2).optional(),
|
|
663
|
+
stopSequences: z.array(z.string()).optional(),
|
|
664
|
+
metadata: z.record(z.any()).optional()
|
|
665
|
+
})
|
|
666
|
+
}), async (request) => {
|
|
667
|
+
const { messages, modelPreferences, systemPrompt, maxTokens, temperature, stopSequences, metadata } = request.params;
|
|
668
|
+
mcpLog('info', 'Sampling request received', {
|
|
669
|
+
messageCount: messages.length,
|
|
670
|
+
modelPreferences: modelPreferences ? Object.keys(modelPreferences) : undefined,
|
|
671
|
+
hasSystemPrompt: !!systemPrompt,
|
|
672
|
+
maxTokens
|
|
673
|
+
});
|
|
674
|
+
// In a real implementation, this would:
|
|
675
|
+
// 1. Forward the request to the client's LLM service
|
|
676
|
+
// 2. Apply model preferences and selection logic
|
|
677
|
+
// 3. Handle different content types (text, image, audio)
|
|
678
|
+
// 4. Return the LLM response
|
|
679
|
+
// For this MCP server implementation, we return a helpful response
|
|
680
|
+
// explaining that this is a demonstration of the sampling protocol
|
|
681
|
+
// and that the actual LLM processing would be handled by the client
|
|
682
|
+
const demoResponse = {
|
|
683
|
+
role: "assistant",
|
|
684
|
+
content: {
|
|
685
|
+
type: "text",
|
|
686
|
+
text: `This is a demonstration of MCP sampling protocol support.
|
|
687
|
+
|
|
688
|
+
In a production environment, this request would be forwarded to an LLM service based on your model preferences:
|
|
689
|
+
${modelPreferences?.hints?.length ? `- Preferred models: ${modelPreferences.hints.map(h => h.name).join(', ')}` : '- No specific model preferences'}
|
|
690
|
+
${modelPreferences?.intelligencePriority ? `- Intelligence priority: ${modelPreferences.intelligencePriority}` : ''}
|
|
691
|
+
${modelPreferences?.speedPriority ? `- Speed priority: ${modelPreferences.speedPriority}` : ''}
|
|
692
|
+
${modelPreferences?.costPriority ? `- Cost priority: ${modelPreferences.costPriority}` : ''}
|
|
693
|
+
|
|
694
|
+
Your message: "${messages[messages.length - 1]?.content?.type === 'text' ? messages[messages.length - 1].content.text : 'Non-text content'}"
|
|
695
|
+
|
|
696
|
+
${systemPrompt ? `System prompt: "${systemPrompt}"` : 'No system prompt provided'}
|
|
697
|
+
${maxTokens ? `Max tokens: ${maxTokens}` : 'No token limit specified'}
|
|
698
|
+
|
|
699
|
+
This server supports the full MCP 2025-06-18 sampling specification and is ready for production use with proper LLM integration.`
|
|
700
|
+
},
|
|
701
|
+
model: "mcp-demo-server",
|
|
702
|
+
stopReason: "endTurn",
|
|
703
|
+
usage: {
|
|
704
|
+
inputTokens: messages.reduce((sum, msg) => sum + (msg.content.type === 'text' ? msg.content.text.length / 4 : 100), 0),
|
|
705
|
+
outputTokens: 150
|
|
706
|
+
}
|
|
707
|
+
};
|
|
708
|
+
mcpLog('debug', 'Sampling response generated', {
|
|
709
|
+
model: demoResponse.model,
|
|
710
|
+
stopReason: demoResponse.stopReason,
|
|
711
|
+
outputTokens: demoResponse.usage.outputTokens
|
|
712
|
+
});
|
|
713
|
+
return demoResponse;
|
|
248
714
|
});
|
|
249
715
|
// VS Code MCP Compliance: Implement Resources
|
|
250
716
|
server.registerResource("server-manifest", new ResourceTemplate("manifest://{type}", {
|
|
@@ -483,7 +949,9 @@ function getAnalysisPrompt(analysisType, content) {
|
|
|
483
949
|
async function loadModularTools(server, category) {
|
|
484
950
|
const toolsDir = path.join(__dirname, 'tools', category);
|
|
485
951
|
if (!fs.existsSync(toolsDir)) {
|
|
486
|
-
|
|
952
|
+
if (isDevelopment) {
|
|
953
|
+
mcpLog('warning', `Category directory does not exist: ${toolsDir}`);
|
|
954
|
+
}
|
|
487
955
|
return;
|
|
488
956
|
}
|
|
489
957
|
const toolDirs = fs.readdirSync(toolsDir, { withFileTypes: true })
|
|
@@ -499,22 +967,33 @@ async function loadModularTools(server, category) {
|
|
|
499
967
|
if (registerFunction) {
|
|
500
968
|
try {
|
|
501
969
|
registerFunction(server);
|
|
502
|
-
|
|
970
|
+
// Only log tool loading in development mode
|
|
971
|
+
if (isDevelopment) {
|
|
972
|
+
mcpLog('debug', `Loaded tool: ${category}/${toolDir}`);
|
|
973
|
+
}
|
|
503
974
|
}
|
|
504
975
|
catch (regError) {
|
|
505
|
-
|
|
976
|
+
// Always log errors
|
|
977
|
+
mcpLog('error', `Failed to register tool ${category}/${toolDir}`, regError instanceof Error ? regError.message : 'Unknown registration error');
|
|
506
978
|
}
|
|
507
979
|
}
|
|
508
980
|
else {
|
|
509
|
-
|
|
981
|
+
// Only warn in development mode
|
|
982
|
+
if (isDevelopment) {
|
|
983
|
+
mcpLog('warning', `No register function found in ${toolPath}`);
|
|
984
|
+
}
|
|
510
985
|
}
|
|
511
986
|
}
|
|
512
987
|
catch (error) {
|
|
513
|
-
|
|
988
|
+
// Always log errors
|
|
989
|
+
mcpLog('error', `Failed to load tool ${category}/${toolDir}`, error instanceof Error ? error.message : 'Unknown error');
|
|
514
990
|
}
|
|
515
991
|
}
|
|
516
992
|
else {
|
|
517
|
-
|
|
993
|
+
// Only warn in development mode
|
|
994
|
+
if (isDevelopment) {
|
|
995
|
+
mcpLog('warning', `Tool index file does not exist: ${toolPath}`);
|
|
996
|
+
}
|
|
518
997
|
}
|
|
519
998
|
}
|
|
520
999
|
}
|
|
@@ -608,7 +1087,9 @@ async function getCategoryDescription(category, toolNames) {
|
|
|
608
1087
|
async function registerAllTools(server) {
|
|
609
1088
|
const toolsBaseDir = path.join(__dirname, 'tools');
|
|
610
1089
|
if (!fs.existsSync(toolsBaseDir)) {
|
|
611
|
-
|
|
1090
|
+
if (isDevelopment) {
|
|
1091
|
+
mcpLog('warning', 'Tools directory does not exist', toolsBaseDir);
|
|
1092
|
+
}
|
|
612
1093
|
return;
|
|
613
1094
|
}
|
|
614
1095
|
// Discover categories dynamically from the filesystem
|
|
@@ -789,42 +1270,43 @@ server.registerResource("readme", new ResourceTemplate("readme://{section}", {
|
|
|
789
1270
|
async function main() {
|
|
790
1271
|
try {
|
|
791
1272
|
// VS Code MCP Compliance: Dev Mode Support
|
|
792
|
-
const isDevelopment = process.env.NODE_ENV === 'development' || process.env.MCP_DEV_MODE === 'true';
|
|
793
1273
|
const isTest = process.env.NODE_ENV === 'test' && process.env.MCP_TEST_MODE === 'true';
|
|
794
1274
|
if (isDevelopment) {
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
1275
|
+
mcpLog('info', "🔧 IT Tools MCP Server starting in DEVELOPMENT mode");
|
|
1276
|
+
mcpLog('debug', " - Enhanced logging enabled");
|
|
1277
|
+
mcpLog('debug', " - Hot reload capabilities active");
|
|
1278
|
+
mcpLog('debug', " - Debug information available");
|
|
799
1279
|
}
|
|
800
1280
|
// Add error handling for unhandled rejections
|
|
801
1281
|
process.on('unhandledRejection', (reason, promise) => {
|
|
802
|
-
|
|
1282
|
+
mcpLog('error', 'Unhandled Rejection', { promise: promise.toString(), reason });
|
|
803
1283
|
});
|
|
804
1284
|
process.on('uncaughtException', (error) => {
|
|
805
|
-
|
|
1285
|
+
mcpLog('critical', 'Uncaught Exception', error.message);
|
|
806
1286
|
process.exit(1);
|
|
807
1287
|
});
|
|
808
1288
|
await registerAllTools(server);
|
|
809
1289
|
const transport = new StdioServerTransport();
|
|
810
1290
|
await server.connect(transport);
|
|
1291
|
+
// Mark MCP transport as ready for logging
|
|
1292
|
+
mcpTransportReady = true;
|
|
811
1293
|
// Log startup information based on environment
|
|
812
1294
|
if (isTest) {
|
|
813
|
-
|
|
1295
|
+
mcpLog('info', "IT Tools MCP Server running on stdio");
|
|
814
1296
|
// Exit after stdin closes (for test automation)
|
|
815
1297
|
process.stdin.on('end', () => {
|
|
816
1298
|
setTimeout(() => process.exit(0), 100);
|
|
817
1299
|
});
|
|
818
1300
|
}
|
|
819
1301
|
else if (isDevelopment) {
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
1302
|
+
mcpLog('info', "🚀 IT Tools MCP Server connected successfully");
|
|
1303
|
+
mcpLog('info', `📊 Loaded ${await getToolCount()} tools across ${await getCategoryCount()} categories`);
|
|
1304
|
+
mcpLog('info', `🔗 Protocol: Model Context Protocol (MCP) via stdio`);
|
|
1305
|
+
mcpLog('info', `📦 Version: ${packageInfo.version}`);
|
|
824
1306
|
}
|
|
825
1307
|
else {
|
|
826
1308
|
// Production mode - simple ready message
|
|
827
|
-
|
|
1309
|
+
mcpLog('info', `IT Tools MCP Server v${packageInfo.version} ready - ${await getToolCount()} tools loaded`);
|
|
828
1310
|
}
|
|
829
1311
|
// Enhanced monitoring in development mode
|
|
830
1312
|
if (isDevelopment && !isTest) {
|
|
@@ -832,10 +1314,10 @@ async function main() {
|
|
|
832
1314
|
setInterval(() => {
|
|
833
1315
|
const usage = getResourceUsage();
|
|
834
1316
|
if (usage.memory.heapUsedBytes > 200 * 1024 * 1024) {
|
|
835
|
-
|
|
1317
|
+
mcpLog('warning', "⚠️ High memory usage detected", usage.memory);
|
|
836
1318
|
}
|
|
837
1319
|
// Log periodic status in dev mode
|
|
838
|
-
|
|
1320
|
+
mcpLog('debug', `📈 Status: Memory ${usage.memory.heapUsed}, CPU ${usage.cpu.user}ms user, ${usage.cpu.system}ms system`);
|
|
839
1321
|
}, 60 * 1000); // Every minute in dev mode
|
|
840
1322
|
}
|
|
841
1323
|
else if (!isTest) {
|
|
@@ -843,17 +1325,17 @@ async function main() {
|
|
|
843
1325
|
setInterval(() => {
|
|
844
1326
|
const usage = getResourceUsage();
|
|
845
1327
|
if (usage.memory.heapUsedBytes > 200 * 1024 * 1024) {
|
|
846
|
-
|
|
1328
|
+
mcpLog('warning', "High memory usage detected", usage.memory);
|
|
847
1329
|
}
|
|
848
1330
|
}, 5 * 60 * 1000);
|
|
849
1331
|
}
|
|
850
1332
|
// Handle graceful shutdown
|
|
851
1333
|
const shutdown = () => {
|
|
852
1334
|
if (isDevelopment) {
|
|
853
|
-
|
|
1335
|
+
mcpLog('info', "🛑 Shutting down IT Tools MCP Server (Development Mode)...");
|
|
854
1336
|
}
|
|
855
1337
|
else {
|
|
856
|
-
|
|
1338
|
+
mcpLog('info', "Shutting down IT Tools MCP Server...");
|
|
857
1339
|
}
|
|
858
1340
|
process.exit(0);
|
|
859
1341
|
};
|
|
@@ -861,7 +1343,7 @@ async function main() {
|
|
|
861
1343
|
process.on('SIGTERM', shutdown);
|
|
862
1344
|
}
|
|
863
1345
|
catch (error) {
|
|
864
|
-
|
|
1346
|
+
mcpLog('critical', "Failed to start MCP server", error instanceof Error ? error.message : 'Unknown error');
|
|
865
1347
|
process.exit(1);
|
|
866
1348
|
}
|
|
867
1349
|
}
|
|
@@ -905,7 +1387,7 @@ function extractReadmeSection(content, heading) {
|
|
|
905
1387
|
// Start the server if this file is executed directly
|
|
906
1388
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
907
1389
|
main().catch((error) => {
|
|
908
|
-
|
|
1390
|
+
mcpLog('emergency', "Fatal error starting MCP server", error instanceof Error ? error.message : 'Unknown error');
|
|
909
1391
|
process.exit(1);
|
|
910
1392
|
});
|
|
911
1393
|
}
|
package/package.json
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "it-tools-mcp",
|
|
3
|
-
"version": "4.1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "4.1.14",
|
|
4
|
+
"description": "Full MCP 2025-06-18 compliant server with 121+ IT tools, logging, ping, progress tracking, cancellation, and sampling utilities",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./build/index.js",
|
|
7
7
|
"bin": {
|
|
8
8
|
"it-tools-mcp": "build/index.js"
|
|
9
9
|
},
|
|
10
10
|
"scripts": {
|
|
11
|
-
"build": "tsc && chmod +x build/index.js",
|
|
11
|
+
"build": "npm run sync:manifest || true && tsc && chmod +x build/index.js",
|
|
12
|
+
"build:docker": "tsc && chmod +x build/index.js",
|
|
12
13
|
"start": "docker-compose up --build",
|
|
13
14
|
"start:node": "node build/index.js",
|
|
14
15
|
"dev": "NODE_ENV=development MCP_DEV_MODE=true tsc && node build/index.js",
|
|
@@ -65,7 +66,7 @@
|
|
|
65
66
|
"node": ">=18.0.0"
|
|
66
67
|
},
|
|
67
68
|
"mcp": {
|
|
68
|
-
"mcpVersion": "
|
|
69
|
+
"mcpVersion": "2025-06-18",
|
|
69
70
|
"transport": "stdio",
|
|
70
71
|
"capabilities": [
|
|
71
72
|
"tools",
|
|
@@ -111,7 +112,7 @@
|
|
|
111
112
|
},
|
|
112
113
|
"dependencies": {
|
|
113
114
|
"@iarna/toml": "^2.2.5",
|
|
114
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
115
|
+
"@modelcontextprotocol/sdk": "^1.17.0",
|
|
115
116
|
"@types/js-yaml": "^4.0.9",
|
|
116
117
|
"@types/papaparse": "^5.3.16",
|
|
117
118
|
"@types/qrcode": "^1.5.5",
|