mcp-adder-simple 1.0.6 → 1.0.8

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.
Files changed (2) hide show
  1. package/mcp-adder.js +196 -99
  2. package/package.json +4 -3
package/mcp-adder.js CHANGED
@@ -1,130 +1,227 @@
1
+ /**
2
+ * MCP Calculator Server
3
+ * 一个简单的 MCP (Model Context Protocol) 服务器,提供基本的数学计算功能
4
+ */
5
+
1
6
  const readline = require('readline');
2
7
 
3
- // 创建 readline 接口
8
+ // ========== 配置和初始化 ==========
9
+
10
+ // 创建 readline 接口用于处理 stdin/stdout 通信
4
11
  const rl = readline.createInterface({
5
12
  input: process.stdin,
6
13
  output: process.stdout,
7
- terminal: false
14
+ terminal: false // 非终端模式,避免额外的输出格式化
8
15
  });
9
16
 
10
- // 强制启用 stdin,避免延迟
17
+ // 设置 stdin 编码为 UTF-8
11
18
  process.stdin.setEncoding('utf8');
12
- process.stdin.resume(); // 关键!防止 Node.js 缓冲输入
13
19
 
14
- console.error('[MCP] 服务启动,等待 initialize...');
20
+ // 立即恢复 stdin 流,防止缓冲输入延迟
21
+ process.stdin.resume();
22
+
23
+ // ========== 主逻辑 ==========
15
24
 
25
+ // 监听输入行事件,处理 MCP 请求
16
26
  rl.on('line', (line) => {
17
- console.error('[MCP] 📥 收到数据:', line);
18
27
  try {
28
+ // 跳过空行
19
29
  const trimmed = line.trim();
20
- if (!trimmed) return; // 跳过空行
30
+ if (!trimmed) return;
31
+
32
+ // 解析 JSON-RPC 请求
21
33
  const msg = JSON.parse(trimmed);
22
- console.error('[MCP] ✅ 解析成功:', msg.method);
23
-
24
- if (msg.id === undefined || msg.id === null) return;
25
-
26
- let result = null;
27
- let error = null;
28
-
29
- try {
30
- switch (msg.method) {
31
- case 'tools/list':
32
- result = {
33
- tools: [
34
- {
35
- name: 'add_numbers',
36
- description: '将两个数字相加',
37
- inputSchema: {
38
- type: 'object',
39
- properties: {
40
- a: { type: 'number', description: '第一个数' },
41
- b: { type: 'number', description: '第二个数' }
42
- },
43
- required: ['a', 'b']
44
- }
45
- }
46
- ]
47
- };
48
- console.error('[MCP] ← tools/list 成功响应');
49
- break;
50
-
51
- case 'initialize':
52
- result = {
53
- protocolVersion: '2024-10-07',
54
- serverInfo: {
55
- name: 'mcp-adder-server',
56
- version: '1.0.0'
34
+
35
+ // 打印完整的请求消息(用于调试)
36
+ console.error('[MCP] 收到请求:', JSON.stringify(msg, null, 2));
37
+
38
+ // 检查请求是否包含 id(id 可以为 0,不能只检查 !msg.id)
39
+ if (msg.id === undefined || msg.id === null) {
40
+ return;
41
+ }
42
+
43
+ // 处理请求
44
+ handleRequest(msg);
45
+
46
+ } catch (e) {
47
+ // JSON 解析失败,记录错误但不中断服务
48
+ console.error(`[MCP] JSON 解析失败: ${line}`);
49
+ }
50
+ });
51
+
52
+ /**
53
+ * 处理 MCP 请求
54
+ * @param {Object} msg - JSON-RPC 请求对象
55
+ */
56
+ function handleRequest(msg) {
57
+ let result = null;
58
+ let error = null;
59
+
60
+ try {
61
+ // 根据方法名分发处理
62
+ switch (msg.method) {
63
+ case 'initialize':
64
+ result = handleInitialize();
65
+ break;
66
+
67
+ case 'tools/list':
68
+ result = handleToolsList();
69
+ break;
70
+
71
+ case 'tools/call':
72
+ result = handleToolCall(msg.params);
73
+ break;
74
+
75
+ default:
76
+ throw new Error(`不支持的方法: ${msg.method}`);
77
+ }
78
+ } catch (err) {
79
+ // 处理过程中的错误
80
+ error = {
81
+ code: -32602,
82
+ message: err.message
83
+ };
84
+ }
85
+
86
+ // 构建并发送响应
87
+ const response = {
88
+ jsonrpc: '2.0',
89
+ id: msg.id
90
+ };
91
+
92
+ if (error) {
93
+ response.error = error;
94
+ } else {
95
+ response.result = result;
96
+ }
97
+
98
+ // 输出响应到 stdout(MCP 客户端读取)
99
+ console.log(JSON.stringify(response));
100
+ }
101
+
102
+ /**
103
+ * 处理 initialize 请求
104
+ * @returns {Object} 初始化响应
105
+ */
106
+ function handleInitialize() {
107
+ return {
108
+ protocolVersion: '2024-10-07',
109
+ serverInfo: {
110
+ name: 'mcp-calculator-server',
111
+ version: '1.0.0'
112
+ },
113
+ capabilities: {
114
+ tools: {} // 声明支持 tools 功能
115
+ }
116
+ };
117
+ }
118
+
119
+ /**
120
+ * 处理工具列表请求
121
+ * @returns {Object} 工具列表响应
122
+ */
123
+ function handleToolsList() {
124
+ return {
125
+ tools: [
126
+ {
127
+ name: 'add_numbers',
128
+ description: '将两个数字相加',
129
+ inputSchema: {
130
+ type: 'object',
131
+ properties: {
132
+ a: {
133
+ type: 'number',
134
+ description: '第一个数'
57
135
  },
58
- capabilities: {
59
- tools: {}
136
+ b: {
137
+ type: 'number',
138
+ description: '第二个数'
60
139
  }
61
- };
62
- console.error('[MCP] ← initialize 成功响应');
63
- break;
64
-
65
- case 'list_tools':
66
- result = {
67
- tools: [
68
- {
69
- name: 'add_numbers',
70
- description: '将两个数字相加',
71
- inputSchema: {
72
- type: 'object',
73
- properties: {
74
- a: { type: 'number', description: '第一个数' },
75
- b: { type: 'number', description: '第二个数' }
76
- },
77
- required: ['a', 'b']
78
- }
79
- }
80
- ]
81
- };
82
- console.error('[MCP] ← list_tools 成功响应');
83
- break;
84
-
85
- case 'call_tool':
86
- case 'tools/call':
87
- const { name, arguments: args } = msg.params;
88
- if (name === 'add_numbers') {
89
- const { a, b } = args;
90
- if (typeof a !== 'number' || typeof b !== 'number') {
91
- throw new Error('参数必须是数字');
140
+ },
141
+ required: ['a', 'b']
142
+ }
143
+ },
144
+ {
145
+ name: 'multiply_numbers',
146
+ description: '将两个数字相乘',
147
+ inputSchema: {
148
+ type: 'object',
149
+ properties: {
150
+ a: {
151
+ type: 'number',
152
+ description: '第一个数'
153
+ },
154
+ b: {
155
+ type: 'number',
156
+ description: '第二个数'
92
157
  }
93
- result = {
94
- content: [{ type: 'text', text: `${a} + ${b} = ${a + b}` }]
95
- };
96
- } else {
97
- throw new Error(`未知工具: ${name}`);
98
- }
99
- break;
100
-
101
- default:
102
- throw new Error(`不支持的方法: ${msg.method}`);
158
+ },
159
+ required: ['a', 'b']
160
+ }
103
161
  }
104
- } catch (err) {
105
- error = { code: -32602, message: err.message };
106
- console.error('[MCP] ❌ 错误:', err.message);
162
+ ]
163
+ };
164
+ }
165
+
166
+ /**
167
+ * 处理工具调用请求
168
+ * @param {Object} params - 请求参数
169
+ * @param {string} params.name - 工具名称
170
+ * @param {Object} params.arguments - 工具参数
171
+ * @returns {Object} 工具执行结果
172
+ */
173
+ function handleToolCall(params) {
174
+ const { name, arguments: args } = params;
175
+
176
+ if (name === 'add_numbers') {
177
+ const { a, b } = args;
178
+
179
+ // 参数类型验证
180
+ if (typeof a !== 'number' || typeof b !== 'number') {
181
+ throw new Error('参数必须是数字');
107
182
  }
108
183
 
109
- const response = { jsonrpc: '2.0', id: msg.id };
110
- if (error) {
111
- response.error = error;
112
- } else {
113
- response.result = result;
184
+ // 计算并返回结果
185
+ return {
186
+ content: [
187
+ {
188
+ type: 'text',
189
+ text: `${a} + ${b} = ${a + b}`
190
+ }
191
+ ]
192
+ };
193
+
194
+ } else if (name === 'multiply_numbers') {
195
+ const { a, b } = args;
196
+
197
+ // 参数类型验证
198
+ if (typeof a !== 'number' || typeof b !== 'number') {
199
+ throw new Error('参数必须是数字');
114
200
  }
115
201
 
116
- console.log(JSON.stringify(response));
117
- } catch (e) {
118
- console.error('[MCP] ❌ JSON 解析失败:', line);
202
+ // 计算并返回结果
203
+ return {
204
+ content: [
205
+ {
206
+ type: 'text',
207
+ text: `${a} × ${b} = ${a * b}`
208
+ }
209
+ ]
210
+ };
211
+
212
+ } else {
213
+ throw new Error(`未知工具: ${name}`);
119
214
  }
120
- });
215
+ }
216
+
217
+ // ========== 清理和退出 ==========
121
218
 
219
+ // 当连接关闭时退出进程
122
220
  rl.on('close', () => {
123
- console.error('[MCP] 连接关闭,退出服务');
124
221
  process.exit(0);
125
222
  });
126
223
 
127
- // ⚠️ 关键:防止 Node.js 阻塞
224
+ // stdin 结束时退出进程(防止 Node.js 阻塞)
128
225
  process.stdin.on('end', () => {
129
226
  process.exit(0);
130
227
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-adder-simple",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "main": "mcp-adder.js",
5
5
  "bin": {
6
6
  "mcp-adder-simple": "./bin/mcp-adder-simple.cmd"
@@ -12,11 +12,12 @@
12
12
  "mcp",
13
13
  "model-context-protocol",
14
14
  "calculator",
15
- "add"
15
+ "add",
16
+ "multiply"
16
17
  ],
17
18
  "author": "xiaosheng_2021",
18
19
  "license": "MIT",
19
- "description": "A simple MCP server for adding numbers",
20
+ "description": "A simple MCP server for basic math calculations",
20
21
  "repository": {
21
22
  "type": "git",
22
23
  "url": "https://github.com/xiaosheng-2021/mcp-adder.git"