@maplezzk/mcps 1.0.1

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # mcps - MCP CLI Manager
2
+
3
+ [English](./README_EN.md) | [简体中文](./README.md)
4
+
5
+ 一个用于管理和交互 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 服务的强大命令行工具。
6
+
7
+ ## 功能特性
8
+
9
+ - 🔌 **服务管理**:轻松添加、移除、查看和更新 MCP 服务(支持 Stdio 和 SSE 模式)。
10
+ - 🛠️ **工具发现**:查看已配置服务中所有可用的工具。
11
+ - 🚀 **工具执行**:直接在命令行调用工具,支持参数自动解析。
12
+ - 🔄 **持久化存储**:配置自动保存至 `~/.mcps/mcp.json`。
13
+
14
+ ## 安装
15
+
16
+ ```bash
17
+ npm install -g @maplezzk/mcps
18
+ ```
19
+
20
+ ## 使用指南
21
+
22
+ ### 1. 守护进程 (Daemon Mode)
23
+
24
+ mcps 支持守护进程模式,可以保持与 MCP 服务的长连接,显著提高频繁调用的性能。
25
+
26
+ **启动守护进程:**
27
+ ```bash
28
+ mcps daemon
29
+ ```
30
+ 或者
31
+ ```bash
32
+ mcps daemon start
33
+ ```
34
+
35
+ **重启连接:**
36
+ 如果修改了配置文件,或者服务出现异常,可以使用重启命令刷新连接:
37
+
38
+ ```bash
39
+ # 重置所有连接
40
+ mcps daemon restart
41
+
42
+ # 仅重置特定服务的连接
43
+ mcps daemon restart my-server
44
+ ```
45
+
46
+ **停止守护进程:**
47
+ ```bash
48
+ mcps daemon stop
49
+ ```
50
+
51
+ ### 2. 服务管理 (Server Management)
52
+
53
+ **查看所有服务:**
54
+ ```bash
55
+ mcps server list
56
+ ```
57
+
58
+ **添加 Stdio 服务:**
59
+ ```bash
60
+ # 添加本地 Node.js 服务
61
+ mcps server add my-server --command node --args ./build/index.js
62
+
63
+ # 使用 npx/uvx 添加服务
64
+ mcps server add fetch --command uvx --args mcp-server-fetch
65
+ ```
66
+
67
+ **添加 SSE 服务:**
68
+ ```bash
69
+ mcps server add remote-server --type sse --url http://localhost:8000/sse
70
+ ```
71
+
72
+ **添加 Streamable HTTP 服务:**
73
+ ```bash
74
+ mcps server add my-http-server --type http --url http://localhost:8000/mcp
75
+ ```
76
+
77
+ **移除服务:**
78
+ ```bash
79
+ mcps server remove my-server
80
+ ```
81
+
82
+ ### 2. 工具交互 (Tool Interaction)
83
+
84
+ **查看服务下的可用工具:**
85
+ ```bash
86
+ mcps tools fetch
87
+ ```
88
+
89
+ **调用工具:**
90
+
91
+ 语法:
92
+ ```bash
93
+ mcps call <server_name> <tool_name> [arguments...]
94
+ ```
95
+
96
+ - `<server_name>`: 已配置的 MCP 服务名称
97
+ - `<tool_name>`: 要调用的工具名称
98
+ - `[arguments...]`: 以 `key=value` 形式传递的参数。CLI 会尝试自动将值解析为 JSON(数字、布尔值、对象)。
99
+
100
+ 示例:
101
+ ```bash
102
+ # 简单的字符串参数
103
+ mcps call fetch fetch url="https://example.com"
104
+
105
+ # JSON 对象参数
106
+ mcps call my-server createUser user='{"name": "Alice", "age": 30}'
107
+
108
+ # 布尔值/数字参数
109
+ mcps call my-server config debug=true timeout=5000
110
+ ```
111
+
112
+ ## 配置文件
113
+
114
+ 默认情况下,配置文件存储在:
115
+ `~/.mcps/mcp.json`
116
+
117
+ 您可以通过设置 `MCP_CONFIG_DIR` 环境变量来更改存储位置。
118
+
119
+ ## 许可证
120
+
121
+ ISC
@@ -0,0 +1,115 @@
1
+ import chalk from 'chalk';
2
+ import { configManager } from '../core/config.js';
3
+ import { McpClientService } from '../core/client.js';
4
+ const DAEMON_PORT = 4100;
5
+ async function tryCallDaemon(serverName, toolName, args) {
6
+ try {
7
+ const response = await fetch(`http://localhost:${DAEMON_PORT}/call`, {
8
+ method: 'POST',
9
+ headers: { 'Content-Type': 'application/json' },
10
+ body: JSON.stringify({ server: serverName, tool: toolName, args }),
11
+ });
12
+ if (!response.ok) {
13
+ // If daemon returns error, we might want to show it or fallback?
14
+ // Let's assume 500 means daemon tried and failed, so we shouldn't fallback to local spawn as it might fail same way.
15
+ // But if 404/Connection Refused, then daemon is not running.
16
+ // fetch throws on connection refused.
17
+ const err = await response.json();
18
+ throw new Error(err.error || 'Daemon error');
19
+ }
20
+ const data = await response.json();
21
+ console.log(chalk.green('Tool execution successful (via Daemon):'));
22
+ printResult(data.result);
23
+ return true;
24
+ }
25
+ catch (error) {
26
+ // If connection failed (daemon not running), return false to fallback
27
+ if (error.cause?.code === 'ECONNREFUSED' || error.message.includes('fetch failed')) {
28
+ return false;
29
+ }
30
+ // If daemon connected but returned error (e.g. tool failed), rethrow
31
+ throw error;
32
+ }
33
+ }
34
+ function printResult(result) {
35
+ if (result.content) {
36
+ result.content.forEach((item) => {
37
+ if (item.type === 'text') {
38
+ console.log(item.text);
39
+ }
40
+ else if (item.type === 'image') {
41
+ console.log(`[Image: ${item.mimeType}]`);
42
+ }
43
+ else if (item.type === 'resource') {
44
+ console.log(`[Resource: ${item.resource.uri}]`);
45
+ }
46
+ });
47
+ }
48
+ else {
49
+ console.log(JSON.stringify(result, null, 2));
50
+ }
51
+ }
52
+ export const registerCallCommand = (program) => {
53
+ program.command('call <server> <tool> [args...]')
54
+ .description('Call a tool on a server. Arguments format: key=value')
55
+ .addHelpText('after', `
56
+ Examples:
57
+ $ mcps call my-server echo message="Hello World"
58
+ $ mcps call my-server add a=10 b=20
59
+ $ mcps call my-server config debug=true
60
+ $ mcps call my-server createUser user='{"name":"Alice","age":30}'
61
+
62
+ Notes:
63
+ - Arguments are parsed as key=value pairs.
64
+ - Values are automatically parsed as JSON if possible (numbers, booleans, objects).
65
+ - If JSON parsing fails, the value is treated as a string.
66
+ - For strings with spaces, wrap the value in quotes (e.g., msg="hello world").
67
+ `)
68
+ .action(async (serverName, toolName, args) => {
69
+ const params = {};
70
+ if (args) {
71
+ args.forEach((arg) => {
72
+ const eqIndex = arg.indexOf('=');
73
+ if (eqIndex > 0) {
74
+ const key = arg.slice(0, eqIndex);
75
+ const valStr = arg.slice(eqIndex + 1);
76
+ try {
77
+ params[key] = JSON.parse(valStr);
78
+ }
79
+ catch {
80
+ params[key] = valStr;
81
+ }
82
+ }
83
+ });
84
+ }
85
+ // 1. Try Daemon first
86
+ try {
87
+ const handled = await tryCallDaemon(serverName, toolName, params);
88
+ if (handled)
89
+ return;
90
+ }
91
+ catch (error) {
92
+ console.error(chalk.red(`Daemon call failed: ${error.message}`));
93
+ process.exit(1);
94
+ }
95
+ // 2. Fallback to standalone execution
96
+ const serverConfig = configManager.getServer(serverName);
97
+ if (!serverConfig) {
98
+ console.error(chalk.red(`Server "${serverName}" not found.`));
99
+ process.exit(1);
100
+ }
101
+ const client = new McpClientService();
102
+ try {
103
+ await client.connect(serverConfig);
104
+ const result = await client.callTool(toolName, params);
105
+ console.log(chalk.green('Tool execution successful:'));
106
+ printResult(result);
107
+ }
108
+ catch (error) {
109
+ console.error(chalk.red(`Tool call failed: ${error.message}`));
110
+ }
111
+ finally {
112
+ await client.close();
113
+ }
114
+ });
115
+ };
@@ -0,0 +1,83 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import chalk from 'chalk';
4
+ import { configManager } from '../core/config.js';
5
+ export const registerConfigCommand = (program) => {
6
+ const configCmd = program.command('config')
7
+ .description('Manage configuration');
8
+ configCmd.command('import <file>')
9
+ .description('Import servers from a JSON configuration file (e.g., mcporter.json)')
10
+ .option('-f, --force', 'Overwrite existing servers with the same name', false)
11
+ .action((file, options) => {
12
+ try {
13
+ const absolutePath = path.resolve(file);
14
+ if (!fs.existsSync(absolutePath)) {
15
+ console.error(chalk.red(`File not found: ${absolutePath}`));
16
+ process.exit(1);
17
+ }
18
+ const content = fs.readFileSync(absolutePath, 'utf-8');
19
+ let json;
20
+ try {
21
+ json = JSON.parse(content);
22
+ }
23
+ catch (e) {
24
+ console.error(chalk.red('Invalid JSON file.'));
25
+ process.exit(1);
26
+ }
27
+ let importedCount = 0;
28
+ let skippedCount = 0;
29
+ // Support standard MCP config format (mcpServers object)
30
+ const serversMap = json.mcpServers || {};
31
+ Object.entries(serversMap).forEach(([name, config]) => {
32
+ // Skip disabled servers
33
+ if (config.disabled === true) {
34
+ skippedCount++;
35
+ return;
36
+ }
37
+ const serverName = name;
38
+ let newServer;
39
+ if (config.command) {
40
+ newServer = {
41
+ name: serverName,
42
+ type: 'stdio',
43
+ command: config.command,
44
+ args: config.args || [],
45
+ env: config.env,
46
+ };
47
+ }
48
+ else if (config.url) {
49
+ newServer = {
50
+ name: serverName,
51
+ type: 'sse',
52
+ url: config.url
53
+ };
54
+ }
55
+ else {
56
+ console.warn(chalk.yellow(`Skipping invalid server config for "${serverName}": missing command or url`));
57
+ return;
58
+ }
59
+ const existing = configManager.getServer(serverName);
60
+ if (existing) {
61
+ if (options.force) {
62
+ configManager.updateServer(serverName, newServer);
63
+ console.log(chalk.gray(`Updated existing server: ${serverName}`));
64
+ importedCount++;
65
+ }
66
+ else {
67
+ console.log(chalk.yellow(`Skipping existing server: ${serverName} (use --force to overwrite)`));
68
+ skippedCount++;
69
+ }
70
+ }
71
+ else {
72
+ configManager.addServer(newServer);
73
+ console.log(chalk.green(`Imported server: ${serverName}`));
74
+ importedCount++;
75
+ }
76
+ });
77
+ console.log(chalk.bold(`\nImport complete. Imported: ${importedCount}, Skipped: ${skippedCount}`));
78
+ }
79
+ catch (error) {
80
+ console.error(chalk.red(`Import failed: ${error.message}`));
81
+ }
82
+ });
83
+ };
@@ -0,0 +1,141 @@
1
+ import http from 'http';
2
+ import chalk from 'chalk';
3
+ import { connectionPool } from '../core/pool.js';
4
+ const PORT = 4100;
5
+ export const registerDaemonCommand = (program) => {
6
+ const daemonCmd = program.command('daemon')
7
+ .description('Manage the mcps daemon');
8
+ daemonCmd.command('start', { isDefault: true })
9
+ .description('Start the daemon (default)')
10
+ .option('-p, --port <number>', 'Port to listen on', String(PORT))
11
+ .action(async (options) => {
12
+ const port = parseInt(options.port);
13
+ // ... (server logic) ...
14
+ // Need to move the server creation logic here or keep it in the main action if no subcommands match?
15
+ // Commander handling of default commands with subcommands can be tricky.
16
+ // Let's refactor to use separate actions.
17
+ startDaemon(port);
18
+ });
19
+ daemonCmd.command('stop')
20
+ .description('Stop the running daemon')
21
+ .action(async () => {
22
+ try {
23
+ await fetch(`http://localhost:${PORT}/stop`, { method: 'POST' });
24
+ console.log(chalk.green('Daemon stopped successfully.'));
25
+ }
26
+ catch (e) {
27
+ console.error(chalk.red('Failed to stop daemon. Is it running?'));
28
+ }
29
+ });
30
+ daemonCmd.command('restart [server]')
31
+ .description('Restart the daemon or a specific server connection')
32
+ .action(async (serverName) => {
33
+ try {
34
+ const res = await fetch(`http://localhost:${PORT}/restart`, {
35
+ method: 'POST',
36
+ body: JSON.stringify({ server: serverName })
37
+ });
38
+ const data = await res.json();
39
+ console.log(chalk.green(data.message));
40
+ }
41
+ catch (e) {
42
+ console.error(chalk.red('Failed to restart. Is the daemon running?'));
43
+ }
44
+ });
45
+ };
46
+ const startDaemon = (port) => {
47
+ const server = http.createServer(async (req, res) => {
48
+ // ... (middleware) ...
49
+ res.setHeader('Access-Control-Allow-Origin', '*');
50
+ res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
51
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
52
+ if (req.method === 'OPTIONS') {
53
+ res.writeHead(204);
54
+ res.end();
55
+ return;
56
+ }
57
+ if (req.method === 'GET' && req.url === '/status') {
58
+ res.writeHead(200, { 'Content-Type': 'application/json' });
59
+ res.end(JSON.stringify({ status: 'running', version: '1.0.0' }));
60
+ return;
61
+ }
62
+ // ... (restart/stop/call handlers) ...
63
+ if (req.method === 'POST' && req.url === '/restart') {
64
+ let body = '';
65
+ req.on('data', chunk => { body += chunk.toString(); });
66
+ req.on('end', async () => {
67
+ try {
68
+ const { server: serverName } = JSON.parse(body || '{}');
69
+ if (serverName) {
70
+ const closed = await connectionPool.closeClient(serverName);
71
+ res.writeHead(200, { 'Content-Type': 'application/json' });
72
+ res.end(JSON.stringify({ message: `Server "${serverName}" connection closed. It will be reconnected on next call.`, closed }));
73
+ }
74
+ else {
75
+ await connectionPool.closeAll();
76
+ res.writeHead(200, { 'Content-Type': 'application/json' });
77
+ res.end(JSON.stringify({ message: 'All connections closed.' }));
78
+ }
79
+ }
80
+ catch (error) {
81
+ res.writeHead(500, { 'Content-Type': 'application/json' });
82
+ res.end(JSON.stringify({ error: error.message }));
83
+ }
84
+ });
85
+ return;
86
+ }
87
+ if (req.method === 'POST' && req.url === '/stop') {
88
+ res.writeHead(200, { 'Content-Type': 'application/json' });
89
+ res.end(JSON.stringify({ message: 'Daemon shutting down...' }));
90
+ setTimeout(() => {
91
+ server.close();
92
+ connectionPool.closeAll();
93
+ process.exit(0);
94
+ }, 100);
95
+ return;
96
+ }
97
+ if (req.method === 'POST' && req.url === '/call') {
98
+ let body = '';
99
+ req.on('data', chunk => { body += chunk.toString(); });
100
+ req.on('end', async () => {
101
+ try {
102
+ const { server: serverName, tool, args } = JSON.parse(body);
103
+ if (!serverName || !tool) {
104
+ res.writeHead(400, { 'Content-Type': 'application/json' });
105
+ res.end(JSON.stringify({ error: 'Missing server or tool' }));
106
+ return;
107
+ }
108
+ const client = await connectionPool.getClient(serverName);
109
+ const result = await client.callTool(tool, args || {});
110
+ res.writeHead(200, { 'Content-Type': 'application/json' });
111
+ res.end(JSON.stringify({ result }));
112
+ }
113
+ catch (error) {
114
+ console.error(`[Daemon] Error executing tool:`, error);
115
+ res.writeHead(500, { 'Content-Type': 'application/json' });
116
+ res.end(JSON.stringify({ error: error.message }));
117
+ }
118
+ });
119
+ return;
120
+ }
121
+ res.writeHead(404);
122
+ res.end();
123
+ });
124
+ server.listen(port, () => {
125
+ console.log(chalk.green(`
126
+ 🚀 mcps Daemon started on port ${port}
127
+ -----------------------------------
128
+ - Keeps connections to MCP servers alive
129
+ - Improves performance for frequent tool calls
130
+ - Run 'mcps call ...' in another terminal to use it automatically
131
+ `));
132
+ });
133
+ const shutdown = async () => {
134
+ console.log('\n[Daemon] Shutting down...');
135
+ server.close();
136
+ await connectionPool.closeAll();
137
+ process.exit(0);
138
+ };
139
+ process.on('SIGINT', shutdown);
140
+ process.on('SIGTERM', shutdown);
141
+ };
@@ -0,0 +1,108 @@
1
+ import chalk from 'chalk';
2
+ import { configManager } from '../core/config.js';
3
+ export const registerServerCommands = (program) => {
4
+ const serverCmd = program.command('server')
5
+ .description('Manage MCP servers');
6
+ serverCmd.command('list')
7
+ .alias('ls')
8
+ .description('List all configured servers')
9
+ .action(() => {
10
+ const servers = configManager.listServers();
11
+ if (servers.length === 0) {
12
+ console.log(chalk.yellow('No servers configured.'));
13
+ return;
14
+ }
15
+ console.log(chalk.bold('\nConfigured Servers:'));
16
+ servers.forEach(s => {
17
+ console.log(`- ${chalk.cyan(s.name)} [${chalk.magenta(s.type)}]`);
18
+ if (s.type === 'stdio') {
19
+ console.log(` Command: ${s.command} ${s.args.join(' ')}`);
20
+ if (s.env)
21
+ console.log(` Env: ${Object.keys(s.env).join(', ')}`);
22
+ }
23
+ else {
24
+ console.log(` URL: ${s.url}`);
25
+ }
26
+ console.log('');
27
+ });
28
+ });
29
+ serverCmd.command('add <name>')
30
+ .description('Add a new MCP server')
31
+ .option('--type <type>', 'Server type (stdio, sse, or http)', 'stdio')
32
+ .option('--command <command>', 'Command to execute (for stdio)')
33
+ .option('--args [args...]', 'Arguments for the command', [])
34
+ .option('--url <url>', 'URL for SSE/HTTP connection')
35
+ .option('--env <env...>', 'Environment variables (KEY=VALUE)', [])
36
+ .action((name, options) => {
37
+ try {
38
+ if (options.type === 'sse' || options.type === 'http') {
39
+ if (!options.url)
40
+ throw new Error(`URL is required for ${options.type} servers`);
41
+ configManager.addServer({
42
+ name,
43
+ type: options.type,
44
+ url: options.url,
45
+ });
46
+ }
47
+ else {
48
+ if (!options.command)
49
+ throw new Error('Command is required for Stdio servers');
50
+ const env = {};
51
+ if (options.env) {
52
+ options.env.forEach((e) => {
53
+ const parts = e.split('=');
54
+ const k = parts[0];
55
+ const v = parts.slice(1).join('=');
56
+ if (k && v)
57
+ env[k] = v;
58
+ });
59
+ }
60
+ configManager.addServer({
61
+ name,
62
+ type: 'stdio',
63
+ command: options.command,
64
+ args: options.args || [],
65
+ env: Object.keys(env).length > 0 ? env : undefined,
66
+ });
67
+ }
68
+ console.log(chalk.green(`Server "${name}" added successfully.`));
69
+ }
70
+ catch (error) {
71
+ console.error(chalk.red(`Error adding server: ${error.message}`));
72
+ }
73
+ });
74
+ serverCmd.command('remove <name>')
75
+ .alias('rm')
76
+ .description('Remove a server')
77
+ .action((name) => {
78
+ try {
79
+ configManager.removeServer(name);
80
+ console.log(chalk.green(`Server "${name}" removed.`));
81
+ }
82
+ catch (error) {
83
+ console.error(chalk.red(error.message));
84
+ }
85
+ });
86
+ serverCmd.command('update <name>')
87
+ .description('Update a server')
88
+ .option('--command <command>', 'New command')
89
+ .option('--url <url>', 'New URL')
90
+ .action((name, options) => {
91
+ try {
92
+ const updates = {};
93
+ if (options.command)
94
+ updates.command = options.command;
95
+ if (options.url)
96
+ updates.url = options.url;
97
+ if (Object.keys(updates).length === 0) {
98
+ console.log(chalk.yellow('No updates provided.'));
99
+ return;
100
+ }
101
+ configManager.updateServer(name, updates);
102
+ console.log(chalk.green(`Server "${name}" updated.`));
103
+ }
104
+ catch (error) {
105
+ console.error(chalk.red(`Error updating server: ${error.message}`));
106
+ }
107
+ });
108
+ };
@@ -0,0 +1,49 @@
1
+ import chalk from 'chalk';
2
+ import { configManager } from '../core/config.js';
3
+ import { McpClientService } from '../core/client.js';
4
+ export const registerToolsCommand = (program) => {
5
+ program.command('tools <server>')
6
+ .description('List available tools on a server')
7
+ .action(async (serverName) => {
8
+ const serverConfig = configManager.getServer(serverName);
9
+ if (!serverConfig) {
10
+ console.error(chalk.red(`Server "${serverName}" not found.`));
11
+ process.exit(1);
12
+ }
13
+ const client = new McpClientService();
14
+ try {
15
+ // console.log(chalk.gray(`Connecting to ${serverName}...`));
16
+ await client.connect(serverConfig);
17
+ const tools = await client.listTools();
18
+ console.log(chalk.bold(`\nAvailable Tools for ${serverName}:`));
19
+ if (tools.tools.length === 0) {
20
+ console.log(chalk.yellow('No tools found.'));
21
+ }
22
+ else {
23
+ tools.tools.forEach(tool => {
24
+ console.log(chalk.cyan(`\n- ${tool.name}`));
25
+ if (tool.description) {
26
+ console.log(` ${tool.description}`);
27
+ }
28
+ console.log(chalk.gray(' Arguments:'));
29
+ const schema = tool.inputSchema;
30
+ if (schema.properties) {
31
+ Object.entries(schema.properties).forEach(([key, value]) => {
32
+ const required = schema.required?.includes(key) ? chalk.red('*') : '';
33
+ console.log(` ${key}${required}: ${value.type || 'any'} ${value.description ? `(${value.description})` : ''}`);
34
+ });
35
+ }
36
+ else {
37
+ console.log(' None');
38
+ }
39
+ });
40
+ }
41
+ }
42
+ catch (error) {
43
+ console.error(chalk.red(`Failed to list tools: ${error.message}`));
44
+ }
45
+ finally {
46
+ await client.close();
47
+ }
48
+ });
49
+ };
@@ -0,0 +1,66 @@
1
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
3
+ import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
4
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
5
+ import { EventSource } from 'eventsource';
6
+ // Required for SSEClientTransport in Node.js environment
7
+ // @ts-ignore
8
+ global.EventSource = EventSource;
9
+ export class McpClientService {
10
+ client = null;
11
+ transport = null;
12
+ async connect(config) {
13
+ try {
14
+ if (config.type === 'stdio') {
15
+ const rawEnv = config.env ? { ...process.env, ...config.env } : process.env;
16
+ const env = {};
17
+ for (const key in rawEnv) {
18
+ const val = rawEnv[key];
19
+ if (typeof val === 'string') {
20
+ env[key] = val;
21
+ }
22
+ }
23
+ this.transport = new StdioClientTransport({
24
+ command: config.command,
25
+ args: config.args,
26
+ env: env,
27
+ });
28
+ }
29
+ else if (config.type === 'http') {
30
+ this.transport = new StreamableHTTPClientTransport(new URL(config.url));
31
+ }
32
+ else {
33
+ this.transport = new SSEClientTransport(new URL(config.url));
34
+ }
35
+ this.client = new Client({
36
+ name: 'mcp-cli',
37
+ version: '1.0.0',
38
+ }, {
39
+ capabilities: {},
40
+ });
41
+ await this.client.connect(this.transport);
42
+ }
43
+ catch (error) {
44
+ console.error(`Failed to connect to server ${config.name}:`, error);
45
+ throw error;
46
+ }
47
+ }
48
+ async listTools() {
49
+ if (!this.client)
50
+ throw new Error('Client not connected');
51
+ return this.client.listTools();
52
+ }
53
+ async callTool(toolName, args) {
54
+ if (!this.client)
55
+ throw new Error('Client not connected');
56
+ return this.client.callTool({
57
+ name: toolName,
58
+ arguments: args,
59
+ });
60
+ }
61
+ async close() {
62
+ if (this.transport) {
63
+ await this.transport.close();
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,89 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { ServerConfigSchema } from '../types/config.js';
5
+ const CONFIG_DIR = process.env.MCP_CONFIG_DIR || path.join(os.homedir(), '.mcps');
6
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'mcp.json');
7
+ export class ConfigManager {
8
+ ensureConfigDir() {
9
+ if (!fs.existsSync(CONFIG_DIR)) {
10
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
11
+ }
12
+ }
13
+ loadConfig() {
14
+ this.ensureConfigDir();
15
+ if (!fs.existsSync(CONFIG_FILE)) {
16
+ return { servers: [] };
17
+ }
18
+ try {
19
+ const content = fs.readFileSync(CONFIG_FILE, 'utf-8');
20
+ const json = JSON.parse(content);
21
+ if (!json || typeof json !== 'object' || !Array.isArray(json.servers)) {
22
+ // If the root structure is invalid, we can't do much.
23
+ console.warn('Invalid config file structure. Expected { servers: [] }.');
24
+ return { servers: [] };
25
+ }
26
+ const validServers = [];
27
+ const servers = json.servers;
28
+ for (const server of servers) {
29
+ const result = ServerConfigSchema.safeParse(server);
30
+ if (result.success) {
31
+ validServers.push(result.data);
32
+ }
33
+ else {
34
+ console.warn(`Skipping invalid server config "${server?.name || 'unknown'}":`, result.error.errors[0]?.message);
35
+ }
36
+ }
37
+ return { servers: validServers };
38
+ }
39
+ catch (error) {
40
+ console.error('Failed to parse config file:', error);
41
+ return { servers: [] };
42
+ }
43
+ }
44
+ saveConfig(config) {
45
+ this.ensureConfigDir();
46
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');
47
+ }
48
+ listServers() {
49
+ return this.loadConfig().servers;
50
+ }
51
+ getServer(name) {
52
+ const config = this.loadConfig();
53
+ return config.servers.find(s => s.name === name);
54
+ }
55
+ addServer(server) {
56
+ const config = this.loadConfig();
57
+ if (config.servers.find(s => s.name === server.name)) {
58
+ throw new Error(`Server with name "${server.name}" already exists.`);
59
+ }
60
+ config.servers.push(server);
61
+ this.saveConfig(config);
62
+ }
63
+ removeServer(name) {
64
+ const config = this.loadConfig();
65
+ const initialLength = config.servers.length;
66
+ config.servers = config.servers.filter(s => s.name !== name);
67
+ if (config.servers.length === initialLength) {
68
+ throw new Error(`Server with name "${name}" not found.`);
69
+ }
70
+ this.saveConfig(config);
71
+ }
72
+ updateServer(name, updates) {
73
+ const config = this.loadConfig();
74
+ const index = config.servers.findIndex(s => s.name === name);
75
+ if (index === -1) {
76
+ throw new Error(`Server with name "${name}" not found.`);
77
+ }
78
+ const current = config.servers[index];
79
+ const updated = { ...current, ...updates };
80
+ // Validate the updated object matches the schema (especially type consistency)
81
+ const result = ServerConfigSchema.safeParse(updated);
82
+ if (!result.success) {
83
+ throw new Error(`Invalid update: ${result.error.message}`);
84
+ }
85
+ config.servers[index] = result.data;
86
+ this.saveConfig(config);
87
+ }
88
+ }
89
+ export const configManager = new ConfigManager();
@@ -0,0 +1,46 @@
1
+ import { McpClientService } from './client.js';
2
+ import { configManager } from './config.js';
3
+ export class ConnectionPool {
4
+ clients = new Map();
5
+ async getClient(serverName) {
6
+ if (this.clients.has(serverName)) {
7
+ return this.clients.get(serverName);
8
+ }
9
+ const serverConfig = configManager.getServer(serverName);
10
+ if (!serverConfig) {
11
+ throw new Error(`Server "${serverName}" not found in config.`);
12
+ }
13
+ console.log(`[Daemon] Connecting to server: ${serverName}...`);
14
+ const client = new McpClientService();
15
+ await client.connect(serverConfig);
16
+ this.clients.set(serverName, client);
17
+ return client;
18
+ }
19
+ async closeClient(serverName) {
20
+ if (this.clients.has(serverName)) {
21
+ console.log(`[Daemon] Closing connection to ${serverName}...`);
22
+ try {
23
+ await this.clients.get(serverName).close();
24
+ }
25
+ catch (e) {
26
+ console.error(`[Daemon] Error closing ${serverName}:`, e);
27
+ }
28
+ this.clients.delete(serverName);
29
+ return true;
30
+ }
31
+ return false;
32
+ }
33
+ async closeAll() {
34
+ for (const [name, client] of this.clients) {
35
+ console.log(`[Daemon] Closing connection to ${name}...`);
36
+ try {
37
+ await client.close();
38
+ }
39
+ catch (e) {
40
+ console.error(`[Daemon] Error closing ${name}:`, e);
41
+ }
42
+ }
43
+ this.clients.clear();
44
+ }
45
+ }
46
+ export const connectionPool = new ConnectionPool();
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { registerServerCommands } from './commands/server.js';
4
+ import { registerToolsCommand } from './commands/tools.js';
5
+ import { registerCallCommand } from './commands/call.js';
6
+ import { registerDaemonCommand } from './commands/daemon.js';
7
+ const program = new Command();
8
+ program
9
+ .name('mcps')
10
+ .description('A CLI to manage and use MCP servers')
11
+ .version('1.0.0');
12
+ registerServerCommands(program);
13
+ registerToolsCommand(program);
14
+ registerCallCommand(program);
15
+ registerDaemonCommand(program);
16
+ program.parse(process.argv);
@@ -0,0 +1,23 @@
1
+ import { z } from 'zod';
2
+ export const ServerConfigSchema = z.union([
3
+ z.object({
4
+ name: z.string(),
5
+ type: z.literal('stdio'),
6
+ command: z.string(),
7
+ args: z.array(z.string()).default([]),
8
+ env: z.record(z.string()).optional(),
9
+ }),
10
+ z.object({
11
+ name: z.string(),
12
+ type: z.literal('sse'),
13
+ url: z.string().url(),
14
+ }),
15
+ z.object({
16
+ name: z.string(),
17
+ type: z.literal('http'),
18
+ url: z.string().url(),
19
+ }),
20
+ ]);
21
+ export const ConfigSchema = z.object({
22
+ servers: z.array(ServerConfigSchema).default([]),
23
+ });
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@maplezzk/mcps",
3
+ "version": "1.0.1",
4
+ "description": "A CLI to manage and use MCP servers",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "main": "dist/index.js",
9
+ "keywords": [
10
+ "mcp",
11
+ "cli",
12
+ "ai",
13
+ "tool"
14
+ ],
15
+ "author": "",
16
+ "license": "ISC",
17
+ "type": "module",
18
+ "bin": {
19
+ "mcps": "./dist/index.js"
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "build": "tsc",
26
+ "prepublishOnly": "npm run build",
27
+ "start": "node dist/index.js",
28
+ "dev": "ts-node src/index.ts",
29
+ "test": "echo \"Error: no test specified\" && exit 1"
30
+ },
31
+ "dependencies": {
32
+ "@modelcontextprotocol/sdk": "^1.25.3",
33
+ "chalk": "^5.6.2",
34
+ "commander": "^14.0.2",
35
+ "conf": "^15.0.2",
36
+ "eventsource": "^4.1.0",
37
+ "zod": "^3.24.1"
38
+ },
39
+ "devDependencies": {
40
+ "@types/eventsource": "^1.1.15",
41
+ "@types/node": "^22.10.7",
42
+ "ts-node": "^10.9.2",
43
+ "typescript": "^5.7.3"
44
+ }
45
+ }