@ywldan/kiro 0.4.0 → 0.5.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.
@@ -1,5 +1,5 @@
1
1
  import { ProviderError } from '../providers/types.js';
2
- import { executeTool, isReadOnlyTool, toolDefinitions, } from '../tools/index.js';
2
+ import { allToolDefinitions, executeTool, isReadOnlyTool, } from '../tools/index.js';
3
3
  export const MAX_TOOL_ROUNDS = 25;
4
4
  /** Groups contiguous read-only calls so they can run in parallel; mutations stay sequential. */
5
5
  export function planToolBatches(calls) {
@@ -32,6 +32,24 @@ function cancelledResult() {
32
32
  * Runs one user turn, appending assistant/tool messages to `messages` as it goes.
33
33
  * The messages array must already contain the system prompt and the new user message.
34
34
  */
35
+ /**
36
+ * Bridges a tool's live output callback to the async generator. Events queue up
37
+ * between awaits, and the generator drains them right before `tool-end`, so a
38
+ * chatty command cannot reorder or outrun the result.
39
+ */
40
+ function liveOutput(ctx) {
41
+ const pending = [];
42
+ return {
43
+ ctx: {
44
+ ...ctx,
45
+ onOutput: (update) => {
46
+ // Keep only the newest line; a build log does not need a backlog.
47
+ pending.length > 0 ? (pending[0] = update.tail) : pending.push(update.tail);
48
+ },
49
+ },
50
+ drain: () => pending.splice(0, pending.length),
51
+ };
52
+ }
35
53
  export async function* runAgentTurn(options) {
36
54
  const { provider, messages, ctx } = options;
37
55
  const maxRounds = options.maxToolRounds ?? MAX_TOOL_ROUNDS;
@@ -77,7 +95,7 @@ export async function* runAgentTurn(options) {
77
95
  let streamError;
78
96
  let finishReason;
79
97
  try {
80
- for await (const event of provider.stream(messages, toolDefinitions, { signal: ctx.signal })) {
98
+ for await (const event of provider.stream(messages, allToolDefinitions(), { signal: ctx.signal })) {
81
99
  if (ctx.signal.aborted)
82
100
  break;
83
101
  if (event.type === 'text') {
@@ -206,7 +224,8 @@ export async function* runAgentTurn(options) {
206
224
  for (const toolCall of batch.calls) {
207
225
  yield { type: 'tool-start', toolCall };
208
226
  const startedAt = Date.now();
209
- const result = await executeTool(toolCall.function.name, toolCall.function.arguments, ctx);
227
+ const live = liveOutput(ctx);
228
+ const result = await executeTool(toolCall.function.name, toolCall.function.arguments, live.ctx);
210
229
  const durationMs = Date.now() - startedAt;
211
230
  messages.push({
212
231
  role: 'tool',
@@ -214,6 +233,9 @@ export async function* runAgentTurn(options) {
214
233
  name: toolCall.function.name,
215
234
  content: result.content,
216
235
  });
236
+ for (const tail of live.drain()) {
237
+ yield { type: 'tool-output', toolCall, tail };
238
+ }
217
239
  yield { type: 'tool-end', toolCall, result, durationMs };
218
240
  }
219
241
  continue;
@@ -2,6 +2,7 @@ import { readFile } from 'node:fs/promises';
2
2
  import { platform, release } from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { formatSkillIndex, loadSkills } from './skills.js';
5
+ import { mcpPromptSection } from '../mcp/prompt.js';
5
6
  const MAX_AGENTS_MD_BYTES = 200_000;
6
7
  function osName() {
7
8
  switch (platform()) {
@@ -55,7 +56,8 @@ export async function buildSystemPrompt(cwd) {
55
56
  'You have these tools: read_file, write_file, edit_file, multi_edit, apply_patch, list_dir, glob, grep, run_command, ask_user.',
56
57
  ].join('\n');
57
58
  const [agents, inventory] = await Promise.all([readAgentsSection(cwd), loadSkills(cwd)]);
58
- const sections = [base, agents, formatSkillIndex(inventory.skills)].filter(Boolean);
59
+ const mcp = mcpPromptSection();
60
+ const sections = [base, agents, formatSkillIndex(inventory.skills), mcp].filter(Boolean);
59
61
  return sections.length === 1 ? base : `${sections.join('\n\n')}\n`;
60
62
  }
61
63
  //# sourceMappingURL=prompt.js.map
package/dist/config.js CHANGED
@@ -111,6 +111,83 @@ function validateModels(name, raw, model) {
111
111
  }
112
112
  return models;
113
113
  }
114
+ const MAX_HEADERS = 24;
115
+ const HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
116
+ /** Names that would break the request or duplicate the key; both go through other fields. */
117
+ const RESERVED_HEADERS = new Set([
118
+ 'content-type',
119
+ 'content-length',
120
+ 'accept',
121
+ 'authorization',
122
+ 'host',
123
+ 'connection',
124
+ 'transfer-encoding',
125
+ ]);
126
+ /**
127
+ * Parses one `Name: value` line, the form both the wizard and `kiro model add
128
+ * --header` accept. Values may use `${VAR}` to read the environment.
129
+ */
130
+ export function parseHeaderEntry(text) {
131
+ const trimmed = text.trim();
132
+ const colon = trimmed.indexOf(':');
133
+ if (colon <= 0) {
134
+ throw new ConfigError('Write a header as "Name: value", for example "api-key: ${AZURE_KEY}".');
135
+ }
136
+ const name = trimmed.slice(0, colon).trim();
137
+ const value = trimmed.slice(colon + 1).trim();
138
+ if (!HEADER_NAME_PATTERN.test(name)) {
139
+ throw new ConfigError(`"${name}" is not a valid header name.`);
140
+ }
141
+ if (!value)
142
+ throw new ConfigError(`Header "${name}" needs a value.`);
143
+ if (/[\r\n]/.test(value))
144
+ throw new ConfigError(`Header "${name}" must stay on one line.`);
145
+ if (RESERVED_HEADERS.has(name.toLowerCase())) {
146
+ throw new ConfigError(`Header "${name}" is set by Kiro. Use "apiKeyEnv" for the key; the other headers are managed automatically.`);
147
+ }
148
+ return { name, value };
149
+ }
150
+ export function validateHeaders(profileName, raw) {
151
+ if (raw === undefined)
152
+ return undefined;
153
+ if (!isRecord(raw)) {
154
+ throw new ConfigError(`Profile "${profileName}": "headers" must be an object of string values.`);
155
+ }
156
+ const entries = Object.entries(raw);
157
+ if (entries.length > MAX_HEADERS) {
158
+ throw new ConfigError(`Profile "${profileName}": "headers" may hold at most ${MAX_HEADERS} entries.`);
159
+ }
160
+ const headers = {};
161
+ for (const [name, value] of entries) {
162
+ if (!HEADER_NAME_PATTERN.test(name)) {
163
+ throw new ConfigError(`Profile "${profileName}": "${name}" is not a valid header name.`);
164
+ }
165
+ if (typeof value !== 'string' || value.includes('\n') || value.includes('\r')) {
166
+ throw new ConfigError(`Profile "${profileName}": header "${name}" must be a single-line string.`);
167
+ }
168
+ if (RESERVED_HEADERS.has(name.toLowerCase())) {
169
+ throw new ConfigError(`Profile "${profileName}": header "${name}" is set by Kiro. ` +
170
+ 'Use "apiKeyEnv" for the key; the other headers are managed automatically.');
171
+ }
172
+ headers[name] = value;
173
+ }
174
+ return Object.keys(headers).length > 0 ? headers : undefined;
175
+ }
176
+ function validatePricing(profileName, raw) {
177
+ if (raw === undefined)
178
+ return undefined;
179
+ if (!isRecord(raw)) {
180
+ throw new ConfigError(`Profile "${profileName}": "pricing" must be an object.`);
181
+ }
182
+ const read = (key) => {
183
+ const value = raw[key];
184
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
185
+ throw new ConfigError(`Profile "${profileName}": "pricing.${key}" must be a non-negative number (dollars per million tokens).`);
186
+ }
187
+ return value;
188
+ };
189
+ return { input: read('input'), output: read('output') };
190
+ }
114
191
  function validateProfile(name, raw) {
115
192
  if (!isRecord(raw)) {
116
193
  throw new ConfigError(`Profile "${name}" must be an object.`);
@@ -153,6 +230,8 @@ function validateProfile(name, raw) {
153
230
  temperature: raw.temperature,
154
231
  maxTokens: raw.maxTokens,
155
232
  contextWindow: raw.contextWindow,
233
+ headers: validateHeaders(name, raw.headers),
234
+ pricing: validatePricing(name, raw.pricing),
156
235
  };
157
236
  }
158
237
  export function validateConfig(raw) {
@@ -300,6 +379,14 @@ export async function saveConfig(config, options = {}) {
300
379
  merged.models = profile.models;
301
380
  else
302
381
  delete merged.models;
382
+ if (profile.headers !== undefined)
383
+ merged.headers = profile.headers;
384
+ else
385
+ delete merged.headers;
386
+ if (profile.pricing !== undefined)
387
+ merged.pricing = profile.pricing;
388
+ else
389
+ delete merged.pricing;
303
390
  profiles[name] = merged;
304
391
  }
305
392
  output.activeProfile = normalized.activeProfile;
package/dist/cost.js ADDED
@@ -0,0 +1,87 @@
1
+ /** Matched in order; the first pattern found anywhere in the model id wins. */
2
+ const PRICES = [
3
+ // OpenAI
4
+ { pattern: /^gpt-5(\.|-|$)/i, price: { input: 1.25, output: 10 } },
5
+ { pattern: /^o4-mini/i, price: { input: 1.1, output: 4.4 } },
6
+ { pattern: /^o3-mini/i, price: { input: 1.1, output: 4.4 } },
7
+ { pattern: /^o3(\.|-|$)/i, price: { input: 2, output: 8 } },
8
+ { pattern: /^o1-mini/i, price: { input: 1.1, output: 4.4 } },
9
+ { pattern: /^o1(\.|-|$)/i, price: { input: 15, output: 60 } },
10
+ { pattern: /^gpt-4\.1-mini/i, price: { input: 0.4, output: 1.6 } },
11
+ { pattern: /^gpt-4\.1-nano/i, price: { input: 0.1, output: 0.4 } },
12
+ { pattern: /^gpt-4\.1/i, price: { input: 2, output: 8 } },
13
+ { pattern: /^gpt-4o-mini/i, price: { input: 0.15, output: 0.6 } },
14
+ { pattern: /^gpt-4o/i, price: { input: 2.5, output: 10 } },
15
+ { pattern: /^gpt-4-turbo/i, price: { input: 10, output: 30 } },
16
+ // Anthropic, as sold through OpenRouter and gateways
17
+ { pattern: /claude-(3[.-]5|3\.7|4)-?sonnet/i, price: { input: 3, output: 15 } },
18
+ { pattern: /claude-.*haiku/i, price: { input: 0.8, output: 4 } },
19
+ { pattern: /claude-.*opus/i, price: { input: 15, output: 75 } },
20
+ // Google
21
+ { pattern: /gemini-2\.5-pro/i, price: { input: 1.25, output: 10 } },
22
+ { pattern: /gemini-2\.5-flash/i, price: { input: 0.3, output: 2.5 } },
23
+ { pattern: /gemini-2\.0-flash/i, price: { input: 0.1, output: 0.4 } },
24
+ // DeepSeek and Groq
25
+ { pattern: /deepseek-(v3|chat|reasoner)/i, price: { input: 0.27, output: 1.1 } },
26
+ { pattern: /^qwen|^llama|^mixtral|^mistral/i, price: { input: 0.2, output: 0.6 } },
27
+ ];
28
+ /** Local servers are free, so a localhost base URL reports zero instead of a guess. */
29
+ function isLocalBaseUrl(baseUrl) {
30
+ try {
31
+ const host = new URL(baseUrl).hostname.toLowerCase();
32
+ return (host === 'localhost' ||
33
+ host === '127.0.0.1' ||
34
+ host === '::1' ||
35
+ host === '0.0.0.0' ||
36
+ host.endsWith('.local') ||
37
+ /^10\./.test(host) ||
38
+ /^192\.168\./.test(host) ||
39
+ /^172\.(1[6-9]|2\d|3[01])\./.test(host));
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ export function priceFor(model, baseUrl) {
46
+ if (baseUrl && isLocalBaseUrl(baseUrl))
47
+ return { input: 0, output: 0 };
48
+ const id = model.split('/').pop() ?? model;
49
+ for (const entry of PRICES) {
50
+ if (entry.pattern.test(id))
51
+ return entry.price;
52
+ }
53
+ return null;
54
+ }
55
+ /** Cost of one request, in dollars. */
56
+ export function costOf(usage, price) {
57
+ return (usage.promptTokens / 1_000_000) * price.input + (usage.completionTokens / 1_000_000) * price.output;
58
+ }
59
+ /**
60
+ * Cost of one usage report, added to the running total. The caller tracks
61
+ * whether any earlier request was unpriced, so the card can show a `~`.
62
+ */
63
+ export function addCost(current, usage, price) {
64
+ if (!price)
65
+ return { dollars: current.dollars, complete: false };
66
+ return { dollars: current.dollars + costOf(usage, price), complete: current.complete };
67
+ }
68
+ /** Cost of a whole session at one price; used when a session is resumed. */
69
+ export function sessionCost(totals, price) {
70
+ if (totals.requests === 0)
71
+ return { dollars: 0, complete: true };
72
+ if (!price)
73
+ return { dollars: 0, complete: false };
74
+ return { dollars: costOf(totals, price), complete: true };
75
+ }
76
+ const SMALL = 0.01;
77
+ /** `$0.0042`, `$0.42`, `$1.20`: two decimals once cents matter, three below a cent. */
78
+ export function formatCost(dollars) {
79
+ if (!Number.isFinite(dollars) || dollars <= 0)
80
+ return '$0';
81
+ if (dollars < SMALL)
82
+ return `$${dollars.toFixed(4)}`;
83
+ if (dollars < 1)
84
+ return `$${dollars.toFixed(3)}`;
85
+ return `$${dollars.toFixed(2)}`;
86
+ }
87
+ //# sourceMappingURL=cost.js.map
package/dist/doctor.js CHANGED
@@ -6,19 +6,19 @@ import { discoverModels, testConnection } from './model/discovery.js';
6
6
  import { redactSecrets, registerSecretEnv } from './secrets.js';
7
7
  import { formatDuration } from './ui/text.js';
8
8
  import { VERSION } from './version.js';
9
- const DOCTOR_HELP = `Kiro doctor
10
-
11
- Usage:
12
- kiro doctor [options]
13
-
14
- Checks the Node version, config file, where the key is stored, and the active
15
- endpoint. Prints one line per check and exits 1 when a check fails.
16
-
17
- Options:
18
- --profile <name> inspect a profile other than the active one
19
- --offline skip the network checks
20
- --test send a small chat completion to verify the key and model
21
- -h, --help show this help
9
+ const DOCTOR_HELP = `Kiro doctor
10
+
11
+ Usage:
12
+ kiro doctor [options]
13
+
14
+ Checks the Node version, config file, where the key is stored, and the active
15
+ endpoint. Prints one line per check and exits 1 when a check fails.
16
+
17
+ Options:
18
+ --profile <name> inspect a profile other than the active one
19
+ --offline skip the network checks
20
+ --test send a small chat completion to verify the key and model
21
+ -h, --help show this help
22
22
  `;
23
23
  class DoctorUsageError extends Error {
24
24
  }
@@ -167,6 +167,7 @@ async function networkChecks(profile, apiKey, test) {
167
167
  const result = await discoverModels({
168
168
  baseUrl: profile.baseUrl,
169
169
  apiKey,
170
+ headers: profile.headers,
170
171
  timeoutMs: 5000,
171
172
  });
172
173
  const latency = formatDuration(Math.max(0, Math.round(performance.now() - started)));
package/dist/headless.js CHANGED
@@ -6,6 +6,8 @@ import { estimateMessagesTokens } from './agent/tokens.js';
6
6
  import { createProvider } from './providers/index.js';
7
7
  import { dropIncompleteToolCalls, latestSession, loadSession, newSessionId, saveSession, titleFromMessages, } from './sessions.js';
8
8
  import { redactSecrets } from './secrets.js';
9
+ import { evaluateRules, loadRules } from './permissions.js';
10
+ import { costOf, formatCost, priceFor } from './cost.js';
9
11
  import { addUsage, normalizeUsage } from './usage.js';
10
12
  /**
11
13
  * One-shot agent run without a TUI: `kiro -p "fix the tests"`.
@@ -59,16 +61,26 @@ export async function runHeadless(options) {
59
61
  return 1;
60
62
  }
61
63
  const warnedTools = new Set();
64
+ // Saved rules let CI approve a narrow pattern (say "npm test*") without --yolo.
65
+ const rules = yolo ? [] : (await loadRules(cwd)).rules;
62
66
  const ctx = {
63
67
  cwd,
64
68
  signal: options.signal,
65
69
  approve: yolo
66
70
  ? () => Promise.resolve('allow')
67
71
  : (request) => {
68
- if (!warnedTools.has(request.tool)) {
69
- warnedTools.add(request.tool);
70
- stderr.write(`# ${request.tool} denied: headless runs never approve tool calls. ` +
71
- `Run Kiro interactively, or pass --yolo to allow every tool.\n`);
72
+ const verdict = request.insideWorkspace === false
73
+ ? 'ask'
74
+ : evaluateRules(rules, { tool: request.tool, subject: request.subject });
75
+ if (verdict === 'allow')
76
+ return Promise.resolve('allow');
77
+ const key = verdict === 'deny' ? `${request.tool}:deny` : request.tool;
78
+ if (!warnedTools.has(key)) {
79
+ warnedTools.add(key);
80
+ stderr.write(verdict === 'deny'
81
+ ? `# ${request.tool} denied: a saved rule in .kiro/permissions.json refuses it.\n`
82
+ : `# ${request.tool} denied: headless runs never approve tool calls. ` +
83
+ 'Run Kiro interactively, or pass --yolo to allow every tool.\n');
72
84
  }
73
85
  return Promise.resolve('deny');
74
86
  },
@@ -182,6 +194,11 @@ export async function runHeadless(options) {
182
194
  // Keep shell prompts and piped files tidy without altering the model's text.
183
195
  if (lastTextChar && lastTextChar !== '\n')
184
196
  writeOut('\n');
197
+ const price = profile.pricing ?? priceFor(profile.model, profile.baseUrl);
198
+ if (price && usage.requests > 0) {
199
+ stderr.write(`# usage: ${usage.promptTokens} sent, ${usage.completionTokens} received, ` +
200
+ `~${formatCost(costOf(usage, price))}\n`);
201
+ }
185
202
  const cleaned = dropIncompleteToolCalls(working.filter((message) => message.role !== 'system'));
186
203
  if (cleaned.length > 0) {
187
204
  await saveSession({
package/dist/index.js CHANGED
@@ -14,50 +14,53 @@ import { App } from './ui/App.js';
14
14
  import { runCheck, runUpdate } from './update.js';
15
15
  import { runDoctor } from './doctor.js';
16
16
  import { VERSION } from './version.js';
17
- const HELP = `Kiro: a small terminal coding agent
18
-
19
- Usage: kiro [options]
20
- kiro model [command]
21
- kiro doctor [options]
22
-
23
- Options:
24
- --profile <name> Use a profile from ~/.kiro/config.json
25
- --base-url <url> Override the active profile's OpenAI-compatible base URL
26
- --model <name> Override the active profile's model name
27
- -c, --continue Resume the most recent session for this directory
28
- --resume <id> Resume a specific saved session
29
- -p, --prompt <text>
30
- Run one turn without a TUI ("-" or no text reads the
31
- prompt from stdin); replies stream to stdout, notices
32
- and reasoning to stderr
33
- --yolo Skip all approval prompts (use with care)
34
- --mouse Mouse reporting is on by default: the wheel scrolls the
35
- transcript, Shift+drag selects text for copying.
36
- --no-mouse Disable mouse reporting so plain click-drag selection works.
37
- --no-alt-screen Do not switch to the terminal's alternate screen
38
- --no-skills Do not load skills from .kiro/skills, .claude/skills, or
39
- ~/.kiro/skills (KIRO_NO_SKILLS=1 does the same)
40
- -h, --help Show this help
41
- -v, --version Show the version
42
-
43
- Model commands:
44
- kiro model Interactive wizard: select, add, edit, or remove models
45
- kiro model list List configured profiles
46
- kiro model add ... Add a profile without prompts (see "kiro model --help")
47
- kiro model use <n> Make a profile active
48
- kiro model remove <n>
49
- kiro model test [n]
50
-
51
- Update commands:
52
- kiro check Compare the installed version with the latest on npm
53
- kiro update Install the latest version from npm globally
54
-
55
- Diagnostics:
56
- kiro doctor Check Node, config, key storage, and the active endpoint
57
-
58
- Config: ~/.kiro/config.json (created with a template on first run)
59
- Keys: ~/.kiro/.env (mode 0600), or the environment variable named by "apiKeyEnv".
60
- Sessions: ~/.kiro/sessions (one directory per working directory)
17
+ import { setExtraTools } from './tools/index.js';
18
+ import { setupMcp } from './mcp/registry.js';
19
+ const HELP = `Kiro: a small terminal coding agent
20
+
21
+ Usage: kiro [options]
22
+ kiro model [command]
23
+ kiro doctor [options]
24
+
25
+ Options:
26
+ --profile <name> Use a profile from ~/.kiro/config.json
27
+ --base-url <url> Override the active profile's OpenAI-compatible base URL
28
+ --model <name> Override the active profile's model name
29
+ -c, --continue Resume the most recent session for this directory
30
+ --resume <id> Resume a specific saved session
31
+ -p, --prompt <text>
32
+ Run one turn without a TUI ("-" or no text reads the
33
+ prompt from stdin); replies stream to stdout, notices
34
+ and reasoning to stderr
35
+ --yolo Skip all approval prompts (use with care)
36
+ --mouse Mouse reporting is on by default: the wheel scrolls the
37
+ transcript, Shift+drag selects text for copying.
38
+ --no-mouse Disable mouse reporting so plain click-drag selection works.
39
+ --no-alt-screen Do not switch to the terminal's alternate screen
40
+ --no-skills Do not load skills from .kiro/skills, .claude/skills, or
41
+ ~/.kiro/skills (KIRO_NO_SKILLS=1 does the same)
42
+ --no-mcp Do not start MCP servers from .kiro/mcp.json
43
+ -h, --help Show this help
44
+ -v, --version Show the version
45
+
46
+ Model commands:
47
+ kiro model Interactive wizard: select, add, edit, or remove models
48
+ kiro model list List configured profiles
49
+ kiro model add ... Add a profile without prompts (see "kiro model --help")
50
+ kiro model use <n> Make a profile active
51
+ kiro model remove <n>
52
+ kiro model test [n]
53
+
54
+ Update commands:
55
+ kiro check Compare the installed version with the latest on npm
56
+ kiro update Install the latest version from npm globally
57
+
58
+ Diagnostics:
59
+ kiro doctor Check Node, config, key storage, and the active endpoint
60
+
61
+ Config: ~/.kiro/config.json (created with a template on first run)
62
+ Keys: ~/.kiro/.env (mode 0600), or the environment variable named by "apiKeyEnv".
63
+ Sessions: ~/.kiro/sessions (one directory per working directory)
61
64
  `;
62
65
  const ENTER_ALT_SCREEN = '\x1b[?1049h\x1b[H\x1b[2J';
63
66
  const LEAVE_ALT_SCREEN = '\x1b[?1049l';
@@ -92,6 +95,7 @@ function parseArgs(argv) {
92
95
  const options = {
93
96
  continueSession: false,
94
97
  yolo: false,
98
+ mcp: true,
95
99
  mouse: true,
96
100
  altScreen: true,
97
101
  skills: true,
@@ -132,6 +136,10 @@ function parseArgs(argv) {
132
136
  options.skills = false;
133
137
  continue;
134
138
  }
139
+ if (arg === '--no-mcp') {
140
+ options.mcp = false;
141
+ continue;
142
+ }
135
143
  const equals = arg.indexOf('=');
136
144
  const flag = equals === -1 ? arg : arg.slice(0, equals);
137
145
  if (flag === '--profile' ||
@@ -265,6 +273,32 @@ async function main() {
265
273
  registerSecretEnv(profile.apiKeyEnv, process.env[profile.apiKeyEnv], true);
266
274
  }
267
275
  }
276
+ /** MCP servers start before the UI so their tools are in the first request. */
277
+ const startupNotices = [];
278
+ const mcpEnabled = options.mcp && process.env.KIRO_NO_MCP !== '1';
279
+ const startupMcp = mcpEnabled
280
+ ? await setupMcp(process.cwd(), {
281
+ onNotice: (message) => startupNotices.push({ level: 'muted', text: message }),
282
+ })
283
+ : null;
284
+ if (startupMcp) {
285
+ setExtraTools(startupMcp.tools);
286
+ const ready = startupMcp.statuses.filter((status) => status.state === 'ready');
287
+ if (ready.length > 0) {
288
+ startupNotices.push({
289
+ level: 'info',
290
+ text: `MCP: ${ready.length} server${ready.length === 1 ? '' : 's'} ready (${ready
291
+ .map((status) => `${status.name}: ${status.tools} tool${status.tools === 1 ? '' : 's'}`)
292
+ .join(', ')}). /mcp for details.`,
293
+ });
294
+ }
295
+ for (const status of startupMcp.statuses.filter((entry) => entry.state === 'error')) {
296
+ startupNotices.push({
297
+ level: 'error',
298
+ text: `MCP server "${status.name}" did not start: ${status.detail ?? 'unknown error'}`,
299
+ });
300
+ }
301
+ }
268
302
  if (headless) {
269
303
  if (options.resume && options.continueSession) {
270
304
  console.error('Kiro: both --resume and --continue were given with -p; --resume wins.');
@@ -286,11 +320,11 @@ async function main() {
286
320
  }
287
321
  finally {
288
322
  process.off('SIGINT', onInterrupt);
323
+ // Servers are started for this run; a headless exit must not leave them alive.
324
+ await startupMcp?.close();
289
325
  }
290
326
  return;
291
327
  }
292
- let initialSession = null;
293
- const startupNotices = [];
294
328
  if (options.resume && options.continueSession) {
295
329
  startupNotices.push({
296
330
  level: 'info',
@@ -303,6 +337,7 @@ async function main() {
303
337
  text: `The previous config was unreadable and was backed up to ${backup}; a fresh template is now in use.`,
304
338
  });
305
339
  }
340
+ let initialSession = null;
306
341
  if (options.resume) {
307
342
  try {
308
343
  initialSession = await loadSession(process.cwd(), options.resume);
@@ -332,11 +367,13 @@ async function main() {
332
367
  }
333
368
  const leaveScreen = enterAlternateScreen(options.altScreen);
334
369
  try {
335
- const instance = render(_jsx(App, { config: config, baseConfig: baseConfig, overrides: overrides, configPath: loaded.path, configCreated: loaded.created, cwd: process.cwd(), version: VERSION, yolo: options.yolo, mouseEnabled: options.mouse, initialSession: initialSession, startupNotices: startupNotices }), { exitOnCtrlC: false, maxFps: 30 });
370
+ const instance = render(_jsx(App, { config: config, baseConfig: baseConfig, overrides: overrides, configPath: loaded.path, configCreated: loaded.created, cwd: process.cwd(), version: VERSION, yolo: options.yolo, mouseEnabled: options.mouse, initialSession: initialSession, startupNotices: startupNotices, mcp: startupMcp }), { exitOnCtrlC: false, maxFps: 30 });
336
371
  await instance.waitUntilExit();
337
372
  }
338
373
  finally {
339
374
  leaveScreen();
375
+ // Server processes must not outlive the session.
376
+ await startupMcp?.close();
340
377
  }
341
378
  process.exit(0);
342
379
  }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * MCP handshake and the pieces Kiro uses: initialize, list tools, call a tool.
3
+ *
4
+ * The transport is chosen in `sdk.ts`: the official SDK when its optional
5
+ * package is installed, otherwise a built-in stdio client that speaks the same
6
+ * JSON-RPC subset. Both produce the same `McpEndpoint` shape, so the tool
7
+ * registry never has to know which one is running.
8
+ */
9
+ export const MCP_PROTOCOL_VERSION = '2025-06-18';
10
+ export const MCP_CLIENT_NAME = 'kiro';
11
+ export const MCP_CLIENT_VERSION = '0.4.0';
12
+ /**
13
+ * Flattens MCP content blocks into text. JSON blocks are pretty-printed so a
14
+ * returned object stays readable, and binary blocks say what they were rather
15
+ * than dumping base64 into the context window.
16
+ */
17
+ export function flattenContent(content) {
18
+ if (!Array.isArray(content)) {
19
+ return typeof content === 'string' ? content : '';
20
+ }
21
+ const parts = [];
22
+ for (const block of content) {
23
+ if (typeof block === 'string') {
24
+ parts.push(block);
25
+ continue;
26
+ }
27
+ if (typeof block !== 'object' || block === null)
28
+ continue;
29
+ const entry = block;
30
+ const type = typeof entry.type === 'string' ? entry.type : 'unknown';
31
+ if (type === 'text' && typeof entry.text === 'string') {
32
+ parts.push(entry.text);
33
+ }
34
+ else if (type === 'resource' && typeof entry.resource === 'object' && entry.resource !== null) {
35
+ const resource = entry.resource;
36
+ const text = typeof resource.text === 'string' ? resource.text : '';
37
+ const uri = typeof resource.uri === 'string' ? resource.uri : 'resource';
38
+ parts.push(text ? `${uri}\n${text}` : `${uri} (no text content)`);
39
+ }
40
+ else if (type === 'image') {
41
+ parts.push('[image content omitted: Kiro cannot display images]');
42
+ }
43
+ else if (type === 'audio') {
44
+ parts.push('[audio content omitted]');
45
+ }
46
+ else {
47
+ parts.push(JSON.stringify(entry));
48
+ }
49
+ }
50
+ return parts.join('\n').trim();
51
+ }
52
+ /** Validates and normalizes a tool list; a server may omit fields. */
53
+ export function readToolList(result) {
54
+ if (typeof result !== 'object' || result === null)
55
+ return [];
56
+ const tools = result.tools;
57
+ if (!Array.isArray(tools))
58
+ return [];
59
+ const out = [];
60
+ for (const raw of tools) {
61
+ if (typeof raw !== 'object' || raw === null)
62
+ continue;
63
+ const tool = raw;
64
+ const name = typeof tool.name === 'string' ? tool.name.trim() : '';
65
+ if (!name)
66
+ continue;
67
+ const schema = typeof tool.inputSchema === 'object' && tool.inputSchema !== null
68
+ ? tool.inputSchema
69
+ : { type: 'object', properties: {} };
70
+ const annotations = typeof tool.annotations === 'object' && tool.annotations !== null
71
+ ? tool.annotations
72
+ : undefined;
73
+ out.push({
74
+ name,
75
+ description: typeof tool.description === 'string' ? tool.description : '',
76
+ inputSchema: schema,
77
+ annotations,
78
+ });
79
+ }
80
+ return out;
81
+ }
82
+ /** Builds an endpoint from an already-initialized connection. */
83
+ export function endpointFrom(serverName, transport, serverInfo, call, close) {
84
+ return {
85
+ serverName,
86
+ transport,
87
+ serverInfo,
88
+ async listTools() {
89
+ const result = await call('tools/list', {});
90
+ return readToolList(result);
91
+ },
92
+ async callTool(name, args, signal) {
93
+ if (signal?.aborted)
94
+ throw new Error('The tool call was cancelled.');
95
+ const result = await call('tools/call', { name, arguments: args }, signal);
96
+ const record = typeof result === 'object' && result !== null ? result : {};
97
+ return {
98
+ content: flattenContent(record.content),
99
+ isError: record.isError === true,
100
+ };
101
+ },
102
+ async close() {
103
+ await close();
104
+ },
105
+ };
106
+ }
107
+ /** A tool name the model can call: namespaced so two servers cannot collide. */
108
+ export function mcpToolName(server, tool) {
109
+ const clean = (value) => value.replace(/[^A-Za-z0-9_]/g, '_');
110
+ return `mcp__${clean(server)}__${clean(tool)}`;
111
+ }
112
+ //# sourceMappingURL=client.js.map