-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
324 lines (324 loc) · 13.2 KB
/
Copy pathindex.js
File metadata and controls
324 lines (324 loc) · 13.2 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/**
* FacturaScripts MCP Server
* Main entry point for the Model Context Protocol server
*/
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
import { connectionManager } from './connection-manager.js';
import { registerAccountingTools, handleAccountingTool } from './modules/accounting/index.js';
import { registerCoreBusinessTools, handleCoreBusinessTool } from './modules/core-business/index.js';
import { registerSalesOrdersTools, handleSalesOrdersTool } from './modules/sales-orders/index.js';
import { registerPurchasingTools, handlePurchasingTool } from './modules/purchasing/index.js';
import { registerFinanceTools, handleFinanceTool } from './modules/finance/index.js';
import { registerConfigurationTools, handleConfigurationTool } from './modules/configuration/index.js';
import { registerGeographicTools, handleGeographicTool } from './modules/geographic/index.js';
import { registerCommunicationTools, handleCommunicationTool } from './modules/communication/index.js';
import { registerSystemTools, handleSystemTool } from './modules/system/index.js';
import { registerAnalyticsTools, handleAnalyticsTool } from './modules/analytics/index.js';
import { registerSchemaTools, handleSchemaTool } from './modules/schema/index.js';
import { listSchemaResources, readSchemaResource } from './resources/schema-resources.js';
import { addDateRangeParams } from './metadata/dateRange.js';
import { enrichAllTools } from './metadata/enrich.js';
import { bootstrapCoreMetadata, getAllModelMetadata } from './metadata/registry.js';
import { loadLocalModules } from './local-loader.js';
// Track registered tools
const tools = new Map();
// Handlers de módulos locales privados (cargados desde FS_LOCAL_MODULES_PATH)
let localModuleHandlers = [];
/**
* Initialize and configure the MCP server
*/
const server = new Server({
name: 'fs-mcp',
version: '0.1.0',
}, {
capabilities: {
tools: {},
resources: {},
},
});
/**
* Register connection management tools
*/
function registerConnectionTools() {
// Tool: add_connection
const addConnectionTool = {
name: 'add_connection',
description: 'Add a new FacturaScripts server connection. Use this to connect to a FacturaScripts instance.',
inputSchema: {
type: 'object',
properties: {
key: {
type: 'string',
description: 'Unique identifier for this connection',
},
name: {
type: 'string',
description: 'Display name for this connection',
},
url: {
type: 'string',
description: 'Base URL of the FacturaScripts instance (e.g., https://facturascripts.example.com)',
},
token: {
type: 'string',
description: 'API token for authentication',
},
version: {
type: 'string',
description: 'FacturaScripts version (optional, used for API compatibility)',
},
setAsDefault: {
type: 'boolean',
description: 'Set this connection as the default one for subsequent requests',
},
},
required: ['key', 'name', 'url', 'token'],
},
};
tools.set('add_connection', addConnectionTool);
// Tool: list_connections
const listConnectionsTool = {
name: 'list_connections',
description: 'List all configured FacturaScripts server connections',
inputSchema: {
type: 'object',
properties: {},
required: [],
},
};
tools.set('list_connections', listConnectionsTool);
// Tool: set_default_connection
const setDefaultConnectionTool = {
name: 'set_default_connection',
description: 'Set the default FacturaScripts server connection for subsequent requests',
inputSchema: {
type: 'object',
properties: {
key: {
type: 'string',
description: 'Key of the connection to set as default',
},
},
required: ['key'],
},
};
tools.set('set_default_connection', setDefaultConnectionTool);
}
/**
* Register all tool modules
*/
async function registerAllTools() {
// 1. Cargar la metadata del core en el registry mutable.
const coreCount = await bootstrapCoreMetadata();
console.error(`[fs-mcp] Modelos del core registrados: ${coreCount}`);
// 2. Tools de gestión de conexiones.
registerConnectionTools();
// 3. Tools de cada módulo del MCP.
await registerAccountingTools(tools);
await registerCoreBusinessTools(tools);
await registerSalesOrdersTools(tools);
await registerPurchasingTools(tools);
await registerFinanceTools(tools);
await registerConfigurationTools(tools);
await registerGeographicTools(tools);
await registerCommunicationTools(tools);
await registerSystemTools(tools);
await registerAnalyticsTools(tools);
// Tools del core, ANTES de cargar las locales: solo a éstas se les inyectan los
// filtros de rango de fecha (paso 8), porque son las únicas cuyos handlers los
// reenvían. Los módulos locales ya ofrecen rangos por su propio parámetro `filter`.
const coreToolNames = new Set(tools.keys());
// 4. Cargar módulos locales privados: registran sus tools y, si los exponen,
// sus modelos en el registry de metadata.
localModuleHandlers = await loadLocalModules(tools);
// 5. Tools del schema (describe_model, list_models, verify_model_columns):
// se construyen DESPUÉS de cargar locales para que sus enums incluyan tanto
// los modelos del core como los privados.
await registerSchemaTools(tools);
// 6. Resumen final del registry (core + privados ya cargados).
const totalModels = getAllModelMetadata().length;
console.error(`[fs-mcp] Modelos totales en el registry: ${totalModels} (core + privados).`);
// 7. Enriquecer los inputSchema de los tools con la metadata: completa
// descripciones vacías, maxLength y enums sin pisar descripciones hardcoded.
const stats = enrichAllTools(tools);
console.error(`[fs-mcp] Tools enriquecidas: ${stats.toolsEnriched}/${stats.toolsProcessed} ` +
`(+${stats.descriptionsAdded} descripciones, +${stats.maxLengthsAdded} maxLength, +${stats.enumsAdded} enums)`);
// 8. Añadir a las tools get_* los filtros de rango (<columna>_gte / <columna>_lte)
// de sus columnas de fecha. Los handlers reenvían esos mismos parámetros usando
// la misma regla (metadata/dateRange.ts), así esquema y reenvío no pueden divergir.
const dateRangeParams = addDateRangeParams(tools, coreToolNames);
console.error(`[fs-mcp] Filtros de rango de fecha añadidos: ${dateRangeParams}`);
}
/**
* List resources handler: expone la metadata de modelos como MCP Resources
* bajo el esquema fs-schema://...
*/
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return { resources: listSchemaResources() };
});
/**
* Read resource handler: devuelve el contenido del resource solicitado.
*/
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const uri = request.params.uri;
const result = readSchemaResource(uri);
if (!result) {
throw new Error(`Resource no soportado: ${uri}`);
}
return { contents: [result] };
});
/**
* List tools handler
*/
server.setRequestHandler(ListToolsRequestSchema, async () => {
const toolList = Array.from(tools.values());
// Combine with tools from modules that are registered via setRequestHandler
return { tools: toolList };
});
/**
* Call tool handler
*/
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const toolName = request.params.name;
const toolInput = request.params.arguments;
try {
switch (toolName) {
case 'add_connection': {
const { key, name, url, token, version, setAsDefault } = toolInput;
connectionManager.addConnection(key, {
name,
url,
token,
...(version ? { version } : {}),
});
if (setAsDefault) {
connectionManager.setDefault(key);
}
return {
content: [
{
type: 'text',
text: `Connection "${name}" (${key}) added successfully${setAsDefault ? ' and set as default' : ''}`,
},
],
};
}
case 'list_connections': {
const connections = connectionManager.listConnections();
if (connections.length === 0) {
return {
content: [
{
type: 'text',
text: 'No connections configured. Use add_connection to add one.',
},
],
};
}
const connectionList = connections
.map((conn) => {
const isDefault = conn.isDefault ? ' (default)' : '';
return `- ${conn.name} (${conn.key}): ${conn.url}${isDefault}`;
})
.join('\n');
return {
content: [
{
type: 'text',
text: `Configured connections:\n${connectionList}`,
},
],
};
}
case 'set_default_connection': {
const { key } = toolInput;
connectionManager.setDefault(key);
const conn = connectionManager.getConnection(key);
return {
content: [
{
type: 'text',
text: `Connection "${conn?.name}" (${key}) set as default`,
},
],
};
}
default: {
// Try to dispatch to module handlers
let result = await handleAccountingTool(toolName, toolInput)
?? await handleCoreBusinessTool(toolName, toolInput)
?? await handleSalesOrdersTool(toolName, toolInput)
?? await handlePurchasingTool(toolName, toolInput)
?? await handleFinanceTool(toolName, toolInput)
?? await handleConfigurationTool(toolName, toolInput)
?? await handleGeographicTool(toolName, toolInput)
?? await handleCommunicationTool(toolName, toolInput)
?? await handleSystemTool(toolName, toolInput)
?? await handleAnalyticsTool(toolName, toolInput)
?? await handleSchemaTool(toolName, toolInput);
if (result) {
return result;
}
// Intentar con módulos locales privados
for (const handler of localModuleHandlers) {
const localResult = await handler.handleTool(toolName, toolInput);
if (localResult) {
return localResult;
}
}
return {
content: [
{
type: 'text',
text: `Unknown tool: ${toolName}`,
},
],
isError: true,
};
}
}
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [
{
type: 'text',
text: `Error executing tool ${toolName}: ${errorMessage}`,
},
],
isError: true,
};
}
});
/**
* Main server initialization and startup
*/
async function main() {
const transport = new StdioServerTransport();
// Register all tools before connecting
await registerAllTools();
// Connect server to transport
await server.connect(transport);
console.error('[fs-mcp] Server started successfully');
}
/**
* Error handling
*/
process.on('uncaughtException', (error) => {
console.error('[fs-mcp] Uncaught exception:', error);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('[fs-mcp] Unhandled rejection at promise:', promise);
console.error('[fs-mcp] Reason:', reason);
process.exit(1);
});
// Start the server
main().catch((error) => {
console.error('[fs-mcp] Failed to start server:', error);
process.exit(1);
});
//# sourceMappingURL=index.js.map