termux-dev 1.3.0 → 1.4.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/README.md +2 -0
- package/assets/banner.svg +1 -1
- package/assets/preview.png +0 -0
- package/dist/cli/doctor.js +8 -2
- package/dist/cli/headless.js +1 -1
- package/dist/cli/index.js +207 -188
- package/dist/cli/prompt.js +48 -15
- package/dist/cli/server.js +1 -1
- package/dist/cli/updater.js +0 -6
- package/dist/core/commands.js +3 -3
- package/dist/core/history.js +10 -0
- package/dist/core/loop.js +5 -1
- package/dist/core/models.js +1 -1
- package/dist/core/pricing.js +1 -1
- package/dist/core/usage.js +21 -21
- package/dist/mcp/client.js +218 -0
- package/dist/mcp/manager.js +196 -0
- package/dist/mcp/types.js +1 -0
- package/dist/permissions/guard.js +34 -10
- package/dist/providers/openai.js +14 -5
- package/dist/tools/bash.js +7 -0
- package/dist/tools/fs.js +1 -1
- package/dist/tools/index.js +4 -2
- package/dist/tools/web.js +3 -3
- package/package.json +1 -1
package/dist/cli/prompt.js
CHANGED
|
@@ -10,6 +10,7 @@ export const SLASH_COMMANDS = [
|
|
|
10
10
|
{ cmd: '/session del', desc: 'Select and delete saved sessions' },
|
|
11
11
|
{ cmd: '/usage', desc: 'Show network bandwidth, data saver & token cost' },
|
|
12
12
|
{ cmd: '/export', desc: 'Export session conversation to Markdown' },
|
|
13
|
+
{ cmd: '/mcp', desc: 'Manage Model Context Protocol (MCP) servers & tools' },
|
|
13
14
|
{ cmd: '/theme', desc: 'Switch UI theme (Cyan, Purple, Matrix, Amber, etc.)' },
|
|
14
15
|
{ cmd: '/doctor', desc: 'Run system & environment health diagnostics' },
|
|
15
16
|
{ cmd: '/settings', desc: 'Configure permissions & auto-approval' },
|
|
@@ -151,18 +152,27 @@ export function askPrompt(opts = {}) {
|
|
|
151
152
|
}
|
|
152
153
|
return result;
|
|
153
154
|
}
|
|
155
|
+
function stripAnsi(str) {
|
|
156
|
+
return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
|
|
157
|
+
}
|
|
154
158
|
function render() {
|
|
155
159
|
if (disposed)
|
|
156
160
|
return;
|
|
157
161
|
const items = getDropdownItems();
|
|
158
162
|
const dropdownLines = [];
|
|
163
|
+
const cols = Math.max(28, process.stdout.columns || 80);
|
|
164
|
+
const rows = Math.max(8, process.stdout.rows || 24);
|
|
159
165
|
if (items.length > 0) {
|
|
160
166
|
if (selectedIndex >= items.length)
|
|
161
167
|
selectedIndex = 0;
|
|
162
168
|
if (selectedIndex < 0)
|
|
163
169
|
selectedIndex = items.length - 1;
|
|
164
|
-
|
|
165
|
-
const
|
|
170
|
+
// Ensure inner box width strictly fits: innerBoxWidth + 5 <= cols - 2
|
|
171
|
+
const innerBoxWidth = Math.max(16, Math.min(cols - 8, 54));
|
|
172
|
+
const isNarrowOrShort = rows <= 16 || cols < 50;
|
|
173
|
+
const pageSize = isNarrowOrShort
|
|
174
|
+
? Math.max(2, Math.min(3, rows - 5))
|
|
175
|
+
: Math.min(5, Math.max(3, Math.floor((rows - 4) / 2)));
|
|
166
176
|
const total = items.length;
|
|
167
177
|
let startIndex = 0;
|
|
168
178
|
if (total > pageSize) {
|
|
@@ -173,26 +183,47 @@ export function askPrompt(opts = {}) {
|
|
|
173
183
|
const endIndex = Math.min(startIndex + pageSize, total);
|
|
174
184
|
const hasMoreUp = startIndex > 0;
|
|
175
185
|
const hasMoreDown = endIndex < total;
|
|
176
|
-
let topBorderStr = '─'.repeat(
|
|
186
|
+
let topBorderStr = '─'.repeat(innerBoxWidth);
|
|
177
187
|
if (hasMoreUp) {
|
|
178
|
-
const mid = Math.max(0, Math.floor(
|
|
179
|
-
topBorderStr = '─'.repeat(mid) + ' ▲ ' + '─'.repeat(Math.max(0,
|
|
188
|
+
const mid = Math.max(0, Math.floor(innerBoxWidth / 2) - 2);
|
|
189
|
+
topBorderStr = '─'.repeat(mid) + ' ▲ ' + '─'.repeat(Math.max(0, innerBoxWidth - mid - 3));
|
|
180
190
|
}
|
|
181
|
-
let botBorderStr = '─'.repeat(
|
|
191
|
+
let botBorderStr = '─'.repeat(innerBoxWidth);
|
|
182
192
|
if (hasMoreDown) {
|
|
183
|
-
const mid = Math.max(0, Math.floor(
|
|
184
|
-
botBorderStr = '─'.repeat(mid) + ' ▼ ' + '─'.repeat(Math.max(0,
|
|
193
|
+
const mid = Math.max(0, Math.floor(innerBoxWidth / 2) - 2);
|
|
194
|
+
botBorderStr = '─'.repeat(mid) + ' ▼ ' + '─'.repeat(Math.max(0, innerBoxWidth - mid - 3));
|
|
185
195
|
}
|
|
186
196
|
dropdownLines.push(pc.dim('│') + ' ' + pc.dim('╭' + topBorderStr + '╮'));
|
|
187
197
|
for (let i = startIndex; i < endIndex; i++) {
|
|
188
198
|
const item = items[i];
|
|
189
199
|
const isSelected = i === selectedIndex;
|
|
190
|
-
const
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
200
|
+
const pointer = isSelected ? '› ' : ' ';
|
|
201
|
+
const availWidth = innerBoxWidth - 2;
|
|
202
|
+
let row = '';
|
|
203
|
+
if (availWidth < 20) {
|
|
204
|
+
// Very narrow mobile screen: show command name only
|
|
205
|
+
const labelStr = item.label.length > availWidth ? item.label.slice(0, availWidth - 1) + '…' : item.label.padEnd(availWidth);
|
|
206
|
+
const plain = pointer + labelStr;
|
|
207
|
+
row = isSelected ? theme.badgeFn(plain) : (pointer + theme.boldFn(labelStr));
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
// Show command name and truncated description
|
|
211
|
+
const labelMax = Math.min(15, Math.floor(availWidth * 0.45));
|
|
212
|
+
const labelStr = item.label.length > labelMax ? item.label.slice(0, labelMax - 1) + '…' : item.label.padEnd(labelMax);
|
|
213
|
+
const descMax = availWidth - labelMax - 1;
|
|
214
|
+
const descStr = item.desc.length > descMax ? item.desc.slice(0, descMax - 1) + '…' : item.desc.padEnd(descMax);
|
|
215
|
+
const plain = `${pointer}${labelStr} ${descStr}`;
|
|
216
|
+
if (isSelected) {
|
|
217
|
+
row = theme.badgeFn(plain);
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
row = `${pointer}${theme.boldFn(labelStr)} ${pc.gray(descStr)}`;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// Safety guarantee: exact visible width must match innerBoxWidth
|
|
224
|
+
const currentLen = stripAnsi(row).length;
|
|
225
|
+
if (currentLen < innerBoxWidth) {
|
|
226
|
+
row += ' '.repeat(innerBoxWidth - currentLen);
|
|
196
227
|
}
|
|
197
228
|
dropdownLines.push(pc.dim('│') + ' ' + pc.dim('│') + row + pc.dim('│'));
|
|
198
229
|
}
|
|
@@ -201,7 +232,9 @@ export function askPrompt(opts = {}) {
|
|
|
201
232
|
// 1. Draw/update input line (line 0)
|
|
202
233
|
let inputDisplay = pc.dim('│') + ' ';
|
|
203
234
|
if (input.length === 0) {
|
|
204
|
-
|
|
235
|
+
const maxPlace = Math.max(12, cols - 8);
|
|
236
|
+
const displayPlace = placeholder.length > maxPlace ? placeholder.slice(0, maxPlace - 1) + '…' : placeholder;
|
|
237
|
+
inputDisplay += pc.dim(displayPlace);
|
|
205
238
|
}
|
|
206
239
|
else {
|
|
207
240
|
inputDisplay += formatInputWithBadges(input);
|
package/dist/cli/server.js
CHANGED
|
@@ -139,7 +139,7 @@ function renderDirectoryHtml(dirPath, relPath, files, port) {
|
|
|
139
139
|
${parentLink}
|
|
140
140
|
${items || '<li style="padding: 20px; text-align: center; color: #6e7681;">No visible files in this directory</li>'}
|
|
141
141
|
</ul>
|
|
142
|
-
<div class="footer">devx v1.
|
|
142
|
+
<div class="footer">devx v1.4.1 • Terminal-Native AI Assistant</div>
|
|
143
143
|
</div>
|
|
144
144
|
</body>
|
|
145
145
|
</html>`;
|
package/dist/cli/updater.js
CHANGED
|
@@ -85,12 +85,6 @@ export async function checkForUpdates(timeoutMs = 10000) {
|
|
|
85
85
|
currentVersion,
|
|
86
86
|
latestVersion: latestVersion || currentVersion
|
|
87
87
|
};
|
|
88
|
-
return {
|
|
89
|
-
updateAvailable: false,
|
|
90
|
-
currentVersion,
|
|
91
|
-
latestVersion: currentVersion,
|
|
92
|
-
error: `HTTP ${res.status}`
|
|
93
|
-
};
|
|
94
88
|
}
|
|
95
89
|
catch (err) {
|
|
96
90
|
clearTimeout(timer);
|
package/dist/core/commands.js
CHANGED
|
@@ -64,12 +64,12 @@ export class CustomCommandManager {
|
|
|
64
64
|
return trimmedArgs ? `${template}\n\nUser Arguments: ${trimmedArgs}` : template;
|
|
65
65
|
}
|
|
66
66
|
let expanded = template;
|
|
67
|
-
expanded = expanded.replace(/\$ARG/g, trimmedArgs);
|
|
68
|
-
expanded = expanded.replace(/\$\*/g, trimmedArgs);
|
|
67
|
+
expanded = expanded.replace(/\$ARG/g, () => trimmedArgs);
|
|
68
|
+
expanded = expanded.replace(/\$\*/g, () => trimmedArgs);
|
|
69
69
|
// Support positional parameters: $1, $2, etc.
|
|
70
70
|
const parts = trimmedArgs.split(/\s+/);
|
|
71
71
|
for (let i = 0; i < parts.length; i++) {
|
|
72
|
-
expanded = expanded.replace(new RegExp(`\\$${i + 1}`, 'g'), parts[i]);
|
|
72
|
+
expanded = expanded.replace(new RegExp(`\\$${i + 1}`, 'g'), () => parts[i]);
|
|
73
73
|
}
|
|
74
74
|
return expanded;
|
|
75
75
|
}
|
package/dist/core/history.js
CHANGED
|
@@ -16,6 +16,16 @@ export class History {
|
|
|
16
16
|
getMessages() {
|
|
17
17
|
return [...this.messages];
|
|
18
18
|
}
|
|
19
|
+
popLastTurn() {
|
|
20
|
+
// Pop assistant and tool messages from the end of history
|
|
21
|
+
while (this.messages.length > 1 && this.messages[this.messages.length - 1].role !== 'user') {
|
|
22
|
+
this.messages.pop();
|
|
23
|
+
}
|
|
24
|
+
// Pop the triggering user message
|
|
25
|
+
if (this.messages.length > 1 && this.messages[this.messages.length - 1].role === 'user') {
|
|
26
|
+
this.messages.pop();
|
|
27
|
+
}
|
|
28
|
+
}
|
|
19
29
|
clear() {
|
|
20
30
|
this.messages = [];
|
|
21
31
|
}
|
package/dist/core/loop.js
CHANGED
|
@@ -94,9 +94,13 @@ export class Agent {
|
|
|
94
94
|
response = chunk.response;
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
|
-
if (response
|
|
97
|
+
if (response) {
|
|
98
98
|
break;
|
|
99
99
|
}
|
|
100
|
+
if (!receivedAnyChunk) {
|
|
101
|
+
throw new Error('Provider stream ended unexpectedly without receiving any data.');
|
|
102
|
+
}
|
|
103
|
+
break;
|
|
100
104
|
}
|
|
101
105
|
else {
|
|
102
106
|
response = await this.provider.chat(request);
|
package/dist/core/models.js
CHANGED
|
@@ -33,7 +33,7 @@ export function getModelContextLimit(modelName) {
|
|
|
33
33
|
return cache[clean];
|
|
34
34
|
if (cache[short])
|
|
35
35
|
return cache[short];
|
|
36
|
-
const baseName = short.replace(
|
|
36
|
+
const baseName = short.replace(/-\d{4,8}$/, '').replace(/:latest$/, '');
|
|
37
37
|
if (cache[baseName])
|
|
38
38
|
return cache[baseName];
|
|
39
39
|
if (clean.includes('kimi-k2') || clean.includes('kimi'))
|
package/dist/core/pricing.js
CHANGED
|
@@ -42,7 +42,7 @@ export function getModelPricing(modelName) {
|
|
|
42
42
|
return cache[clean];
|
|
43
43
|
if (cache[short])
|
|
44
44
|
return cache[short];
|
|
45
|
-
const baseName = short.replace(
|
|
45
|
+
const baseName = short.replace(/-\d{4,8}$/, '').replace(/:latest$/, '');
|
|
46
46
|
if (cache[baseName])
|
|
47
47
|
return cache[baseName];
|
|
48
48
|
if (clean.includes('gpt-4o-mini'))
|
package/dist/core/usage.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import pc from 'picocolors';
|
|
2
2
|
import { getCurrentTheme } from '../cli/theme.js';
|
|
3
|
+
function stripAnsi(str) {
|
|
4
|
+
return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
|
|
5
|
+
}
|
|
3
6
|
export class UsageTracker {
|
|
4
7
|
static instance;
|
|
5
|
-
requestsCount = 0;
|
|
6
8
|
bytesSent = 0;
|
|
7
9
|
bytesReceived = 0;
|
|
10
|
+
requestsCount = 0;
|
|
8
11
|
promptTokens = 0;
|
|
9
12
|
completionTokens = 0;
|
|
10
13
|
totalCost = 0;
|
|
@@ -20,24 +23,24 @@ export class UsageTracker {
|
|
|
20
23
|
setLimit(limitMB) {
|
|
21
24
|
this.dataSaverLimitMB = limitMB;
|
|
22
25
|
}
|
|
23
|
-
recordRequest(
|
|
24
|
-
this.
|
|
25
|
-
this.
|
|
26
|
+
recordRequest(payloadBytes) {
|
|
27
|
+
this.bytesSent += payloadBytes;
|
|
28
|
+
this.requestsCount += 1;
|
|
26
29
|
}
|
|
27
|
-
recordResponseChunk(
|
|
28
|
-
this.bytesReceived +=
|
|
30
|
+
recordResponseChunk(chunkBytes) {
|
|
31
|
+
this.bytesReceived += chunkBytes;
|
|
29
32
|
}
|
|
30
|
-
recordTokens(
|
|
31
|
-
this.promptTokens +=
|
|
32
|
-
this.completionTokens +=
|
|
33
|
-
this.totalCost +=
|
|
33
|
+
recordTokens(promptTokens, completionTokens, cost) {
|
|
34
|
+
this.promptTokens += promptTokens;
|
|
35
|
+
this.completionTokens += completionTokens;
|
|
36
|
+
this.totalCost += cost;
|
|
34
37
|
}
|
|
35
38
|
getSummary() {
|
|
36
39
|
return {
|
|
37
|
-
requestsCount: this.requestsCount,
|
|
38
40
|
bytesSent: this.bytesSent,
|
|
39
41
|
bytesReceived: this.bytesReceived,
|
|
40
42
|
totalBytes: this.bytesSent + this.bytesReceived,
|
|
43
|
+
requestsCount: this.requestsCount,
|
|
41
44
|
promptTokens: this.promptTokens,
|
|
42
45
|
completionTokens: this.completionTokens,
|
|
43
46
|
totalTokens: this.promptTokens + this.completionTokens,
|
|
@@ -46,19 +49,15 @@ export class UsageTracker {
|
|
|
46
49
|
};
|
|
47
50
|
}
|
|
48
51
|
static formatBytes(bytes) {
|
|
49
|
-
if (bytes <= 0)
|
|
50
|
-
return '0 B';
|
|
51
52
|
if (bytes < 1024)
|
|
52
53
|
return `${bytes} B`;
|
|
53
54
|
if (bytes < 1024 * 1024)
|
|
54
55
|
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
55
|
-
|
|
56
|
-
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
|
57
|
-
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
56
|
+
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
|
58
57
|
}
|
|
59
58
|
static formatTokens(n) {
|
|
60
|
-
if (n >=
|
|
61
|
-
return `${(n /
|
|
59
|
+
if (n >= 1000000)
|
|
60
|
+
return `${(n / 1000000).toFixed(2)}M`;
|
|
62
61
|
if (n >= 1000)
|
|
63
62
|
return `${(n / 1000).toFixed(1)}k`;
|
|
64
63
|
return `${n}`;
|
|
@@ -67,10 +66,11 @@ export class UsageTracker {
|
|
|
67
66
|
const theme = getCurrentTheme();
|
|
68
67
|
const summary = this.getSummary();
|
|
69
68
|
const cols = Math.min(process.stdout.columns || 80, 75);
|
|
70
|
-
const boxWidth = Math.max(
|
|
71
|
-
const innerWidth = boxWidth -
|
|
69
|
+
const boxWidth = Math.max(38, cols - 4);
|
|
70
|
+
const innerWidth = boxWidth - 6;
|
|
72
71
|
const padRow = (label, value) => {
|
|
73
|
-
const
|
|
72
|
+
const visibleValLen = stripAnsi(value).length;
|
|
73
|
+
const plainLen = label.length + visibleValLen;
|
|
74
74
|
const spaces = Math.max(1, innerWidth - plainLen);
|
|
75
75
|
return `│ ${pc.bold(label)}${' '.repeat(spaces)}${value} │`;
|
|
76
76
|
};
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { spawn } from 'child_process';
|
|
2
|
+
export class MCPClient {
|
|
3
|
+
name;
|
|
4
|
+
config;
|
|
5
|
+
process = null;
|
|
6
|
+
nextRequestId = 1;
|
|
7
|
+
pendingRequests = new Map();
|
|
8
|
+
buffer = '';
|
|
9
|
+
tools = [];
|
|
10
|
+
isConnected = false;
|
|
11
|
+
constructor(name, config) {
|
|
12
|
+
this.name = name;
|
|
13
|
+
this.config = config;
|
|
14
|
+
}
|
|
15
|
+
async start() {
|
|
16
|
+
if (this.config.disabled) {
|
|
17
|
+
throw new Error(`MCP server "${this.name}" is disabled in configuration.`);
|
|
18
|
+
}
|
|
19
|
+
return new Promise(async (resolve, reject) => {
|
|
20
|
+
let isSettled = false;
|
|
21
|
+
const initialTimer = setTimeout(() => {
|
|
22
|
+
if (!isSettled) {
|
|
23
|
+
isSettled = true;
|
|
24
|
+
this.close();
|
|
25
|
+
reject(new Error(`MCP server "${this.name}" initialization timed out after 15s.`));
|
|
26
|
+
}
|
|
27
|
+
}, 15000);
|
|
28
|
+
try {
|
|
29
|
+
const env = {
|
|
30
|
+
...process.env,
|
|
31
|
+
...(this.config.env || {})
|
|
32
|
+
};
|
|
33
|
+
const isWindows = process.platform === 'win32';
|
|
34
|
+
const useShell = isWindows && (this.config.command.endsWith('.cmd') ||
|
|
35
|
+
this.config.command.endsWith('.bat') ||
|
|
36
|
+
this.config.command === 'npx' ||
|
|
37
|
+
this.config.command === 'npm');
|
|
38
|
+
this.process = spawn(this.config.command, this.config.args || [], {
|
|
39
|
+
env,
|
|
40
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
41
|
+
shell: useShell
|
|
42
|
+
});
|
|
43
|
+
this.process.stdout?.on('data', (data) => {
|
|
44
|
+
this.handleStdout(data.toString());
|
|
45
|
+
});
|
|
46
|
+
this.process.stderr?.on('data', (_data) => {
|
|
47
|
+
// Stderr from MCP servers is used for logging/debugging
|
|
48
|
+
});
|
|
49
|
+
this.process.on('error', (err) => {
|
|
50
|
+
if (!isSettled) {
|
|
51
|
+
isSettled = true;
|
|
52
|
+
clearTimeout(initialTimer);
|
|
53
|
+
reject(new Error(`Failed to start MCP server "${this.name}": ${err.message}`));
|
|
54
|
+
}
|
|
55
|
+
this.cleanup();
|
|
56
|
+
});
|
|
57
|
+
this.process.on('close', (_code) => {
|
|
58
|
+
this.cleanup();
|
|
59
|
+
});
|
|
60
|
+
// 1. Initialize Handshake
|
|
61
|
+
const initResult = await this.sendRequest('initialize', {
|
|
62
|
+
protocolVersion: '2024-11-05',
|
|
63
|
+
capabilities: {},
|
|
64
|
+
clientInfo: {
|
|
65
|
+
name: 'devx',
|
|
66
|
+
version: '1.4.1'
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
if (!initResult) {
|
|
70
|
+
throw new Error(`Invalid initialize response from MCP server "${this.name}".`);
|
|
71
|
+
}
|
|
72
|
+
// 2. Send initialized notification
|
|
73
|
+
this.sendNotification('notifications/initialized', {});
|
|
74
|
+
// 3. Fetch Tools List
|
|
75
|
+
const toolsResult = await this.sendRequest('tools/list', {});
|
|
76
|
+
this.tools = toolsResult?.tools || [];
|
|
77
|
+
this.isConnected = true;
|
|
78
|
+
if (!isSettled) {
|
|
79
|
+
isSettled = true;
|
|
80
|
+
clearTimeout(initialTimer);
|
|
81
|
+
resolve(this.tools);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
if (!isSettled) {
|
|
86
|
+
isSettled = true;
|
|
87
|
+
clearTimeout(initialTimer);
|
|
88
|
+
this.close();
|
|
89
|
+
reject(err);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
getTools() {
|
|
95
|
+
return this.tools;
|
|
96
|
+
}
|
|
97
|
+
hasConnected() {
|
|
98
|
+
return this.isConnected;
|
|
99
|
+
}
|
|
100
|
+
async callTool(toolName, args) {
|
|
101
|
+
if (!this.process || !this.isConnected) {
|
|
102
|
+
throw new Error(`MCP server "${this.name}" is not connected.`);
|
|
103
|
+
}
|
|
104
|
+
const res = await this.sendRequest('tools/call', {
|
|
105
|
+
name: toolName,
|
|
106
|
+
arguments: args || {}
|
|
107
|
+
}, 60000); // 60s timeout for tool calls
|
|
108
|
+
if (!res || !res.content) {
|
|
109
|
+
return JSON.stringify(res || {});
|
|
110
|
+
}
|
|
111
|
+
const outputParts = [];
|
|
112
|
+
for (const c of res.content) {
|
|
113
|
+
if (c.type === 'text' && c.text) {
|
|
114
|
+
outputParts.push(c.text);
|
|
115
|
+
}
|
|
116
|
+
else if (c.type === 'image' && c.data) {
|
|
117
|
+
outputParts.push(`[Image content (${c.mimeType || 'image/png'})]`);
|
|
118
|
+
}
|
|
119
|
+
else if (c.type === 'resource') {
|
|
120
|
+
outputParts.push(`[Resource: ${JSON.stringify(c)}]`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const finalResult = outputParts.join('\n\n') || JSON.stringify(res);
|
|
124
|
+
if (res.isError) {
|
|
125
|
+
throw new Error(finalResult);
|
|
126
|
+
}
|
|
127
|
+
return finalResult;
|
|
128
|
+
}
|
|
129
|
+
handleStdout(chunk) {
|
|
130
|
+
this.buffer += chunk;
|
|
131
|
+
const lines = this.buffer.split('\n');
|
|
132
|
+
this.buffer = lines.pop() || '';
|
|
133
|
+
for (const line of lines) {
|
|
134
|
+
const trimmed = line.trim();
|
|
135
|
+
if (!trimmed)
|
|
136
|
+
continue;
|
|
137
|
+
try {
|
|
138
|
+
const msg = JSON.parse(trimmed);
|
|
139
|
+
if ('id' in msg && msg.id !== undefined) {
|
|
140
|
+
const pending = this.pendingRequests.get(msg.id);
|
|
141
|
+
if (pending) {
|
|
142
|
+
clearTimeout(pending.timer);
|
|
143
|
+
this.pendingRequests.delete(msg.id);
|
|
144
|
+
if (msg.error) {
|
|
145
|
+
pending.reject(new Error(`MCP error ${msg.error.code}: ${msg.error.message}`));
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
pending.resolve(msg.result);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
// Ignore non-JSON line outputs (e.g. startup banner)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
sendRequest(method, params, timeoutMs = 15000) {
|
|
159
|
+
return new Promise((resolve, reject) => {
|
|
160
|
+
if (!this.process || !this.process.stdin) {
|
|
161
|
+
return reject(new Error(`MCP server "${this.name}" process is not running.`));
|
|
162
|
+
}
|
|
163
|
+
const id = this.nextRequestId++;
|
|
164
|
+
const timer = setTimeout(() => {
|
|
165
|
+
if (this.pendingRequests.has(id)) {
|
|
166
|
+
this.pendingRequests.delete(id);
|
|
167
|
+
reject(new Error(`MCP request "${method}" to server "${this.name}" timed out (${timeoutMs / 1000}s).`));
|
|
168
|
+
}
|
|
169
|
+
}, timeoutMs);
|
|
170
|
+
this.pendingRequests.set(id, { resolve, reject, timer });
|
|
171
|
+
const request = {
|
|
172
|
+
jsonrpc: '2.0',
|
|
173
|
+
id,
|
|
174
|
+
method,
|
|
175
|
+
params
|
|
176
|
+
};
|
|
177
|
+
try {
|
|
178
|
+
this.process.stdin.write(JSON.stringify(request) + '\n');
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
this.pendingRequests.delete(id);
|
|
183
|
+
reject(new Error(`Failed to write to MCP server "${this.name}": ${err.message}`));
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
sendNotification(method, params) {
|
|
188
|
+
if (!this.process || !this.process.stdin)
|
|
189
|
+
return;
|
|
190
|
+
const notif = {
|
|
191
|
+
jsonrpc: '2.0',
|
|
192
|
+
method,
|
|
193
|
+
params
|
|
194
|
+
};
|
|
195
|
+
try {
|
|
196
|
+
this.process.stdin.write(JSON.stringify(notif) + '\n');
|
|
197
|
+
}
|
|
198
|
+
catch { }
|
|
199
|
+
}
|
|
200
|
+
close() {
|
|
201
|
+
this.cleanup();
|
|
202
|
+
if (this.process) {
|
|
203
|
+
try {
|
|
204
|
+
this.process.kill();
|
|
205
|
+
}
|
|
206
|
+
catch { }
|
|
207
|
+
this.process = null;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
cleanup() {
|
|
211
|
+
this.isConnected = false;
|
|
212
|
+
for (const [id, req] of this.pendingRequests.entries()) {
|
|
213
|
+
clearTimeout(req.timer);
|
|
214
|
+
req.reject(new Error(`MCP server "${this.name}" disconnected.`));
|
|
215
|
+
}
|
|
216
|
+
this.pendingRequests.clear();
|
|
217
|
+
}
|
|
218
|
+
}
|