@kilncraft/mcp 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/dist/index.d.ts +75 -0
- package/dist/index.js +192 -0
- package/dist/index.js.map +1 -0
- package/package.json +36 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kilncraft contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { ToolDefinition, ToolOutput } from '@kilncraft/shared';
|
|
2
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
3
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
|
+
|
|
5
|
+
type McpServerConfig = {
|
|
6
|
+
command: string;
|
|
7
|
+
args?: string[];
|
|
8
|
+
env?: Record<string, string>;
|
|
9
|
+
} | {
|
|
10
|
+
url: string;
|
|
11
|
+
headers?: Record<string, string>;
|
|
12
|
+
};
|
|
13
|
+
interface McpConnection {
|
|
14
|
+
name: string;
|
|
15
|
+
client: Client;
|
|
16
|
+
tools: Array<ToolDefinition<Record<string, unknown>>>;
|
|
17
|
+
close: () => Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
interface McpContent$1 {
|
|
20
|
+
type: string;
|
|
21
|
+
text?: string;
|
|
22
|
+
data?: string;
|
|
23
|
+
mimeType?: string;
|
|
24
|
+
}
|
|
25
|
+
interface McpTool {
|
|
26
|
+
name: string;
|
|
27
|
+
description?: string;
|
|
28
|
+
inputSchema: Record<string, unknown>;
|
|
29
|
+
annotations?: {
|
|
30
|
+
readOnlyHint?: boolean;
|
|
31
|
+
destructiveHint?: boolean;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
declare function mcpResultToOutput(result: {
|
|
35
|
+
content?: McpContent$1[];
|
|
36
|
+
isError?: boolean;
|
|
37
|
+
}): ToolOutput;
|
|
38
|
+
declare function toolFromMcpTool(serverName: string, client: Client, tool: McpTool): ToolDefinition<Record<string, unknown>>;
|
|
39
|
+
declare function connectMcpServer(name: string, config: McpServerConfig, options?: {
|
|
40
|
+
logger?: {
|
|
41
|
+
warn: (payload: unknown, message?: string) => void;
|
|
42
|
+
};
|
|
43
|
+
}): Promise<McpConnection>;
|
|
44
|
+
declare function registerMcpTools(registry: {
|
|
45
|
+
register: (tool: ToolDefinition<unknown>) => void;
|
|
46
|
+
}, servers: Record<string, unknown>, options?: {
|
|
47
|
+
env?: NodeJS.ProcessEnv;
|
|
48
|
+
logger?: {
|
|
49
|
+
warn: (payload: unknown, message?: string) => void;
|
|
50
|
+
};
|
|
51
|
+
}): Promise<McpConnection[]>;
|
|
52
|
+
|
|
53
|
+
type McpContent = {
|
|
54
|
+
type: "text";
|
|
55
|
+
text: string;
|
|
56
|
+
} | {
|
|
57
|
+
type: "image";
|
|
58
|
+
data: string;
|
|
59
|
+
mimeType: string;
|
|
60
|
+
};
|
|
61
|
+
declare function mcpContentFromOutput(output: ToolOutput): {
|
|
62
|
+
content: McpContent[];
|
|
63
|
+
};
|
|
64
|
+
declare function createMcpServer(tools: ToolDefinition<unknown>[], options?: {
|
|
65
|
+
allowDestructive?: boolean;
|
|
66
|
+
}): McpServer;
|
|
67
|
+
declare function startMcpStdioServer(tools?: ToolDefinition<unknown>[], options?: {
|
|
68
|
+
allowDestructive?: boolean;
|
|
69
|
+
}): Promise<McpServer>;
|
|
70
|
+
declare function createMcpHttpHandler(tools?: ToolDefinition<unknown>[], options?: {
|
|
71
|
+
allowDestructive?: boolean;
|
|
72
|
+
}): Promise<(request: Request) => Promise<Response>>;
|
|
73
|
+
|
|
74
|
+
export { connectMcpServer, createMcpHttpHandler, createMcpServer, mcpContentFromOutput, mcpResultToOutput, registerMcpTools, startMcpStdioServer, toolFromMcpTool };
|
|
75
|
+
export type { McpConnection, McpServerConfig };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { KilncraftError, createLogger } from '@kilncraft/shared';
|
|
2
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
3
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
4
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { randomUUID } from 'crypto';
|
|
7
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
8
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
9
|
+
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
|
10
|
+
|
|
11
|
+
// src/client.ts
|
|
12
|
+
function mcpResultToOutput(result) {
|
|
13
|
+
const content = Array.isArray(result.content) ? result.content : [];
|
|
14
|
+
const text = content.filter((entry) => entry.type === "text" && typeof entry.text === "string").map((entry) => entry.text).join("\n");
|
|
15
|
+
if (result.isError) {
|
|
16
|
+
return { kind: "text", text: text || "MCP tool reported an error." };
|
|
17
|
+
}
|
|
18
|
+
if (text.length > 0) return { kind: "text", text };
|
|
19
|
+
const image = content.find((entry) => entry.type === "image" && entry.data);
|
|
20
|
+
if (image?.data) {
|
|
21
|
+
return {
|
|
22
|
+
kind: "image",
|
|
23
|
+
mime: image.mimeType ?? "image/png",
|
|
24
|
+
data: image.data
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
return { kind: "json", value: result };
|
|
28
|
+
}
|
|
29
|
+
function toolFromMcpTool(serverName, client, tool) {
|
|
30
|
+
const input = z.record(z.string(), z.unknown());
|
|
31
|
+
return {
|
|
32
|
+
id: `mcp_${serverName}_${tool.name}`,
|
|
33
|
+
description: `${tool.description ?? `MCP tool ${tool.name} from ${serverName}`}${tool.annotations?.readOnlyHint ? " (read-only)" : ""}`,
|
|
34
|
+
input,
|
|
35
|
+
parametersOverride: tool.inputSchema,
|
|
36
|
+
readOnly: false,
|
|
37
|
+
parallelizable: false,
|
|
38
|
+
defaultDecision: "ask",
|
|
39
|
+
timeoutMs: 12e4,
|
|
40
|
+
execute: async (args, context) => {
|
|
41
|
+
const result = await client.callTool(
|
|
42
|
+
{
|
|
43
|
+
name: tool.name,
|
|
44
|
+
arguments: args
|
|
45
|
+
},
|
|
46
|
+
void 0,
|
|
47
|
+
{ signal: context.signal, timeout: 12e4 }
|
|
48
|
+
);
|
|
49
|
+
return mcpResultToOutput(result);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
async function connectMcpServer(name, config, options = {}) {
|
|
54
|
+
const client = new Client({ name: "kilncraft", version: "0.0.0" });
|
|
55
|
+
const env = {};
|
|
56
|
+
for (const key of [
|
|
57
|
+
"PATH",
|
|
58
|
+
"HOME",
|
|
59
|
+
"TMPDIR",
|
|
60
|
+
"LANG",
|
|
61
|
+
"LC_ALL",
|
|
62
|
+
"TERM",
|
|
63
|
+
"USER",
|
|
64
|
+
"SHELL",
|
|
65
|
+
"NODE_PATH"
|
|
66
|
+
]) {
|
|
67
|
+
const value = process.env[key];
|
|
68
|
+
if (value !== void 0) env[key] = value;
|
|
69
|
+
}
|
|
70
|
+
Object.assign(env, "command" in config ? config.env ?? {} : {});
|
|
71
|
+
const transport = "url" in config ? new StreamableHTTPClientTransport(
|
|
72
|
+
new URL(config.url),
|
|
73
|
+
config.headers ? { requestInit: { headers: config.headers } } : void 0
|
|
74
|
+
) : new StdioClientTransport({
|
|
75
|
+
command: config.command,
|
|
76
|
+
args: config.args ?? [],
|
|
77
|
+
env,
|
|
78
|
+
stderr: "pipe"
|
|
79
|
+
});
|
|
80
|
+
try {
|
|
81
|
+
await client.connect(transport);
|
|
82
|
+
const stderr = transport.stderr;
|
|
83
|
+
stderr?.resume?.();
|
|
84
|
+
const listed = await client.listTools();
|
|
85
|
+
const tools = listed.tools.map((tool) => toolFromMcpTool(name, client, tool));
|
|
86
|
+
return {
|
|
87
|
+
name,
|
|
88
|
+
client,
|
|
89
|
+
tools,
|
|
90
|
+
close: async () => {
|
|
91
|
+
await client.close();
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
} catch (error) {
|
|
95
|
+
await client.close().catch(() => void 0);
|
|
96
|
+
options.logger?.warn({ err: error }, `failed to connect MCP server ${name}`);
|
|
97
|
+
throw new KilncraftError("provider_error", `MCP server ${name} failed: ${String(error)}`, {
|
|
98
|
+
cause: error,
|
|
99
|
+
recoverable: true
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async function registerMcpTools(registry, servers, options = {}) {
|
|
104
|
+
const connections = [];
|
|
105
|
+
for (const [name, raw] of Object.entries(servers)) {
|
|
106
|
+
const config = raw;
|
|
107
|
+
try {
|
|
108
|
+
const connection = await connectMcpServer(name, config, options);
|
|
109
|
+
for (const tool of connection.tools) registry.register(tool);
|
|
110
|
+
connections.push(connection);
|
|
111
|
+
} catch {
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return connections;
|
|
115
|
+
}
|
|
116
|
+
function mcpContentFromOutput(output) {
|
|
117
|
+
switch (output.kind) {
|
|
118
|
+
case "text":
|
|
119
|
+
return { content: [{ type: "text", text: output.text }] };
|
|
120
|
+
case "json":
|
|
121
|
+
case "structured":
|
|
122
|
+
return { content: [{ type: "text", text: JSON.stringify(output.value, null, 2) }] };
|
|
123
|
+
case "diff":
|
|
124
|
+
return { content: [{ type: "text", text: output.diff || "(no diff)" }] };
|
|
125
|
+
case "terminal": {
|
|
126
|
+
const text = [output.stdout, output.stderr, `exit ${output.exitCode}`].filter((part) => part.length > 0).join("\n");
|
|
127
|
+
return { content: [{ type: "text", text }] };
|
|
128
|
+
}
|
|
129
|
+
case "image":
|
|
130
|
+
return {
|
|
131
|
+
content: [{ type: "image", data: output.data, mimeType: output.mime }]
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
function createMcpServer(tools, options = {}) {
|
|
136
|
+
const server = new McpServer({ name: "kilncraft", version: "0.0.0" });
|
|
137
|
+
const logger = createLogger({ level: "silent" });
|
|
138
|
+
const exposed = options.allowDestructive ? tools : tools.filter((tool) => tool.readOnly);
|
|
139
|
+
for (const tool of exposed) {
|
|
140
|
+
server.registerTool(
|
|
141
|
+
tool.id,
|
|
142
|
+
{
|
|
143
|
+
description: tool.description,
|
|
144
|
+
inputSchema: tool.input
|
|
145
|
+
},
|
|
146
|
+
async (args) => {
|
|
147
|
+
const output = await tool.execute(args, {
|
|
148
|
+
sessionID: "mcp",
|
|
149
|
+
cwd: process.cwd(),
|
|
150
|
+
workspaceRoot: process.cwd(),
|
|
151
|
+
signal: new AbortController().signal,
|
|
152
|
+
logger,
|
|
153
|
+
state: {}
|
|
154
|
+
});
|
|
155
|
+
return mcpContentFromOutput(output);
|
|
156
|
+
}
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
return server;
|
|
160
|
+
}
|
|
161
|
+
async function startMcpStdioServer(tools = [], options = {}) {
|
|
162
|
+
const server = createMcpServer(tools, options);
|
|
163
|
+
const transport = new StdioServerTransport();
|
|
164
|
+
await server.connect(transport);
|
|
165
|
+
return server;
|
|
166
|
+
}
|
|
167
|
+
async function createMcpHttpHandler(tools = [], options = {}) {
|
|
168
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
169
|
+
return async (request) => {
|
|
170
|
+
const sessionID = request.headers.get("mcp-session-id");
|
|
171
|
+
const existing = sessionID ? sessions.get(sessionID) : void 0;
|
|
172
|
+
if (existing) return existing.transport.handleRequest(request);
|
|
173
|
+
const server = createMcpServer(tools, options);
|
|
174
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
175
|
+
sessionIdGenerator: () => randomUUID(),
|
|
176
|
+
onsessioninitialized: (id) => {
|
|
177
|
+
sessions.set(id, { server, transport });
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
transport.onclose = () => {
|
|
181
|
+
const id = transport.sessionId;
|
|
182
|
+
if (id) sessions.delete(id);
|
|
183
|
+
void server.close();
|
|
184
|
+
};
|
|
185
|
+
await server.connect(transport);
|
|
186
|
+
return transport.handleRequest(request);
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export { connectMcpServer, createMcpHttpHandler, createMcpServer, mcpContentFromOutput, mcpResultToOutput, registerMcpTools, startMcpStdioServer, toolFromMcpTool };
|
|
191
|
+
//# sourceMappingURL=index.js.map
|
|
192
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/server.ts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A,MAC7D,kBAAA,EAAoB,MAAM,UAAA,EAAW;AAAA,MACrC,oBAAA,EAAsB,CAAC,EAAA,KAAe;AACpC,QAAA,QAAA,CAAS,GAAA,CAAI,EAAA,EAAI,EAAE,MAAA,EAAQ,WAAW,CAAA;AAAA,MACxC;AAAA,KACD,CAAA;AAED,IAAA,SAAA,CAAU,UAAU,MAAM;AACxB,MAAA,MAAM,KAAK,SAAA,CAAU,SAAA;AACrB,MAAA,IAAI,EAAA,EAAI,QAAA,CAAS,MAAA,CAAO,EAAE,CAAA;AAC1B,MAAA,KAAK,OAAO,KAAA,EAAM;AAAA,IACpB,CAAA;AAEA,IAAA,MAAM,MAAA,CAAO,QAAQ,SAAS,CAAA;AAC9B,IAAA,OAAO,SAAA,CAAU,cAAc,OAAO,CAAA;AAAA,EACxC,CAAA;AACF","file":"index.js","sourcesContent":["import type { ToolDefinition, ToolOutput } from \"@kilncraft/shared\";\nimport { KilncraftError } from \"@kilncraft/shared\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { z } from \"zod\";\n\nexport type McpServerConfig =\n | {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n }\n | {\n url: string;\n headers?: Record<string, string>;\n };\n\nexport interface McpConnection {\n name: string;\n client: Client;\n tools: Array<ToolDefinition<Record<string, unknown>>>;\n close: () => Promise<void>;\n}\n\ninterface McpContent {\n type: string;\n text?: string;\n data?: string;\n mimeType?: string;\n}\n\ninterface McpTool {\n name: string;\n description?: string;\n inputSchema: Record<string, unknown>;\n annotations?: {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n };\n}\n\nexport function mcpResultToOutput(result: {\n content?: McpContent[];\n isError?: boolean;\n}): ToolOutput {\n const content = Array.isArray(result.content) ? result.content : [];\n const text = content\n .filter((entry) => entry.type === \"text\" && typeof entry.text === \"string\")\n .map((entry) => entry.text)\n .join(\"\\n\");\n\n if (result.isError) {\n return { kind: \"text\", text: text || \"MCP tool reported an error.\" };\n }\n\n if (text.length > 0) return { kind: \"text\", text };\n\n const image = content.find((entry) => entry.type === \"image\" && entry.data);\n if (image?.data) {\n return {\n kind: \"image\",\n mime: image.mimeType ?? \"image/png\",\n data: image.data,\n };\n }\n\n return { kind: \"json\", value: result };\n}\n\nexport function toolFromMcpTool(\n serverName: string,\n client: Client,\n tool: McpTool,\n): ToolDefinition<Record<string, unknown>> {\n const input = z.record(z.string(), z.unknown());\n\n return {\n id: `mcp_${serverName}_${tool.name}`,\n description: `${tool.description ?? `MCP tool ${tool.name} from ${serverName}`}${tool.annotations?.readOnlyHint ? \" (read-only)\" : \"\"}`,\n input,\n parametersOverride: tool.inputSchema,\n readOnly: false,\n parallelizable: false,\n defaultDecision: \"ask\",\n timeoutMs: 120_000,\n execute: async (args, context) => {\n const result = await client.callTool(\n {\n name: tool.name,\n arguments: args,\n },\n undefined,\n { signal: context.signal, timeout: 120_000 },\n );\n return mcpResultToOutput(result as unknown as { content?: McpContent[]; isError?: boolean });\n },\n };\n}\n\nexport async function connectMcpServer(\n name: string,\n config: McpServerConfig,\n options: { logger?: { warn: (payload: unknown, message?: string) => void } } = {},\n): Promise<McpConnection> {\n const client = new Client({ name: \"kilncraft\", version: \"0.0.0\" });\n const env: Record<string, string> = {};\n for (const key of [\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"LANG\",\n \"LC_ALL\",\n \"TERM\",\n \"USER\",\n \"SHELL\",\n \"NODE_PATH\",\n ]) {\n const value = process.env[key];\n if (value !== undefined) env[key] = value;\n }\n Object.assign(env, \"command\" in config ? (config.env ?? {}) : {});\n\n const transport =\n \"url\" in config\n ? new StreamableHTTPClientTransport(\n new URL(config.url),\n config.headers ? { requestInit: { headers: config.headers } } : undefined,\n )\n : new StdioClientTransport({\n command: config.command,\n args: config.args ?? [],\n env,\n stderr: \"pipe\",\n });\n\n try {\n await client.connect(transport);\n const stderr = (transport as { stderr?: { resume?: () => void } }).stderr;\n stderr?.resume?.();\n const listed = await client.listTools();\n const tools = listed.tools.map((tool) => toolFromMcpTool(name, client, tool as McpTool));\n return {\n name,\n client,\n tools,\n close: async () => {\n await client.close();\n },\n };\n } catch (error) {\n await client.close().catch(() => undefined);\n options.logger?.warn({ err: error }, `failed to connect MCP server ${name}`);\n throw new KilncraftError(\"provider_error\", `MCP server ${name} failed: ${String(error)}`, {\n cause: error,\n recoverable: true,\n });\n }\n}\n\nexport async function registerMcpTools(\n registry: { register: (tool: ToolDefinition<unknown>) => void },\n servers: Record<string, unknown>,\n options: {\n env?: NodeJS.ProcessEnv;\n logger?: { warn: (payload: unknown, message?: string) => void };\n } = {},\n): Promise<McpConnection[]> {\n const connections: McpConnection[] = [];\n\n for (const [name, raw] of Object.entries(servers)) {\n const config = raw as McpServerConfig;\n try {\n const connection = await connectMcpServer(name, config, options);\n for (const tool of connection.tools) registry.register(tool as ToolDefinition<unknown>);\n connections.push(connection);\n } catch {\n // connectMcpServer logs and throws; one bad server must not break the rest.\n }\n }\n\n return connections;\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { ToolDefinition, ToolOutput } from \"@kilncraft/shared\";\nimport { createLogger } from \"@kilncraft/shared\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\n\ntype McpContent =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mimeType: string };\n\nexport function mcpContentFromOutput(output: ToolOutput): { content: McpContent[] } {\n switch (output.kind) {\n case \"text\":\n return { content: [{ type: \"text\", text: output.text }] };\n case \"json\":\n case \"structured\":\n return { content: [{ type: \"text\", text: JSON.stringify(output.value, null, 2) }] };\n case \"diff\":\n return { content: [{ type: \"text\", text: output.diff || \"(no diff)\" }] };\n case \"terminal\": {\n const text = [output.stdout, output.stderr, `exit ${output.exitCode}`]\n .filter((part) => part.length > 0)\n .join(\"\\n\");\n return { content: [{ type: \"text\", text }] };\n }\n case \"image\":\n return {\n content: [{ type: \"image\", data: output.data, mimeType: output.mime }],\n };\n }\n}\n\nexport function createMcpServer(\n tools: ToolDefinition<unknown>[],\n options: { allowDestructive?: boolean } = {},\n): McpServer {\n const server = new McpServer({ name: \"kilncraft\", version: \"0.0.0\" });\n const logger = createLogger({ level: \"silent\" });\n const exposed = options.allowDestructive ? tools : tools.filter((tool) => tool.readOnly);\n\n for (const tool of exposed) {\n server.registerTool(\n tool.id,\n {\n description: tool.description,\n inputSchema: tool.input,\n },\n async (args: unknown) => {\n const output = await tool.execute(args, {\n sessionID: \"mcp\",\n cwd: process.cwd(),\n workspaceRoot: process.cwd(),\n signal: new AbortController().signal,\n logger,\n state: {},\n });\n return mcpContentFromOutput(output);\n },\n );\n }\n\n return server;\n}\n\nexport async function startMcpStdioServer(\n tools: ToolDefinition<unknown>[] = [],\n options: { allowDestructive?: boolean } = {},\n): Promise<McpServer> {\n const server = createMcpServer(tools, options);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n return server;\n}\n\nexport async function createMcpHttpHandler(\n tools: ToolDefinition<unknown>[] = [],\n options: { allowDestructive?: boolean } = {},\n): Promise<(request: Request) => Promise<Response>> {\n const sessions = new Map<\n string,\n { server: McpServer; transport: WebStandardStreamableHTTPServerTransport }\n >();\n\n return async (request: Request) => {\n const sessionID = request.headers.get(\"mcp-session-id\");\n const existing = sessionID ? sessions.get(sessionID) : undefined;\n if (existing) return existing.transport.handleRequest(request);\n\n const server = createMcpServer(tools, options);\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n onsessioninitialized: (id: string) => {\n sessions.set(id, { server, transport });\n },\n });\n\n transport.onclose = () => {\n const id = transport.sessionId;\n if (id) sessions.delete(id);\n void server.close();\n };\n\n await server.connect(transport);\n return transport.handleRequest(request);\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kilncraft/mcp",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@kilncraft/core": "1.0.0",
|
|
19
|
+
"@kilncraft/shared": "1.0.0",
|
|
20
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
21
|
+
"zod": "4.6.7"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@types/node": "26.6.6",
|
|
25
|
+
"@vitest/coverage-v8": "5.1.0",
|
|
26
|
+
"tsup": "9.0.0",
|
|
27
|
+
"typescript": "5.9.3",
|
|
28
|
+
"vitest": "5.1.0"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsup",
|
|
35
|
+
"typecheck": "tsc --noEmit",
|
|
36
|
+
"test": "vitest run",
|
|
37
|
+
"clean": "rm -rf dist .turbo coverage"
|
|
38
|
+
}
|
|
6
39
|
}
|
package/README.md
DELETED