Repository navigation
Expand file tree
/
Copy pathgenerateToolsDoc.js
More file actions
286 lines (232 loc) · 8.05 KB
/
Copy pathgenerateToolsDoc.js
File metadata and controls
286 lines (232 loc) · 8.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env node
/**
* Generate tools.md documentation from JSON tool definitions
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Path to the definitions directory
const DEFINITIONS_DIR = path.join(__dirname, 'src/server/tools/definitions');
/**
* Load all tool definitions from JSON files
*/
function loadToolDefinitions() {
const toolDefinitions = [];
try {
const files = fs.readdirSync(DEFINITIONS_DIR)
.filter(file => file.endsWith('.json') && !file.startsWith('_'))
.sort();
for (const file of files) {
try {
const filePath = path.join(DEFINITIONS_DIR, file);
const fileContent = fs.readFileSync(filePath, 'utf8');
const toolDefinition = JSON.parse(fileContent);
toolDefinitions.push(toolDefinition);
} catch (error) {
console.warn(`⚠️ Failed to load tool definition from ${file}: ${error.message}`);
}
}
console.log(`📚 Loaded ${toolDefinitions.length} tool definitions`);
} catch (error) {
throw new Error(`Failed to load tool definitions: ${error.message}`);
}
return toolDefinitions;
}
/**
* Group tools by their API category
*/
function groupToolsByCategory(tools) {
const groups = {
'Tables & Records API': [],
'Machines API': [],
'Apps API': [],
'Stations API (Next-Gen)': {
'Interfaces': [],
'Station Groups': [],
'Stations': []
},
'Users API (Next-Gen)': {
'User Roles': [],
'User Groups': [],
'Users': []
},
'Utilities API': []
};
for (const tool of tools) {
const { type, name, category } = tool;
// Categorize based on type and name patterns
if (type === 'table') {
groups['Tables & Records API'].push(tool);
} else if (type === 'machine') {
groups['Machines API'].push(tool);
} else if (type === 'app') {
groups['Apps API'].push(tool);
} else if (type === 'interface') {
groups['Stations API (Next-Gen)']['Interfaces'].push(tool);
} else if (type === 'station-group') {
groups['Stations API (Next-Gen)']['Station Groups'].push(tool);
} else if (type === 'station') {
groups['Stations API (Next-Gen)']['Stations'].push(tool);
} else if (type === 'user') {
if (name.includes('Role')) {
groups['Users API (Next-Gen)']['User Roles'].push(tool);
} else if (name.includes('Group') || name.includes('UserGroups')) {
groups['Users API (Next-Gen)']['User Groups'].push(tool);
} else {
groups['Users API (Next-Gen)']['Users'].push(tool);
}
} else if (type === 'utility') {
groups['Utilities API'].push(tool);
} else {
// Default fallback - add to most appropriate category
if (name.includes('machine') || name.includes('Machine')) {
groups['Machines API'].push(tool);
} else if (name.includes('table') || name.includes('Table')) {
groups['Tables & Records API'].push(tool);
} else {
groups['Utilities API'].push(tool);
}
}
}
return groups;
}
/**
* Format parameter information
*/
function formatParameters(inputSchema) {
if (!inputSchema || !inputSchema.properties) {
return '**Parameters**: None';
}
const { properties, required = [] } = inputSchema;
const params = [];
for (const [name, config] of Object.entries(properties)) {
const isRequired = required.includes(name);
const type = config.type || 'string';
const description = config.description || '';
const requiredText = isRequired ? 'required' : 'optional';
params.push(`- \`${name}\` (${type}, ${requiredText}): ${description}`);
}
return `**Parameters**:\n${params.join('\n')}`;
}
/**
* Generate markdown for a single tool
*/
function generateToolMarkdown(tool) {
const { name, description, url, httpType, dangerous, inputSchema } = tool;
// Add [ADMIN] marker for dangerous operations
const adminMarker = dangerous ? ' [ADMIN]' : '';
// Extract scope from description if present
const scopeMatch = description.match(/Requires `([^`]+)` scope/);
const scope = scopeMatch ? scopeMatch[1] : 'unknown';
// Clean description (remove scope and endpoint info)
let cleanDescription = description
.replace(/\s*Corresponds to [^.]+\.\s*/, '')
.replace(/\s*Requires `[^`]+` scope\.\s*/, '')
.replace(/\s*\[[\w-]+\]\s*$/, '')
.replace(/^⚠️ ADMIN OPERATION ⚠️\s*/, '');
// Convert URL format from :param to {param}
const endpoint = url ? url.replace(/:(\w+)/g, '{$1}') : '';
const parametersSection = formatParameters(inputSchema);
return `#### \`${name}\`${adminMarker}
**Description**: ${cleanDescription}
**Endpoint**: \`${httpType} ${endpoint}\`
**Scope**: \`${scope}\`
${parametersSection}
---`;
}
/**
* Generate markdown for a group of tools
*/
function generateGroupMarkdown(tools, groupName) {
if (Array.isArray(tools)) {
if (tools.length === 0) return '';
let markdown = `## ${groupName}\n\n`;
for (const tool of tools) {
markdown += generateToolMarkdown(tool) + '\n';
}
return markdown;
}
// Handle nested groups (like Stations API)
let markdown = `## ${groupName}\n\n`;
for (const [subGroupName, subTools] of Object.entries(tools)) {
if (subTools.length === 0) continue;
markdown += `### ${subGroupName}\n\n`;
for (const tool of subTools) {
markdown += generateToolMarkdown(tool) + '\n';
}
}
return markdown;
}
/**
* Generate statistics
*/
function generateStatistics(tools) {
const totalTools = tools.length;
const adminOps = tools.filter(t => t.dangerous).length;
const writeOps = tools.filter(t => t.category === 'write').length;
const readOps = tools.filter(t => t.category === 'read-only').length;
// Count by type
const typeCounts = {};
for (const tool of tools) {
const type = tool.type || 'other';
typeCounts[type] = (typeCounts[type] || 0) + 1;
}
return `## Tool Summary
**Total Tools**: ${totalTools}
**Categories**:
- **Read Operations**: ${readOps} tools
- **Write Operations**: ${writeOps} tools
- **Admin Operations**: ${adminOps} tools
**API Types**:
- **Tables & Records**: ${typeCounts.table || 0} tools
- **Stations & Interfaces**: ${(typeCounts.station || 0) + (typeCounts.interface || 0) + (typeCounts['station-group'] || 0)} tools
- **Users & Access Control**: ${typeCounts.user || 0} tools
- **Machines**: ${typeCounts.machine || 0} tools
- **Apps**: ${typeCounts.app || 0} tools
- **Utilities**: ${typeCounts.utility || 0} tools`;
}
/**
* Main function to generate tools.md
*/
function generateToolsMarkdown() {
console.log('🔄 Generating tools.md from JSON definitions...');
const tools = loadToolDefinitions();
const groupedTools = groupToolsByCategory(tools);
let markdown = `# Tulip MCP Tools Reference
Complete reference for all ${tools.length} Tulip API tools available through the MCP server.
## Categories
**Admin Operations**: Tools marked as [ADMIN] can permanently delete data or disable resources.
---
`;
// Generate sections for each group
for (const [groupName, groupTools] of Object.entries(groupedTools)) {
const groupMarkdown = generateGroupMarkdown(groupTools, groupName);
if (groupMarkdown) {
markdown += groupMarkdown + '\n';
}
}
// Add statistics
markdown += generateStatistics(tools);
return markdown;
}
/**
* Write the generated markdown to tools.md
*/
function writeToolsDoc() {
try {
const markdown = generateToolsMarkdown();
const outputPath = path.join(__dirname, 'tools.md');
fs.writeFileSync(outputPath, markdown, 'utf8');
console.log(`✅ Successfully generated tools.md with ${markdown.split('\n#### `').length - 1} tools`);
} catch (error) {
console.error('❌ Error generating tools.md:', error.message);
process.exit(1);
}
}
// Run the script
if (path.resolve(fileURLToPath(import.meta.url)) === path.resolve(process.argv[1])) {
writeToolsDoc();
}
export { generateToolsMarkdown, loadToolDefinitions, groupToolsByCategory };