@open-mercato/ai-assistant 0.6.1-develop.3287.1.450f4ffb56 → 0.6.1-develop.3291.1.6fad645fd0
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.
- package/.turbo/turbo-build.log +1 -1
- package/AGENTS.md +39 -14
- package/README.md +2 -1
- package/dist/modules/ai_assistant/lib/api-endpoint-index.js +0 -111
- package/dist/modules/ai_assistant/lib/api-endpoint-index.js.map +2 -2
- package/dist/modules/ai_assistant/lib/codemode-tools.js.map +2 -2
- package/dist/modules/ai_assistant/lib/http-server.js +0 -5
- package/dist/modules/ai_assistant/lib/http-server.js.map +2 -2
- package/dist/modules/ai_assistant/lib/mcp-dev-server.js +0 -5
- package/dist/modules/ai_assistant/lib/mcp-dev-server.js.map +2 -2
- package/dist/modules/ai_assistant/lib/mcp-server.js +0 -5
- package/dist/modules/ai_assistant/lib/mcp-server.js.map +2 -2
- package/package.json +4 -4
- package/src/modules/ai_assistant/lib/__tests__/mcp-startup-no-dead-index.test.ts +65 -0
- package/src/modules/ai_assistant/lib/api-endpoint-index.ts +5 -186
- package/src/modules/ai_assistant/lib/codemode-tools.ts +0 -2
- package/src/modules/ai_assistant/lib/http-server.ts +2 -9
- package/src/modules/ai_assistant/lib/mcp-dev-server.ts +2 -8
- package/src/modules/ai_assistant/lib/mcp-server.ts +1 -10
- package/dist/modules/ai_assistant/lib/api-discovery-tools.js +0 -170
- package/dist/modules/ai_assistant/lib/api-discovery-tools.js.map +0 -7
- package/dist/modules/ai_assistant/lib/api-endpoint-index-config.js +0 -177
- package/dist/modules/ai_assistant/lib/api-endpoint-index-config.js.map +0 -7
- package/dist/modules/ai_assistant/lib/entity-graph-tools.js +0 -127
- package/dist/modules/ai_assistant/lib/entity-graph-tools.js.map +0 -7
- package/src/modules/ai_assistant/lib/api-discovery-tools.ts +0 -250
- package/src/modules/ai_assistant/lib/api-endpoint-index-config.ts +0 -243
- package/src/modules/ai_assistant/lib/entity-graph-tools.ts +0 -192
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/modules/ai_assistant/lib/api-discovery-tools.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * API Discovery Tools\n *\n * Meta-tools for discovering and executing API endpoints via search.\n *\n * 2 tools total:\n * - find_api: Search for endpoints (includes schema summary)\n * - call_api: Execute an endpoint\n */\n\nimport { z } from 'zod'\nimport { registerMcpTool } from './tool-registry'\nimport type { McpToolContext } from './types'\nimport {\n getApiEndpoints,\n searchEndpoints,\n simplifyRequestBodySchema,\n} from './api-endpoint-index'\nimport { fetchWithTimeout, resolveTimeoutMs } from '@open-mercato/shared/lib/http/fetchWithTimeout'\n\nconst DEFAULT_AI_API_REQUEST_TIMEOUT_MS = 30_000\n\nfunction resolveAiApiRequestTimeoutMs(): number {\n const raw = process.env.AI_API_REQUEST_TIMEOUT_MS\n const parsed = raw ? Number.parseInt(raw, 10) : undefined\n return resolveTimeoutMs(parsed, DEFAULT_AI_API_REQUEST_TIMEOUT_MS)\n}\n\n/**\n * Load API discovery tools into the registry\n */\nexport async function loadApiDiscoveryTools(): Promise<number> {\n // Ensure endpoints are parsed and cached\n const endpoints = await getApiEndpoints()\n console.error(`[API Discovery] ${endpoints.length} endpoints available for discovery`)\n\n // Register the two discovery tools\n registerApiDiscoverTool()\n registerApiExecuteTool()\n\n return 2\n}\n\n/**\n * find_api - Find relevant API endpoints based on a query.\n * Enhanced to include request body schema summary.\n */\nfunction registerApiDiscoverTool(): void {\n registerMcpTool(\n {\n name: 'find_api',\n description: `Search for API endpoints. Use discover_schema first to understand entity fields, then find_api to get the endpoint schema.\n\nReturns: path, method, operationId, parameters, and requestBody schema showing required fields and structure.\n\nWorkflow: discover_schema(\"Company\") \u2192 understand fields \u2192 find_api(\"update company\") \u2192 see request body schema \u2192 call_api`,\n inputSchema: z.object({\n query: z\n .string()\n .describe('Natural language query to find endpoints (e.g., \"update company\", \"create order\", \"list customers\")'),\n method: z\n .enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])\n .optional()\n .describe('Filter by HTTP method'),\n limit: z.number().optional().default(10).describe('Max results to return (default: 10)'),\n }),\n requiredFeatures: [], // Available to all authenticated users\n handler: async (input: { query: string; method?: string; limit?: number }, ctx) => {\n const { query, method, limit = 10 } = input\n\n // Search for matching endpoints\n const searchService = ctx.container?.resolve<any>('searchService')\n const matches = await searchEndpoints(searchService, query, { limit, method })\n\n if (matches.length === 0) {\n return {\n success: true,\n message: 'No matching endpoints found. Try different search terms.',\n endpoints: [],\n suggestions: [\n 'Try broader terms like \"customer\", \"company\", \"order\", or \"sales\"',\n 'Use method filter to narrow results (e.g., method: \"PUT\" for updates)',\n 'Use discover_schema to find entity names first, then search for those entity names',\n ],\n }\n }\n\n // Format results for LLM consumption - now includes schema\n const results = matches.map((endpoint) => {\n const result: Record<string, unknown> = {\n operationId: endpoint.operationId,\n method: endpoint.method,\n path: endpoint.path,\n description: endpoint.description || endpoint.summary,\n tags: endpoint.tags,\n parameters: endpoint.parameters.map((p) => ({\n name: p.name,\n in: p.in,\n required: p.required,\n type: p.type,\n })),\n }\n\n // Include request body schema for mutation endpoints\n if (endpoint.requestBodySchema) {\n const simplifiedSchema = simplifyRequestBodySchema(endpoint.requestBodySchema)\n if (simplifiedSchema) {\n result.requestBody = simplifiedSchema\n }\n }\n\n return result\n })\n\n return {\n success: true,\n message: `Found ${results.length} matching endpoint(s)`,\n endpoints: results,\n hint: 'Use call_api with the method, path, and body structure shown in requestBody schema above.',\n }\n },\n },\n { moduleId: 'api' }\n )\n}\n\n/**\n * call_api - Execute an API endpoint\n */\nfunction registerApiExecuteTool(): void {\n registerMcpTool(\n {\n name: 'call_api',\n description: `Execute an API call using path and body structure from find_api results.\n\nConfirm with user before POST/PUT/DELETE operations.`,\n inputSchema: z.object({\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method from find_api result'),\n path: z\n .string()\n .describe('API path from find_api result (e.g., /api/customers/companies)'),\n query: z\n .record(z.string(), z.string())\n .optional()\n .describe('Query parameters as key-value pairs'),\n body: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Request body matching the schema from find_api'),\n }),\n requiredFeatures: [], // ACL checked at API level\n handler: async (\n input: {\n method: string\n path: string\n query?: Record<string, string>\n body?: Record<string, unknown>\n },\n ctx: McpToolContext\n ) => {\n const { method, path, query, body } = input\n\n // Build URL\n const baseUrl =\n process.env.NEXT_PUBLIC_API_BASE_URL ||\n process.env.NEXT_PUBLIC_APP_URL ||\n process.env.APP_URL ||\n 'http://localhost:3000'\n\n // Ensure path starts with /api\n const apiPath = path.startsWith('/api') ? path : `/api${path}`\n let url = `${baseUrl}${apiPath}`\n\n // Add query parameters\n const queryParams = { ...query }\n\n // Add context to query for GET, to body for mutations\n if (method === 'GET') {\n if (ctx.tenantId) queryParams.tenantId = ctx.tenantId\n if (ctx.organizationId) queryParams.organizationId = ctx.organizationId\n }\n\n if (Object.keys(queryParams).length > 0) {\n const separator = url.includes('?') ? '&' : '?'\n url += separator + new URLSearchParams(queryParams).toString()\n }\n\n // Build body with context\n let requestBody: Record<string, unknown> | undefined\n if (['POST', 'PUT', 'PATCH'].includes(method)) {\n requestBody = { ...body }\n if (ctx.tenantId) requestBody.tenantId = ctx.tenantId\n if (ctx.organizationId) requestBody.organizationId = ctx.organizationId\n }\n\n // Build headers\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n }\n if (ctx.apiKeySecret) headers['X-API-Key'] = ctx.apiKeySecret\n if (ctx.tenantId) headers['X-Tenant-Id'] = ctx.tenantId\n if (ctx.organizationId) headers['X-Organization-Id'] = ctx.organizationId\n\n // Execute request\n try {\n const response = await fetchWithTimeout(url, {\n method,\n headers,\n body: requestBody ? JSON.stringify(requestBody) : undefined,\n timeoutMs: resolveAiApiRequestTimeoutMs(),\n })\n\n const responseText = await response.text()\n\n if (!response.ok) {\n return {\n success: false,\n statusCode: response.status,\n error: `API error ${response.status}`,\n details: tryParseJson(responseText),\n }\n }\n\n return {\n success: true,\n statusCode: response.status,\n data: tryParseJson(responseText),\n }\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Request failed',\n }\n }\n },\n },\n { moduleId: 'api' }\n )\n}\n\n/**\n * Try to parse JSON, return original string if fails\n */\nfunction tryParseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n"],
|
|
5
|
-
"mappings": "AAUA,SAAS,SAAS;AAClB,SAAS,uBAAuB;AAEhC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AAEnD,MAAM,oCAAoC;AAE1C,SAAS,+BAAuC;AAC9C,QAAM,MAAM,QAAQ,IAAI;AACxB,QAAM,SAAS,MAAM,OAAO,SAAS,KAAK,EAAE,IAAI;AAChD,SAAO,iBAAiB,QAAQ,iCAAiC;AACnE;AAKA,eAAsB,wBAAyC;AAE7D,QAAM,YAAY,MAAM,gBAAgB;AACxC,UAAQ,MAAM,mBAAmB,UAAU,MAAM,oCAAoC;AAGrF,0BAAwB;AACxB,yBAAuB;AAEvB,SAAO;AACT;AAMA,SAAS,0BAAgC;AACvC;AAAA,IACE;AAAA,MACE,MAAM;AAAA,MACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA,MAKb,aAAa,EAAE,OAAO;AAAA,QACpB,OAAO,EACJ,OAAO,EACP,SAAS,qGAAqG;AAAA,QACjH,QAAQ,EACL,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,QAAQ,CAAC,EAC9C,SAAS,EACT,SAAS,uBAAuB;AAAA,QACnC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,SAAS,qCAAqC;AAAA,MACzF,CAAC;AAAA,MACD,kBAAkB,CAAC;AAAA;AAAA,MACnB,SAAS,OAAO,OAA2D,QAAQ;AACjF,cAAM,EAAE,OAAO,QAAQ,QAAQ,GAA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,IAAI,IAAI;AAC/C,YAAI,IAAI,eAAgB,SAAQ,mBAAmB,IAAI,IAAI;AAG3D,YAAI;AACF,gBAAM,WAAW,MAAM,iBAAiB,KAAK;AAAA,YAC3C;AAAA,YACA;AAAA,YACA,MAAM,cAAc,KAAK,UAAU,WAAW,IAAI;AAAA,YAClD,WAAW,6BAA6B;AAAA,UAC1C,CAAC;AAED,gBAAM,eAAe,MAAM,SAAS,KAAK;AAEzC,cAAI,CAAC,SAAS,IAAI;AAChB,mBAAO;AAAA,cACL,SAAS;AAAA,cACT,YAAY,SAAS;AAAA,cACrB,OAAO,aAAa,SAAS,MAAM;AAAA,cACnC,SAAS,aAAa,YAAY;AAAA,YACpC;AAAA,UACF;AAEA,iBAAO;AAAA,YACL,SAAS;AAAA,YACT,YAAY,SAAS;AAAA,YACrB,MAAM,aAAa,YAAY;AAAA,UACjC;AAAA,QACF,SAAS,OAAO;AACd,iBAAO;AAAA,YACL,SAAS;AAAA,YACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU;AAAA,UAClD;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,IACA,EAAE,UAAU,MAAM;AAAA,EACpB;AACF;AAKA,SAAS,aAAa,MAAuB;AAC3C,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
const API_ENDPOINT_ENTITY_ID = "ai_assistant:api_endpoint";
|
|
2
|
-
const GLOBAL_TENANT_ID = "00000000-0000-0000-0000-000000000000";
|
|
3
|
-
const API_ENDPOINT_SEARCH_CONFIG = {
|
|
4
|
-
/** Maximum endpoints to return from search */
|
|
5
|
-
defaultLimit: 20,
|
|
6
|
-
/** Minimum relevance score (0-1) */
|
|
7
|
-
minScore: 0.15,
|
|
8
|
-
/** Strategies to use (in priority order) */
|
|
9
|
-
strategies: ["fulltext", "vector"]
|
|
10
|
-
};
|
|
11
|
-
const apiEndpointEntityConfig = {
|
|
12
|
-
entityId: API_ENDPOINT_ENTITY_ID,
|
|
13
|
-
enabled: true,
|
|
14
|
-
priority: 90,
|
|
15
|
-
// High priority, just below tools
|
|
16
|
-
/**
|
|
17
|
-
* Build searchable content from an API endpoint.
|
|
18
|
-
*/
|
|
19
|
-
buildSource: (ctx) => {
|
|
20
|
-
const endpoint = ctx.record;
|
|
21
|
-
const method = endpoint.method || "";
|
|
22
|
-
const path = endpoint.path || "";
|
|
23
|
-
const summary = endpoint.summary || "";
|
|
24
|
-
const description = endpoint.description || "";
|
|
25
|
-
const tags = endpoint.tags || [];
|
|
26
|
-
const operationId = endpoint.operationId || "";
|
|
27
|
-
const normalizedPath = path.replace(/[/{}\[\]]/g, " ").trim();
|
|
28
|
-
const actionWords = getActionWordsForMethod(method);
|
|
29
|
-
const textContent = [
|
|
30
|
-
`${method} ${normalizedPath}`,
|
|
31
|
-
operationId.replace(/[_.-]/g, " "),
|
|
32
|
-
summary,
|
|
33
|
-
description,
|
|
34
|
-
...actionWords,
|
|
35
|
-
...tags
|
|
36
|
-
].filter(Boolean).join(" | ");
|
|
37
|
-
return {
|
|
38
|
-
text: textContent,
|
|
39
|
-
fields: {
|
|
40
|
-
method,
|
|
41
|
-
path,
|
|
42
|
-
operationId,
|
|
43
|
-
summary,
|
|
44
|
-
description,
|
|
45
|
-
tags,
|
|
46
|
-
module: extractModuleFromPath(path),
|
|
47
|
-
deprecated: endpoint.deprecated ?? false,
|
|
48
|
-
requiredFeatures: endpoint.requiredFeatures ?? []
|
|
49
|
-
},
|
|
50
|
-
presenter: {
|
|
51
|
-
title: `${method} ${path}`,
|
|
52
|
-
subtitle: summary || description.slice(0, 100),
|
|
53
|
-
icon: getIconForMethod(method)
|
|
54
|
-
},
|
|
55
|
-
checksumSource: { operationId, method, path, summary }
|
|
56
|
-
};
|
|
57
|
-
},
|
|
58
|
-
/**
|
|
59
|
-
* Format result for display in search UI.
|
|
60
|
-
*/
|
|
61
|
-
formatResult: (ctx) => {
|
|
62
|
-
const endpoint = ctx.record;
|
|
63
|
-
return {
|
|
64
|
-
title: `${endpoint.method} ${endpoint.path}`,
|
|
65
|
-
subtitle: (endpoint.summary || endpoint.description || "").slice(0, 100),
|
|
66
|
-
icon: getIconForMethod(endpoint.method)
|
|
67
|
-
};
|
|
68
|
-
},
|
|
69
|
-
/**
|
|
70
|
-
* Field policy for search strategies.
|
|
71
|
-
*/
|
|
72
|
-
fieldPolicy: {
|
|
73
|
-
searchable: ["method", "path", "operationId", "summary", "description", "tags", "module"],
|
|
74
|
-
hashOnly: [],
|
|
75
|
-
excluded: ["parameters", "requestBodySchema", "requiredFeatures"]
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
function endpointToIndexableRecord(endpoint) {
|
|
79
|
-
const method = endpoint.method;
|
|
80
|
-
const path = endpoint.path;
|
|
81
|
-
const normalizedPath = path.replace(/[/{}\[\]]/g, " ").trim();
|
|
82
|
-
const actionWords = getActionWordsForMethod(method);
|
|
83
|
-
const embeddingText = [
|
|
84
|
-
`${method} ${normalizedPath}`,
|
|
85
|
-
endpoint.operationId.replace(/[_.-]/g, " "),
|
|
86
|
-
endpoint.summary,
|
|
87
|
-
endpoint.description,
|
|
88
|
-
...actionWords,
|
|
89
|
-
...endpoint.tags
|
|
90
|
-
].filter(Boolean).join(" | ");
|
|
91
|
-
const presenter = {
|
|
92
|
-
title: `${method} ${path}`,
|
|
93
|
-
subtitle: (endpoint.summary || endpoint.description || "").slice(0, 100),
|
|
94
|
-
icon: getIconForMethod(method)
|
|
95
|
-
};
|
|
96
|
-
return {
|
|
97
|
-
entityId: API_ENDPOINT_ENTITY_ID,
|
|
98
|
-
recordId: endpoint.operationId,
|
|
99
|
-
tenantId: GLOBAL_TENANT_ID,
|
|
100
|
-
organizationId: null,
|
|
101
|
-
fields: {
|
|
102
|
-
method,
|
|
103
|
-
path,
|
|
104
|
-
operationId: endpoint.operationId,
|
|
105
|
-
summary: endpoint.summary,
|
|
106
|
-
description: endpoint.description,
|
|
107
|
-
tags: endpoint.tags,
|
|
108
|
-
module: extractModuleFromPath(path),
|
|
109
|
-
deprecated: endpoint.deprecated,
|
|
110
|
-
requiredFeatures: endpoint.requiredFeatures
|
|
111
|
-
},
|
|
112
|
-
presenter,
|
|
113
|
-
text: embeddingText,
|
|
114
|
-
checksumSource: {
|
|
115
|
-
operationId: endpoint.operationId,
|
|
116
|
-
method,
|
|
117
|
-
path,
|
|
118
|
-
summary: endpoint.summary
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
function getActionWordsForMethod(method) {
|
|
123
|
-
switch (method.toUpperCase()) {
|
|
124
|
-
case "GET":
|
|
125
|
-
return ["read", "fetch", "get", "list", "retrieve", "find", "search", "query"];
|
|
126
|
-
case "POST":
|
|
127
|
-
return ["create", "add", "new", "insert", "submit", "register"];
|
|
128
|
-
case "PUT":
|
|
129
|
-
return ["update", "replace", "modify", "set", "change", "edit"];
|
|
130
|
-
case "PATCH":
|
|
131
|
-
return ["update", "modify", "partial", "change", "edit", "patch"];
|
|
132
|
-
case "DELETE":
|
|
133
|
-
return ["delete", "remove", "destroy", "cancel", "erase"];
|
|
134
|
-
default:
|
|
135
|
-
return [];
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
function getIconForMethod(method) {
|
|
139
|
-
switch (method.toUpperCase()) {
|
|
140
|
-
case "GET":
|
|
141
|
-
return "search";
|
|
142
|
-
case "POST":
|
|
143
|
-
return "plus";
|
|
144
|
-
case "PUT":
|
|
145
|
-
case "PATCH":
|
|
146
|
-
return "edit";
|
|
147
|
-
case "DELETE":
|
|
148
|
-
return "trash";
|
|
149
|
-
default:
|
|
150
|
-
return "api";
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
function extractModuleFromPath(path) {
|
|
154
|
-
const match = path.match(/^\/([\w-]+)/);
|
|
155
|
-
if (match) {
|
|
156
|
-
return match[1];
|
|
157
|
-
}
|
|
158
|
-
return null;
|
|
159
|
-
}
|
|
160
|
-
function computeEndpointsChecksum(endpoints) {
|
|
161
|
-
const content = endpoints.map((e) => `${e.operationId}:${e.method}:${e.path}`).sort().join("|");
|
|
162
|
-
let hash = 0;
|
|
163
|
-
for (let i = 0; i < content.length; i++) {
|
|
164
|
-
const char = content.charCodeAt(i);
|
|
165
|
-
hash = (hash << 5) - hash + char | 0;
|
|
166
|
-
}
|
|
167
|
-
return hash.toString(16);
|
|
168
|
-
}
|
|
169
|
-
export {
|
|
170
|
-
API_ENDPOINT_ENTITY_ID,
|
|
171
|
-
API_ENDPOINT_SEARCH_CONFIG,
|
|
172
|
-
GLOBAL_TENANT_ID,
|
|
173
|
-
apiEndpointEntityConfig,
|
|
174
|
-
computeEndpointsChecksum,
|
|
175
|
-
endpointToIndexableRecord
|
|
176
|
-
};
|
|
177
|
-
//# sourceMappingURL=api-endpoint-index-config.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/modules/ai_assistant/lib/api-endpoint-index-config.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n SearchEntityConfig,\n SearchResultPresenter,\n IndexableRecord,\n} from '@open-mercato/search/types'\nimport type { ApiEndpoint } from './api-endpoint-index'\n\n/**\n * Entity ID for API endpoints in the search index.\n * Following the module:entity naming convention.\n */\nexport const API_ENDPOINT_ENTITY_ID = 'ai_assistant:api_endpoint' as const\n\n/**\n * Tenant ID for global endpoints.\n * API endpoints are not tenant-scoped, so we use a special \"system\" UUID.\n * This is the nil UUID (all zeros) reserved for system-wide resources.\n */\nexport const GLOBAL_TENANT_ID = '00000000-0000-0000-0000-000000000000'\n\n/**\n * Default configuration for API endpoint search.\n */\nexport const API_ENDPOINT_SEARCH_CONFIG = {\n /** Maximum endpoints to return from search */\n defaultLimit: 20,\n /** Minimum relevance score (0-1) */\n minScore: 0.15,\n /** Strategies to use (in priority order) */\n strategies: ['fulltext', 'vector'] as const,\n} as const\n\n/**\n * Search entity configuration for API endpoints.\n * This configures how endpoints are indexed and searched.\n */\nexport const apiEndpointEntityConfig: SearchEntityConfig = {\n entityId: API_ENDPOINT_ENTITY_ID,\n enabled: true,\n priority: 90, // High priority, just below tools\n\n /**\n * Build searchable content from an API endpoint.\n */\n buildSource: (ctx) => {\n const endpoint = ctx.record as unknown as ApiEndpoint\n const method = endpoint.method || ''\n const path = endpoint.path || ''\n const summary = endpoint.summary || ''\n const description = endpoint.description || ''\n const tags = endpoint.tags || []\n const operationId = endpoint.operationId || ''\n\n // Normalize path: replace slashes and braces with spaces for better search\n const normalizedPath = path.replace(/[/{}\\[\\]]/g, ' ').trim()\n\n // Build action words from method\n const actionWords = getActionWordsForMethod(method)\n\n // Build text content for embedding and fulltext search\n const textContent = [\n `${method} ${normalizedPath}`,\n operationId.replace(/[_.-]/g, ' '),\n summary,\n description,\n ...actionWords,\n ...tags,\n ]\n .filter(Boolean)\n .join(' | ')\n\n return {\n text: textContent,\n fields: {\n method,\n path,\n operationId,\n summary,\n description,\n tags,\n module: extractModuleFromPath(path),\n deprecated: endpoint.deprecated ?? false,\n requiredFeatures: endpoint.requiredFeatures ?? [],\n },\n presenter: {\n title: `${method} ${path}`,\n subtitle: summary || description.slice(0, 100),\n icon: getIconForMethod(method),\n },\n checksumSource: { operationId, method, path, summary },\n }\n },\n\n /**\n * Format result for display in search UI.\n */\n formatResult: (ctx) => {\n const endpoint = ctx.record as unknown as ApiEndpoint\n return {\n title: `${endpoint.method} ${endpoint.path}`,\n subtitle: (endpoint.summary || endpoint.description || '').slice(0, 100),\n icon: getIconForMethod(endpoint.method),\n }\n },\n\n /**\n * Field policy for search strategies.\n */\n fieldPolicy: {\n searchable: ['method', 'path', 'operationId', 'summary', 'description', 'tags', 'module'],\n hashOnly: [],\n excluded: ['parameters', 'requestBodySchema', 'requiredFeatures'],\n },\n}\n\n/**\n * Convert an API endpoint to an indexable record for search.\n *\n * @param endpoint - The API endpoint to index\n * @returns IndexableRecord ready for search indexing\n */\nexport function endpointToIndexableRecord(endpoint: ApiEndpoint): IndexableRecord {\n const method = endpoint.method\n const path = endpoint.path\n const normalizedPath = path.replace(/[/{}\\[\\]]/g, ' ').trim()\n const actionWords = getActionWordsForMethod(method)\n\n // Build text for vector embedding\n const embeddingText = [\n `${method} ${normalizedPath}`,\n endpoint.operationId.replace(/[_.-]/g, ' '),\n endpoint.summary,\n endpoint.description,\n ...actionWords,\n ...endpoint.tags,\n ]\n .filter(Boolean)\n .join(' | ')\n\n const presenter: SearchResultPresenter = {\n title: `${method} ${path}`,\n subtitle: (endpoint.summary || endpoint.description || '').slice(0, 100),\n icon: getIconForMethod(method),\n }\n\n return {\n entityId: API_ENDPOINT_ENTITY_ID,\n recordId: endpoint.operationId,\n tenantId: GLOBAL_TENANT_ID,\n organizationId: null,\n fields: {\n method,\n path,\n operationId: endpoint.operationId,\n summary: endpoint.summary,\n description: endpoint.description,\n tags: endpoint.tags,\n module: extractModuleFromPath(path),\n deprecated: endpoint.deprecated,\n requiredFeatures: endpoint.requiredFeatures,\n },\n presenter,\n text: embeddingText,\n checksumSource: {\n operationId: endpoint.operationId,\n method,\n path,\n summary: endpoint.summary,\n },\n }\n}\n\n/**\n * Get action words for HTTP method to improve semantic search.\n */\nfunction getActionWordsForMethod(method: string): string[] {\n switch (method.toUpperCase()) {\n case 'GET':\n return ['read', 'fetch', 'get', 'list', 'retrieve', 'find', 'search', 'query']\n case 'POST':\n return ['create', 'add', 'new', 'insert', 'submit', 'register']\n case 'PUT':\n return ['update', 'replace', 'modify', 'set', 'change', 'edit']\n case 'PATCH':\n return ['update', 'modify', 'partial', 'change', 'edit', 'patch']\n case 'DELETE':\n return ['delete', 'remove', 'destroy', 'cancel', 'erase']\n default:\n return []\n }\n}\n\n/**\n * Get icon for HTTP method.\n */\nfunction getIconForMethod(method: string): string {\n switch (method.toUpperCase()) {\n case 'GET':\n return 'search'\n case 'POST':\n return 'plus'\n case 'PUT':\n case 'PATCH':\n return 'edit'\n case 'DELETE':\n return 'trash'\n default:\n return 'api'\n }\n}\n\n/**\n * Extract module name from API path.\n */\nfunction extractModuleFromPath(path: string): string | null {\n // Common module patterns in paths\n const match = path.match(/^\\/([\\w-]+)/)\n if (match) {\n return match[1]\n }\n return null\n}\n\n/**\n * Compute a simple checksum for endpoint definitions.\n * Used to detect changes and avoid unnecessary re-indexing.\n */\nexport function computeEndpointsChecksum(\n endpoints: Array<{ operationId: string; method: string; path: string }>\n): string {\n const content = endpoints\n .map((e) => `${e.operationId}:${e.method}:${e.path}`)\n .sort()\n .join('|')\n\n // Simple hash using string code points\n let hash = 0\n for (let i = 0; i < content.length; i++) {\n const char = content.charCodeAt(i)\n hash = ((hash << 5) - hash + char) | 0\n }\n return hash.toString(16)\n}\n"],
|
|
5
|
-
"mappings": "AAWO,MAAM,yBAAyB;AAO/B,MAAM,mBAAmB;AAKzB,MAAM,6BAA6B;AAAA;AAAA,EAExC,cAAc;AAAA;AAAA,EAEd,UAAU;AAAA;AAAA,EAEV,YAAY,CAAC,YAAY,QAAQ;AACnC;AAMO,MAAM,0BAA8C;AAAA,EACzD,UAAU;AAAA,EACV,SAAS;AAAA,EACT,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA,EAKV,aAAa,CAAC,QAAQ;AACpB,UAAM,WAAW,IAAI;AACrB,UAAM,SAAS,SAAS,UAAU;AAClC,UAAM,OAAO,SAAS,QAAQ;AAC9B,UAAM,UAAU,SAAS,WAAW;AACpC,UAAM,cAAc,SAAS,eAAe;AAC5C,UAAM,OAAO,SAAS,QAAQ,CAAC;AAC/B,UAAM,cAAc,SAAS,eAAe;AAG5C,UAAM,iBAAiB,KAAK,QAAQ,cAAc,GAAG,EAAE,KAAK;AAG5D,UAAM,cAAc,wBAAwB,MAAM;AAGlD,UAAM,cAAc;AAAA,MAClB,GAAG,MAAM,IAAI,cAAc;AAAA,MAC3B,YAAY,QAAQ,UAAU,GAAG;AAAA,MACjC;AAAA,MACA;A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AAO,CAAC;AAAA,EACZ;AACF;AAKA,SAAS,iBAAiB,QAAwB;AAChD,UAAQ,OAAO,YAAY,GAAG;AAAA,IAC5B,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAKA,SAAS,sBAAsB,MAA6B;AAE1D,QAAM,QAAQ,KAAK,MAAM,aAAa;AACtC,MAAI,OAAO;AACT,WAAO,MAAM,CAAC;AAAA,EAChB;AACA,SAAO;AACT;AAMO,SAAS,yBACd,WACQ;AACR,QAAM,UAAU,UACb,IAAI,CAAC,MAAM,GAAG,EAAE,WAAW,IAAI,EAAE,MAAM,IAAI,EAAE,IAAI,EAAE,EACnD,KAAK,EACL,KAAK,GAAG;AAGX,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,WAAW,CAAC;AACjC,YAAS,QAAQ,KAAK,OAAO,OAAQ;AAAA,EACvC;AACA,SAAO,KAAK,SAAS,EAAE;AACzB;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import {
|
|
3
|
-
getCachedEntityGraph,
|
|
4
|
-
inferModuleFromEntity
|
|
5
|
-
} from "./entity-graph.js";
|
|
6
|
-
import {
|
|
7
|
-
ENTITY_SCHEMA_ENTITY_ID,
|
|
8
|
-
GLOBAL_TENANT_ID,
|
|
9
|
-
ENTITY_SCHEMA_SEARCH_CONFIG
|
|
10
|
-
} from "./entity-index-config.js";
|
|
11
|
-
function buildEntityResult(graph, node) {
|
|
12
|
-
const relationships = graph.edges.filter((edge) => edge.source === node.className).map((edge) => ({
|
|
13
|
-
relationship: edge.relationship,
|
|
14
|
-
target: edge.target,
|
|
15
|
-
property: edge.property,
|
|
16
|
-
nullable: edge.nullable
|
|
17
|
-
}));
|
|
18
|
-
return {
|
|
19
|
-
className: node.className,
|
|
20
|
-
tableName: node.tableName,
|
|
21
|
-
module: inferModuleFromEntity(node.className, node.tableName),
|
|
22
|
-
fields: node.properties,
|
|
23
|
-
relationships
|
|
24
|
-
};
|
|
25
|
-
}
|
|
26
|
-
const discoverSchemaTool = {
|
|
27
|
-
name: "discover_schema",
|
|
28
|
-
description: `Search for database entity schemas by name or keyword.
|
|
29
|
-
|
|
30
|
-
Returns entity schema with: className, tableName, module, fields with types, relationships.
|
|
31
|
-
|
|
32
|
-
Examples:
|
|
33
|
-
- discover_schema({ query: "Company" }) \u2192 CustomerCompanyProfile schema
|
|
34
|
-
- discover_schema({ query: "sales order" }) \u2192 SalesOrder schema
|
|
35
|
-
- discover_schema({ query: "customer" }) \u2192 all customer-related entities
|
|
36
|
-
|
|
37
|
-
Use this tool to understand what data structures exist before making API calls.`,
|
|
38
|
-
inputSchema: z.object({
|
|
39
|
-
query: z.string().describe('Entity name or keyword to search (e.g., "Company", "sales order", "customer")'),
|
|
40
|
-
limit: z.number().optional().default(5).describe("Maximum number of results to return (default: 5)")
|
|
41
|
-
}),
|
|
42
|
-
requiredFeatures: [],
|
|
43
|
-
handler: async (rawInput, ctx) => {
|
|
44
|
-
const input = rawInput;
|
|
45
|
-
const limit = input.limit ?? ENTITY_SCHEMA_SEARCH_CONFIG.defaultLimit;
|
|
46
|
-
const graph = getCachedEntityGraph();
|
|
47
|
-
if (!graph) {
|
|
48
|
-
return {
|
|
49
|
-
success: false,
|
|
50
|
-
error: "Entity graph not available. The MCP server may need to be restarted."
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
const entityByClassName = /* @__PURE__ */ new Map();
|
|
54
|
-
for (const node of graph.nodes) {
|
|
55
|
-
entityByClassName.set(node.className, node);
|
|
56
|
-
}
|
|
57
|
-
let searchService = null;
|
|
58
|
-
try {
|
|
59
|
-
searchService = ctx.container.resolve("searchService");
|
|
60
|
-
} catch {
|
|
61
|
-
}
|
|
62
|
-
if (searchService) {
|
|
63
|
-
try {
|
|
64
|
-
const results = await searchService.search(input.query, {
|
|
65
|
-
tenantId: GLOBAL_TENANT_ID,
|
|
66
|
-
organizationId: null,
|
|
67
|
-
entityTypes: [ENTITY_SCHEMA_ENTITY_ID],
|
|
68
|
-
limit: limit * 2
|
|
69
|
-
});
|
|
70
|
-
if (results.length > 0) {
|
|
71
|
-
const entities2 = results.slice(0, limit).map((result) => {
|
|
72
|
-
const node = entityByClassName.get(result.recordId);
|
|
73
|
-
if (node) {
|
|
74
|
-
return buildEntityResult(graph, node);
|
|
75
|
-
}
|
|
76
|
-
return null;
|
|
77
|
-
}).filter((e) => e !== null);
|
|
78
|
-
if (entities2.length > 0) {
|
|
79
|
-
return {
|
|
80
|
-
success: true,
|
|
81
|
-
count: entities2.length,
|
|
82
|
-
entities: entities2
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
} catch {
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
const queryLower = input.query.toLowerCase();
|
|
90
|
-
const queryTerms = queryLower.split(/\s+/).filter(Boolean);
|
|
91
|
-
const matches = graph.nodes.filter((node) => {
|
|
92
|
-
const className = node.className.toLowerCase();
|
|
93
|
-
const tableName = node.tableName.toLowerCase();
|
|
94
|
-
const module = inferModuleFromEntity(node.className, node.tableName).toLowerCase();
|
|
95
|
-
return queryTerms.some(
|
|
96
|
-
(term) => className.includes(term) || tableName.includes(term) || module.includes(term)
|
|
97
|
-
);
|
|
98
|
-
});
|
|
99
|
-
if (matches.length === 0) {
|
|
100
|
-
const suggestions = graph.nodes.filter((node) => {
|
|
101
|
-
const className = node.className.toLowerCase();
|
|
102
|
-
return queryTerms.some(
|
|
103
|
-
(term) => className.split(/(?=[A-Z])/).some((part) => part.toLowerCase().includes(term))
|
|
104
|
-
);
|
|
105
|
-
}).slice(0, 5).map((node) => node.className);
|
|
106
|
-
return {
|
|
107
|
-
success: false,
|
|
108
|
-
error: `No entities found matching "${input.query}"`,
|
|
109
|
-
suggestions: suggestions.length > 0 ? suggestions : void 0,
|
|
110
|
-
hint: 'Try a different search term or use broader keywords like "customer", "sales", "order".'
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
const entities = matches.slice(0, limit).map((node) => buildEntityResult(graph, node));
|
|
114
|
-
return {
|
|
115
|
-
success: true,
|
|
116
|
-
count: entities.length,
|
|
117
|
-
entities
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
const entityGraphTools = [
|
|
122
|
-
discoverSchemaTool
|
|
123
|
-
];
|
|
124
|
-
export {
|
|
125
|
-
entityGraphTools
|
|
126
|
-
};
|
|
127
|
-
//# sourceMappingURL=entity-graph-tools.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/modules/ai_assistant/lib/entity-graph-tools.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Entity Graph MCP Tools\n *\n * Unified tool for AI to discover database entity schemas via Meilisearch search.\n *\n * 1 tool:\n * - discover_schema: Search for entity schemas by name or keyword\n */\n\nimport { z } from 'zod'\nimport type { McpToolDefinition, McpToolContext } from './types'\nimport type { SearchService } from '@open-mercato/search/service'\nimport {\n getCachedEntityGraph,\n inferModuleFromEntity,\n type EntityGraph,\n type EntityNode,\n} from './entity-graph'\nimport {\n ENTITY_SCHEMA_ENTITY_ID,\n GLOBAL_TENANT_ID,\n ENTITY_SCHEMA_SEARCH_CONFIG,\n} from './entity-index-config'\n\n/**\n * Build entity schema result from cached graph node.\n */\nfunction buildEntityResult(graph: EntityGraph, node: EntityNode) {\n // Find all outgoing relationships for this entity\n const relationships = graph.edges\n .filter((edge) => edge.source === node.className)\n .map((edge) => ({\n relationship: edge.relationship,\n target: edge.target,\n property: edge.property,\n nullable: edge.nullable,\n }))\n\n return {\n className: node.className,\n tableName: node.tableName,\n module: inferModuleFromEntity(node.className, node.tableName),\n fields: node.properties,\n relationships,\n }\n}\n\n/**\n * discover_schema - Search for entity schemas by name or keyword.\n *\n * Returns: className, tableName, module, fields with types, relationships.\n *\n * This tool uses Meilisearch hybrid search (fulltext + vector) to find\n * relevant entity schemas based on the query, then looks up full schema\n * from the cached entity graph.\n */\nconst discoverSchemaTool: McpToolDefinition = {\n name: 'discover_schema',\n description: `Search for database entity schemas by name or keyword.\n\nReturns entity schema with: className, tableName, module, fields with types, relationships.\n\nExamples:\n- discover_schema({ query: \"Company\" }) \u2192 CustomerCompanyProfile schema\n- discover_schema({ query: \"sales order\" }) \u2192 SalesOrder schema\n- discover_schema({ query: \"customer\" }) \u2192 all customer-related entities\n\nUse this tool to understand what data structures exist before making API calls.`,\n inputSchema: z.object({\n query: z.string().describe('Entity name or keyword to search (e.g., \"Company\", \"sales order\", \"customer\")'),\n limit: z.number().optional().default(5).describe('Maximum number of results to return (default: 5)'),\n }),\n requiredFeatures: [],\n handler: async (rawInput: unknown, ctx: McpToolContext) => {\n const input = rawInput as { query: string; limit?: number }\n const limit = input.limit ?? ENTITY_SCHEMA_SEARCH_CONFIG.defaultLimit\n\n // Get cached entity graph for full schema lookup\n const graph = getCachedEntityGraph()\n if (!graph) {\n return {\n success: false,\n error: 'Entity graph not available. The MCP server may need to be restarted.',\n }\n }\n\n // Build entity lookup map by className\n const entityByClassName = new Map<string, EntityNode>()\n for (const node of graph.nodes) {\n entityByClassName.set(node.className, node)\n }\n\n // Try to get search service for Meilisearch-powered discovery\n let searchService: SearchService | null = null\n try {\n searchService = ctx.container.resolve('searchService') as SearchService\n } catch {\n // Search service not available, fallback to in-memory search\n }\n\n // Search using Meilisearch if available\n if (searchService) {\n try {\n const results = await searchService.search(input.query, {\n tenantId: GLOBAL_TENANT_ID,\n organizationId: null,\n entityTypes: [ENTITY_SCHEMA_ENTITY_ID],\n limit: limit * 2,\n })\n\n if (results.length > 0) {\n // Look up full schema from cached graph using recordId (which is className)\n const entities = results\n .slice(0, limit)\n .map((result) => {\n const node = entityByClassName.get(result.recordId)\n if (node) {\n return buildEntityResult(graph, node)\n }\n return null\n })\n .filter((e): e is NonNullable<typeof e> => e !== null)\n\n if (entities.length > 0) {\n return {\n success: true,\n count: entities.length,\n entities,\n }\n }\n }\n // Fall through to in-memory search if no results\n } catch {\n // Fall through to in-memory search on error\n }\n }\n\n // Fallback: In-memory fuzzy search on entity names\n const queryLower = input.query.toLowerCase()\n const queryTerms = queryLower.split(/\\s+/).filter(Boolean)\n\n const matches = graph.nodes.filter((node) => {\n const className = node.className.toLowerCase()\n const tableName = node.tableName.toLowerCase()\n const module = inferModuleFromEntity(node.className, node.tableName).toLowerCase()\n\n // Match any query term against class name, table name, or module\n return queryTerms.some(\n (term) =>\n className.includes(term) ||\n tableName.includes(term) ||\n module.includes(term)\n )\n })\n\n if (matches.length === 0) {\n // Suggest similar entities\n const suggestions = graph.nodes\n .filter((node) => {\n const className = node.className.toLowerCase()\n return queryTerms.some((term) =>\n className.split(/(?=[A-Z])/).some((part) => part.toLowerCase().includes(term))\n )\n })\n .slice(0, 5)\n .map((node) => node.className)\n\n return {\n success: false,\n error: `No entities found matching \"${input.query}\"`,\n suggestions: suggestions.length > 0 ? suggestions : undefined,\n hint: 'Try a different search term or use broader keywords like \"customer\", \"sales\", \"order\".',\n }\n }\n\n // Build results from matches\n const entities = matches.slice(0, limit).map((node) => buildEntityResult(graph, node))\n\n return {\n success: true,\n count: entities.length,\n entities,\n }\n },\n}\n\n/**\n * All entity graph tools for registration.\n */\nexport const entityGraphTools: McpToolDefinition[] = [\n discoverSchemaTool,\n]\n"],
|
|
5
|
-
"mappings": "AASA,SAAS,SAAS;AAGlB;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,kBAAkB,OAAoB,MAAkB;AAE/D,QAAM,gBAAgB,MAAM,MACzB,OAAO,CAAC,SAAS,KAAK,WAAW,KAAK,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ACL,SAAS;AAAA,QACT,OAAO,+BAA+B,MAAM,KAAK;AAAA,QACjD,aAAa,YAAY,SAAS,IAAI,cAAc;AAAA,QACpD,MAAM;AAAA,MACR;AAAA,IACF;AAGA,UAAM,WAAW,QAAQ,MAAM,GAAG,KAAK,EAAE,IAAI,CAAC,SAAS,kBAAkB,OAAO,IAAI,CAAC;AAErF,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,SAAS;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;AAKO,MAAM,mBAAwC;AAAA,EACnD;AACF;",
|
|
6
|
-
"names": ["entities"]
|
|
7
|
-
}
|
|
@@ -1,250 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* API Discovery Tools
|
|
3
|
-
*
|
|
4
|
-
* Meta-tools for discovering and executing API endpoints via search.
|
|
5
|
-
*
|
|
6
|
-
* 2 tools total:
|
|
7
|
-
* - find_api: Search for endpoints (includes schema summary)
|
|
8
|
-
* - call_api: Execute an endpoint
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import { z } from 'zod'
|
|
12
|
-
import { registerMcpTool } from './tool-registry'
|
|
13
|
-
import type { McpToolContext } from './types'
|
|
14
|
-
import {
|
|
15
|
-
getApiEndpoints,
|
|
16
|
-
searchEndpoints,
|
|
17
|
-
simplifyRequestBodySchema,
|
|
18
|
-
} from './api-endpoint-index'
|
|
19
|
-
import { fetchWithTimeout, resolveTimeoutMs } from '@open-mercato/shared/lib/http/fetchWithTimeout'
|
|
20
|
-
|
|
21
|
-
const DEFAULT_AI_API_REQUEST_TIMEOUT_MS = 30_000
|
|
22
|
-
|
|
23
|
-
function resolveAiApiRequestTimeoutMs(): number {
|
|
24
|
-
const raw = process.env.AI_API_REQUEST_TIMEOUT_MS
|
|
25
|
-
const parsed = raw ? Number.parseInt(raw, 10) : undefined
|
|
26
|
-
return resolveTimeoutMs(parsed, DEFAULT_AI_API_REQUEST_TIMEOUT_MS)
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Load API discovery tools into the registry
|
|
31
|
-
*/
|
|
32
|
-
export async function loadApiDiscoveryTools(): Promise<number> {
|
|
33
|
-
// Ensure endpoints are parsed and cached
|
|
34
|
-
const endpoints = await getApiEndpoints()
|
|
35
|
-
console.error(`[API Discovery] ${endpoints.length} endpoints available for discovery`)
|
|
36
|
-
|
|
37
|
-
// Register the two discovery tools
|
|
38
|
-
registerApiDiscoverTool()
|
|
39
|
-
registerApiExecuteTool()
|
|
40
|
-
|
|
41
|
-
return 2
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* find_api - Find relevant API endpoints based on a query.
|
|
46
|
-
* Enhanced to include request body schema summary.
|
|
47
|
-
*/
|
|
48
|
-
function registerApiDiscoverTool(): void {
|
|
49
|
-
registerMcpTool(
|
|
50
|
-
{
|
|
51
|
-
name: 'find_api',
|
|
52
|
-
description: `Search for API endpoints. Use discover_schema first to understand entity fields, then find_api to get the endpoint schema.
|
|
53
|
-
|
|
54
|
-
Returns: path, method, operationId, parameters, and requestBody schema showing required fields and structure.
|
|
55
|
-
|
|
56
|
-
Workflow: discover_schema("Company") → understand fields → find_api("update company") → see request body schema → call_api`,
|
|
57
|
-
inputSchema: z.object({
|
|
58
|
-
query: z
|
|
59
|
-
.string()
|
|
60
|
-
.describe('Natural language query to find endpoints (e.g., "update company", "create order", "list customers")'),
|
|
61
|
-
method: z
|
|
62
|
-
.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
|
|
63
|
-
.optional()
|
|
64
|
-
.describe('Filter by HTTP method'),
|
|
65
|
-
limit: z.number().optional().default(10).describe('Max results to return (default: 10)'),
|
|
66
|
-
}),
|
|
67
|
-
requiredFeatures: [], // Available to all authenticated users
|
|
68
|
-
handler: async (input: { query: string; method?: string; limit?: number }, ctx) => {
|
|
69
|
-
const { query, method, limit = 10 } = input
|
|
70
|
-
|
|
71
|
-
// Search for matching endpoints
|
|
72
|
-
const searchService = ctx.container?.resolve<any>('searchService')
|
|
73
|
-
const matches = await searchEndpoints(searchService, query, { limit, method })
|
|
74
|
-
|
|
75
|
-
if (matches.length === 0) {
|
|
76
|
-
return {
|
|
77
|
-
success: true,
|
|
78
|
-
message: 'No matching endpoints found. Try different search terms.',
|
|
79
|
-
endpoints: [],
|
|
80
|
-
suggestions: [
|
|
81
|
-
'Try broader terms like "customer", "company", "order", or "sales"',
|
|
82
|
-
'Use method filter to narrow results (e.g., method: "PUT" for updates)',
|
|
83
|
-
'Use discover_schema to find entity names first, then search for those entity names',
|
|
84
|
-
],
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// Format results for LLM consumption - now includes schema
|
|
89
|
-
const results = matches.map((endpoint) => {
|
|
90
|
-
const result: Record<string, unknown> = {
|
|
91
|
-
operationId: endpoint.operationId,
|
|
92
|
-
method: endpoint.method,
|
|
93
|
-
path: endpoint.path,
|
|
94
|
-
description: endpoint.description || endpoint.summary,
|
|
95
|
-
tags: endpoint.tags,
|
|
96
|
-
parameters: endpoint.parameters.map((p) => ({
|
|
97
|
-
name: p.name,
|
|
98
|
-
in: p.in,
|
|
99
|
-
required: p.required,
|
|
100
|
-
type: p.type,
|
|
101
|
-
})),
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// Include request body schema for mutation endpoints
|
|
105
|
-
if (endpoint.requestBodySchema) {
|
|
106
|
-
const simplifiedSchema = simplifyRequestBodySchema(endpoint.requestBodySchema)
|
|
107
|
-
if (simplifiedSchema) {
|
|
108
|
-
result.requestBody = simplifiedSchema
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
return result
|
|
113
|
-
})
|
|
114
|
-
|
|
115
|
-
return {
|
|
116
|
-
success: true,
|
|
117
|
-
message: `Found ${results.length} matching endpoint(s)`,
|
|
118
|
-
endpoints: results,
|
|
119
|
-
hint: 'Use call_api with the method, path, and body structure shown in requestBody schema above.',
|
|
120
|
-
}
|
|
121
|
-
},
|
|
122
|
-
},
|
|
123
|
-
{ moduleId: 'api' }
|
|
124
|
-
)
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* call_api - Execute an API endpoint
|
|
129
|
-
*/
|
|
130
|
-
function registerApiExecuteTool(): void {
|
|
131
|
-
registerMcpTool(
|
|
132
|
-
{
|
|
133
|
-
name: 'call_api',
|
|
134
|
-
description: `Execute an API call using path and body structure from find_api results.
|
|
135
|
-
|
|
136
|
-
Confirm with user before POST/PUT/DELETE operations.`,
|
|
137
|
-
inputSchema: z.object({
|
|
138
|
-
method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method from find_api result'),
|
|
139
|
-
path: z
|
|
140
|
-
.string()
|
|
141
|
-
.describe('API path from find_api result (e.g., /api/customers/companies)'),
|
|
142
|
-
query: z
|
|
143
|
-
.record(z.string(), z.string())
|
|
144
|
-
.optional()
|
|
145
|
-
.describe('Query parameters as key-value pairs'),
|
|
146
|
-
body: z
|
|
147
|
-
.record(z.string(), z.unknown())
|
|
148
|
-
.optional()
|
|
149
|
-
.describe('Request body matching the schema from find_api'),
|
|
150
|
-
}),
|
|
151
|
-
requiredFeatures: [], // ACL checked at API level
|
|
152
|
-
handler: async (
|
|
153
|
-
input: {
|
|
154
|
-
method: string
|
|
155
|
-
path: string
|
|
156
|
-
query?: Record<string, string>
|
|
157
|
-
body?: Record<string, unknown>
|
|
158
|
-
},
|
|
159
|
-
ctx: McpToolContext
|
|
160
|
-
) => {
|
|
161
|
-
const { method, path, query, body } = input
|
|
162
|
-
|
|
163
|
-
// Build URL
|
|
164
|
-
const baseUrl =
|
|
165
|
-
process.env.NEXT_PUBLIC_API_BASE_URL ||
|
|
166
|
-
process.env.NEXT_PUBLIC_APP_URL ||
|
|
167
|
-
process.env.APP_URL ||
|
|
168
|
-
'http://localhost:3000'
|
|
169
|
-
|
|
170
|
-
// Ensure path starts with /api
|
|
171
|
-
const apiPath = path.startsWith('/api') ? path : `/api${path}`
|
|
172
|
-
let url = `${baseUrl}${apiPath}`
|
|
173
|
-
|
|
174
|
-
// Add query parameters
|
|
175
|
-
const queryParams = { ...query }
|
|
176
|
-
|
|
177
|
-
// Add context to query for GET, to body for mutations
|
|
178
|
-
if (method === 'GET') {
|
|
179
|
-
if (ctx.tenantId) queryParams.tenantId = ctx.tenantId
|
|
180
|
-
if (ctx.organizationId) queryParams.organizationId = ctx.organizationId
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
if (Object.keys(queryParams).length > 0) {
|
|
184
|
-
const separator = url.includes('?') ? '&' : '?'
|
|
185
|
-
url += separator + new URLSearchParams(queryParams).toString()
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// Build body with context
|
|
189
|
-
let requestBody: Record<string, unknown> | undefined
|
|
190
|
-
if (['POST', 'PUT', 'PATCH'].includes(method)) {
|
|
191
|
-
requestBody = { ...body }
|
|
192
|
-
if (ctx.tenantId) requestBody.tenantId = ctx.tenantId
|
|
193
|
-
if (ctx.organizationId) requestBody.organizationId = ctx.organizationId
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// Build headers
|
|
197
|
-
const headers: Record<string, string> = {
|
|
198
|
-
'Content-Type': 'application/json',
|
|
199
|
-
}
|
|
200
|
-
if (ctx.apiKeySecret) headers['X-API-Key'] = ctx.apiKeySecret
|
|
201
|
-
if (ctx.tenantId) headers['X-Tenant-Id'] = ctx.tenantId
|
|
202
|
-
if (ctx.organizationId) headers['X-Organization-Id'] = ctx.organizationId
|
|
203
|
-
|
|
204
|
-
// Execute request
|
|
205
|
-
try {
|
|
206
|
-
const response = await fetchWithTimeout(url, {
|
|
207
|
-
method,
|
|
208
|
-
headers,
|
|
209
|
-
body: requestBody ? JSON.stringify(requestBody) : undefined,
|
|
210
|
-
timeoutMs: resolveAiApiRequestTimeoutMs(),
|
|
211
|
-
})
|
|
212
|
-
|
|
213
|
-
const responseText = await response.text()
|
|
214
|
-
|
|
215
|
-
if (!response.ok) {
|
|
216
|
-
return {
|
|
217
|
-
success: false,
|
|
218
|
-
statusCode: response.status,
|
|
219
|
-
error: `API error ${response.status}`,
|
|
220
|
-
details: tryParseJson(responseText),
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
return {
|
|
225
|
-
success: true,
|
|
226
|
-
statusCode: response.status,
|
|
227
|
-
data: tryParseJson(responseText),
|
|
228
|
-
}
|
|
229
|
-
} catch (error) {
|
|
230
|
-
return {
|
|
231
|
-
success: false,
|
|
232
|
-
error: error instanceof Error ? error.message : 'Request failed',
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
},
|
|
236
|
-
},
|
|
237
|
-
{ moduleId: 'api' }
|
|
238
|
-
)
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
* Try to parse JSON, return original string if fails
|
|
243
|
-
*/
|
|
244
|
-
function tryParseJson(text: string): unknown {
|
|
245
|
-
try {
|
|
246
|
-
return JSON.parse(text)
|
|
247
|
-
} catch {
|
|
248
|
-
return text
|
|
249
|
-
}
|
|
250
|
-
}
|