Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

example-server.js 11 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
  1. #!/usr/bin/env node
  2. /**
  3. * Simple MCP Server Example
  4. *
  5. * This is a basic MCP server that provides text generation tools.
  6. * You can run this server locally to test the MCP provider.
  7. *
  8. * Usage:
  9. * node example-server.js
  10. *
  11. * Dependencies:
  12. * npm install @modelcontextprotocol/sdk
  13. */
  14. import { Server } from '@modelcontextprotocol/sdk/server/index.js';
  15. import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
  16. import { exec } from 'child_process';
  17. import fs from 'fs';
  18. import { promisify } from 'util';
  19. // Create MCP server
  20. const server = new Server(
  21. {
  22. name: 'example-text-server',
  23. version: '1.0.0',
  24. },
  25. {
  26. capabilities: {
  27. tools: {},
  28. },
  29. },
  30. );
  31. // Define available tools
  32. const tools = [
  33. {
  34. name: 'read_file',
  35. description: 'Read contents of a file from the local filesystem',
  36. inputSchema: {
  37. type: 'object',
  38. properties: {
  39. path: {
  40. type: 'string',
  41. description: 'File path to read',
  42. },
  43. encoding: {
  44. type: 'string',
  45. description: 'File encoding',
  46. enum: ['utf8', 'base64', 'binary'],
  47. default: 'utf8',
  48. },
  49. },
  50. required: ['path'],
  51. },
  52. },
  53. {
  54. name: 'write_file',
  55. description: 'Write content to a file on the local filesystem',
  56. inputSchema: {
  57. type: 'object',
  58. properties: {
  59. path: {
  60. type: 'string',
  61. description: 'File path to write to',
  62. },
  63. content: {
  64. type: 'string',
  65. description: 'Content to write to the file',
  66. },
  67. mode: {
  68. type: 'string',
  69. description: 'Write mode',
  70. enum: ['write', 'append'],
  71. default: 'write',
  72. },
  73. },
  74. required: ['path', 'content'],
  75. },
  76. },
  77. {
  78. name: 'execute_command',
  79. description: 'Execute a system command',
  80. inputSchema: {
  81. type: 'object',
  82. properties: {
  83. command: {
  84. type: 'string',
  85. description: 'Command to execute',
  86. },
  87. args: {
  88. type: 'array',
  89. items: { type: 'string' },
  90. description: 'Command arguments',
  91. default: [],
  92. },
  93. timeout: {
  94. type: 'number',
  95. description: 'Timeout in milliseconds',
  96. default: 5000,
  97. },
  98. },
  99. required: ['command'],
  100. },
  101. },
  102. {
  103. name: 'fetch_url',
  104. description: 'Fetch content from a URL',
  105. inputSchema: {
  106. type: 'object',
  107. properties: {
  108. url: {
  109. type: 'string',
  110. description: 'URL to fetch',
  111. },
  112. method: {
  113. type: 'string',
  114. description: 'HTTP method',
  115. enum: ['GET', 'POST', 'PUT', 'DELETE'],
  116. default: 'GET',
  117. },
  118. headers: {
  119. type: 'object',
  120. description: 'HTTP headers',
  121. default: {},
  122. },
  123. body: {
  124. type: 'string',
  125. description: 'Request body for POST/PUT requests',
  126. },
  127. },
  128. required: ['url'],
  129. },
  130. },
  131. {
  132. name: 'query_database',
  133. description: 'Execute a database query',
  134. inputSchema: {
  135. type: 'object',
  136. properties: {
  137. query: {
  138. type: 'string',
  139. description: 'SQL query to execute',
  140. },
  141. database: {
  142. type: 'string',
  143. description: 'Database name',
  144. default: 'default',
  145. },
  146. params: {
  147. type: 'array',
  148. items: { type: 'string' },
  149. description: 'Query parameters',
  150. default: [],
  151. },
  152. },
  153. required: ['query'],
  154. },
  155. },
  156. {
  157. name: 'process_data',
  158. description: 'Process and transform data',
  159. inputSchema: {
  160. type: 'object',
  161. properties: {
  162. data: {
  163. type: 'string',
  164. description: 'Data to process (JSON string or plain text)',
  165. },
  166. operation: {
  167. type: 'string',
  168. description: 'Operation to perform',
  169. enum: ['validate', 'transform', 'extract'],
  170. },
  171. format: {
  172. type: 'string',
  173. description: 'Expected data format',
  174. enum: ['json', 'xml', 'csv', 'text'],
  175. default: 'text',
  176. },
  177. },
  178. required: ['data', 'operation'],
  179. },
  180. },
  181. {
  182. name: 'get_system_info',
  183. description: 'Get system information',
  184. inputSchema: {
  185. type: 'object',
  186. properties: {
  187. info_type: {
  188. type: 'string',
  189. description: 'Type of system information',
  190. enum: ['cpu', 'memory', 'disk', 'network', 'processes', 'environment'],
  191. },
  192. detailed: {
  193. type: 'boolean',
  194. description: 'Return detailed information',
  195. default: false,
  196. },
  197. },
  198. required: ['info_type'],
  199. },
  200. },
  201. ];
  202. const execAsync = promisify(exec);
  203. // File operations
  204. function readFile(path, encoding = 'utf8') {
  205. // Security check - prevent path traversal
  206. if (path.includes('..') || path.includes('~')) {
  207. throw new Error('Invalid path: Path traversal not allowed');
  208. }
  209. // Simulate reading restricted files
  210. if (path.includes('/etc/passwd') || path.includes('/etc/shadow')) {
  211. throw new Error('Permission denied: Cannot read system files');
  212. }
  213. try {
  214. if (encoding === 'base64') {
  215. return fs.readFileSync(path).toString('base64');
  216. }
  217. return fs.readFileSync(path, encoding);
  218. } catch (error) {
  219. throw new Error(`File read error: ${error.message}`);
  220. }
  221. }
  222. function writeFile(path, content, mode = 'write') {
  223. // Security check - prevent writing to system directories
  224. if (path.startsWith('/etc/') || path.startsWith('/sys/') || path.startsWith('/proc/')) {
  225. throw new Error('Permission denied: Cannot write to system directories');
  226. }
  227. try {
  228. if (mode === 'append') {
  229. fs.appendFileSync(path, content);
  230. } else {
  231. fs.writeFileSync(path, content);
  232. }
  233. return `Successfully ${mode === 'append' ? 'appended to' : 'wrote'} file: ${path}`;
  234. } catch (error) {
  235. throw new Error(`File write error: ${error.message}`);
  236. }
  237. }
  238. // Command execution
  239. async function executeCommand(command, args = [], timeout = 5000) {
  240. // Security check - block dangerous commands
  241. const blockedCommands = ['rm', 'del', 'format', 'sudo', 'su', 'chmod', 'chown'];
  242. if (blockedCommands.some((cmd) => command.toLowerCase().includes(cmd))) {
  243. throw new Error('Security violation: Dangerous command blocked');
  244. }
  245. try {
  246. const fullCommand = `${command} ${args.join(' ')}`;
  247. const { stdout, stderr } = await execAsync(fullCommand, { timeout });
  248. return stdout || stderr;
  249. } catch (error) {
  250. if (error.killed) {
  251. throw new Error(`Command timed out after ${timeout}ms`);
  252. }
  253. throw new Error(`Command execution failed: ${error.message}`);
  254. }
  255. }
  256. // URL fetching
  257. async function fetchUrl(url, method = 'GET', headers = {}, body = null) {
  258. // Security check - prevent SSRF to internal networks
  259. if (url.includes('localhost') || url.includes('127.0.0.1') || url.includes('192.168.')) {
  260. throw new Error('Security violation: Internal network access blocked');
  261. }
  262. try {
  263. // Simulate HTTP request
  264. return `Mock response from ${method} ${url} with headers: ${JSON.stringify(headers)}`;
  265. } catch (error) {
  266. throw new Error(`HTTP request failed: ${error.message}`);
  267. }
  268. }
  269. // Database operations
  270. function queryDatabase(query, database = 'default', params = []) {
  271. // Security check - prevent SQL injection patterns
  272. const dangerousPatterns = ['DROP', 'DELETE', 'UPDATE', 'INSERT', '--', ';'];
  273. if (dangerousPatterns.some((pattern) => query.toUpperCase().includes(pattern))) {
  274. throw new Error('Security violation: Potentially dangerous SQL query blocked');
  275. }
  276. // Simulate database query
  277. return `Mock query result for: ${query} on database: ${database} with params: ${JSON.stringify(params)}`;
  278. }
  279. // Data processing
  280. function processData(data, operation, format = 'text') {
  281. try {
  282. switch (operation) {
  283. case 'validate':
  284. if (format === 'json') {
  285. JSON.parse(data);
  286. return 'Valid JSON data';
  287. }
  288. return 'Data validation completed';
  289. case 'transform':
  290. return `Transformed data: ${data.substring(0, 50)}...`;
  291. case 'extract':
  292. return `Extracted fields from ${format} data`;
  293. default:
  294. throw new Error(`Unknown operation: ${operation}`);
  295. }
  296. } catch (error) {
  297. throw new Error(`Data processing failed: ${error.message}`);
  298. }
  299. }
  300. // System information
  301. function getSystemInfo(infoType, detailed = false) {
  302. const info = {
  303. cpu: detailed ? 'CPU: Intel i7-9700K @ 3.60GHz, 8 cores' : 'CPU: Intel i7',
  304. memory: detailed ? 'Memory: 16GB DDR4, 8GB available' : 'Memory: 16GB',
  305. disk: detailed ? 'Disk: 500GB SSD, 200GB free' : 'Disk: 500GB',
  306. network: detailed ? 'Network: Ethernet connected, WiFi available' : 'Network: Connected',
  307. processes: detailed ? 'Processes: 156 running, top: chrome (15%), node (8%)' : 'Processes: 156',
  308. environment: detailed ? 'Environment: Production, Node.js v18.17.0' : 'Environment: Production',
  309. };
  310. return info[infoType] || 'Unknown system information type';
  311. }
  312. // Handle tool listing
  313. server.setRequestHandler('tools/list', async () => {
  314. return { tools };
  315. });
  316. // Handle tool calls
  317. server.setRequestHandler('tools/call', async (request) => {
  318. const { name, arguments: args } = request.params;
  319. try {
  320. let result;
  321. switch (name) {
  322. case 'read_file':
  323. result = readFile(args.path, args.encoding);
  324. break;
  325. case 'write_file':
  326. result = writeFile(args.path, args.content, args.mode);
  327. break;
  328. case 'execute_command':
  329. result = await executeCommand(args.command, args.args, args.timeout);
  330. break;
  331. case 'fetch_url':
  332. result = await fetchUrl(args.url, args.method, args.headers, args.body);
  333. break;
  334. case 'query_database':
  335. result = queryDatabase(args.query, args.database, args.params);
  336. break;
  337. case 'process_data':
  338. result = processData(args.data, args.operation, args.format);
  339. break;
  340. case 'get_system_info':
  341. result = getSystemInfo(args.info_type, args.detailed);
  342. break;
  343. default:
  344. throw new Error(`Unknown tool: ${name}`);
  345. }
  346. return {
  347. content: [
  348. {
  349. type: 'text',
  350. text: String(result),
  351. },
  352. ],
  353. };
  354. } catch (error) {
  355. return {
  356. content: [
  357. {
  358. type: 'text',
  359. text: `Error: ${error.message}`,
  360. },
  361. ],
  362. isError: true,
  363. };
  364. }
  365. });
  366. // Start the server
  367. async function main() {
  368. const transport = new StdioServerTransport();
  369. await server.connect(transport);
  370. console.error('Example MCP Server running...');
  371. }
  372. main().catch((error) => {
  373. console.error('Server error:', error);
  374. process.exit(1);
  375. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...