@ptkl/toolkit 0.11.0 → 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.
@@ -0,0 +1,193 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFileSync, existsSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ class MCPConnection {
5
+ process;
6
+ buffer = '';
7
+ nextId = 1;
8
+ pending = new Map();
9
+ serverName;
10
+ constructor(serverName, config) {
11
+ this.serverName = serverName;
12
+ const env = { ...process.env, ...config.env };
13
+ this.process = spawn(config.command, config.args || [], {
14
+ env,
15
+ stdio: ['pipe', 'pipe', 'pipe'],
16
+ });
17
+ this.process.stdout.on('data', (chunk) => {
18
+ this.buffer += chunk.toString();
19
+ this.processBuffer();
20
+ });
21
+ this.process.stderr.on('data', (chunk) => {
22
+ // MCP servers may log to stderr — ignore
23
+ });
24
+ this.process.on('error', (err) => {
25
+ for (const [, p] of this.pending) {
26
+ p.reject(new Error(`MCP server "${serverName}" process error: ${err.message}`));
27
+ }
28
+ this.pending.clear();
29
+ });
30
+ this.process.on('exit', () => {
31
+ for (const [, p] of this.pending) {
32
+ p.reject(new Error(`MCP server "${serverName}" exited unexpectedly`));
33
+ }
34
+ this.pending.clear();
35
+ });
36
+ }
37
+ processBuffer() {
38
+ const lines = this.buffer.split('\n');
39
+ this.buffer = lines.pop() || '';
40
+ for (const line of lines) {
41
+ const trimmed = line.trim();
42
+ if (!trimmed)
43
+ continue;
44
+ try {
45
+ const msg = JSON.parse(trimmed);
46
+ if (msg.id !== undefined && this.pending.has(msg.id)) {
47
+ const p = this.pending.get(msg.id);
48
+ this.pending.delete(msg.id);
49
+ if (msg.error) {
50
+ p.reject(new Error(msg.error.message));
51
+ }
52
+ else {
53
+ p.resolve(msg.result);
54
+ }
55
+ }
56
+ }
57
+ catch {
58
+ // Not valid JSON — skip
59
+ }
60
+ }
61
+ }
62
+ send(method, params) {
63
+ return new Promise((resolve, reject) => {
64
+ const id = this.nextId++;
65
+ const req = { jsonrpc: '2.0', id, method, params };
66
+ this.pending.set(id, { resolve, reject });
67
+ this.process.stdin.write(JSON.stringify(req) + '\n');
68
+ setTimeout(() => {
69
+ if (this.pending.has(id)) {
70
+ this.pending.delete(id);
71
+ reject(new Error(`MCP server "${this.serverName}" timed out on ${method}`));
72
+ }
73
+ }, 30_000);
74
+ });
75
+ }
76
+ async initialize() {
77
+ await this.send('initialize', {
78
+ protocolVersion: '2024-11-05',
79
+ capabilities: {},
80
+ clientInfo: { name: 'ptkl-kortex', version: '1.0.0' },
81
+ });
82
+ await this.send('notifications/initialized');
83
+ }
84
+ async listTools() {
85
+ const result = await this.send('tools/list');
86
+ return result?.tools || [];
87
+ }
88
+ async callTool(name, args) {
89
+ const result = await this.send('tools/call', { name, arguments: args });
90
+ if (result?.content) {
91
+ return result.content
92
+ .map((c) => c.text || JSON.stringify(c))
93
+ .join('\n');
94
+ }
95
+ return JSON.stringify(result);
96
+ }
97
+ close() {
98
+ this.process.kill();
99
+ }
100
+ }
101
+ export class MCPManager {
102
+ connections = new Map();
103
+ toolToServer = new Map();
104
+ async loadConfig(cwd) {
105
+ const configPaths = [
106
+ resolve(cwd, '.kortex.json'),
107
+ resolve(cwd, '.ptkl/kortex.json'),
108
+ resolve(process.env.HOME || '', '.ptkl/kortex.json'),
109
+ ];
110
+ let config = null;
111
+ for (const p of configPaths) {
112
+ if (existsSync(p)) {
113
+ try {
114
+ config = JSON.parse(readFileSync(p, 'utf-8'));
115
+ break;
116
+ }
117
+ catch {
118
+ // Skip invalid config
119
+ }
120
+ }
121
+ }
122
+ if (!config?.mcp_servers)
123
+ return;
124
+ for (const [name, serverConfig] of Object.entries(config.mcp_servers)) {
125
+ try {
126
+ const conn = new MCPConnection(name, serverConfig);
127
+ await conn.initialize();
128
+ this.connections.set(name, conn);
129
+ }
130
+ catch (err) {
131
+ console.error(` MCP "${name}": failed to connect — ${err.message}`);
132
+ }
133
+ }
134
+ }
135
+ async discoverTools() {
136
+ const tools = [];
137
+ for (const [serverName, conn] of this.connections) {
138
+ try {
139
+ const mcpTools = await conn.listTools();
140
+ for (const t of mcpTools) {
141
+ const qualifiedName = `mcp_${serverName}_${t.name}`;
142
+ this.toolToServer.set(qualifiedName, serverName);
143
+ tools.push({
144
+ type: 'function',
145
+ function: {
146
+ name: qualifiedName,
147
+ description: `[MCP: ${serverName}] ${t.description || t.name}`,
148
+ parameters: t.inputSchema || { type: 'object', properties: {}, required: [] },
149
+ },
150
+ });
151
+ }
152
+ }
153
+ catch (err) {
154
+ console.error(` MCP "${serverName}": failed to list tools — ${err.message}`);
155
+ }
156
+ }
157
+ return tools;
158
+ }
159
+ canHandle(toolName) {
160
+ return this.toolToServer.has(toolName);
161
+ }
162
+ async executeTool(callId, toolName, args) {
163
+ const serverName = this.toolToServer.get(toolName);
164
+ if (!serverName) {
165
+ return { tool_call_id: callId, name: toolName, content: `Error: no MCP server for tool "${toolName}"` };
166
+ }
167
+ const conn = this.connections.get(serverName);
168
+ if (!conn) {
169
+ return { tool_call_id: callId, name: toolName, content: `Error: MCP server "${serverName}" not connected` };
170
+ }
171
+ // Strip the mcp_{server}_ prefix to get the original tool name
172
+ const originalName = toolName.replace(`mcp_${serverName}_`, '');
173
+ try {
174
+ const content = await conn.callTool(originalName, args);
175
+ return { tool_call_id: callId, name: toolName, content };
176
+ }
177
+ catch (err) {
178
+ return { tool_call_id: callId, name: toolName, content: `Error: ${err.message}` };
179
+ }
180
+ }
181
+ get serverCount() {
182
+ return this.connections.size;
183
+ }
184
+ get serverNames() {
185
+ return Array.from(this.connections.keys());
186
+ }
187
+ close() {
188
+ for (const conn of this.connections.values()) {
189
+ conn.close();
190
+ }
191
+ this.connections.clear();
192
+ }
193
+ }