@sontoriyama/mcp-code-mode 0.0.0-stage → 0.4.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,154 @@
1
+ // Generic declarative CLI manifest adapter with anti-flag-injection validation
2
+ // and progressive tool discovery.
3
+ import { readFileSync } from 'node:fs';
4
+ import { basename, resolve } from 'node:path';
5
+ import {
6
+ assertPositiveInt,
7
+ assertRepo,
8
+ execJson,
9
+ execTool,
10
+ SAFE_TOKEN_RE,
11
+ ToolCallError,
12
+ } from './core.mjs';
13
+
14
+ const TOOL_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*$/;
15
+ const PLACEHOLDER_RE = /\{\{([A-Za-z0-9_]+)\}\}/g;
16
+ const RESERVED_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor', 'describe', 'call']);
17
+
18
+ function validateParam(toolName, paramName, spec = {}, rawValue) {
19
+ const value = rawValue === undefined ? spec.default : rawValue;
20
+ if (value === undefined || value === null || value === '') {
21
+ if (spec.required) {
22
+ throw new ToolCallError(toolName, `missing required parameter: ${paramName}`);
23
+ }
24
+ return undefined;
25
+ }
26
+
27
+ const type = spec.type ?? 'string';
28
+ if (type === 'int') {
29
+ return String(assertPositiveInt(toolName, paramName, value));
30
+ }
31
+ if (type === 'repo') {
32
+ return assertRepo(toolName, value);
33
+ }
34
+ if (type === 'safeToken') {
35
+ if (typeof value !== 'string' || !SAFE_TOKEN_RE.test(value)) {
36
+ throw new ToolCallError(toolName, `${paramName} must be a safe non-flag token`);
37
+ }
38
+ return value;
39
+ }
40
+ if (type === 'enum') {
41
+ const allowed = Array.isArray(spec.values) ? spec.values : [];
42
+ if (typeof value !== 'string' || !allowed.includes(value)) {
43
+ throw new ToolCallError(toolName, `${paramName} must be one of: ${allowed.join(', ')}`);
44
+ }
45
+ return value;
46
+ }
47
+
48
+ // Default: string (rejects leading '-' unless spec.allowFlag === true)
49
+ const str = String(value);
50
+ if (str.length === 0) {
51
+ if (spec.required) throw new ToolCallError(toolName, `${paramName} must be non-empty`);
52
+ return undefined;
53
+ }
54
+ if (spec.allowFlag !== true && str.startsWith('-')) {
55
+ throw new ToolCallError(toolName, `${paramName} must not start with '-' (flag injection blocked)`);
56
+ }
57
+ return str;
58
+ }
59
+
60
+ function resolveArgv(toolName, argTemplates, paramsSpec, input = {}) {
61
+ const validated = {};
62
+ for (const [paramName, spec] of Object.entries(paramsSpec ?? {})) {
63
+ validated[paramName] = validateParam(toolName, paramName, spec, input?.[paramName]);
64
+ }
65
+
66
+ const argv = [];
67
+ for (const template of argTemplates) {
68
+ if (typeof template !== 'string') {
69
+ throw new ToolCallError(toolName, 'manifest args must be strings');
70
+ }
71
+ // Whole-argument placeholder: omit arg if optional param is undefined
72
+ const exactMatch = /^\{\{([A-Za-z0-9_]+)\}\}$/.exec(template);
73
+ if (exactMatch) {
74
+ const key = exactMatch[1];
75
+ if (!(key in validated)) {
76
+ validated[key] = validateParam(toolName, key, { type: 'string', required: true }, input?.[key]);
77
+ }
78
+ if (validated[key] !== undefined) argv.push(validated[key]);
79
+ continue;
80
+ }
81
+
82
+ let missingOptional = false;
83
+ const expanded = template.replace(PLACEHOLDER_RE, (_m, key) => {
84
+ if (!(key in validated)) {
85
+ validated[key] = validateParam(toolName, key, { type: 'string', required: true }, input?.[key]);
86
+ }
87
+ if (validated[key] === undefined) {
88
+ missingOptional = true;
89
+ return '';
90
+ }
91
+ return validated[key];
92
+ });
93
+ if (!missingOptional) argv.push(expanded);
94
+ }
95
+ return argv;
96
+ }
97
+
98
+ export function createManifestTools(manifest, sourceLabel = 'manifest') {
99
+ if (!manifest || typeof manifest !== 'object' || !manifest.tools || typeof manifest.tools !== 'object') {
100
+ throw new Error('manifest must be an object with a "tools" map');
101
+ }
102
+
103
+ const flat = new Map();
104
+ const catalog = [];
105
+
106
+ for (const [name, def] of Object.entries(manifest.tools)) {
107
+ if (!TOOL_NAME_RE.test(name)) {
108
+ throw new Error(`invalid manifest tool name: ${name}`);
109
+ }
110
+ const segments = name.split('.');
111
+ if (segments.some((s) => RESERVED_SEGMENTS.has(s))) {
112
+ throw new Error(`reserved segment in manifest tool name: ${name}`);
113
+ }
114
+ if (!def || typeof def.cmd !== 'string' || def.cmd.trim().length === 0) {
115
+ throw new Error(`manifest tool "${name}" must specify a non-empty "cmd"`);
116
+ }
117
+ const argTemplates = Array.isArray(def.args) ? def.args : [];
118
+ const parse = def.parse === 'json' ? 'json' : 'text';
119
+ const timeout = Number.isInteger(def.timeout) && def.timeout > 0 ? def.timeout : 180000;
120
+ const paramsSpec = def.params && typeof def.params === 'object' ? def.params : {};
121
+
122
+ const fn = async (input = {}, opts) => {
123
+ const signal = opts?.signal;
124
+ const argv = resolveArgv(name, argTemplates, paramsSpec, input);
125
+ if (parse === 'json') {
126
+ return execJson(name, def.cmd, argv, { timeout, signal });
127
+ }
128
+ return (await execTool(name, def.cmd, argv, { timeout, signal })).trim();
129
+ };
130
+
131
+ flat.set(name, fn);
132
+ catalog.push({
133
+ name,
134
+ source: sourceLabel,
135
+ description: typeof def.description === 'string' ? def.description : `Run ${def.cmd}`,
136
+ params: Object.fromEntries(
137
+ Object.entries(paramsSpec).map(([k, spec]) => [
138
+ k,
139
+ `${spec.type ?? 'string'}${spec.required ? ' (required)' : spec.default !== undefined ? ` (default: ${spec.default})` : ' (optional)'}`,
140
+ ]),
141
+ ),
142
+ parse,
143
+ });
144
+ }
145
+
146
+ return { flat, catalog };
147
+ }
148
+
149
+ export function loadManifest(manifestPath) {
150
+ const fullPath = resolve(manifestPath);
151
+ const raw = readFileSync(fullPath, 'utf8');
152
+ const parsed = JSON.parse(raw);
153
+ return createManifestTools(parsed, `manifest:${basename(fullPath)}`);
154
+ }