hataraku
Version:
An autonomous coding agent for building AI-powered development tools. The name "Hataraku" (働く) means "to work" in Japanese.
253 lines • 9.29 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.McpClient = void 0;
const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
const stdio_js_1 = require("@modelcontextprotocol/sdk/client/stdio.js");
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const chalk_1 = __importDefault(require("chalk"));
class McpClient {
connections = new Map();
initialized = false;
defaultConfigPath;
constructor() {
this.defaultConfigPath = path.join(os.homedir(), '.hataraku', 'mcp_settings.json');
// Bind methods to ensure correct 'this' context
this.disconnectServer = this.disconnectServer.bind(this);
this.connectToServer = this.connectToServer.bind(this);
this.getServerTools = this.getServerTools.bind(this);
this.callTool = this.callTool.bind(this);
}
/**
* Initialize MCP servers using the default config path
*/
async initializeServers() {
if (this.initialized) {
return;
}
try {
const configContent = await fs.readFile(this.defaultConfigPath, 'utf-8');
const config = JSON.parse(configContent);
await this.loadConfig(config);
}
catch (error) {
// If file doesn't exist, create it with empty config
if (error.code === 'ENOENT') {
const defaultConfig = { mcpServers: {} };
await fs.mkdir(path.dirname(this.defaultConfigPath), { recursive: true });
await fs.writeFile(this.defaultConfigPath, JSON.stringify(defaultConfig, null, 2));
await this.loadConfig(defaultConfig);
}
else {
throw error;
}
}
this.initialized = true;
}
/**
* Load configuration from a specific config object
*/
async loadConfig(config) {
// Disconnect existing connections
for (const connection of this.connections.values()) {
await this.disconnectServer(connection.name);
}
// Connect to new servers
for (const [name, serverConfig] of Object.entries(config.mcpServers)) {
await this.connectToServer(name, serverConfig);
}
this.initialized = true;
}
/**
* Load configuration from a specific file path
*/
async loadConfigFromPath(configPath) {
const configContent = await fs.readFile(configPath, 'utf-8');
const config = JSON.parse(configContent);
await this.loadConfig(config);
}
async connectToServer(name, config) {
// Remove existing connection if it exists
await this.disconnectServer(name);
try {
const client = new index_js_1.Client({
name: "Hataraku",
version: "1.0.0",
}, {
capabilities: {},
});
const transport = new stdio_js_1.StdioClientTransport({
command: config.command,
args: config.args,
env: {
...config.env,
...(process.env.PATH ? { PATH: process.env.PATH } : {}),
},
stderr: "pipe",
});
const connection = {
name,
client,
transport,
status: "connecting",
};
// Set up stderr handling
const stderrStream = transport.stderr;
if (stderrStream) {
stderrStream.on("data", (data) => {
const errorOutput = data.toString();
if (connection.error) {
connection.error += '\n' + errorOutput;
}
else {
connection.error = errorOutput;
}
});
}
// Connect to the server
await client.connect(transport);
connection.status = "connected";
connection.error = undefined;
this.connections.set(name, connection);
}
catch (error) {
const connection = this.connections.get(name);
if (connection) {
connection.status = "disconnected";
connection.error = error instanceof Error ? error.message : String(error);
}
throw error;
}
}
/**
* Disconnect from a specific server
*/
async disconnectServer(name) {
const connection = this.connections.get(name);
if (connection) {
try {
await connection.client.close();
}
catch (error) {
console.error(chalk_1.default.red(`Error disconnecting from server ${name}:`, error));
}
this.connections.delete(name);
}
}
/**
* Get list of available server names
*/
getAvailableServers() {
return Array.from(this.connections.values())
.filter(conn => conn.status === 'connected')
.map(conn => conn.name);
}
/**
* Get tools for a specific server
*/
async getServerTools(serverName) {
const connection = this.connections.get(serverName);
if (!connection || connection.status !== 'connected') {
return { serverName, tools: [] };
}
try {
const response = await connection.client.request({ method: "tools/list" }, types_js_1.ListToolsResultSchema);
return {
serverName,
tools: response?.tools?.map(tool => ({
name: tool.name,
description: tool.description || '',
inputSchema: tool.inputSchema,
})) || [],
};
}
catch (error) {
console.error(chalk_1.default.red(`Error fetching tools from server ${serverName}:`, error));
return { serverName, tools: [] };
}
}
/**
* Call a tool on a specific server and parse its response
*/
async callTool(serverName, toolName, args) {
if (!this.initialized) {
throw new Error('MCP servers have not been initialized');
}
const connection = this.connections.get(serverName);
if (!connection) {
throw new Error(`Server "${serverName}" not found`);
}
if (connection.status !== 'connected') {
throw new Error(`Server "${serverName}" is not connected (status: ${connection.status})`);
}
const response = await connection.client.request({
method: "tools/call",
params: {
name: toolName,
arguments: args,
},
}, types_js_1.CallToolResultSchema);
if (response.isError) {
throw new Error(`Tool ${serverName}/${toolName} returned an error`);
}
// Parse the response content
const content = response.content[0]?.text;
if (!content) {
throw new Error(`Tool ${serverName}/${toolName} returned no content`);
}
try {
const data = JSON.parse(content);
return {
data,
raw: response
};
}
catch (error) {
// If the content is not JSON, return the content as a string
return {
data: content,
raw: response
};
}
}
}
exports.McpClient = McpClient;
//# sourceMappingURL=mcp-client.js.map