@causyne/agent 1.20.36 → 1.20.39

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.
Files changed (51) hide show
  1. package/LICENSE +1 -1
  2. package/package.json +1 -1
  3. package/src/decisionPolicy.js +1 -1
  4. package/src/decisionPolicy.ts +1 -1
  5. package/src/plugins/pluginsFactory.js +4 -0
  6. package/src/plugins/pluginsFactory.ts +6 -0
  7. package/src/pluginsFactory/costEstimate.js +89 -0
  8. package/src/pluginsFactory/costEstimate.ts +110 -0
  9. package/src/pluginsFactory/discovery.js +97 -0
  10. package/src/pluginsFactory/discovery.ts +114 -0
  11. package/src/pluginsFactory/index.js +9 -0
  12. package/src/pluginsFactory/index.ts +11 -0
  13. package/src/pluginsFactory/pluginsFactory.js +250 -0
  14. package/src/pluginsFactory/pluginsFactory.ts +302 -0
  15. package/src/pluginsFactory/strategy.js +93 -0
  16. package/src/pluginsFactory/strategy.ts +106 -0
  17. package/src/pluginsFactory/templates.js +592 -0
  18. package/src/pluginsFactory/templates.ts +631 -0
  19. package/src/pluginsFactory/types.js +12 -0
  20. package/src/pluginsFactory/types.ts +107 -0
  21. package/src/stallGuard.js +1 -0
  22. package/src/stallGuard.ts +1 -0
  23. package/src/toolPacks.js +1 -0
  24. package/src/toolPacks.ts +1 -0
  25. package/src/tools/pluginsFactory.js +202 -0
  26. package/src/tools/pluginsFactory.ts +246 -0
  27. package/src/tools/registry.js +2 -1
  28. package/src/tools/sysRun.js +22 -6
  29. package/src/tools/sysRun.ts +23 -6
  30. package/src/toolsList.js +1 -0
  31. package/src/toolsList.ts +1 -0
  32. package/src/tui/chatRenderer.js +5 -4
  33. package/src/tui/homeView.js +0 -1
  34. package/src/tui/homeView.ts +0 -1
  35. package/src/tui/markdownMath.js +250 -0
  36. package/src/tui/markdownMath.ts +263 -0
  37. package/src/tui/messageActionPlacement.js +79 -8
  38. package/src/tui/messageActionPlacement.ts +102 -9
  39. package/src/tui/messageInteraction.js +43 -9
  40. package/src/tui/messageInteraction.ts +51 -17
  41. package/src/tui/overlay.js +191 -192
  42. package/src/tui/overlay.ts +320 -0
  43. package/src/tui/prompt.js +4 -1
  44. package/src/tui/stageSurface.js +4 -1
  45. package/src/tui/text.js +204 -208
  46. package/src/tui/text.ts +360 -0
  47. package/src/tui/toolOutputNormalizer.js +3 -1
  48. package/src/tui/toolOutputNormalizer.ts +3 -1
  49. package/src/tui/turnRail.js +11 -1
  50. package/src/tui/turnRail.ts +11 -1
  51. package/src/tui/text.d.ts +0 -7
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Route Selection Strategy for PluginsFactory.
3
+ *
4
+ * Implements deterministic route assessment prioritizing token efficiency and cost:
5
+ * 1. Check existing coverage: Built-in tools, installed plugins, configured MCP servers.
6
+ * 2. Honor explicit user preference immediately without unnecessary friction.
7
+ * 3. Route 1: Native Plugin (HTTP/CLI) - Leanest token footprint, lowest cost.
8
+ * 4. Route 2: Python Bridge - Lightweight on-demand buffer for Python-only libraries.
9
+ * 5. Route 3: MCP Server - Used when service is MCP-only or user explicitly requests it.
10
+ */
11
+
12
+ import { estimateServiceCosts, formatMcpDisclosure } from './costEstimate.js';
13
+ import { findExistingCapability } from './discovery.js';
14
+ import type { FactoryRouteProposal, RouteKind, ServiceDescriptor } from './types.js';
15
+
16
+ const PYTHON_KEYWORDS = [
17
+ 'python',
18
+ 'scipy',
19
+ 'numpy',
20
+ 'pandas',
21
+ 'torch',
22
+ 'pytorch',
23
+ 'tensorflow',
24
+ 'keras',
25
+ 'blender',
26
+ 'resolve',
27
+ 'bpy',
28
+ 'da_vinci',
29
+ 'sympy',
30
+ 'nltk',
31
+ 'spacy',
32
+ 'huggingface'
33
+ ];
34
+
35
+ function isPythonSpecific(service: ServiceDescriptor): boolean {
36
+ if (service.serviceKind === 'python_sdk') return true;
37
+ if (service.pythonModule && service.pythonModule.trim()) return true;
38
+ const nameLower = service.name.toLowerCase();
39
+ const descLower = (service.description || '').toLowerCase();
40
+ return PYTHON_KEYWORDS.some(kw => nameLower.includes(kw) || descLower.includes(kw));
41
+ }
42
+
43
+ export function assessRoute(
44
+ service: ServiceDescriptor,
45
+ userPreference?: RouteKind
46
+ ): FactoryRouteProposal {
47
+ const costComparison = estimateServiceCosts(service);
48
+ const existingCapability = findExistingCapability(service.name);
49
+
50
+ // 1. User Preference Override
51
+ const chosenRoute = userPreference ?? service.userPreferredRoute;
52
+ if (chosenRoute) {
53
+ const isMcp = chosenRoute === 'mcp_server';
54
+ const proposal: FactoryRouteProposal = {
55
+ service,
56
+ recommendedRoute: chosenRoute,
57
+ reason: `Honoring user explicit preference for route '${chosenRoute}'.`,
58
+ costComparison,
59
+ userConsentRequired: false,
60
+ userConfirmedRoute: chosenRoute,
61
+ existingCapability: existingCapability.covered ? existingCapability : undefined
62
+ };
63
+ if (isMcp) {
64
+ proposal.mcpDisclosure = formatMcpDisclosure(service.name, costComparison);
65
+ }
66
+ return proposal;
67
+ }
68
+
69
+ // 2. Python SDK Route (Bridge Buffer)
70
+ if (isPythonSpecific(service)) {
71
+ return {
72
+ service,
73
+ recommendedRoute: 'python_bridge',
74
+ reason:
75
+ 'Service depends on Python SDK or specialized scientific/creative modules. A Python bridge provides an on-demand subprocess buffer without full MCP overhead.',
76
+ costComparison,
77
+ userConsentRequired: false,
78
+ existingCapability: existingCapability.covered ? existingCapability : undefined
79
+ };
80
+ }
81
+
82
+ // 3. MCP-Only Service Route
83
+ if (service.serviceKind === 'mcp_only') {
84
+ return {
85
+ service,
86
+ recommendedRoute: 'mcp_server',
87
+ reason:
88
+ 'Service exclusively exposes an MCP endpoint or protocol. Recommending MCP server scaffold with token overhead disclosure.',
89
+ costComparison,
90
+ mcpDisclosure: formatMcpDisclosure(service.name, costComparison),
91
+ userConsentRequired: true,
92
+ existingCapability: existingCapability.covered ? existingCapability : undefined
93
+ };
94
+ }
95
+
96
+ // 4. Default / Native Plugin Route (HTTP API or CLI)
97
+ return {
98
+ service,
99
+ recommendedRoute: 'native_plugin',
100
+ reason:
101
+ 'Service supports HTTP/REST API or CLI interface. Native plugin is selected as the most token-lean and cost-effective route.',
102
+ costComparison,
103
+ userConsentRequired: false,
104
+ existingCapability: existingCapability.covered ? existingCapability : undefined
105
+ };
106
+ }
@@ -0,0 +1,592 @@
1
+ /**
2
+ * Code and Manifest Templates for PluginsFactory.
3
+ *
4
+ * Scaffolds production-grade, secure implementations for:
5
+ * 1. Native HTTP Plugin (Leanest, zero daemon overhead)
6
+ * 2. Native CLI Plugin (Subprocess wrapper)
7
+ * 3. Python Bridge Plugin (Lightweight JSON stdio bridge for Python libraries)
8
+ * 4. Stdio MCP Server (Zero-dependency JSON-RPC 2.0 stdio daemon)
9
+ */
10
+ function sanitizeIdentifier(name) {
11
+ return name.replace(/[^a-zA-Z0-9_]/g, '_');
12
+ }
13
+ /**
14
+ * Generates scaffold files for a Native HTTP Plugin.
15
+ */
16
+ export function generateHttpPluginScaffold(service) {
17
+ const capabilities = Array.from(new Set(['network', ...(service.capabilities || [])]));
18
+ const primaryTool = service.tools[0] || {
19
+ name: 'query',
20
+ description: `Execute request against ${service.name}`,
21
+ parameters: { type: 'object', properties: {} }
22
+ };
23
+ const manifest = {
24
+ schemaVersion: 1,
25
+ name: service.name,
26
+ version: '1.0.0',
27
+ description: service.description || `Native HTTP plugin for ${service.name}`,
28
+ capabilities,
29
+ tools: service.tools.map(tool => ({
30
+ name: tool.name,
31
+ description: tool.description,
32
+ parameters: tool.parameters,
33
+ entry: 'index.js',
34
+ export: tool.name === primaryTool.name ? 'execute' : tool.name,
35
+ timeoutMs: 30000
36
+ }))
37
+ };
38
+ const toolExecutors = service.tools.map(tool => {
39
+ const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
40
+ const httpMethod = tool.httpMethod || 'POST';
41
+ const httpPath = tool.httpPath || '/';
42
+ return `
43
+ /**
44
+ * ${tool.description}
45
+ */
46
+ export async function ${fnName}(args = {}, context = {}) {
47
+ const endpoint = ${JSON.stringify(service.endpoint || 'https://api.example.com')};
48
+ const url = new URL(${JSON.stringify(httpPath)}, endpoint).toString();
49
+ const authHeader = ${service.authEnvVar
50
+ ? `process.env[${JSON.stringify(service.authEnvVar)}] ? \`Bearer \${process.env[${JSON.stringify(service.authEnvVar)}]}\` : undefined`
51
+ : 'undefined'};
52
+
53
+ const headers = {
54
+ 'Accept': 'application/json',
55
+ 'Content-Type': 'application/json'
56
+ };
57
+ if (authHeader) headers['Authorization'] = authHeader;
58
+
59
+ try {
60
+ const response = await fetch(url, {
61
+ method: ${JSON.stringify(httpMethod)},
62
+ headers,
63
+ body: ${httpMethod !== 'GET' ? 'JSON.stringify(args)' : 'undefined'}
64
+ });
65
+
66
+ if (!response.ok) {
67
+ const errorText = await response.text();
68
+ return {
69
+ success: false,
70
+ status: response.status,
71
+ error: \`HTTP \${response.status}: \${errorText.slice(0, 500)}\`
72
+ };
73
+ }
74
+
75
+ const data = await response.json().catch(() => ({}));
76
+ return {
77
+ success: true,
78
+ data
79
+ };
80
+ } catch (err) {
81
+ return {
82
+ success: false,
83
+ error: err instanceof Error ? err.message : String(err)
84
+ };
85
+ }
86
+ }
87
+ `;
88
+ }).join('\n');
89
+ const indexJs = `// Native HTTP plugin for ${service.name}
90
+ // Auto-generated by Causyne PluginsFactory
91
+
92
+ ${toolExecutors}
93
+ `;
94
+ const readmeMd = `# ${service.name} Plugin
95
+
96
+ ${service.description}
97
+
98
+ ## Route Information
99
+ - **Kind**: Native HTTP Plugin (Token-lean, on-demand execution)
100
+ - **Capabilities Required**: \`${capabilities.join(', ')}\`
101
+ ${service.authEnvVar ? `- **Environment Variable**: Set \`${service.authEnvVar}\` for authentication.` : ''}
102
+
103
+ ## Security & Activation
104
+ By default, this plugin is created in a **disabled** state to allow code review.
105
+ To activate after reviewing the code:
106
+ \`\`\`bash
107
+ causyne plugins enable ${service.name}
108
+ \`\`\`
109
+ `;
110
+ return {
111
+ entryPoint: 'index.js',
112
+ files: [
113
+ { relativePath: 'plugin.json', content: JSON.stringify(manifest, null, 2) + '\n' },
114
+ { relativePath: 'index.js', content: indexJs },
115
+ { relativePath: 'README.md', content: readmeMd }
116
+ ]
117
+ };
118
+ }
119
+ /**
120
+ * Generates scaffold files for a Native CLI Wrapper Plugin.
121
+ */
122
+ export function generateCliPluginScaffold(service) {
123
+ const capabilities = Array.from(new Set(['subprocess', ...(service.capabilities || [])]));
124
+ const primaryTool = service.tools[0] || {
125
+ name: 'run',
126
+ description: `Execute command for ${service.name}`,
127
+ parameters: { type: 'object', properties: {} }
128
+ };
129
+ const manifest = {
130
+ schemaVersion: 1,
131
+ name: service.name,
132
+ version: '1.0.0',
133
+ description: service.description || `Native CLI plugin for ${service.name}`,
134
+ capabilities,
135
+ tools: service.tools.map(tool => ({
136
+ name: tool.name,
137
+ description: tool.description,
138
+ parameters: tool.parameters,
139
+ entry: 'index.js',
140
+ export: tool.name === primaryTool.name ? 'execute' : tool.name,
141
+ timeoutMs: 45000
142
+ }))
143
+ };
144
+ const toolExecutors = service.tools.map(tool => {
145
+ const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
146
+ const binary = service.cliBinary || service.name;
147
+ const subcommand = tool.cliSubcommand ? ` ${tool.cliSubcommand}` : '';
148
+ return `
149
+ /**
150
+ * ${tool.description}
151
+ */
152
+ export async function ${fnName}(args = {}, context = {}) {
153
+ const { execFile } = await import('node:child_process');
154
+ const { promisify } = await import('node:util');
155
+ const execFileAsync = promisify(execFile);
156
+
157
+ const bin = ${JSON.stringify(binary)};
158
+ const cliArgs = [];
159
+ ${tool.cliSubcommand ? `cliArgs.push(${JSON.stringify(tool.cliSubcommand)});` : ''}
160
+
161
+ for (const [key, val] of Object.entries(args)) {
162
+ if (val === true) cliArgs.push(\`--\${key}\`);
163
+ else if (val !== false && val !== null && val !== undefined) {
164
+ cliArgs.push(\`--\${key}\`, String(val));
165
+ }
166
+ }
167
+
168
+ try {
169
+ const { stdout, stderr } = await execFileAsync(bin, cliArgs, {
170
+ timeout: 40000,
171
+ maxBuffer: 1024 * 1024,
172
+ cwd: context.workspaceRoot || process.cwd()
173
+ });
174
+
175
+ return {
176
+ success: true,
177
+ stdout: stdout.trim(),
178
+ stderr: stderr.trim()
179
+ };
180
+ } catch (err) {
181
+ return {
182
+ success: false,
183
+ error: err instanceof Error ? err.message : String(err)
184
+ };
185
+ }
186
+ }
187
+ `;
188
+ }).join('\n');
189
+ const indexJs = `// Native CLI wrapper plugin for ${service.name}
190
+ // Auto-generated by Causyne PluginsFactory
191
+
192
+ ${toolExecutors}
193
+ `;
194
+ const readmeMd = `# ${service.name} CLI Plugin
195
+
196
+ ${service.description}
197
+
198
+ ## Route Information
199
+ - **Kind**: Native CLI Plugin (Subprocess wrapper)
200
+ - **Binary**: \`${service.cliBinary || service.name}\`
201
+ - **Capabilities Required**: \`${capabilities.join(', ')}\`
202
+
203
+ ## Security & Activation
204
+ This plugin is created disabled. After verifying the source code:
205
+ \`\`\`bash
206
+ causyne plugins enable ${service.name}
207
+ \`\`\`
208
+ `;
209
+ return {
210
+ entryPoint: 'index.js',
211
+ files: [
212
+ { relativePath: 'plugin.json', content: JSON.stringify(manifest, null, 2) + '\n' },
213
+ { relativePath: 'index.js', content: indexJs },
214
+ { relativePath: 'README.md', content: readmeMd }
215
+ ]
216
+ };
217
+ }
218
+ /**
219
+ * Generates scaffold files for a Python Bridge Plugin.
220
+ * Uses a Node runner with subprocess capability piping JSON stdin/stdout to bridge.py.
221
+ */
222
+ export function generatePythonBridgeScaffold(service) {
223
+ const capabilities = Array.from(new Set(['subprocess', ...(service.capabilities || [])]));
224
+ const primaryTool = service.tools[0] || {
225
+ name: 'run_python',
226
+ description: `Execute Python workflow for ${service.name}`,
227
+ parameters: { type: 'object', properties: {} }
228
+ };
229
+ const manifest = {
230
+ schemaVersion: 1,
231
+ name: service.name,
232
+ version: '1.0.0',
233
+ description: service.description || `Python bridge plugin for ${service.name}`,
234
+ capabilities,
235
+ tools: service.tools.map(tool => ({
236
+ name: tool.name,
237
+ description: tool.description,
238
+ parameters: tool.parameters,
239
+ entry: 'index.js',
240
+ export: tool.name === primaryTool.name ? 'execute' : tool.name,
241
+ timeoutMs: 60000
242
+ }))
243
+ };
244
+ const toolExecutors = service.tools.map(tool => {
245
+ const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
246
+ const pythonMethod = tool.pythonMethod || tool.name;
247
+ return `
248
+ /**
249
+ * ${tool.description}
250
+ */
251
+ export async function ${fnName}(args = {}, context = {}) {
252
+ return invokePythonBridge(${JSON.stringify(pythonMethod)}, args, context);
253
+ }
254
+ `;
255
+ }).join('\n');
256
+ const indexJs = `// Python bridge wrapper for ${service.name}
257
+ // Auto-generated by Causyne PluginsFactory
258
+
259
+ import { spawn } from 'node:child_process';
260
+ import path from 'node:path';
261
+ import { fileURLToPath } from 'node:url';
262
+
263
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
264
+ const BRIDGE_SCRIPT = path.join(__dirname, 'bridge.py');
265
+
266
+ async function invokePythonBridge(action, args, context) {
267
+ const payload = JSON.stringify({
268
+ action,
269
+ args: args || {},
270
+ context: {
271
+ workspaceRoot: context.workspaceRoot || process.cwd()
272
+ }
273
+ });
274
+
275
+ return new Promise((resolve) => {
276
+ const child = spawn('python3', [BRIDGE_SCRIPT], {
277
+ stdio: ['pipe', 'pipe', 'pipe'],
278
+ env: { ...process.env, PYTHONUNBUFFERED: '1' }
279
+ });
280
+
281
+ let stdout = '';
282
+ let stderr = '';
283
+ let settled = false;
284
+
285
+ const finish = (val) => {
286
+ if (settled) return;
287
+ settled = true;
288
+ clearTimeout(timer);
289
+ resolve(val);
290
+ };
291
+
292
+ const timer = setTimeout(() => {
293
+ child.kill('SIGTERM');
294
+ finish({ success: false, error: 'Python bridge timed out after 55 seconds' });
295
+ }, 55000);
296
+
297
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
298
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
299
+
300
+ child.on('error', (err) => {
301
+ finish({
302
+ success: false,
303
+ error: \`Failed to spawn python3: \${err.message}. Ensure python3 is installed and in PATH.\`
304
+ });
305
+ });
306
+
307
+ child.on('close', (code) => {
308
+ if (code !== 0 && !stdout.trim()) {
309
+ finish({
310
+ success: false,
311
+ exitCode: code,
312
+ error: stderr.trim() || \`Python bridge exited with code \${code}\`
313
+ });
314
+ return;
315
+ }
316
+
317
+ try {
318
+ const parsed = JSON.parse(stdout.trim());
319
+ finish(parsed);
320
+ } catch (parseErr) {
321
+ finish({
322
+ success: code === 0,
323
+ rawOutput: stdout.trim(),
324
+ stderr: stderr.trim(),
325
+ parseError: parseErr.message
326
+ });
327
+ }
328
+ });
329
+
330
+ child.stdin.write(payload);
331
+ child.stdin.end();
332
+ });
333
+ }
334
+
335
+ ${toolExecutors}
336
+ `;
337
+ const pythonModule = service.pythonModule || service.name;
338
+ const bridgePy = `#!/usr/bin/env python3
339
+ # -*- coding: utf-8 -*-
340
+ """
341
+ Python Bridge for ${service.name}
342
+ Auto-generated by Causyne PluginsFactory
343
+
344
+ Communicates with Causyne Agent via JSON on stdin/stdout.
345
+ Provides on-demand buffer for ${pythonModule}.
346
+ """
347
+
348
+ import sys
349
+ import json
350
+ import traceback
351
+
352
+ def handle_request(payload):
353
+ action = payload.get("action", "")
354
+ args = payload.get("args", {})
355
+ context = payload.get("context", {})
356
+
357
+ # Dispatched action handler
358
+ try:
359
+ # Example: Import target python library safely
360
+ # import ${pythonModule}
361
+
362
+ result = {
363
+ "action": action,
364
+ "processed": True,
365
+ "args_echo": args,
366
+ "message": f"Successfully executed {action} via Python bridge."
367
+ }
368
+ return {"success": True, "result": result}
369
+ except Exception as exc:
370
+ return {
371
+ "success": False,
372
+ "error": str(exc),
373
+ "traceback": traceback.format_exc()
374
+ }
375
+
376
+ def main():
377
+ try:
378
+ raw_input = sys.stdin.read()
379
+ if not raw_input.strip():
380
+ payload = {}
381
+ else:
382
+ payload = json.loads(raw_input)
383
+
384
+ response = handle_request(payload)
385
+ print(json.dumps(response))
386
+ sys.stdout.flush()
387
+ except Exception as exc:
388
+ print(json.dumps({
389
+ "success": False,
390
+ "error": f"Fatal bridge exception: {str(exc)}",
391
+ "traceback": traceback.format_exc()
392
+ }))
393
+ sys.stdout.flush()
394
+ sys.exit(1)
395
+
396
+ if __name__ == "__main__":
397
+ main()
398
+ `;
399
+ const readmeMd = `# ${service.name} Python Bridge Plugin
400
+
401
+ ${service.description}
402
+
403
+ ## Route Information
404
+ - **Kind**: Python Bridge (Subprocess JSON buffer)
405
+ - **Python Module**: \`${pythonModule}\`
406
+ - **Capabilities Required**: \`${capabilities.join(', ')}\`
407
+
408
+ ## Prerequisites
409
+ Ensure Python 3 is installed:
410
+ \`\`\`bash
411
+ python3 --version
412
+ \`\`\`
413
+
414
+ ## Security & Activation
415
+ This plugin is created disabled. Review the code in \`bridge.py\` and \`index.js\`, then enable:
416
+ \`\`\`bash
417
+ causyne plugins enable ${service.name}
418
+ \`\`\`
419
+ `;
420
+ return {
421
+ entryPoint: 'index.js',
422
+ files: [
423
+ { relativePath: 'plugin.json', content: JSON.stringify(manifest, null, 2) + '\n' },
424
+ { relativePath: 'index.js', content: indexJs },
425
+ { relativePath: 'bridge.py', content: bridgePy },
426
+ { relativePath: 'README.md', content: readmeMd }
427
+ ]
428
+ };
429
+ }
430
+ /**
431
+ * Generates scaffold files for a standalone Stdio MCP Server.
432
+ * Lightweight, zero-external-dependency JSON-RPC 2.0 stdio server.
433
+ */
434
+ export function generateMcpServerScaffold(service) {
435
+ const serverName = `mcp-server-${service.name}`;
436
+ const packageJson = {
437
+ name: serverName,
438
+ version: '1.0.0',
439
+ type: 'module',
440
+ description: service.description || `MCP Server for ${service.name}`,
441
+ main: 'server.js',
442
+ scripts: {
443
+ start: 'node server.js'
444
+ }
445
+ };
446
+ const toolsListJson = JSON.stringify(service.tools.map(tool => ({
447
+ name: tool.name,
448
+ description: tool.description,
449
+ inputSchema: tool.parameters
450
+ })), null, 2);
451
+ const serverJs = `#!/usr/bin/env node
452
+ // MCP Server for ${service.name}
453
+ // Protocol: Model Context Protocol (JSON-RPC 2.0 stdio)
454
+ // Auto-generated by Causyne PluginsFactory
455
+
456
+ import readline from 'node:readline';
457
+
458
+ const TOOLS = ${toolsListJson};
459
+
460
+ const rl = readline.createInterface({
461
+ input: process.stdin,
462
+ output: process.stdout,
463
+ terminal: false
464
+ });
465
+
466
+ function send(message) {
467
+ process.stdout.write(JSON.stringify(message) + '\\n');
468
+ }
469
+
470
+ function handleRequest(request) {
471
+ const { id, method, params } = request;
472
+
473
+ switch (method) {
474
+ case 'initialize':
475
+ return {
476
+ id,
477
+ jsonrpc: '2.0',
478
+ result: {
479
+ protocolVersion: '2024-11-05',
480
+ capabilities: { tools: {} },
481
+ serverInfo: {
482
+ name: ${JSON.stringify(serverName)},
483
+ version: '1.0.0'
484
+ }
485
+ }
486
+ };
487
+
488
+ case 'notifications/initialized':
489
+ return null;
490
+
491
+ case 'ping':
492
+ return { id, jsonrpc: '2.0', result: {} };
493
+
494
+ case 'tools/list':
495
+ return {
496
+ id,
497
+ jsonrpc: '2.0',
498
+ result: { tools: TOOLS }
499
+ };
500
+
501
+ case 'tools/call': {
502
+ const toolName = params?.name;
503
+ const toolArgs = params?.arguments || {};
504
+ const found = TOOLS.find(t => t.name === toolName);
505
+
506
+ if (!found) {
507
+ return {
508
+ id,
509
+ jsonrpc: '2.0',
510
+ error: { code: -32601, message: \`Tool '\${toolName}' not found\` }
511
+ };
512
+ }
513
+
514
+ // Execute tool logic
515
+ const resultData = {
516
+ tool: toolName,
517
+ success: true,
518
+ echo: toolArgs,
519
+ timestamp: new Date().toISOString()
520
+ };
521
+
522
+ return {
523
+ id,
524
+ jsonrpc: '2.0',
525
+ result: {
526
+ content: [
527
+ {
528
+ type: 'text',
529
+ text: JSON.stringify(resultData, null, 2)
530
+ }
531
+ ]
532
+ }
533
+ };
534
+ }
535
+
536
+ default:
537
+ if (id !== undefined) {
538
+ return {
539
+ id,
540
+ jsonrpc: '2.0',
541
+ error: { code: -32601, message: \`Method '\${method}' not supported\` }
542
+ };
543
+ }
544
+ return null;
545
+ }
546
+ }
547
+
548
+ rl.on('line', (line) => {
549
+ const trimmed = line.trim();
550
+ if (!trimmed) return;
551
+ try {
552
+ const request = JSON.parse(trimmed);
553
+ const response = handleRequest(request);
554
+ if (response) send(response);
555
+ } catch (err) {
556
+ send({
557
+ jsonrpc: '2.0',
558
+ id: null,
559
+ error: { code: -32700, message: 'Parse error: ' + String(err) }
560
+ });
561
+ }
562
+ });
563
+ `;
564
+ const readmeMd = `# ${serverName}
565
+
566
+ ${service.description}
567
+
568
+ ## Route Information
569
+ - **Kind**: Model Context Protocol (MCP) stdio Server
570
+ - **Protocol**: JSON-RPC 2.0 over standard I/O
571
+ - **Tools Supported**: ${service.tools.map(t => t.name).join(', ')}
572
+
573
+ ## Token Footprint Note
574
+ MCP servers consume additional tokens per turn due to persistent JSON-RPC schema envelopes.
575
+ Where feasible, prefer native plugins or Python bridges for higher token efficiency.
576
+
577
+ ## Registration & Grant
578
+ In Causyne Agent, register and review this server:
579
+ \`\`\`bash
580
+ causyne mcp add ${service.name} node ~/.causyne/mcp-servers/${service.name}/server.js
581
+ causyne mcp grant ${service.name}
582
+ \`\`\`
583
+ `;
584
+ return {
585
+ entryPoint: 'server.js',
586
+ files: [
587
+ { relativePath: 'package.json', content: JSON.stringify(packageJson, null, 2) + '\n' },
588
+ { relativePath: 'server.js', content: serverJs },
589
+ { relativePath: 'README.md', content: readmeMd }
590
+ ]
591
+ };
592
+ }