@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.
Files changed (28) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +39 -14
  3. package/README.md +2 -1
  4. package/dist/modules/ai_assistant/lib/api-endpoint-index.js +0 -111
  5. package/dist/modules/ai_assistant/lib/api-endpoint-index.js.map +2 -2
  6. package/dist/modules/ai_assistant/lib/codemode-tools.js.map +2 -2
  7. package/dist/modules/ai_assistant/lib/http-server.js +0 -5
  8. package/dist/modules/ai_assistant/lib/http-server.js.map +2 -2
  9. package/dist/modules/ai_assistant/lib/mcp-dev-server.js +0 -5
  10. package/dist/modules/ai_assistant/lib/mcp-dev-server.js.map +2 -2
  11. package/dist/modules/ai_assistant/lib/mcp-server.js +0 -5
  12. package/dist/modules/ai_assistant/lib/mcp-server.js.map +2 -2
  13. package/package.json +4 -4
  14. package/src/modules/ai_assistant/lib/__tests__/mcp-startup-no-dead-index.test.ts +65 -0
  15. package/src/modules/ai_assistant/lib/api-endpoint-index.ts +5 -186
  16. package/src/modules/ai_assistant/lib/codemode-tools.ts +0 -2
  17. package/src/modules/ai_assistant/lib/http-server.ts +2 -9
  18. package/src/modules/ai_assistant/lib/mcp-dev-server.ts +2 -8
  19. package/src/modules/ai_assistant/lib/mcp-server.ts +1 -10
  20. package/dist/modules/ai_assistant/lib/api-discovery-tools.js +0 -170
  21. package/dist/modules/ai_assistant/lib/api-discovery-tools.js.map +0 -7
  22. package/dist/modules/ai_assistant/lib/api-endpoint-index-config.js +0 -177
  23. package/dist/modules/ai_assistant/lib/api-endpoint-index-config.js.map +0 -7
  24. package/dist/modules/ai_assistant/lib/entity-graph-tools.js +0 -127
  25. package/dist/modules/ai_assistant/lib/entity-graph-tools.js.map +0 -7
  26. package/src/modules/ai_assistant/lib/api-discovery-tools.ts +0 -250
  27. package/src/modules/ai_assistant/lib/api-endpoint-index-config.ts +0 -243
  28. package/src/modules/ai_assistant/lib/entity-graph-tools.ts +0 -192
@@ -135,11 +135,6 @@ async function runMcpServer(options) {
135
135
  try {
136
136
  const searchService = options.container.resolve("searchService");
137
137
  await indexToolsForSearch(searchService);
138
- const { indexApiEndpoints } = await import("./api-endpoint-index.js");
139
- const endpointCount = await indexApiEndpoints(searchService);
140
- if (endpointCount > 0) {
141
- console.error(`[MCP Server] Indexed ${endpointCount} API endpoints for hybrid search`);
142
- }
143
138
  } catch (error) {
144
139
  console.error("[MCP Server] Search indexing skipped (search service not available)");
145
140
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/lib/mcp-server.ts"],
4
- "sourcesContent": ["import { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport { zodToJsonSchema } from 'zod-to-json-schema'\nimport { getToolRegistry } from './tool-registry'\nimport { executeTool } from './tool-executor'\nimport { loadAllModuleTools, indexToolsForSearch } from './tool-loader'\nimport { authenticateMcpRequest, hasRequiredFeatures } from './auth'\nimport type { McpServerOptions, McpToolContext } from './types'\nimport type { SearchService } from '@open-mercato/search/service'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\n\n/**\n * Create and configure an MCP server instance.\n */\nexport async function createMcpServer(options: McpServerOptions): Promise<Server> {\n const { config, container, context, apiKeySecret } = options\n\n let tenantId: string | null = null\n let organizationId: string | null = null\n let userId: string | null = null\n let userFeatures: string[] = []\n let isSuperAdmin = false\n\n // API key authentication takes precedence\n if (apiKeySecret) {\n const authResult = await authenticateMcpRequest(apiKeySecret, container)\n if (!authResult.success) {\n throw new Error(`API key authentication failed: ${authResult.error}`)\n }\n tenantId = authResult.tenantId\n organizationId = authResult.organizationId\n userId = authResult.userId\n userFeatures = authResult.features\n isSuperAdmin = authResult.isSuperAdmin\n console.error(`[MCP Server] Authenticated via API key: ${authResult.keyName}`)\n } else if (context) {\n // Manual context provided\n tenantId = context.tenantId\n organizationId = context.organizationId\n userId = context.userId\n\n if (userId) {\n try {\n const rbacService = container.resolve('rbacService') as {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null }\n ) => Promise<{\n isSuperAdmin: boolean\n features: string[]\n }>\n }\n const acl = await rbacService.loadAcl(userId, {\n tenantId,\n organizationId,\n })\n userFeatures = acl.features\n isSuperAdmin = acl.isSuperAdmin\n } catch (error) {\n console.error('[MCP Server] Failed to load user ACL:', error)\n }\n } else {\n // No user specified - grant superadmin access for development/testing\n isSuperAdmin = true\n console.error('[MCP Server] No user specified, running with superadmin access')\n }\n } else {\n // No context and no API key - superadmin for dev/testing\n isSuperAdmin = true\n console.error('[MCP Server] No auth context, running with superadmin access')\n }\n\n const toolContext: McpToolContext = {\n tenantId,\n organizationId,\n userId,\n container,\n userFeatures,\n isSuperAdmin,\n apiKeySecret,\n }\n\n const server = new Server(\n { name: config.name, version: config.version },\n { capabilities: { tools: {} } }\n )\n\n // List tools handler\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n const registry = getToolRegistry()\n const tools = Array.from(registry.getTools().values())\n\n // Filter tools based on user permissions\n const rbacService = container.resolve<RbacService>('rbacService')\n const accessibleTools = tools.filter((tool) =>\n hasRequiredFeatures(tool.requiredFeatures, userFeatures, isSuperAdmin, rbacService)\n )\n\n if (config.debug) {\n console.error(\n `[MCP Server] Listing ${accessibleTools.length}/${tools.length} tools (filtered by ACL)`\n )\n }\n\n return {\n tools: accessibleTools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n // Cast to any for Zod v4 compatibility with zod-to-json-schema\n inputSchema: zodToJsonSchema(tool.inputSchema as any) as Record<string, unknown>,\n })),\n }\n })\n\n // Call tool handler\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params\n\n if (config.debug) {\n console.error(`[MCP Server] Calling tool: ${name}`, JSON.stringify(args))\n }\n\n const result = await executeTool(name, args ?? {}, toolContext)\n\n if (!result.success) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: result.error, code: result.errorCode }),\n },\n ],\n isError: true,\n }\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result.result, null, 2),\n },\n ],\n }\n })\n\n return server\n}\n\n/**\n * Run MCP server with stdio transport.\n * This keeps the process running until terminated.\n *\n * Supports two authentication modes:\n * 1. API key: Provide `apiKeySecret` option\n * 2. Manual context: Provide `context` with tenant/org/user\n */\nexport async function runMcpServer(options: McpServerOptions): Promise<void> {\n // Generate entity graph for Code Mode search tool\n try {\n const { extractEntityGraph, cacheEntityGraph } = await import('./entity-graph')\n const { getOrm } = await import('@open-mercato/shared/lib/db/mikro')\n const orm = await getOrm()\n const graph = await extractEntityGraph(orm)\n cacheEntityGraph(graph)\n console.error(`[MCP Server] Entity graph: ${graph.nodes.length} entities`)\n } catch (error) {\n console.error('[MCP Server] Entity graph skipped:', error instanceof Error ? error.message : error)\n }\n\n // Pre-cache raw OpenAPI spec for Code Mode search tool\n try {\n const { getRawOpenApiSpec } = await import('./api-endpoint-index')\n await getRawOpenApiSpec()\n console.error('[MCP Server] Raw OpenAPI spec cached for Code Mode')\n } catch (error) {\n console.error('[MCP Server] Raw OpenAPI spec caching skipped:', error instanceof Error ? error.message : error)\n }\n\n // Load tools from all modules before starting\n await loadAllModuleTools()\n\n // Index tools and API endpoints for hybrid search discovery (if search service available)\n try {\n const searchService = options.container.resolve('searchService') as SearchService\n\n // Index MCP tools\n await indexToolsForSearch(searchService)\n\n // Index API endpoints for api_discover\n const { indexApiEndpoints } = await import('./api-endpoint-index')\n const endpointCount = await indexApiEndpoints(searchService)\n if (endpointCount > 0) {\n console.error(`[MCP Server] Indexed ${endpointCount} API endpoints for hybrid search`)\n }\n } catch (error) {\n // Search service might not be configured - discovery will use fallback\n console.error('[MCP Server] Search indexing skipped (search service not available)')\n }\n\n const server = await createMcpServer(options)\n const transport = new StdioServerTransport()\n\n const toolCount = getToolRegistry().listToolNames().length\n\n console.error(`[MCP Server] Starting ${options.config.name} v${options.config.version}`)\n\n if (options.apiKeySecret) {\n console.error(`[MCP Server] Authentication: API key`)\n } else if (options.context) {\n console.error(`[MCP Server] Tenant: ${options.context.tenantId ?? '(none)'}`)\n console.error(`[MCP Server] Organization: ${options.context.organizationId ?? '(none)'}`)\n console.error(`[MCP Server] User: ${options.context.userId ?? '(superadmin)'}`)\n } else {\n console.error(`[MCP Server] Authentication: none (superadmin mode)`)\n }\n\n console.error(`[MCP Server] Tools registered: ${toolCount}`)\n\n await server.connect(transport)\n\n console.error('[MCP Server] Connected and ready for requests')\n\n // Handle shutdown gracefully\n const shutdown = async () => {\n console.error('[MCP Server] Shutting down...')\n await server.close()\n process.exit(0)\n }\n\n process.on('SIGINT', shutdown)\n process.on('SIGTERM', shutdown)\n}\n"],
5
- "mappings": "AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAChC,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB,2BAA2B;AACxD,SAAS,wBAAwB,2BAA2B;AAQ5D,eAAsB,gBAAgB,SAA4C;AAChF,QAAM,EAAE,QAAQ,WAAW,SAAS,aAAa,IAAI;AAErD,MAAI,WAA0B;AAC9B,MAAI,iBAAgC;AACpC,MAAI,SAAwB;AAC5B,MAAI,eAAyB,CAAC;AAC9B,MAAI,eAAe;AAGnB,MAAI,cAAc;AAChB,UAAM,aAAa,MAAM,uBAAuB,cAAc,SAAS;AACvE,QAAI,CAAC,WAAW,SAAS;AACvB,YAAM,IAAI,MAAM,kCAAkC,WAAW,KAAK,EAAE;AAAA,IACtE;AACA,eAAW,WAAW;AACtB,qBAAiB,WAAW;AAC5B,aAAS,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C,UAAM,OAAO,MAAM;AACnB,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,UAAQ,GAAG,UAAU,QAAQ;AAC7B,UAAQ,GAAG,WAAW,QAAQ;AAChC;",
4
+ "sourcesContent": ["import { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport { zodToJsonSchema } from 'zod-to-json-schema'\nimport { getToolRegistry } from './tool-registry'\nimport { executeTool } from './tool-executor'\nimport { loadAllModuleTools, indexToolsForSearch } from './tool-loader'\nimport { authenticateMcpRequest, hasRequiredFeatures } from './auth'\nimport type { McpServerOptions, McpToolContext } from './types'\nimport type { SearchService } from '@open-mercato/search/service'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\n\n/**\n * Create and configure an MCP server instance.\n */\nexport async function createMcpServer(options: McpServerOptions): Promise<Server> {\n const { config, container, context, apiKeySecret } = options\n\n let tenantId: string | null = null\n let organizationId: string | null = null\n let userId: string | null = null\n let userFeatures: string[] = []\n let isSuperAdmin = false\n\n // API key authentication takes precedence\n if (apiKeySecret) {\n const authResult = await authenticateMcpRequest(apiKeySecret, container)\n if (!authResult.success) {\n throw new Error(`API key authentication failed: ${authResult.error}`)\n }\n tenantId = authResult.tenantId\n organizationId = authResult.organizationId\n userId = authResult.userId\n userFeatures = authResult.features\n isSuperAdmin = authResult.isSuperAdmin\n console.error(`[MCP Server] Authenticated via API key: ${authResult.keyName}`)\n } else if (context) {\n // Manual context provided\n tenantId = context.tenantId\n organizationId = context.organizationId\n userId = context.userId\n\n if (userId) {\n try {\n const rbacService = container.resolve('rbacService') as {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null }\n ) => Promise<{\n isSuperAdmin: boolean\n features: string[]\n }>\n }\n const acl = await rbacService.loadAcl(userId, {\n tenantId,\n organizationId,\n })\n userFeatures = acl.features\n isSuperAdmin = acl.isSuperAdmin\n } catch (error) {\n console.error('[MCP Server] Failed to load user ACL:', error)\n }\n } else {\n // No user specified - grant superadmin access for development/testing\n isSuperAdmin = true\n console.error('[MCP Server] No user specified, running with superadmin access')\n }\n } else {\n // No context and no API key - superadmin for dev/testing\n isSuperAdmin = true\n console.error('[MCP Server] No auth context, running with superadmin access')\n }\n\n const toolContext: McpToolContext = {\n tenantId,\n organizationId,\n userId,\n container,\n userFeatures,\n isSuperAdmin,\n apiKeySecret,\n }\n\n const server = new Server(\n { name: config.name, version: config.version },\n { capabilities: { tools: {} } }\n )\n\n // List tools handler\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n const registry = getToolRegistry()\n const tools = Array.from(registry.getTools().values())\n\n // Filter tools based on user permissions\n const rbacService = container.resolve<RbacService>('rbacService')\n const accessibleTools = tools.filter((tool) =>\n hasRequiredFeatures(tool.requiredFeatures, userFeatures, isSuperAdmin, rbacService)\n )\n\n if (config.debug) {\n console.error(\n `[MCP Server] Listing ${accessibleTools.length}/${tools.length} tools (filtered by ACL)`\n )\n }\n\n return {\n tools: accessibleTools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n // Cast to any for Zod v4 compatibility with zod-to-json-schema\n inputSchema: zodToJsonSchema(tool.inputSchema as any) as Record<string, unknown>,\n })),\n }\n })\n\n // Call tool handler\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params\n\n if (config.debug) {\n console.error(`[MCP Server] Calling tool: ${name}`, JSON.stringify(args))\n }\n\n const result = await executeTool(name, args ?? {}, toolContext)\n\n if (!result.success) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: result.error, code: result.errorCode }),\n },\n ],\n isError: true,\n }\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result.result, null, 2),\n },\n ],\n }\n })\n\n return server\n}\n\n/**\n * Run MCP server with stdio transport.\n * This keeps the process running until terminated.\n *\n * Supports two authentication modes:\n * 1. API key: Provide `apiKeySecret` option\n * 2. Manual context: Provide `context` with tenant/org/user\n */\nexport async function runMcpServer(options: McpServerOptions): Promise<void> {\n // Generate entity graph for Code Mode search tool\n try {\n const { extractEntityGraph, cacheEntityGraph } = await import('./entity-graph')\n const { getOrm } = await import('@open-mercato/shared/lib/db/mikro')\n const orm = await getOrm()\n const graph = await extractEntityGraph(orm)\n cacheEntityGraph(graph)\n console.error(`[MCP Server] Entity graph: ${graph.nodes.length} entities`)\n } catch (error) {\n console.error('[MCP Server] Entity graph skipped:', error instanceof Error ? error.message : error)\n }\n\n // Pre-cache raw OpenAPI spec for Code Mode search tool\n try {\n const { getRawOpenApiSpec } = await import('./api-endpoint-index')\n await getRawOpenApiSpec()\n console.error('[MCP Server] Raw OpenAPI spec cached for Code Mode')\n } catch (error) {\n console.error('[MCP Server] Raw OpenAPI spec caching skipped:', error instanceof Error ? error.message : error)\n }\n\n // Load tools from all modules before starting\n await loadAllModuleTools()\n\n // Index tools for hybrid search discovery (if search service available)\n try {\n const searchService = options.container.resolve('searchService') as SearchService\n await indexToolsForSearch(searchService)\n } catch (error) {\n // Search service might not be configured - discovery will use fallback\n console.error('[MCP Server] Search indexing skipped (search service not available)')\n }\n\n const server = await createMcpServer(options)\n const transport = new StdioServerTransport()\n\n const toolCount = getToolRegistry().listToolNames().length\n\n console.error(`[MCP Server] Starting ${options.config.name} v${options.config.version}`)\n\n if (options.apiKeySecret) {\n console.error(`[MCP Server] Authentication: API key`)\n } else if (options.context) {\n console.error(`[MCP Server] Tenant: ${options.context.tenantId ?? '(none)'}`)\n console.error(`[MCP Server] Organization: ${options.context.organizationId ?? '(none)'}`)\n console.error(`[MCP Server] User: ${options.context.userId ?? '(superadmin)'}`)\n } else {\n console.error(`[MCP Server] Authentication: none (superadmin mode)`)\n }\n\n console.error(`[MCP Server] Tools registered: ${toolCount}`)\n\n await server.connect(transport)\n\n console.error('[MCP Server] Connected and ready for requests')\n\n // Handle shutdown gracefully\n const shutdown = async () => {\n console.error('[MCP Server] Shutting down...')\n await server.close()\n process.exit(0)\n }\n\n process.on('SIGINT', shutdown)\n process.on('SIGTERM', shutdown)\n}\n"],
5
+ "mappings": "AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAChC,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB,2BAA2B;AACxD,SAAS,wBAAwB,2BAA2B;AAQ5D,eAAsB,gBAAgB,SAA4C;AAChF,QAAM,EAAE,QAAQ,WAAW,SAAS,aAAa,IAAI;AAErD,MAAI,WAA0B;AAC9B,MAAI,iBAAgC;AACpC,MAAI,SAAwB;AAC5B,MAAI,eAAyB,CAAC;AAC9B,MAAI,eAAe;AAGnB,MAAI,cAAc;AAChB,UAAM,aAAa,MAAM,uBAAuB,cAAc,SAAS;AACvE,QAAI,CAAC,WAAW,SAAS;AACvB,YAAM,IAAI,MAAM,kCAAkC,WAAW,KAAK,EAAE;AAAA,IACtE;AACA,eAAW,WAAW;AACtB,qBAAiB,WAAW;AAC5B,aAAS,WAAW;AACpB,mBAAe,WAAW;AAC1B,mBAAe,WAAW;AAC1B,YAAQ,MAAM,2CAA2C,WAAW,OAAO,EAAE;AAAA,EAC/E,WAAW,SAAS;AAElB,eAAW,QAAQ;AACnB,qBAAiB,QAAQ;AACzB,aAAS,QAAQ;AAEjB,QAAI,QAAQ;AACV,UAAI;AACF,cAAM,cAAc,UAAU,QAAQ,aAAa;AASnD,cAAM,MAAM,MAAM,YAAY,QAAQ,QAAQ;AAAA,UAC5C;AAAA,UACA;AAAA,QACF,CAAC;AACD,uBAAe,IAAI;AACnB,uBAAe,IAAI;AAAA,MACrB,SAAS,OAAO;AACd,gBAAQ,MAAM,yCAAyC,KAAK;AAAA,MAC9D;AAAA,IACF,OAAO;AAEL,qBAAe;AACf,cAAQ,MAAM,gEAAgE;AAAA,IAChF;AAAA,EACF,OAAO;AAE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,IAAI,KAAK,QAAQ,OAAO,OAAO,EAAE;AAEvF,MAAI,QAAQ,cAAc;AACxB,YAAQ,MAAM,sCAAsC;AAAA,EACtD,WAAW,QAAQ,SAAS;AAC1B,YAAQ,MAAM,wBAAwB,QAAQ,QAAQ,YAAY,QAAQ,EAAE;AAC5E,YAAQ,MAAM,8BAA8B,QAAQ,QAAQ,kBAAkB,QAAQ,EAAE;AACxF,YAAQ,MAAM,sBAAsB,QAAQ,QAAQ,UAAU,cAAc,EAAE;AAAA,EAChF,OAAO;AACL,YAAQ,MAAM,qDAAqD;AAAA,EACrE;AAEA,UAAQ,MAAM,kCAAkC,SAAS,EAAE;AAE3D,QAAM,OAAO,QAAQ,SAAS;AAE9B,UAAQ,MAAM,+CAA+C;AAG7D,QAAM,WAAW,YAAY;AAC3B,YAAQ,MAAM,+BAA+B;AAC7C,UAAM,OAAO,MAAM;AACnB,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,UAAQ,GAAG,UAAU,QAAQ;AAC7B,UAAQ,GAAG,WAAW,QAAQ;AAChC;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/ai-assistant",
3
- "version": "0.6.1-develop.3287.1.450f4ffb56",
3
+ "version": "0.6.1-develop.3291.1.6fad645fd0",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22.0.0"
@@ -98,12 +98,12 @@
98
98
  "zod-to-json-schema": "^3.25.2"
99
99
  },
100
100
  "peerDependencies": {
101
- "@open-mercato/shared": "0.6.1-develop.3287.1.450f4ffb56",
102
- "@open-mercato/ui": "0.6.1-develop.3287.1.450f4ffb56",
101
+ "@open-mercato/shared": "0.6.1-develop.3291.1.6fad645fd0",
102
+ "@open-mercato/ui": "0.6.1-develop.3291.1.6fad645fd0",
103
103
  "zod": ">=3.23.0"
104
104
  },
105
105
  "devDependencies": {
106
- "@open-mercato/cli": "0.6.1-develop.3287.1.450f4ffb56",
106
+ "@open-mercato/cli": "0.6.1-develop.3291.1.6fad645fd0",
107
107
  "tsx": "^4.21.0"
108
108
  },
109
109
  "publishConfig": {
@@ -0,0 +1,65 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ import * as apiEndpointIndex from '../api-endpoint-index'
5
+
6
+ const LIB_DIR = join(__dirname, '..')
7
+
8
+ const MCP_ENTRY_FILES = [
9
+ 'http-server.ts',
10
+ 'mcp-server.ts',
11
+ 'mcp-dev-server.ts',
12
+ ] as const
13
+
14
+ describe('issue #1876 — MCP boot must not index dead API endpoints', () => {
15
+ describe('MCP entry points no longer call indexApiEndpoints', () => {
16
+ test.each(MCP_ENTRY_FILES)(
17
+ '%s does not import or call indexApiEndpoints',
18
+ (file) => {
19
+ const source = readFileSync(join(LIB_DIR, file), 'utf-8')
20
+ expect(source).not.toMatch(/indexApiEndpoints/)
21
+ },
22
+ )
23
+ })
24
+
25
+ describe('api-endpoint-index public surface', () => {
26
+ it('exports only the symbols Code Mode still relies on', () => {
27
+ expect(typeof apiEndpointIndex.getApiEndpoints).toBe('function')
28
+ expect(typeof apiEndpointIndex.getEndpointByOperationId).toBe('function')
29
+ expect(typeof apiEndpointIndex.getRawOpenApiSpec).toBe('function')
30
+ expect(typeof apiEndpointIndex.loadRichOpenApiSpec).toBe('function')
31
+ expect(typeof apiEndpointIndex.setRawSpecCache).toBe('function')
32
+ expect(typeof apiEndpointIndex.clearRawSpecCache).toBe('function')
33
+ expect(typeof apiEndpointIndex.clearEndpointCache).toBe('function')
34
+ expect(typeof apiEndpointIndex.simplifyRequestBodySchema).toBe('function')
35
+ })
36
+
37
+ it.each([
38
+ 'indexApiEndpoints',
39
+ 'searchEndpoints',
40
+ 'searchEndpointsFallback',
41
+ 'buildSearchableContent',
42
+ 'API_ENDPOINT_ENTITY',
43
+ ])('no longer exports the dead-index symbol %s', (name) => {
44
+ expect((apiEndpointIndex as Record<string, unknown>)[name]).toBeUndefined()
45
+ })
46
+
47
+ it('no longer imports SearchService or IndexableRecord types', () => {
48
+ const source = readFileSync(join(LIB_DIR, 'api-endpoint-index.ts'), 'utf-8')
49
+ expect(source).not.toMatch(/SearchService/)
50
+ expect(source).not.toMatch(/IndexableRecord/)
51
+ expect(source).not.toMatch(/bulkIndex/)
52
+ expect(source).not.toMatch(/Promise\.race/)
53
+ })
54
+ })
55
+
56
+ describe('legacy files are removed from the tree', () => {
57
+ it.each([
58
+ 'api-discovery-tools.ts',
59
+ 'entity-graph-tools.ts',
60
+ 'api-endpoint-index-config.ts',
61
+ ])('%s no longer exists on disk', (file) => {
62
+ expect(existsSync(join(LIB_DIR, file))).toBe(false)
63
+ })
64
+ })
65
+ })
@@ -1,22 +1,17 @@
1
1
  /**
2
2
  * API Endpoint Index
3
3
  *
4
- * Parses OpenAPI spec and indexes endpoints for discovery via hybrid search.
4
+ * Parses the OpenAPI spec into a cached, in-memory list of endpoints and
5
+ * exposes the raw OpenAPI document to Code Mode's `search` tool. The Code
6
+ * Mode rewrite (2026-02-22) made this the only consumer — the legacy
7
+ * `find_api` / `call_api` / `discover_schema` tools and their search-index
8
+ * fan-out have been removed.
5
9
  */
6
10
 
7
11
  import type { OpenApiDocument } from '@open-mercato/shared/lib/openapi'
8
12
  import { buildOpenApiDocument } from '@open-mercato/shared/lib/openapi'
9
13
  import type { Module } from '@open-mercato/shared/modules/registry'
10
- import type { SearchService } from '@open-mercato/search/service'
11
- import type { IndexableRecord } from '@open-mercato/search/types'
12
14
  import { fetchWithTimeout, resolveTimeoutMs } from '@open-mercato/shared/lib/http/fetchWithTimeout'
13
- import {
14
- API_ENDPOINT_ENTITY_ID,
15
- GLOBAL_TENANT_ID,
16
- API_ENDPOINT_SEARCH_CONFIG,
17
- endpointToIndexableRecord,
18
- computeEndpointsChecksum,
19
- } from './api-endpoint-index-config'
20
15
 
21
16
  const DEFAULT_OPENAPI_FETCH_TIMEOUT_MS = 10_000
22
17
 
@@ -51,12 +46,6 @@ export interface ApiParameter {
51
46
  description: string
52
47
  }
53
48
 
54
- /**
55
- * Entity type for API endpoints in search index
56
- * @deprecated Use API_ENDPOINT_ENTITY_ID from api-endpoint-index-config.ts
57
- */
58
- export const API_ENDPOINT_ENTITY = API_ENDPOINT_ENTITY_ID
59
-
60
49
  /**
61
50
  * In-memory cache of parsed endpoints (avoid re-parsing on each request)
62
51
  */
@@ -469,176 +458,6 @@ function extractRequestBodySchema(
469
458
  return schema
470
459
  }
471
460
 
472
- /**
473
- * Checksum from last indexing operation
474
- */
475
- let lastIndexChecksum: string | null = null
476
-
477
- /**
478
- * Index endpoints for search discovery using hybrid search strategies.
479
- * Uses checksum-based change detection to avoid unnecessary re-indexing.
480
- *
481
- * @param searchService - The search service to use for indexing
482
- * @param force - Force re-indexing even if checksum hasn't changed
483
- * @returns Number of endpoints indexed
484
- */
485
- export async function indexApiEndpoints(
486
- searchService: SearchService,
487
- force = false
488
- ): Promise<number> {
489
- const endpoints = await getApiEndpoints()
490
-
491
- if (endpoints.length === 0) {
492
- console.error('[API Index] No endpoints to index')
493
- return 0
494
- }
495
-
496
- // Compute checksum to detect changes
497
- const checksum = computeEndpointsChecksum(
498
- endpoints.map((e) => ({ operationId: e.operationId, method: e.method, path: e.path }))
499
- )
500
-
501
- // Skip if checksum matches and not forced
502
- if (!force && lastIndexChecksum === checksum) {
503
- console.error(`[API Index] Skipping indexing - ${endpoints.length} endpoints unchanged`)
504
- return 0
505
- }
506
-
507
- // Convert to indexable records using the proper format
508
- const records: IndexableRecord[] = endpoints.map((endpoint) =>
509
- endpointToIndexableRecord(endpoint)
510
- )
511
-
512
- try {
513
- console.error(`[API Index] Starting bulk index of ${records.length} endpoints...`)
514
- // Bulk index using all available strategies (fulltext + vector)
515
- // Use Promise.race with timeout to prevent hanging
516
- const timeoutMs = 60000 // 60 second timeout
517
- const indexPromise = searchService.bulkIndex(records)
518
- const timeoutPromise = new Promise<never>((_, reject) =>
519
- setTimeout(() => reject(new Error(`Bulk index timed out after ${timeoutMs}ms`)), timeoutMs)
520
- )
521
-
522
- await Promise.race([indexPromise, timeoutPromise])
523
- lastIndexChecksum = checksum
524
- console.error(`[API Index] Indexed ${records.length} API endpoints for hybrid search`)
525
- return records.length
526
- } catch (error) {
527
- console.error('[API Index] Failed to index endpoints:', error)
528
- // Still return the count - some strategies may have succeeded
529
- lastIndexChecksum = checksum
530
- return records.length
531
- }
532
- }
533
-
534
- /**
535
- * Build searchable content from endpoint
536
- */
537
- function buildSearchableContent(endpoint: ApiEndpoint): string {
538
- const parts = [
539
- endpoint.operationId,
540
- endpoint.method,
541
- endpoint.path,
542
- endpoint.summary,
543
- endpoint.description,
544
- ...endpoint.tags,
545
- ...endpoint.parameters.map((p) => `${p.name} ${p.description}`),
546
- ]
547
-
548
- return parts.filter(Boolean).join(' ')
549
- }
550
-
551
- /**
552
- * Search endpoints using hybrid search (fulltext + vector).
553
- * Falls back to in-memory search if search service is not available.
554
- */
555
- export async function searchEndpoints(
556
- searchService: SearchService | null,
557
- query: string,
558
- options: { limit?: number; method?: string } = {}
559
- ): Promise<ApiEndpoint[]> {
560
- const { limit = API_ENDPOINT_SEARCH_CONFIG.defaultLimit, method } = options
561
-
562
- // Ensure endpoints are loaded
563
- await getApiEndpoints()
564
-
565
- // Try hybrid search first if search service is available
566
- if (searchService) {
567
- try {
568
- // Use hybrid search (fulltext + vector)
569
- const results = await searchService.search(query, {
570
- tenantId: GLOBAL_TENANT_ID,
571
- organizationId: null,
572
- entityTypes: [API_ENDPOINT_ENTITY_ID],
573
- limit: limit * 2, // Get extra to account for filtering
574
- })
575
-
576
- // Map search results back to ApiEndpoint objects
577
- const endpoints: ApiEndpoint[] = []
578
- for (const result of results) {
579
- if (endpoints.length >= limit) break
580
-
581
- const endpoint = endpointsByOperationId?.get(result.recordId)
582
- if (endpoint) {
583
- // Apply method filter if not handled by search
584
- if (method && endpoint.method !== method.toUpperCase()) continue
585
- endpoints.push(endpoint)
586
- }
587
- }
588
-
589
- if (endpoints.length > 0) {
590
- return endpoints
591
- }
592
-
593
- // Fall through to fallback if no results from hybrid search
594
- console.error('[API Index] No hybrid search results, falling back to in-memory search')
595
- } catch (error) {
596
- console.error('[API Index] Hybrid search failed, falling back to in-memory:', error)
597
- }
598
- }
599
-
600
- // Fallback: Simple in-memory text matching
601
- return searchEndpointsFallback(query, { limit, method })
602
- }
603
-
604
- /**
605
- * Fallback in-memory search when hybrid search is not available.
606
- */
607
- function searchEndpointsFallback(
608
- query: string,
609
- options: { limit?: number; method?: string } = {}
610
- ): ApiEndpoint[] {
611
- const { limit = API_ENDPOINT_SEARCH_CONFIG.defaultLimit, method } = options
612
-
613
- if (!endpointsCache) {
614
- return []
615
- }
616
-
617
- const queryLower = query.toLowerCase()
618
- const queryTerms = queryLower.split(/\s+/).filter(Boolean)
619
-
620
- let matches = endpointsCache.filter((endpoint) => {
621
- const content = buildSearchableContent(endpoint).toLowerCase()
622
- return queryTerms.some((term) => content.includes(term))
623
- })
624
-
625
- // Filter by method if specified
626
- if (method) {
627
- matches = matches.filter((e) => e.method === method.toUpperCase())
628
- }
629
-
630
- // Sort by relevance (number of matching terms)
631
- matches.sort((a, b) => {
632
- const aContent = buildSearchableContent(a).toLowerCase()
633
- const bContent = buildSearchableContent(b).toLowerCase()
634
- const aScore = queryTerms.filter((t) => aContent.includes(t)).length
635
- const bScore = queryTerms.filter((t) => bContent.includes(t)).length
636
- return bScore - aScore
637
- })
638
-
639
- return matches.slice(0, limit)
640
- }
641
-
642
461
  /**
643
462
  * Clear endpoint cache (for testing)
644
463
  */
@@ -528,7 +528,6 @@ function formatValidationError(data: unknown): string {
528
528
 
529
529
  /**
530
530
  * Build entity schema array from the entity graph.
531
- * Same structure as buildEntityResult in entity-graph-tools.ts.
532
531
  */
533
532
  function buildEntitySchemas(graph: EntityGraph) {
534
533
  return graph.nodes.map((node) => {
@@ -761,7 +760,6 @@ RULES: For FIND/LIST → GET only (1 call). For UPDATE → PUT to collection pat
761
760
 
762
761
  /**
763
762
  * Create the api.request() function for the execute sandbox.
764
- * Replicates the authenticated API call logic from api-discovery-tools.ts.
765
763
  */
766
764
  function createApiRequestFn(
767
765
  ctx: McpToolContext,
@@ -435,21 +435,14 @@ export async function runMcpHttpServer(options: McpHttpServerOptions): Promise<v
435
435
  console.error('[MCP HTTP] OpenAPI spec caching skipped:', error instanceof Error ? error.message : error)
436
436
  }
437
437
 
438
- // Index tools, API endpoints, and entity schemas for hybrid search discovery (if search service available)
438
+ // Index tools and entity schemas for hybrid search discovery (if search service available)
439
439
  try {
440
440
  const searchService = container.resolve('searchService') as SearchService
441
441
 
442
442
  // Index MCP tools
443
443
  await indexToolsForSearch(searchService)
444
444
 
445
- // Index API endpoints for find_api
446
- const { indexApiEndpoints } = await import('./api-endpoint-index')
447
- const endpointCount = await indexApiEndpoints(searchService)
448
- if (endpointCount > 0) {
449
- console.error(`[MCP HTTP] Indexed ${endpointCount} API endpoints for hybrid search`)
450
- }
451
-
452
- // Index entity schemas for discover_schema
445
+ // Index entity schemas for hybrid search
453
446
  try {
454
447
  const { getCachedEntityGraph } = await import('./entity-graph')
455
448
  const { indexEntitiesForSearch } = await import('./entity-index')
@@ -278,18 +278,12 @@ export async function runMcpDevServer(): Promise<void> {
278
278
  log('OpenAPI spec caching skipped:', error instanceof Error ? error.message : error)
279
279
  }
280
280
 
281
- // Index tools, API endpoints, and entity schemas for search (if search service available)
281
+ // Index tools and entity schemas for search (if search service available)
282
282
  try {
283
283
  const searchService = container.resolve('searchService') as SearchService
284
284
  await indexToolsForSearch(searchService)
285
285
 
286
- const { indexApiEndpoints } = await import('./api-endpoint-index')
287
- const endpointCount = await indexApiEndpoints(searchService)
288
- if (endpointCount > 0) {
289
- log(`Indexed ${endpointCount} API endpoints for discovery`)
290
- }
291
-
292
- // Index entity schemas for discover_schema tool
286
+ // Index entity schemas for hybrid search
293
287
  try {
294
288
  const { getCachedEntityGraph } = await import('./entity-graph')
295
289
  const { indexEntitiesForSearch } = await import('./entity-index')
@@ -184,19 +184,10 @@ export async function runMcpServer(options: McpServerOptions): Promise<void> {
184
184
  // Load tools from all modules before starting
185
185
  await loadAllModuleTools()
186
186
 
187
- // Index tools and API endpoints for hybrid search discovery (if search service available)
187
+ // Index tools for hybrid search discovery (if search service available)
188
188
  try {
189
189
  const searchService = options.container.resolve('searchService') as SearchService
190
-
191
- // Index MCP tools
192
190
  await indexToolsForSearch(searchService)
193
-
194
- // Index API endpoints for api_discover
195
- const { indexApiEndpoints } = await import('./api-endpoint-index')
196
- const endpointCount = await indexApiEndpoints(searchService)
197
- if (endpointCount > 0) {
198
- console.error(`[MCP Server] Indexed ${endpointCount} API endpoints for hybrid search`)
199
- }
200
191
  } catch (error) {
201
192
  // Search service might not be configured - discovery will use fallback
202
193
  console.error('[MCP Server] Search indexing skipped (search service not available)')
@@ -1,170 +0,0 @@
1
- import { z } from "zod";
2
- import { registerMcpTool } from "./tool-registry.js";
3
- import {
4
- getApiEndpoints,
5
- searchEndpoints,
6
- simplifyRequestBodySchema
7
- } from "./api-endpoint-index.js";
8
- import { fetchWithTimeout, resolveTimeoutMs } from "@open-mercato/shared/lib/http/fetchWithTimeout";
9
- const DEFAULT_AI_API_REQUEST_TIMEOUT_MS = 3e4;
10
- function resolveAiApiRequestTimeoutMs() {
11
- const raw = process.env.AI_API_REQUEST_TIMEOUT_MS;
12
- const parsed = raw ? Number.parseInt(raw, 10) : void 0;
13
- return resolveTimeoutMs(parsed, DEFAULT_AI_API_REQUEST_TIMEOUT_MS);
14
- }
15
- async function loadApiDiscoveryTools() {
16
- const endpoints = await getApiEndpoints();
17
- console.error(`[API Discovery] ${endpoints.length} endpoints available for discovery`);
18
- registerApiDiscoverTool();
19
- registerApiExecuteTool();
20
- return 2;
21
- }
22
- function registerApiDiscoverTool() {
23
- registerMcpTool(
24
- {
25
- name: "find_api",
26
- description: `Search for API endpoints. Use discover_schema first to understand entity fields, then find_api to get the endpoint schema.
27
-
28
- Returns: path, method, operationId, parameters, and requestBody schema showing required fields and structure.
29
-
30
- Workflow: discover_schema("Company") \u2192 understand fields \u2192 find_api("update company") \u2192 see request body schema \u2192 call_api`,
31
- inputSchema: z.object({
32
- query: z.string().describe('Natural language query to find endpoints (e.g., "update company", "create order", "list customers")'),
33
- method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).optional().describe("Filter by HTTP method"),
34
- limit: z.number().optional().default(10).describe("Max results to return (default: 10)")
35
- }),
36
- requiredFeatures: [],
37
- // Available to all authenticated users
38
- handler: async (input, ctx) => {
39
- const { query, method, limit = 10 } = input;
40
- const searchService = ctx.container?.resolve("searchService");
41
- const matches = await searchEndpoints(searchService, query, { limit, method });
42
- if (matches.length === 0) {
43
- return {
44
- success: true,
45
- message: "No matching endpoints found. Try different search terms.",
46
- endpoints: [],
47
- suggestions: [
48
- 'Try broader terms like "customer", "company", "order", or "sales"',
49
- 'Use method filter to narrow results (e.g., method: "PUT" for updates)',
50
- "Use discover_schema to find entity names first, then search for those entity names"
51
- ]
52
- };
53
- }
54
- const results = matches.map((endpoint) => {
55
- const result = {
56
- operationId: endpoint.operationId,
57
- method: endpoint.method,
58
- path: endpoint.path,
59
- description: endpoint.description || endpoint.summary,
60
- tags: endpoint.tags,
61
- parameters: endpoint.parameters.map((p) => ({
62
- name: p.name,
63
- in: p.in,
64
- required: p.required,
65
- type: p.type
66
- }))
67
- };
68
- if (endpoint.requestBodySchema) {
69
- const simplifiedSchema = simplifyRequestBodySchema(endpoint.requestBodySchema);
70
- if (simplifiedSchema) {
71
- result.requestBody = simplifiedSchema;
72
- }
73
- }
74
- return result;
75
- });
76
- return {
77
- success: true,
78
- message: `Found ${results.length} matching endpoint(s)`,
79
- endpoints: results,
80
- hint: "Use call_api with the method, path, and body structure shown in requestBody schema above."
81
- };
82
- }
83
- },
84
- { moduleId: "api" }
85
- );
86
- }
87
- function registerApiExecuteTool() {
88
- registerMcpTool(
89
- {
90
- name: "call_api",
91
- description: `Execute an API call using path and body structure from find_api results.
92
-
93
- Confirm with user before POST/PUT/DELETE operations.`,
94
- inputSchema: z.object({
95
- method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).describe("HTTP method from find_api result"),
96
- path: z.string().describe("API path from find_api result (e.g., /api/customers/companies)"),
97
- query: z.record(z.string(), z.string()).optional().describe("Query parameters as key-value pairs"),
98
- body: z.record(z.string(), z.unknown()).optional().describe("Request body matching the schema from find_api")
99
- }),
100
- requiredFeatures: [],
101
- // ACL checked at API level
102
- handler: async (input, ctx) => {
103
- const { method, path, query, body } = input;
104
- const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || "http://localhost:3000";
105
- const apiPath = path.startsWith("/api") ? path : `/api${path}`;
106
- let url = `${baseUrl}${apiPath}`;
107
- const queryParams = { ...query };
108
- if (method === "GET") {
109
- if (ctx.tenantId) queryParams.tenantId = ctx.tenantId;
110
- if (ctx.organizationId) queryParams.organizationId = ctx.organizationId;
111
- }
112
- if (Object.keys(queryParams).length > 0) {
113
- const separator = url.includes("?") ? "&" : "?";
114
- url += separator + new URLSearchParams(queryParams).toString();
115
- }
116
- let requestBody;
117
- if (["POST", "PUT", "PATCH"].includes(method)) {
118
- requestBody = { ...body };
119
- if (ctx.tenantId) requestBody.tenantId = ctx.tenantId;
120
- if (ctx.organizationId) requestBody.organizationId = ctx.organizationId;
121
- }
122
- const headers = {
123
- "Content-Type": "application/json"
124
- };
125
- if (ctx.apiKeySecret) headers["X-API-Key"] = ctx.apiKeySecret;
126
- if (ctx.tenantId) headers["X-Tenant-Id"] = ctx.tenantId;
127
- if (ctx.organizationId) headers["X-Organization-Id"] = ctx.organizationId;
128
- try {
129
- const response = await fetchWithTimeout(url, {
130
- method,
131
- headers,
132
- body: requestBody ? JSON.stringify(requestBody) : void 0,
133
- timeoutMs: resolveAiApiRequestTimeoutMs()
134
- });
135
- const responseText = await response.text();
136
- if (!response.ok) {
137
- return {
138
- success: false,
139
- statusCode: response.status,
140
- error: `API error ${response.status}`,
141
- details: tryParseJson(responseText)
142
- };
143
- }
144
- return {
145
- success: true,
146
- statusCode: response.status,
147
- data: tryParseJson(responseText)
148
- };
149
- } catch (error) {
150
- return {
151
- success: false,
152
- error: error instanceof Error ? error.message : "Request failed"
153
- };
154
- }
155
- }
156
- },
157
- { moduleId: "api" }
158
- );
159
- }
160
- function tryParseJson(text) {
161
- try {
162
- return JSON.parse(text);
163
- } catch {
164
- return text;
165
- }
166
- }
167
- export {
168
- loadApiDiscoveryTools
169
- };
170
- //# sourceMappingURL=api-discovery-tools.js.map