ineedcodes 1.0.2 → 1.1.0
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 +34 -1
- package/package.json +1 -1
- package/src/agent.js +130 -6
- package/src/config.js +1 -0
- package/src/mcp.js +203 -0
- package/src/session.js +29 -0
- package/src/ui.js +1 -1
package/README.md
CHANGED
|
@@ -64,8 +64,12 @@ The agent decides what it needs: list files, read code, search, edit, run shell
|
|
|
64
64
|
| `/plan` | read-only mode, the agent suggests but changes nothing |
|
|
65
65
|
| `/build` | default mode, the agent makes real changes |
|
|
66
66
|
| `/reason` | toggle reasoning effort low/high |
|
|
67
|
-
| `/
|
|
67
|
+
| `/perm` | permission modes: `/perm auto`, `/perm safe` |
|
|
68
|
+
| `/memory` | durable memory status, `/memory on\|off` |
|
|
69
|
+
| `/mcp` | list MCP servers and their tools |
|
|
68
70
|
| `/setup` | redo provider setup |
|
|
71
|
+
| `/config` | show provider config, API key hidden |
|
|
72
|
+
| `/clear` | forget the current conversation |
|
|
69
73
|
| `/exit` | quit |
|
|
70
74
|
|
|
71
75
|
Shortcuts are optional. Normal language always works.
|
|
@@ -94,13 +98,42 @@ Not a chatbot that prints code. A loop that does the work, checks the results, a
|
|
|
94
98
|
| `write_file` | create files |
|
|
95
99
|
| `edit_file` | targeted patch, not a rewrite |
|
|
96
100
|
| `delete_file` | remove a file |
|
|
101
|
+
| `todo` | visible checklist for multi-step work |
|
|
102
|
+
| `spawn_agent` | delegate to a focused sub-agent |
|
|
97
103
|
| `shell` | build, test, install, git, anything |
|
|
98
104
|
|
|
105
|
+
### Multi-agent
|
|
106
|
+
|
|
107
|
+
Big tasks get delegated. The lead agent spawns workers with a role that fits:
|
|
108
|
+
|
|
109
|
+
| role | can |
|
|
110
|
+
|---|---|
|
|
111
|
+
| `research` | read and report, nothing else, runs in parallel |
|
|
112
|
+
| `review` | inspect code, report findings, runs in parallel |
|
|
113
|
+
| `test` | run tests and commands, no source edits |
|
|
114
|
+
| `implement` | make the change, verify it |
|
|
115
|
+
| `debug` | find the root cause, fix it |
|
|
116
|
+
|
|
117
|
+
Workers report back with status, summary, evidence, files changed, and commands run. The lead reconciles everything and answers you.
|
|
118
|
+
|
|
119
|
+
### MCP (Model Context Protocol)
|
|
120
|
+
|
|
121
|
+
Connect any MCP server and its tools appear in the agent automatically. Create `~/.ineedcodes/mcp.json`:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp"] }
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Restart ineed, and every tool from that server is callable. Check what is loaded with `/mcp` inside a session.
|
|
130
|
+
|
|
99
131
|
### Safety
|
|
100
132
|
|
|
101
133
|
- Secrets (.env, ssh keys, pem files) never enter the model context.
|
|
102
134
|
- Destructive shell commands are refused.
|
|
103
135
|
- Everything is jailed to your working directory.
|
|
136
|
+
- Edits and shell commands ask for your approval first (`/perm auto` relaxes this).
|
|
104
137
|
- Plan mode lets you preview intent before any change.
|
|
105
138
|
|
|
106
139
|
## Works with any provider
|
package/package.json
CHANGED
package/src/agent.js
CHANGED
|
@@ -30,15 +30,106 @@ export function trimHistory(history) {
|
|
|
30
30
|
return history.slice(start);
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
// ── multi-agent: roles, task packets, worker execution ──
|
|
34
|
+
const ROLES = {
|
|
35
|
+
research: {
|
|
36
|
+
readonly: true,
|
|
37
|
+
tools: ['list_files', 'read_file', 'search_text', 'todo'],
|
|
38
|
+
prompt: 'You are a research worker. Gather facts and report them. Change nothing.'
|
|
39
|
+
},
|
|
40
|
+
review: {
|
|
41
|
+
readonly: true,
|
|
42
|
+
tools: ['list_files', 'read_file', 'search_text', 'todo'],
|
|
43
|
+
prompt: 'You are a review worker. Inspect the code for correctness, bugs, and quality. Report findings, change nothing.'
|
|
44
|
+
},
|
|
45
|
+
test: {
|
|
46
|
+
readonly: false,
|
|
47
|
+
tools: ['list_files', 'read_file', 'search_text', 'shell', 'todo'],
|
|
48
|
+
prompt: 'You are a test worker. Run the relevant tests or commands and report the evidence. Do not modify source files.'
|
|
49
|
+
},
|
|
50
|
+
implement: {
|
|
51
|
+
readonly: false,
|
|
52
|
+
tools: null, // all tools
|
|
53
|
+
prompt: 'You are an implementation worker. Make the change the lead asked for, verify it works, and report what you did.'
|
|
54
|
+
},
|
|
55
|
+
debug: {
|
|
56
|
+
readonly: false,
|
|
57
|
+
tools: null, // all tools
|
|
58
|
+
prompt: 'You are a debugging worker. Find the root cause, fix it if you can, and report cause plus evidence.'
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
let workerSeq = 0;
|
|
63
|
+
|
|
64
|
+
function workerResultText(r) {
|
|
65
|
+
const files = r.files?.length ? ` files: ${r.files.join(', ')};` : '';
|
|
66
|
+
const cmds = r.commands?.length ? ` ran ${r.commands.length} command(s);` : '';
|
|
67
|
+
return `Worker ${r.id} [${r.status}]: ${String(r.summary).slice(0, 800)}.${files}${cmds}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function runWorker(cfg, spec, cwd, depth, hooks) {
|
|
71
|
+
const roleName = ROLES[spec.input.role] ? spec.input.role : 'research';
|
|
72
|
+
const role = ROLES[roleName];
|
|
73
|
+
const objective = String(spec.input.objective ?? '')
|
|
74
|
+
+ (spec.input.context ? `\nContext from lead agent: ${String(spec.input.context).slice(0, 1_000)}` : '');
|
|
75
|
+
try {
|
|
76
|
+
const res = await runObjective(cfg, objective, cwd, [], {}, {
|
|
77
|
+
depth: depth + 1,
|
|
78
|
+
toolFilter: role.tools,
|
|
79
|
+
worker: { id: spec.id, role: roleName, prompt: role.prompt }
|
|
80
|
+
});
|
|
81
|
+
return { id: spec.id, role: roleName, status: res.aborted ? 'incomplete' : 'completed', summary: res.answer || '(no output)', files: res.changed, commands: res.ran };
|
|
82
|
+
} catch (err) {
|
|
83
|
+
return { id: spec.id, role: roleName, status: 'failed', summary: err.message, files: [], commands: [] };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const SPAWN_TOOL = {
|
|
88
|
+
name: 'spawn_agent',
|
|
89
|
+
description: 'Spawn a focused sub-agent worker. Roles: research (read only), review (read only), test (runs commands, does not edit), implement (edits), debug (finds and fixes). Read-only workers can run in parallel.',
|
|
90
|
+
parameters: {
|
|
91
|
+
type: 'object',
|
|
92
|
+
properties: {
|
|
93
|
+
role: { type: 'string', enum: Object.keys(ROLES) },
|
|
94
|
+
objective: { type: 'string', description: 'the exact task for this worker' },
|
|
95
|
+
context: { type: 'string', description: 'relevant context: files, errors, constraints' }
|
|
96
|
+
},
|
|
97
|
+
required: ['role', 'objective']
|
|
98
|
+
},
|
|
99
|
+
allowedInPlan: true
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
export async function runObjective(cfg, objective, cwd, history, hooks = {}, extra = {}) {
|
|
34
103
|
const ctrl = new AbortController();
|
|
35
104
|
hooks.onRunStart?.(ctrl);
|
|
36
105
|
const plan = cfg.mode === 'plan';
|
|
37
|
-
const
|
|
106
|
+
const depth = extra.depth ?? 0;
|
|
107
|
+
let tools = plan ? TOOLS.filter(t => t.allowedInPlan) : [...TOOLS, SPAWN_TOOL];
|
|
108
|
+
if (extra.toolFilter) tools = tools.filter(t => (extra.toolFilter).includes(t.name));
|
|
38
109
|
const canAsk = typeof hooks.onApprove === 'function';
|
|
39
110
|
|
|
111
|
+
// MCP: load configured servers once per top-level objective, expose their tools
|
|
112
|
+
let mcpManager = null;
|
|
113
|
+
const mcpMap = new Map();
|
|
114
|
+
if (depth === 0 && !plan && cfg.mcp !== false) {
|
|
115
|
+
try {
|
|
116
|
+
const { McpManager, mcpConfigured } = await import('./mcp.js');
|
|
117
|
+
if (mcpConfigured()) {
|
|
118
|
+
mcpManager = new McpManager();
|
|
119
|
+
const errors = await mcpManager.loadFromConfig();
|
|
120
|
+
errors.forEach(e => hooks.onText?.(dim(e)));
|
|
121
|
+
const mcpTools = await mcpManager.allTools();
|
|
122
|
+
const names = new Set(tools.map(t => t.name));
|
|
123
|
+
for (const t of mcpTools) {
|
|
124
|
+
if (!names.has(t.name)) { tools.push(t); mcpMap.set(t.name, t.mcp); names.add(t.name); }
|
|
125
|
+
}
|
|
126
|
+
hooks.onMCP?.(mcpTools.map(t => t.name));
|
|
127
|
+
}
|
|
128
|
+
} catch {}
|
|
129
|
+
}
|
|
130
|
+
|
|
40
131
|
// recall durable memory before meaningful work (rule 12/15: MemoryProvider abstraction)
|
|
41
|
-
const memory = getMemoryProvider(cfg);
|
|
132
|
+
const memory = extra.skipMemory ? null : getMemoryProvider(cfg);
|
|
42
133
|
let recalled = '';
|
|
43
134
|
if (memory) {
|
|
44
135
|
hooks.onMemoryStart?.();
|
|
@@ -46,10 +137,11 @@ export async function runObjective(cfg, objective, cwd, history, hooks = {}) {
|
|
|
46
137
|
hooks.onMemoryEnd?.(recalled);
|
|
47
138
|
}
|
|
48
139
|
|
|
140
|
+
const workerPrefix = extra.worker ? `You are ${extra.worker.id} (${extra.worker.role} worker) spawned by the lead agent. ${extra.worker.prompt}\n` : '';
|
|
49
141
|
const messages = [
|
|
50
142
|
{
|
|
51
143
|
role: 'system',
|
|
52
|
-
content: `${SYSTEM}\nWorking directory: ${cwd}\nMode: ${plan ? 'plan (read only, suggest what to change, do not change anything)' : 'build'}`
|
|
144
|
+
content: `${workerPrefix ? workerPrefix + '\n' : ''}${SYSTEM}\nWorking directory: ${cwd}\nMode: ${plan ? 'plan (read only, suggest what to change, do not change anything)' : 'build'}`
|
|
53
145
|
+ (recalled ? `\nRelevant memory from previous sessions with this user (durable facts, may be stale):\n${recalled}` : '')
|
|
54
146
|
},
|
|
55
147
|
...trimHistory(history),
|
|
@@ -89,12 +181,44 @@ export async function runObjective(cfg, objective, cwd, history, hooks = {}) {
|
|
|
89
181
|
}
|
|
90
182
|
return { answer, changed: [...changed], ran, todos: [...todos], aborted: false };
|
|
91
183
|
}
|
|
184
|
+
// spawn_agent pre-pass: read-only workers run in parallel (max 4), writers sequentially
|
|
185
|
+
const spawnResults = new Map();
|
|
186
|
+
const spawnCalls = calls.filter(c => c.function?.name === 'spawn_agent');
|
|
187
|
+
if (spawnCalls.length && depth === 0) {
|
|
188
|
+
const specs = spawnCalls.map(c => {
|
|
189
|
+
let input = {};
|
|
190
|
+
try { input = JSON.parse(c.function?.arguments || '{}'); } catch {}
|
|
191
|
+
const role = ROLES[input.role] ? input.role : 'research';
|
|
192
|
+
return { call: c, input, role, id: `${role}-${++workerSeq}` };
|
|
193
|
+
});
|
|
194
|
+
const runOne = async s => {
|
|
195
|
+
hooks.onAgentStart?.(s.id, s.input);
|
|
196
|
+
const r = await runWorker(cfg, s, cwd, depth, hooks);
|
|
197
|
+
hooks.onAgentEnd?.(s.id, r);
|
|
198
|
+
spawnResults.set(s.call.id, r);
|
|
199
|
+
};
|
|
200
|
+
const readonly = specs.filter(s => ROLES[s.role].readonly).slice(0, 4);
|
|
201
|
+
const writers = specs.filter(s => !ROLES[s.role].readonly);
|
|
202
|
+
for (let i = 0; i < readonly.length; i += 4) {
|
|
203
|
+
await Promise.all(readonly.slice(i, i + 4).map(runOne));
|
|
204
|
+
}
|
|
205
|
+
for (const s of writers) await runOne(s);
|
|
206
|
+
}
|
|
207
|
+
|
|
92
208
|
for (const call of calls) {
|
|
93
209
|
let input = {};
|
|
94
210
|
try { input = JSON.parse(call.function?.arguments || '{}'); } catch {}
|
|
95
211
|
hooks.onTool?.(call.function?.name, input);
|
|
96
212
|
let result;
|
|
97
|
-
if (call.
|
|
213
|
+
if (spawnResults.has(call.id)) {
|
|
214
|
+
result = { output: workerResultText(spawnResults.get(call.id)) };
|
|
215
|
+
} else if (call.function?.name === 'spawn_agent') {
|
|
216
|
+
result = { output: 'Refused: workers cannot spawn more agents.' };
|
|
217
|
+
} else if (mcpMap.has(call.function?.name)) {
|
|
218
|
+
const m = mcpMap.get(call.function?.name);
|
|
219
|
+
result = await mcpManager.call(m.server, m.tool, input);
|
|
220
|
+
hooks.onMCPResult?.(call.function?.name, result.output);
|
|
221
|
+
} else if (call.function?.name === 'shell') {
|
|
98
222
|
if (plan) result = { output: 'Refused: plan mode is read only. Switch to build mode with /build.' };
|
|
99
223
|
else if (isDestructive(String(input.command ?? ''))) {
|
|
100
224
|
result = { output: 'Refused: that command is destructive. Run it yourself if you are sure.' };
|
|
@@ -112,7 +236,7 @@ export async function runObjective(cfg, objective, cwd, history, hooks = {}) {
|
|
|
112
236
|
ran.push(String(input.command ?? '').slice(0, 120));
|
|
113
237
|
}
|
|
114
238
|
} else {
|
|
115
|
-
if (plan && !
|
|
239
|
+
if (plan && !tools.find(t => t.name === call.function?.name)) {
|
|
116
240
|
result = { output: 'Refused: plan mode is read only. Switch to build mode with /build.' };
|
|
117
241
|
} else if (call.function?.name === 'todo') {
|
|
118
242
|
const list = Array.isArray(input.todos) ? input.todos : [];
|
package/src/config.js
CHANGED
|
@@ -24,6 +24,7 @@ export function normalize(c) {
|
|
|
24
24
|
reasoning: c.reasoning === 'high' ? 'high' : 'low',
|
|
25
25
|
mode: c.mode === 'plan' ? 'plan' : 'build',
|
|
26
26
|
memory: c.memory !== false,
|
|
27
|
+
mcp: c.mcp !== false,
|
|
27
28
|
permEdit: c.permEdit === 'allow' ? 'allow' : 'ask',
|
|
28
29
|
permShell: c.permShell === 'allow' ? 'allow' : 'ask'
|
|
29
30
|
};
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// mcp.js: minimal MCP client. Connects MCP servers over stdio using JSON-RPC 2.0,
|
|
2
|
+
// lists their tools, and lets the agent call them like native tools.
|
|
3
|
+
// Servers are configured in ~/.ineedcodes/mcp.json: { "name": { "command": "...", "args": ["..."] } }
|
|
4
|
+
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import * as fs from 'node:fs';
|
|
7
|
+
import * as path from 'node:path';
|
|
8
|
+
import * as os from 'node:os';
|
|
9
|
+
|
|
10
|
+
export const MCP_CONFIG_FILE = process.env.INEED_MCP_CONFIG
|
|
11
|
+
|| path.join(os.homedir(), '.ineedcodes', 'mcp.json');
|
|
12
|
+
|
|
13
|
+
let nextId = 1;
|
|
14
|
+
|
|
15
|
+
class McpServer {
|
|
16
|
+
constructor(name, spec) {
|
|
17
|
+
this.name = name;
|
|
18
|
+
this.spec = spec;
|
|
19
|
+
this.child = null;
|
|
20
|
+
this.buffer = '';
|
|
21
|
+
this.pending = new Map(); // id -> resolve
|
|
22
|
+
this.tools = [];
|
|
23
|
+
this.dead = false;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
start() {
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
let settled = false;
|
|
29
|
+
let child;
|
|
30
|
+
try {
|
|
31
|
+
child = spawn(this.spec.command, this.spec.args ?? [], {
|
|
32
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
33
|
+
env: { ...process.env, NO_COLOR: '1' }
|
|
34
|
+
});
|
|
35
|
+
} catch (err) {
|
|
36
|
+
this.dead = true;
|
|
37
|
+
return reject(new Error(`cannot start MCP server ${this.name}: ${err.message}`));
|
|
38
|
+
}
|
|
39
|
+
this.child = child;
|
|
40
|
+
child.stdout.on('data', chunk => {
|
|
41
|
+
this.buffer += chunk.toString();
|
|
42
|
+
let idx;
|
|
43
|
+
while ((idx = this.buffer.indexOf('\n')) >= 0) {
|
|
44
|
+
const line = this.buffer.slice(0, idx).trim();
|
|
45
|
+
this.buffer = this.buffer.slice(idx + 1);
|
|
46
|
+
if (!line) continue;
|
|
47
|
+
let msg;
|
|
48
|
+
try { msg = JSON.parse(line); } catch { continue; }
|
|
49
|
+
if (msg.id && this.pending.has(msg.id)) {
|
|
50
|
+
const r = this.pending.get(msg.id);
|
|
51
|
+
this.pending.delete(msg.id);
|
|
52
|
+
r(msg);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
child.stderr.on('data', () => {}); // servers log freely; never leaks into the model
|
|
57
|
+
child.on('error', err => {
|
|
58
|
+
this.dead = true;
|
|
59
|
+
if (!settled) { settled = true; reject(new Error(`MCP server ${this.name}: ${err.message}`)); }
|
|
60
|
+
});
|
|
61
|
+
child.on('close', code => {
|
|
62
|
+
this.dead = true;
|
|
63
|
+
for (const r of this.pending.values()) r({ error: { message: `MCP server ${this.name} exited (code ${code})` } });
|
|
64
|
+
this.pending.clear();
|
|
65
|
+
});
|
|
66
|
+
const fail = setTimeout(() => {
|
|
67
|
+
if (!settled) { settled = true; reject(new Error(`MCP server ${this.name} did not answer initialize (10s)`)); }
|
|
68
|
+
}, 10_000);
|
|
69
|
+
this.request('initialize', {
|
|
70
|
+
protocolVersion: '2024-11-05',
|
|
71
|
+
capabilities: {},
|
|
72
|
+
clientInfo: { name: 'ineed', version: '1.1.0' }
|
|
73
|
+
}).then(init => {
|
|
74
|
+
if (init.error) throw new Error(init.error.message ?? 'initialize failed');
|
|
75
|
+
this.notify('notifications/initialized', {});
|
|
76
|
+
clearTimeout(fail);
|
|
77
|
+
settled = true;
|
|
78
|
+
resolve(this);
|
|
79
|
+
}).catch(err => {
|
|
80
|
+
clearTimeout(fail);
|
|
81
|
+
settled = true;
|
|
82
|
+
this.kill();
|
|
83
|
+
reject(err);
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
request(method, params) {
|
|
89
|
+
if (this.dead) return Promise.resolve({ error: { message: `MCP server ${this.name} is not running` } });
|
|
90
|
+
const id = nextId++;
|
|
91
|
+
return new Promise(resolve => {
|
|
92
|
+
const timer = setTimeout(() => {
|
|
93
|
+
this.pending.delete(id);
|
|
94
|
+
resolve({ error: { message: `MCP server ${this.name} timed out on ${method}` } });
|
|
95
|
+
}, 60_000);
|
|
96
|
+
this.pending.set(id, msg => { clearTimeout(timer); resolve(msg); });
|
|
97
|
+
try {
|
|
98
|
+
this.child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
|
|
99
|
+
} catch (err) {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
this.pending.delete(id);
|
|
102
|
+
resolve({ error: { message: `MCP write failed: ${err.message}` } });
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
notify(method, params) {
|
|
108
|
+
try { this.child?.stdin.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n'); } catch {}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async listTools() {
|
|
112
|
+
const res = await this.request('tools/list', {});
|
|
113
|
+
if (res.error) return [];
|
|
114
|
+
this.tools = (res.result?.tools ?? []).map(t => ({
|
|
115
|
+
name: t.name,
|
|
116
|
+
description: t.description ?? '',
|
|
117
|
+
inputSchema: t.inputSchema ?? { type: 'object', properties: {} }
|
|
118
|
+
}));
|
|
119
|
+
return this.tools;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async callTool(name, args) {
|
|
123
|
+
const res = await this.request('tools/call', { name, arguments: args ?? {} });
|
|
124
|
+
if (res.error) return { output: `Error: MCP ${this.name}/${name}: ${res.error.message}` };
|
|
125
|
+
const parts = res.result?.content ?? [];
|
|
126
|
+
const text = parts.filter(p => p.type === 'text').map(p => p.text).join('\n');
|
|
127
|
+
return { output: (res.result?.isError ? 'Error: ' : '') + (text || '(empty result)') };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
kill() {
|
|
131
|
+
this.dead = true;
|
|
132
|
+
try { this.child?.kill('SIGKILL'); } catch {}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export class McpManager {
|
|
137
|
+
constructor() {
|
|
138
|
+
this.servers = new Map();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async loadFromConfig() {
|
|
142
|
+
let cfg;
|
|
143
|
+
try { cfg = JSON.parse(fs.readFileSync(MCP_CONFIG_FILE, 'utf8')); } catch { return []; }
|
|
144
|
+
const errors = [];
|
|
145
|
+
for (const [name, spec] of Object.entries(cfg)) {
|
|
146
|
+
if (!spec?.command) { errors.push(`mcp: ${name} has no command`); continue; }
|
|
147
|
+
if (this.servers.has(name)) continue;
|
|
148
|
+
try {
|
|
149
|
+
const server = new McpServer(name, spec);
|
|
150
|
+
await server.start();
|
|
151
|
+
this.servers.set(name, server);
|
|
152
|
+
} catch (err) {
|
|
153
|
+
errors.push(err.message);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return errors;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// native-style tool descriptors, namespaced mcp_<server>_<tool>
|
|
160
|
+
async allTools() {
|
|
161
|
+
const out = [];
|
|
162
|
+
for (const [serverName, server] of this.servers) {
|
|
163
|
+
for (const t of await server.listTools()) {
|
|
164
|
+
out.push({
|
|
165
|
+
name: `mcp_${serverName}_${t.name}`.slice(0, 64).replace(/[^a-zA-Z0-9_]/g, '_'),
|
|
166
|
+
description: `[MCP ${serverName}] ${t.description}`.trim(),
|
|
167
|
+
parameters: jsonSchemaToParameters(t.inputSchema),
|
|
168
|
+
mcp: { server: serverName, tool: t.name },
|
|
169
|
+
allowedInPlan: false
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
hasTools() {
|
|
177
|
+
for (const s of this.servers.values()) if (!s.dead && s.tools.length) return true;
|
|
178
|
+
return this.servers.size > 0;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async call(serverName, toolName, args) {
|
|
182
|
+
const server = this.servers.get(serverName);
|
|
183
|
+
if (!server) return { output: `Error: unknown MCP server ${serverName}` };
|
|
184
|
+
if (server.dead) return { output: `Error: MCP server ${serverName} is not running` };
|
|
185
|
+
return server.callTool(toolName, args);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
killAll() {
|
|
189
|
+
for (const s of this.servers.values()) s.kill();
|
|
190
|
+
this.servers.clear();
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function jsonSchemaToParameters(schema) {
|
|
195
|
+
// OpenAI function parameters are JSON Schema; pass through with light sanitation
|
|
196
|
+
const s = schema && typeof schema === 'object' ? schema : { type: 'object' };
|
|
197
|
+
if (s.type !== 'object') return { type: 'object', properties: {} };
|
|
198
|
+
return { type: 'object', properties: s.properties ?? {}, required: s.required ?? [] };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function mcpConfigured() {
|
|
202
|
+
try { return Object.keys(JSON.parse(fs.readFileSync(MCP_CONFIG_FILE, 'utf8'))).length > 0; } catch { return false; }
|
|
203
|
+
}
|
package/src/session.js
CHANGED
|
@@ -8,6 +8,7 @@ import { fetchModels } from './provider.js';
|
|
|
8
8
|
import { makeInput, bold, dim, red, green, yellow, cyan, gray, trunc, BANNER, logo, box, startSpinner, VERSION, RULE, userBubble, screen } from './ui.js';
|
|
9
9
|
import { wizard } from './wizard.js';
|
|
10
10
|
import { getMemoryProvider, ICMAdapter } from './memory.js';
|
|
11
|
+
import { mcpConfigured } from './mcp.js';
|
|
11
12
|
|
|
12
13
|
const plain = s => String(s).replace(/\x1b\[[0-9;]*m/g, '');
|
|
13
14
|
|
|
@@ -99,6 +100,10 @@ export async function startSession(cfg, { fresh = false } = {}) {
|
|
|
99
100
|
const mark = s => s === 'completed' ? green('✔') : s === 'in_progress' ? cyan('▸') : dim('○');
|
|
100
101
|
say(box([bold('To-do'), ...list.map(t => ' ' + mark(t.status) + ' ' + t.content)]));
|
|
101
102
|
},
|
|
103
|
+
onAgentStart: (id, input) => { stopSpinner(); say(cyan(' ◆ spawn ' + id) + gray(` role=${input.role ?? '?'} task=${trunc(String(input.objective ?? ''), 70)}`)); },
|
|
104
|
+
onAgentEnd: (id, r) => { stopSpinner(); say((r.status === 'completed' ? green(' ◆ ' + id + ' done') : yellow(' ◆ ' + id + ' ' + r.status)) + gray(' ' + trunc(String(r.summary ?? '').replaceAll('\n', ' '), 90))); },
|
|
105
|
+
onMCP: names => { if (names.length) say(dim(' MCP tools available: ' + names.join(', '))); },
|
|
106
|
+
onMCPResult: (name, out) => { say(gray(' mcp result: ' + trunc(out, 100))); },
|
|
102
107
|
onApprove: async (cat, name, input2) => {
|
|
103
108
|
stopSpinner();
|
|
104
109
|
say(yellow(' ⚠ approval needed') + ' ' + cyan(name) + gray(' ' + trunc(JSON.stringify(input2), 80)));
|
|
@@ -156,6 +161,7 @@ export async function startSession(cfg, { fresh = false } = {}) {
|
|
|
156
161
|
say(' ' + cyan('/perm') + ' permissions: /perm auto | /perm safe | /perm');
|
|
157
162
|
say(' ' + cyan('/config') + ' show provider config (key hidden)');
|
|
158
163
|
say(' ' + cyan('/memory') + ' memory status, /memory on|off to toggle');
|
|
164
|
+
say(' ' + cyan('/mcp') + ' list MCP servers and their tools');
|
|
159
165
|
say(' ' + cyan('/clear') + ' forget this conversation');
|
|
160
166
|
say(' ' + cyan('/setup') + ' redo provider setup');
|
|
161
167
|
say(' ' + cyan('/reset') + ' clear saved config');
|
|
@@ -241,6 +247,29 @@ export async function startSession(cfg, { fresh = false } = {}) {
|
|
|
241
247
|
busy = false;
|
|
242
248
|
return afterTask();
|
|
243
249
|
}
|
|
250
|
+
if (input === '/mcp' || input === '/mcp reload') {
|
|
251
|
+
if (!mcpConfigured()) {
|
|
252
|
+
say(yellow('No MCP servers configured.') + dim(' Add them to ~/.ineedcodes/mcp.json, e.g.: {"context7":{"command":"npx","args":["-y","@upstash/context7-mcp"]}}'));
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
busy = true;
|
|
256
|
+
try {
|
|
257
|
+
const { McpManager } = await import('./mcp.js');
|
|
258
|
+
const mgr = new McpManager();
|
|
259
|
+
const errors = await mgr.loadFromConfig();
|
|
260
|
+
for (const e of errors) say(red(' ✗ ' + e));
|
|
261
|
+
const tools = await mgr.allTools();
|
|
262
|
+
if (tools.length) {
|
|
263
|
+
say(green(` ${mgr.servers.size} MCP server(s), ${tools.length} tool(s):`));
|
|
264
|
+
for (const t of tools) say(' ' + cyan(t.name) + gray(' ' + trunc(t.description, 90)));
|
|
265
|
+
} else if (!errors.length) {
|
|
266
|
+
say(yellow(' Servers connected but exposed no tools.'));
|
|
267
|
+
}
|
|
268
|
+
mgr.killAll();
|
|
269
|
+
} catch (err) { say(red(' ✗ ' + err.message)); }
|
|
270
|
+
busy = false;
|
|
271
|
+
return afterTask();
|
|
272
|
+
}
|
|
244
273
|
if (input === '/setup' || input === '/reset') {
|
|
245
274
|
clearConfig();
|
|
246
275
|
say(dim('Config cleared. Running setup...'));
|
package/src/ui.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// ui.js: terminal helpers. No dependencies, respects NO_COLOR and non-TTY.
|
|
2
2
|
|
|
3
|
-
export const VERSION = '1.0
|
|
3
|
+
export const VERSION = '1.1.0';
|
|
4
4
|
|
|
5
5
|
const USE_COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
6
6
|
const wrap = (code, t) => USE_COLOR ? `\x1b[${code}m${t}\x1b[0m` : String(t);
|