@ywldan/kiro 0.3.2 → 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.
@@ -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
@@ -0,0 +1,112 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ export function mcpConfigPath(cwd, scope, home) {
4
+ return scope === 'project'
5
+ ? path.join(cwd, '.kiro', 'mcp.json')
6
+ : path.join(home, '.kiro', 'mcp.json');
7
+ }
8
+ function isRecord(value) {
9
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
10
+ }
11
+ /** Reads one file; a missing file is not a problem, a broken one is. */
12
+ export async function readMcpFile(file) {
13
+ let text;
14
+ try {
15
+ text = await readFile(file, 'utf8');
16
+ }
17
+ catch (error) {
18
+ if (error.code === 'ENOENT')
19
+ return { servers: {} };
20
+ return { servers: {}, problem: `Could not read ${file}: ${error.message}` };
21
+ }
22
+ let parsed;
23
+ try {
24
+ parsed = JSON.parse(text);
25
+ }
26
+ catch (error) {
27
+ return {
28
+ servers: {},
29
+ problem: `${file} is not valid JSON (${error.message}); no servers were loaded from it.`,
30
+ };
31
+ }
32
+ if (!isRecord(parsed) || !isRecord(parsed.mcpServers)) {
33
+ return { servers: {}, problem: `${file} needs an "mcpServers" object.` };
34
+ }
35
+ const servers = {};
36
+ for (const [name, raw] of Object.entries(parsed.mcpServers)) {
37
+ if (!isRecord(raw))
38
+ continue;
39
+ servers[name] = normalizeEntry(raw);
40
+ }
41
+ return { servers };
42
+ }
43
+ function stringMap(raw) {
44
+ if (!isRecord(raw))
45
+ return undefined;
46
+ const out = {};
47
+ for (const [key, value] of Object.entries(raw)) {
48
+ if (typeof value === 'string')
49
+ out[key] = value;
50
+ }
51
+ return Object.keys(out).length > 0 ? out : undefined;
52
+ }
53
+ /** `timeout` is milliseconds, matching other MCP clients; `timeoutSec` is the same in seconds. */
54
+ function timeoutMsFrom(raw) {
55
+ const ms = typeof raw.timeout === 'number' ? raw.timeout : undefined;
56
+ const sec = typeof raw.timeoutSec === 'number' ? raw.timeoutSec * 1000 : undefined;
57
+ const value = ms ?? sec;
58
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
59
+ return undefined;
60
+ return Math.min(value, 24 * 60 * 60 * 1000);
61
+ }
62
+ function normalizeEntry(raw) {
63
+ const args = Array.isArray(raw.args) ? raw.args.filter((arg) => typeof arg === 'string') : undefined;
64
+ return {
65
+ type: raw.type === 'http' || raw.type === 'stdio'
66
+ ? raw.type
67
+ : typeof raw.url === 'string'
68
+ ? 'http'
69
+ : 'stdio',
70
+ command: typeof raw.command === 'string' ? raw.command : undefined,
71
+ args,
72
+ env: stringMap(raw.env),
73
+ url: typeof raw.url === 'string' ? raw.url : undefined,
74
+ headers: stringMap(raw.headers),
75
+ timeoutMs: timeoutMsFrom(raw),
76
+ disabled: raw.disabled === true,
77
+ };
78
+ }
79
+ export async function loadMcpConfig(cwd, home, extraPath) {
80
+ const files = [
81
+ { scope: 'project', path: mcpConfigPath(cwd, 'project', home) },
82
+ { scope: 'user', path: mcpConfigPath(cwd, 'user', home) },
83
+ ];
84
+ if (extraPath)
85
+ files.push({ scope: 'user', path: extraPath });
86
+ const servers = {};
87
+ const sources = [];
88
+ const problems = [];
89
+ for (const file of files) {
90
+ const { servers: found, problem } = await readMcpFile(file.path);
91
+ if (problem)
92
+ problems.push(problem);
93
+ if (Object.keys(found).length > 0)
94
+ sources.push({ path: file.path, servers: found });
95
+ for (const [name, entry] of Object.entries(found)) {
96
+ if (!servers[name])
97
+ servers[name] = entry;
98
+ }
99
+ }
100
+ return { servers, sources, problems };
101
+ }
102
+ /** Why a server cannot be started, or null when it can. */
103
+ export function mcpEntryProblem(entry) {
104
+ if (entry.disabled)
105
+ return 'disabled in the config';
106
+ if (entry.type === 'http')
107
+ return entry.url ? null : 'no "url" was given';
108
+ if (!entry.command)
109
+ return 'no "command" was given';
110
+ return null;
111
+ }
112
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,28 @@
1
+ import { childEnv } from '../secrets.js';
2
+ /**
3
+ * Builds the environment for a server process: Kiro's own credentials are
4
+ * stripped by `childEnv`, then the server's configured variables are added.
5
+ * A `${VAR}` value is read from Kiro's environment, so a token can live in
6
+ * ~/.kiro/.env instead of config.json.
7
+ */
8
+ export function expandVars(value) {
9
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, variable) => {
10
+ return process.env[variable] ?? match;
11
+ });
12
+ }
13
+ export function childEnvFor(extra) {
14
+ const env = childEnv();
15
+ for (const [name, value] of Object.entries(extra ?? {}))
16
+ env[name] = expandVars(value);
17
+ return env;
18
+ }
19
+ /** Header values can point at an environment variable, so a token stays out of the config file. */
20
+ export function expandHeaders(headers) {
21
+ if (!headers)
22
+ return undefined;
23
+ const out = {};
24
+ for (const [name, value] of Object.entries(headers))
25
+ out[name] = expandVars(value);
26
+ return out;
27
+ }
28
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1,168 @@
1
+ import { endpointFrom, MCP_CLIENT_NAME, MCP_CLIENT_VERSION, MCP_PROTOCOL_VERSION, } from './client.js';
2
+ import { RpcError } from './rpc.js';
3
+ import { expandHeaders } from './env.js';
4
+ /**
5
+ * Streamable HTTP transport: one POST per JSON-RPC message, and the server
6
+ * answers either as `application/json` or as an SSE stream that carries the
7
+ * reply. A server may hand back `Mcp-Session-Id` on initialize, which every
8
+ * later request repeats.
9
+ *
10
+ * https://modelcontextprotocol.io/specification/2025-06-18/basic/transports
11
+ */
12
+ export const MCP_HTTP_TIMEOUT_MS = Number(process.env.KIRO_MCP_TIMEOUT_MS ?? 30_000);
13
+ const SESSION_HEADER = 'mcp-session-id';
14
+ const MAX_BODY_CHARS = 4 * 1024 * 1024;
15
+ /** Parses the `data:` payloads of an SSE body and returns the last JSON object. */
16
+ export function readSseMessage(body) {
17
+ const events = [];
18
+ for (const line of body.split(/\r?\n/)) {
19
+ if (!line.startsWith('data:'))
20
+ continue;
21
+ const payload = line.slice(5).trim();
22
+ if (!payload || payload === '[DONE]')
23
+ continue;
24
+ try {
25
+ events.push(JSON.parse(payload));
26
+ }
27
+ catch {
28
+ // A partial or non-JSON data line is not a protocol message; skip it.
29
+ }
30
+ }
31
+ // Notifications can precede the response on the same stream.
32
+ const answered = events.filter((event) => typeof event === 'object' && event !== null && 'id' in event);
33
+ return answered.at(-1) ?? events.at(-1);
34
+ }
35
+ async function readBody(response) {
36
+ const text = await response.text();
37
+ return text.length > MAX_BODY_CHARS ? text.slice(0, MAX_BODY_CHARS) : text;
38
+ }
39
+ /** Turns a non-2xx answer into a message that names the status and the server's own text. */
40
+ async function describeFailure(response) {
41
+ const body = (await readBody(response)).trim();
42
+ const hint = body ? `: ${body.slice(0, 300)}` : '';
43
+ if (response.status === 401 || response.status === 403) {
44
+ return `the server refused the request (${response.status} ${response.statusText})${hint}. Check the "headers" in the config entry.`;
45
+ }
46
+ return `the server answered ${response.status} ${response.statusText}${hint}`;
47
+ }
48
+ export async function connectHttp(name, config, options = {}) {
49
+ const timeoutMs = config.timeoutMs ?? MCP_HTTP_TIMEOUT_MS;
50
+ let sessionId;
51
+ let protocolVersion = MCP_PROTOCOL_VERSION;
52
+ let closed = false;
53
+ let nextId = 1;
54
+ const headers = () => ({
55
+ 'content-type': 'application/json',
56
+ accept: 'application/json, text/event-stream',
57
+ ...expandHeaders(config.headers),
58
+ ...(sessionId ? { [SESSION_HEADER]: sessionId } : {}),
59
+ ...(protocolVersion ? { 'mcp-protocol-version': protocolVersion } : {}),
60
+ });
61
+ const post = async (payload, method, signal) => {
62
+ if (closed)
63
+ throw new Error('The MCP connection is closed.');
64
+ if (signal?.aborted)
65
+ throw new Error(`${method} was cancelled.`);
66
+ const timeout = AbortSignal.timeout(timeoutMs);
67
+ let response;
68
+ try {
69
+ response = await fetch(config.url, {
70
+ method: 'POST',
71
+ headers: headers(),
72
+ body: JSON.stringify(payload),
73
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
74
+ });
75
+ }
76
+ catch (error) {
77
+ if (signal?.aborted)
78
+ throw new Error(`${method} was cancelled.`);
79
+ const reason = error.name === 'TimeoutError'
80
+ ? `${method} did not answer within ${timeoutMs / 1000}s.`
81
+ : `could not reach the server: ${error.message}`;
82
+ throw new Error(reason);
83
+ }
84
+ if (!response.ok)
85
+ throw new Error(await describeFailure(response));
86
+ const session = response.headers.get(SESSION_HEADER);
87
+ if (session)
88
+ sessionId = session;
89
+ // A notification is acknowledged with 202 and no body.
90
+ if (response.status === 202 || method === 'notifications/initialized')
91
+ return undefined;
92
+ const body = await readBody(response);
93
+ const contentType = response.headers.get('content-type') ?? '';
94
+ const message = contentType.includes('text/event-stream') ? readSseMessage(body) : parseJson(body);
95
+ if (message === undefined)
96
+ return undefined;
97
+ if (typeof message !== 'object' || message === null)
98
+ return undefined;
99
+ const record = message;
100
+ if (typeof record.error === 'object' && record.error !== null) {
101
+ const error = record.error;
102
+ throw new RpcError({
103
+ code: typeof error.code === 'number' ? error.code : -32000,
104
+ message: typeof error.message === 'string' ? error.message : 'Unknown JSON-RPC error',
105
+ data: error.data,
106
+ });
107
+ }
108
+ if (typeof record.method === 'string') {
109
+ options.onNotice?.(`${name}: the server sent a request over HTTP (${record.method}); Kiro only handles replies here.`);
110
+ return undefined;
111
+ }
112
+ return record.result;
113
+ };
114
+ const request = async (method, params, signal) => {
115
+ const id = nextId++;
116
+ return post({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) }, method, signal);
117
+ };
118
+ let init;
119
+ try {
120
+ init = await request('initialize', {
121
+ protocolVersion: MCP_PROTOCOL_VERSION,
122
+ capabilities: { roots: { listChanged: false } },
123
+ clientInfo: { name: MCP_CLIENT_NAME, version: MCP_CLIENT_VERSION },
124
+ });
125
+ }
126
+ catch (error) {
127
+ throw new Error(`MCP server "${name}" failed over HTTP: ${error.message}`);
128
+ }
129
+ const negotiated = typeof init === 'object' && init !== null ? init.protocolVersion : undefined;
130
+ if (typeof negotiated === 'string')
131
+ protocolVersion = negotiated;
132
+ await post({ jsonrpc: '2.0', method: 'notifications/initialized', params: {} }, 'notifications/initialized');
133
+ const info = typeof init === 'object' && init !== null
134
+ ? (init.serverInfo ?? {})
135
+ : {};
136
+ return endpointFrom(name, 'http', {
137
+ name: typeof info.name === 'string' ? info.name : name,
138
+ version: typeof info.version === 'string' ? info.version : 'unknown',
139
+ }, request, async () => {
140
+ if (closed)
141
+ return;
142
+ closed = true;
143
+ if (!sessionId)
144
+ return;
145
+ // Best effort: a server that dislikes DELETE must not fail the quit path.
146
+ try {
147
+ await fetch(config.url, {
148
+ method: 'DELETE',
149
+ headers: headers(),
150
+ signal: AbortSignal.timeout(2_000),
151
+ });
152
+ }
153
+ catch {
154
+ // Ignored on purpose: the session id expires on the server anyway.
155
+ }
156
+ });
157
+ }
158
+ function parseJson(body) {
159
+ if (!body.trim())
160
+ return undefined;
161
+ try {
162
+ return JSON.parse(body);
163
+ }
164
+ catch {
165
+ return undefined;
166
+ }
167
+ }
168
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1,24 @@
1
+ import { extraTools } from '../tools/registry.js';
2
+ /**
3
+ * The system prompt lists MCP tools by name only. Their descriptions already
4
+ * travel as tool definitions, and the rules differ enough to be worth stating:
5
+ * Kiro cannot see or limit what a server process does.
6
+ */
7
+ export function mcpPromptSection() {
8
+ const names = extraTools()
9
+ .map((tool) => tool.definition.function.name)
10
+ .filter((name) => name.startsWith('mcp__'));
11
+ if (names.length === 0)
12
+ return '';
13
+ return [
14
+ '# MCP tools',
15
+ '',
16
+ 'These tools come from MCP servers the user configured. Every name starts with',
17
+ '`mcp__<server>__`. Each call needs approval because the server runs outside',
18
+ "Kiro's file sandbox, so the user decides what it may do. Do not retry a denied",
19
+ 'call; explain what the server would have done instead.',
20
+ '',
21
+ `Available: ${names.join(', ')}`,
22
+ ].join('\n');
23
+ }
24
+ //# sourceMappingURL=prompt.js.map
@@ -0,0 +1,206 @@
1
+ import path from 'node:path';
2
+ import { mcpToolName, } from './client.js';
3
+ import { loadMcpConfig, mcpEntryProblem } from './config.js';
4
+ import { connectStdio } from './stdio.js';
5
+ import { connectHttp } from './http.js';
6
+ /**
7
+ * Turns a server's tools into Kiro tools, namespaced as `mcp__<server>__<tool>`.
8
+ *
9
+ * An MCP server can do anything its process can do, so every call asks for
10
+ * approval by default. `annotations.readOnlyHint` only changes the wording and
11
+ * lets read-only calls run in parallel; it never skips the prompt.
12
+ */
13
+ export const MCP_CONNECT_TIMEOUT_MS = Number(process.env.KIRO_MCP_CONNECT_MS ?? 15_000);
14
+ /**
15
+ * MCP calls carry no `subject`, so `evaluateRules` cannot match them and a saved
16
+ * rule can never pre-approve one. This predicate documents that invariant for
17
+ * callers that build a request by hand.
18
+ */
19
+ export function mcpNeedsApproval(request) {
20
+ return isMcpTool(request.tool) || request.subject === undefined;
21
+ }
22
+ export function isMcpTool(name) {
23
+ return name.startsWith('mcp__');
24
+ }
25
+ function schemaFor(tool) {
26
+ const schema = tool.inputSchema;
27
+ if (schema.type !== 'object' || typeof schema.properties !== 'object' || schema.properties === null) {
28
+ // Some servers describe no arguments; the model still needs an object schema.
29
+ return { type: 'object', properties: {}, additionalProperties: true };
30
+ }
31
+ return {
32
+ type: 'object',
33
+ properties: schema.properties,
34
+ ...(Array.isArray(schema.required) ? { required: schema.required } : {}),
35
+ ...(typeof schema.additionalProperties === 'boolean'
36
+ ? { additionalProperties: schema.additionalProperties }
37
+ : {}),
38
+ };
39
+ }
40
+ function describe(server, tool) {
41
+ const readOnly = tool.annotations?.readOnlyHint === true;
42
+ const firstLine = tool.description.split('\n')[0]?.trim() ?? '';
43
+ const body = firstLine || `Tool "${tool.name}" from the MCP server "${server}".`;
44
+ return `${body} (MCP server "${server}"${readOnly ? ', read-only' : ''}). Requires user approval.`;
45
+ }
46
+ function mcpTool(server, endpoint, info) {
47
+ const name = mcpToolName(server, info.name);
48
+ return {
49
+ // Always false: an MCP server decides what a tool does, so two calls of the
50
+ // same read-only hint still run one at a time and get their own prompt.
51
+ readOnly: false,
52
+ mcp: true,
53
+ definition: {
54
+ type: 'function',
55
+ function: {
56
+ name,
57
+ description: describe(server, info),
58
+ parameters: schemaFor(info),
59
+ },
60
+ },
61
+ async run(input, ctx) {
62
+ const request = {
63
+ tool: name,
64
+ title: `MCP ${server}: ${info.name}`,
65
+ detail: `$ ${JSON.stringify(input)}\n\nRuns in the MCP server process "${server}", outside Kiro's file sandbox.`,
66
+ // No subject: a saved rule must never pre-approve an MCP call.
67
+ warning: 'This tool runs inside the MCP server, so Kiro cannot see or limit what it does.',
68
+ };
69
+ if (ctx.signal.aborted) {
70
+ return { content: 'Cancelled by user.', summary: 'cancelled', status: 'denied' };
71
+ }
72
+ const decision = await ctx.approve(request);
73
+ if (decision === 'deny') {
74
+ return { content: 'User denied this MCP tool call.', summary: 'denied by user', status: 'denied' };
75
+ }
76
+ try {
77
+ const result = await endpoint.callTool(info.name, input, ctx.signal);
78
+ const content = result.content || '(no content)';
79
+ return {
80
+ content: result.isError ? `Error: ${content}` : content,
81
+ summary: content.split('\n')[0]?.slice(0, 200) ?? info.name,
82
+ status: result.isError ? 'error' : 'ok',
83
+ };
84
+ }
85
+ catch (error) {
86
+ if (ctx.signal.aborted) {
87
+ return { content: 'Cancelled by user.', summary: 'cancelled', status: 'denied' };
88
+ }
89
+ return {
90
+ content: `Error: MCP server "${server}" failed to run "${info.name}": ${error.message}`,
91
+ summary: `${info.name} failed`,
92
+ status: 'error',
93
+ };
94
+ }
95
+ },
96
+ };
97
+ }
98
+ async function withTimeout(promise, ms, what) {
99
+ let timer;
100
+ try {
101
+ return await Promise.race([
102
+ promise,
103
+ new Promise((_, reject) => {
104
+ timer = setTimeout(() => reject(new Error(`${what} timed out after ${ms / 1000}s.`)), ms);
105
+ timer.unref?.();
106
+ }),
107
+ ]);
108
+ }
109
+ finally {
110
+ if (timer)
111
+ clearTimeout(timer);
112
+ }
113
+ }
114
+ /**
115
+ * Starts every enabled server and collects its tools. A server that fails is
116
+ * reported and skipped; the session still starts, because one broken MCP entry
117
+ * must not make the CLI unusable.
118
+ */
119
+ export async function setupMcp(cwd, options = {}) {
120
+ const home = options.home ?? process.env.HOME ?? process.env.USERPROFILE ?? '';
121
+ const config = await loadMcpConfig(cwd, home, options.extraPath ?? process.env.KIRO_MCP_CONFIG);
122
+ for (const problem of config.problems)
123
+ options.onNotice?.(problem);
124
+ const tools = [];
125
+ const statuses = [];
126
+ const endpoints = [];
127
+ const names = Object.keys(config.servers).sort((left, right) => left.localeCompare(right));
128
+ // Servers start in parallel; a slow one delays only itself.
129
+ await Promise.all(names.map(async (name) => {
130
+ const entry = config.servers[name];
131
+ const problem = mcpEntryProblem(entry);
132
+ if (problem) {
133
+ statuses.push({ name, state: 'skipped', detail: problem, tools: 0, entry });
134
+ return;
135
+ }
136
+ try {
137
+ const endpoint = await withTimeout(entry.type === 'http'
138
+ ? connectHttp(name, { url: entry.url, headers: entry.headers, timeoutMs: entry.timeoutMs }, {
139
+ onNotice: options.onNotice,
140
+ })
141
+ : connectStdio(name, { command: entry.command, args: entry.args, env: entry.env, timeoutMs: entry.timeoutMs }, { cwd, onNotice: options.onNotice }), MCP_CONNECT_TIMEOUT_MS, `Starting MCP server "${name}"`);
142
+ const listed = await withTimeout(endpoint.listTools(), MCP_CONNECT_TIMEOUT_MS, `Listing tools from "${name}"`);
143
+ endpoints.push(endpoint);
144
+ for (const info of listed)
145
+ tools.push(mcpTool(name, endpoint, info));
146
+ statuses.push({
147
+ name,
148
+ state: 'ready',
149
+ transport: endpoint.transport,
150
+ detail: `${endpoint.serverInfo.name} ${endpoint.serverInfo.version}`,
151
+ tools: listed.length,
152
+ entry,
153
+ });
154
+ }
155
+ catch (error) {
156
+ statuses.push({
157
+ name,
158
+ state: 'error',
159
+ detail: error.message,
160
+ tools: 0,
161
+ entry,
162
+ });
163
+ }
164
+ }));
165
+ statuses.sort((left, right) => left.name.localeCompare(right.name));
166
+ return {
167
+ tools,
168
+ definitions: tools.map((tool) => tool.definition),
169
+ statuses,
170
+ config,
171
+ async close() {
172
+ await Promise.all(endpoints.map((endpoint) => endpoint.close().catch(() => undefined)));
173
+ },
174
+ };
175
+ }
176
+ /** Human-readable status lines for `/mcp` and the startup notice. */
177
+ export function formatMcpStatus(setup, extraDir) {
178
+ if (!setup)
179
+ return 'MCP is off for this run.';
180
+ if (setup.statuses.length === 0) {
181
+ return [
182
+ 'No MCP servers configured.',
183
+ `Add "mcpServers" to ${path.join(extraDir ?? '.', '.kiro', 'mcp.json')} or ~/.kiro/mcp.json.`,
184
+ ].join('\n');
185
+ }
186
+ const lines = setup.statuses.map((status) => {
187
+ const mark = status.state === 'ready' ? 'ok ' : status.state === 'error' ? 'fail' : 'skip';
188
+ const command = status.entry?.command
189
+ ? `${status.entry.command} ${(status.entry.args ?? []).join(' ')}`.trim()
190
+ : status.entry?.url ?? '';
191
+ const limit = status.entry?.timeoutMs
192
+ ? ` timeout ${Math.round(status.entry.timeoutMs / 1000)}s`
193
+ : '';
194
+ return [
195
+ `${mark} ${status.name}${status.tools > 0 ? ` (${status.tools} tool${status.tools === 1 ? '' : 's'})` : ''}`,
196
+ command ? ` ${command}` : '',
197
+ limit,
198
+ status.detail ? ` ${status.detail}` : '',
199
+ ]
200
+ .filter(Boolean)
201
+ .join('\n');
202
+ });
203
+ const sources = setup.config.sources.map((source) => ` ${source.path}`).join('\n');
204
+ return [lines.join('\n'), sources ? `Read from:\n${sources}` : ''].filter(Boolean).join('\n');
205
+ }
206
+ //# sourceMappingURL=registry.js.map