@open-mercato/ai-assistant 0.6.6-develop.6465.1.019f0fb26f → 0.6.6-develop.6471.1.9ab5bdd79a

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 (199) hide show
  1. package/dist/frontend/hooks/useCommandPalette.js +16 -14
  2. package/dist/frontend/hooks/useCommandPalette.js.map +2 -2
  3. package/dist/modules/ai_assistant/api/ai/actions/[id]/cancel/route.js +3 -1
  4. package/dist/modules/ai_assistant/api/ai/actions/[id]/cancel/route.js.map +2 -2
  5. package/dist/modules/ai_assistant/api/ai/actions/[id]/confirm/route.js +3 -1
  6. package/dist/modules/ai_assistant/api/ai/actions/[id]/confirm/route.js.map +2 -2
  7. package/dist/modules/ai_assistant/api/ai/actions/[id]/route.js +3 -1
  8. package/dist/modules/ai_assistant/api/ai/actions/[id]/route.js.map +2 -2
  9. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/loop-override/route.js +5 -3
  10. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/loop-override/route.js.map +2 -2
  11. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/models/route.js +4 -2
  12. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/models/route.js.map +2 -2
  13. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.js +5 -3
  14. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.js.map +2 -2
  15. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.js +4 -2
  16. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.js.map +2 -2
  17. package/dist/modules/ai_assistant/api/ai/agents/route.js +3 -1
  18. package/dist/modules/ai_assistant/api/ai/agents/route.js.map +2 -2
  19. package/dist/modules/ai_assistant/api/ai/chat/route.js +6 -7
  20. package/dist/modules/ai_assistant/api/ai/chat/route.js.map +2 -2
  21. package/dist/modules/ai_assistant/api/ai/conversations/[conversationId]/route.js +5 -3
  22. package/dist/modules/ai_assistant/api/ai/conversations/[conversationId]/route.js.map +2 -2
  23. package/dist/modules/ai_assistant/api/ai/conversations/import/route.js +3 -1
  24. package/dist/modules/ai_assistant/api/ai/conversations/import/route.js.map +2 -2
  25. package/dist/modules/ai_assistant/api/ai/conversations/route.js +4 -2
  26. package/dist/modules/ai_assistant/api/ai/conversations/route.js.map +2 -2
  27. package/dist/modules/ai_assistant/api/ai/run-object/route.js +3 -1
  28. package/dist/modules/ai_assistant/api/ai/run-object/route.js.map +2 -2
  29. package/dist/modules/ai_assistant/api/chat/route.js +23 -14
  30. package/dist/modules/ai_assistant/api/chat/route.js.map +2 -2
  31. package/dist/modules/ai_assistant/api/health/route.js +3 -1
  32. package/dist/modules/ai_assistant/api/health/route.js.map +2 -2
  33. package/dist/modules/ai_assistant/api/mcp-key/route.js +3 -1
  34. package/dist/modules/ai_assistant/api/mcp-key/route.js.map +2 -2
  35. package/dist/modules/ai_assistant/api/route/route.js +11 -9
  36. package/dist/modules/ai_assistant/api/route/route.js.map +2 -2
  37. package/dist/modules/ai_assistant/api/session-key/route.js +3 -1
  38. package/dist/modules/ai_assistant/api/session-key/route.js.map +2 -2
  39. package/dist/modules/ai_assistant/api/settings/allowlist/route.js +4 -2
  40. package/dist/modules/ai_assistant/api/settings/allowlist/route.js.map +2 -2
  41. package/dist/modules/ai_assistant/api/settings/route.js +6 -4
  42. package/dist/modules/ai_assistant/api/settings/route.js.map +2 -2
  43. package/dist/modules/ai_assistant/api/tools/execute/route.js +3 -1
  44. package/dist/modules/ai_assistant/api/tools/execute/route.js.map +2 -2
  45. package/dist/modules/ai_assistant/api/tools/route.js +3 -1
  46. package/dist/modules/ai_assistant/api/tools/route.js.map +2 -2
  47. package/dist/modules/ai_assistant/api/usage/daily/route.js +3 -1
  48. package/dist/modules/ai_assistant/api/usage/daily/route.js.map +2 -2
  49. package/dist/modules/ai_assistant/api/usage/sessions/[sessionId]/route.js +3 -1
  50. package/dist/modules/ai_assistant/api/usage/sessions/[sessionId]/route.js.map +2 -2
  51. package/dist/modules/ai_assistant/api/usage/sessions/route.js +3 -1
  52. package/dist/modules/ai_assistant/api/usage/sessions/route.js.map +2 -2
  53. package/dist/modules/ai_assistant/cli.js +3 -0
  54. package/dist/modules/ai_assistant/cli.js.map +2 -2
  55. package/dist/modules/ai_assistant/lib/agent-policy.js +7 -5
  56. package/dist/modules/ai_assistant/lib/agent-policy.js.map +2 -2
  57. package/dist/modules/ai_assistant/lib/agent-registry.js +11 -13
  58. package/dist/modules/ai_assistant/lib/agent-registry.js.map +2 -2
  59. package/dist/modules/ai_assistant/lib/agent-runtime.js +21 -44
  60. package/dist/modules/ai_assistant/lib/agent-runtime.js.map +2 -2
  61. package/dist/modules/ai_assistant/lib/agent-tools.js +5 -10
  62. package/dist/modules/ai_assistant/lib/agent-tools.js.map +2 -2
  63. package/dist/modules/ai_assistant/lib/ai-overrides.js +5 -9
  64. package/dist/modules/ai_assistant/lib/ai-overrides.js.map +2 -2
  65. package/dist/modules/ai_assistant/lib/api-endpoint-index.js +22 -22
  66. package/dist/modules/ai_assistant/lib/api-endpoint-index.js.map +2 -2
  67. package/dist/modules/ai_assistant/lib/attachment-parts.js +10 -26
  68. package/dist/modules/ai_assistant/lib/attachment-parts.js.map +2 -2
  69. package/dist/modules/ai_assistant/lib/auth.js +3 -1
  70. package/dist/modules/ai_assistant/lib/auth.js.map +2 -2
  71. package/dist/modules/ai_assistant/lib/codemode-tools.js +15 -17
  72. package/dist/modules/ai_assistant/lib/codemode-tools.js.map +2 -2
  73. package/dist/modules/ai_assistant/lib/entity-index.js +7 -5
  74. package/dist/modules/ai_assistant/lib/entity-index.js.map +2 -2
  75. package/dist/modules/ai_assistant/lib/generated-registry-loader.js +3 -4
  76. package/dist/modules/ai_assistant/lib/generated-registry-loader.js.map +2 -2
  77. package/dist/modules/ai_assistant/lib/http-server.js +45 -48
  78. package/dist/modules/ai_assistant/lib/http-server.js.map +2 -2
  79. package/dist/modules/ai_assistant/lib/llm-bootstrap.js +5 -12
  80. package/dist/modules/ai_assistant/lib/llm-bootstrap.js.map +2 -2
  81. package/dist/modules/ai_assistant/lib/mcp-client.js +3 -1
  82. package/dist/modules/ai_assistant/lib/mcp-client.js.map +2 -2
  83. package/dist/modules/ai_assistant/lib/mcp-dev-key-resolution.js +3 -1
  84. package/dist/modules/ai_assistant/lib/mcp-dev-key-resolution.js.map +2 -2
  85. package/dist/modules/ai_assistant/lib/mcp-dev-server.js +3 -1
  86. package/dist/modules/ai_assistant/lib/mcp-dev-server.js.map +2 -2
  87. package/dist/modules/ai_assistant/lib/mcp-server.js +24 -19
  88. package/dist/modules/ai_assistant/lib/mcp-server.js.map +2 -2
  89. package/dist/modules/ai_assistant/lib/mcp-tool-adapter.js +3 -1
  90. package/dist/modules/ai_assistant/lib/mcp-tool-adapter.js.map +2 -2
  91. package/dist/modules/ai_assistant/lib/model-factory.js +4 -2
  92. package/dist/modules/ai_assistant/lib/model-factory.js.map +2 -2
  93. package/dist/modules/ai_assistant/lib/opencode-client.js +5 -3
  94. package/dist/modules/ai_assistant/lib/opencode-client.js.map +2 -2
  95. package/dist/modules/ai_assistant/lib/opencode-handlers.js +30 -12
  96. package/dist/modules/ai_assistant/lib/opencode-handlers.js.map +2 -2
  97. package/dist/modules/ai_assistant/lib/pending-action-cancel.js +3 -1
  98. package/dist/modules/ai_assistant/lib/pending-action-cancel.js.map +2 -2
  99. package/dist/modules/ai_assistant/lib/pending-action-executor.js +3 -1
  100. package/dist/modules/ai_assistant/lib/pending-action-executor.js.map +2 -2
  101. package/dist/modules/ai_assistant/lib/prepare-mutation.js +4 -6
  102. package/dist/modules/ai_assistant/lib/prepare-mutation.js.map +2 -2
  103. package/dist/modules/ai_assistant/lib/schema-utils.js +3 -1
  104. package/dist/modules/ai_assistant/lib/schema-utils.js.map +2 -2
  105. package/dist/modules/ai_assistant/lib/token-usage-recorder.js +4 -8
  106. package/dist/modules/ai_assistant/lib/token-usage-recorder.js.map +2 -2
  107. package/dist/modules/ai_assistant/lib/tool-executor.js +3 -1
  108. package/dist/modules/ai_assistant/lib/tool-executor.js.map +2 -2
  109. package/dist/modules/ai_assistant/lib/tool-loader.js +18 -25
  110. package/dist/modules/ai_assistant/lib/tool-loader.js.map +2 -2
  111. package/dist/modules/ai_assistant/lib/tool-registry.js +3 -1
  112. package/dist/modules/ai_assistant/lib/tool-registry.js.map +2 -2
  113. package/dist/modules/ai_assistant/lib/tool-test-runner.js +3 -1
  114. package/dist/modules/ai_assistant/lib/tool-test-runner.js.map +2 -2
  115. package/dist/modules/ai_assistant/setup.js +4 -8
  116. package/dist/modules/ai_assistant/setup.js.map +2 -2
  117. package/dist/modules/ai_assistant/subscribers/conversation-shared-notify.js +3 -1
  118. package/dist/modules/ai_assistant/subscribers/conversation-shared-notify.js.map +2 -2
  119. package/dist/modules/ai_assistant/workers/ai-pending-action-cleanup.js +7 -19
  120. package/dist/modules/ai_assistant/workers/ai-pending-action-cleanup.js.map +2 -2
  121. package/dist/modules/ai_assistant/workers/ai-token-usage-prune.js +5 -11
  122. package/dist/modules/ai_assistant/workers/ai-token-usage-prune.js.map +2 -2
  123. package/package.json +6 -6
  124. package/src/frontend/hooks/useCommandPalette.ts +17 -16
  125. package/src/modules/ai_assistant/__tests__/events.test.ts +23 -5
  126. package/src/modules/ai_assistant/__tests__/integration/ws-c-attachment-bridge.test.ts +21 -3
  127. package/src/modules/ai_assistant/__tests__/integration/ws-c-policy-and-tools.test.ts +22 -3
  128. package/src/modules/ai_assistant/__tests__/token-usage-recorder.test.ts +26 -5
  129. package/src/modules/ai_assistant/api/ai/actions/[id]/cancel/route.ts +4 -1
  130. package/src/modules/ai_assistant/api/ai/actions/[id]/confirm/route.ts +4 -1
  131. package/src/modules/ai_assistant/api/ai/actions/[id]/route.ts +4 -1
  132. package/src/modules/ai_assistant/api/ai/agents/[agentId]/loop-override/route.ts +6 -3
  133. package/src/modules/ai_assistant/api/ai/agents/[agentId]/models/route.ts +5 -2
  134. package/src/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.ts +6 -3
  135. package/src/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.ts +5 -2
  136. package/src/modules/ai_assistant/api/ai/agents/route.ts +4 -1
  137. package/src/modules/ai_assistant/api/ai/chat/route.ts +7 -7
  138. package/src/modules/ai_assistant/api/ai/conversations/[conversationId]/route.ts +6 -3
  139. package/src/modules/ai_assistant/api/ai/conversations/import/route.ts +4 -1
  140. package/src/modules/ai_assistant/api/ai/conversations/route.ts +5 -2
  141. package/src/modules/ai_assistant/api/ai/run-object/route.ts +4 -1
  142. package/src/modules/ai_assistant/api/chat/route.ts +24 -15
  143. package/src/modules/ai_assistant/api/health/route.ts +4 -1
  144. package/src/modules/ai_assistant/api/mcp-key/route.ts +4 -1
  145. package/src/modules/ai_assistant/api/route/route.ts +12 -9
  146. package/src/modules/ai_assistant/api/session-key/route.ts +4 -1
  147. package/src/modules/ai_assistant/api/settings/allowlist/route.ts +5 -2
  148. package/src/modules/ai_assistant/api/settings/route.ts +7 -4
  149. package/src/modules/ai_assistant/api/tools/execute/route.ts +4 -1
  150. package/src/modules/ai_assistant/api/tools/route.ts +4 -1
  151. package/src/modules/ai_assistant/api/usage/daily/route.ts +4 -1
  152. package/src/modules/ai_assistant/api/usage/sessions/[sessionId]/route.ts +4 -1
  153. package/src/modules/ai_assistant/api/usage/sessions/route.ts +4 -1
  154. package/src/modules/ai_assistant/cli.ts +5 -0
  155. package/src/modules/ai_assistant/lib/__tests__/agent-policy.mutation-override.test.ts +20 -2
  156. package/src/modules/ai_assistant/lib/__tests__/agent-registry.test.ts +25 -5
  157. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-loop-phase0.test.ts +21 -2
  158. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-parity.test.ts +23 -3
  159. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-phase4a.test.ts +20 -2
  160. package/src/modules/ai_assistant/lib/__tests__/agent-tools.test.ts +22 -3
  161. package/src/modules/ai_assistant/lib/__tests__/ai-overrides.test.ts +23 -3
  162. package/src/modules/ai_assistant/lib/__tests__/attachment-parts.test.ts +25 -7
  163. package/src/modules/ai_assistant/lib/__tests__/model-factory.test.ts +25 -5
  164. package/src/modules/ai_assistant/lib/__tests__/pending-action-cancel.test.ts +19 -1
  165. package/src/modules/ai_assistant/lib/__tests__/prepare-mutation.test.ts +22 -3
  166. package/src/modules/ai_assistant/lib/agent-policy.ts +8 -5
  167. package/src/modules/ai_assistant/lib/agent-registry.ts +12 -15
  168. package/src/modules/ai_assistant/lib/agent-runtime.ts +23 -46
  169. package/src/modules/ai_assistant/lib/agent-tools.ts +7 -11
  170. package/src/modules/ai_assistant/lib/ai-overrides.ts +6 -9
  171. package/src/modules/ai_assistant/lib/api-endpoint-index.ts +23 -22
  172. package/src/modules/ai_assistant/lib/attachment-parts.ts +14 -29
  173. package/src/modules/ai_assistant/lib/auth.ts +4 -1
  174. package/src/modules/ai_assistant/lib/codemode-tools.ts +17 -17
  175. package/src/modules/ai_assistant/lib/entity-index.ts +8 -5
  176. package/src/modules/ai_assistant/lib/generated-registry-loader.ts +4 -4
  177. package/src/modules/ai_assistant/lib/http-server.ts +46 -48
  178. package/src/modules/ai_assistant/lib/llm-bootstrap.ts +7 -13
  179. package/src/modules/ai_assistant/lib/mcp-client.ts +4 -1
  180. package/src/modules/ai_assistant/lib/mcp-dev-key-resolution.ts +4 -1
  181. package/src/modules/ai_assistant/lib/mcp-dev-server.ts +4 -1
  182. package/src/modules/ai_assistant/lib/mcp-server.ts +27 -19
  183. package/src/modules/ai_assistant/lib/mcp-tool-adapter.ts +4 -1
  184. package/src/modules/ai_assistant/lib/model-factory.ts +6 -3
  185. package/src/modules/ai_assistant/lib/opencode-client.ts +6 -3
  186. package/src/modules/ai_assistant/lib/opencode-handlers.ts +32 -12
  187. package/src/modules/ai_assistant/lib/pending-action-cancel.ts +4 -1
  188. package/src/modules/ai_assistant/lib/pending-action-executor.ts +4 -1
  189. package/src/modules/ai_assistant/lib/prepare-mutation.ts +5 -6
  190. package/src/modules/ai_assistant/lib/schema-utils.ts +4 -1
  191. package/src/modules/ai_assistant/lib/token-usage-recorder.ts +5 -8
  192. package/src/modules/ai_assistant/lib/tool-executor.ts +4 -1
  193. package/src/modules/ai_assistant/lib/tool-loader.ts +19 -25
  194. package/src/modules/ai_assistant/lib/tool-registry.ts +4 -1
  195. package/src/modules/ai_assistant/lib/tool-test-runner.ts +4 -1
  196. package/src/modules/ai_assistant/setup.ts +5 -8
  197. package/src/modules/ai_assistant/subscribers/conversation-shared-notify.ts +4 -1
  198. package/src/modules/ai_assistant/workers/ai-pending-action-cleanup.ts +8 -19
  199. package/src/modules/ai_assistant/workers/ai-token-usage-prune.ts +6 -11
@@ -1,3 +1,5 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
2
+
1
3
  /**
2
4
  * Code Mode Tools
3
5
  *
@@ -30,6 +32,8 @@ import {
30
32
  } from './session-memory'
31
33
  import { fetchWithTimeout, resolveTimeoutMs } from '@open-mercato/shared/lib/http/fetchWithTimeout'
32
34
 
35
+ const logger = createLogger('ai_assistant').child({ component: 'codemode' })
36
+
33
37
  const DEFAULT_AI_API_REQUEST_TIMEOUT_MS = 30_000
34
38
 
35
39
  function resolveAiApiRequestTimeoutMs(): number {
@@ -336,7 +340,7 @@ async function generateCommonTypes(): Promise<string> {
336
340
  }
337
341
 
338
342
  cachedCommonTypes = typeLines.join('\n')
339
- console.error(`[Code Mode] Generated ${typeLines.length - 1} common type stubs`)
343
+ logger.debug('Generated common type stubs', { count: typeLines.length - 1 })
340
344
  return cachedCommonTypes
341
345
  }
342
346
 
@@ -586,14 +590,13 @@ Use BEFORE execute to learn endpoint schemas for CREATE/UPDATE. Skip for common
586
590
  }),
587
591
  requiredFeatures: [...CODE_MODE_REQUIRED_FEATURES],
588
592
  handler: async (input: { code: string }, ctx: McpToolContext) => {
589
- const codePreview = input.code.slice(0, 120).replace(/\n/g, ' ')
590
- console.error(`[AI Usage] search: code="${codePreview}${input.code.length > 120 ? '...' : ''}"`)
593
+ logger.debug('search tool invoked', { codeChars: input.code.length })
591
594
 
592
595
  // Check session memory for cached result
593
596
  if (ctx.sessionId) {
594
597
  const cached = lookupSearchCache(ctx.sessionId, input.code)
595
598
  if (cached) {
596
- console.error(`[AI Usage] search: CACHE HIT (label="${cached.label}")`)
599
+ logger.debug('search tool cache hit', { label: cached.label })
597
600
  const memoryContext = buildMemoryContext(ctx.sessionId)
598
601
  return {
599
602
  success: true,
@@ -606,7 +609,7 @@ Use BEFORE execute to learn endpoint schemas for CREATE/UPDATE. Skip for common
606
609
  // Enforce tool call limit
607
610
  const { count, exceeded } = incrementToolCallCount(ctx.sessionId)
608
611
  if (exceeded) {
609
- console.error(`[AI Usage] search: TOOL CALL LIMIT EXCEEDED (count=${count})`)
612
+ logger.warn('search tool call limit exceeded', { count })
610
613
  return {
611
614
  success: false,
612
615
  error: 'Tool call limit exceeded. Summarize what you know and respond to the user.',
@@ -619,7 +622,7 @@ Use BEFORE execute to learn endpoint schemas for CREATE/UPDATE. Skip for common
619
622
  const result = await sandbox.execute(input.code)
620
623
 
621
624
  if (result.error) {
622
- console.error(`[AI Usage] search: ERROR in ${result.durationMs}ms — ${result.error}`)
625
+ logger.info('search tool errored', { durationMs: result.durationMs, err: result.error })
623
626
  return {
624
627
  success: false,
625
628
  error: result.error,
@@ -629,7 +632,7 @@ Use BEFORE execute to learn endpoint schemas for CREATE/UPDATE. Skip for common
629
632
  }
630
633
 
631
634
  const truncated = truncateResult(result.result)
632
- console.error(`[AI Usage] search: OK in ${result.durationMs}ms — ${truncated.length} chars`)
635
+ logger.info('search tool succeeded', { durationMs: result.durationMs, resultChars: truncated.length })
633
636
 
634
637
  // Store in session memory
635
638
  if (ctx.sessionId) {
@@ -674,14 +677,13 @@ RULES: For FIND/LIST → GET only (1 call). For UPDATE → PUT to collection pat
674
677
  }),
675
678
  requiredFeatures: [...CODE_MODE_REQUIRED_FEATURES],
676
679
  handler: async (input: { code: string }, ctx: McpToolContext) => {
677
- const codePreview = input.code.slice(0, 120).replace(/\n/g, ' ')
678
- console.error(`[AI Usage] execute: code="${codePreview}${input.code.length > 120 ? '...' : ''}" user=${ctx.userId || 'unknown'}`)
680
+ logger.debug('execute tool invoked', { codeChars: input.code.length, userId: ctx.userId || 'unknown' })
679
681
 
680
682
  // Enforce tool call limit
681
683
  if (ctx.sessionId) {
682
684
  const { count, exceeded } = incrementToolCallCount(ctx.sessionId)
683
685
  if (exceeded) {
684
- console.error(`[AI Usage] execute: TOOL CALL LIMIT EXCEEDED (count=${count})`)
686
+ logger.warn('execute tool call limit exceeded', { count })
685
687
  return {
686
688
  success: false,
687
689
  error: 'Tool call limit exceeded. Summarize what you know and respond to the user.',
@@ -723,7 +725,7 @@ RULES: For FIND/LIST → GET only (1 call). For UPDATE → PUT to collection pat
723
725
  const result = await sandbox.execute(input.code)
724
726
 
725
727
  if (result.error) {
726
- console.error(`[AI Usage] execute: ERROR in ${result.durationMs}ms — apiCalls=${apiCallCount} — ${result.error}`)
728
+ logger.info('execute tool errored', { durationMs: result.durationMs, apiCalls: apiCallCount, err: result.error })
727
729
  return {
728
730
  success: false,
729
731
  error: result.error,
@@ -734,7 +736,7 @@ RULES: For FIND/LIST → GET only (1 call). For UPDATE → PUT to collection pat
734
736
  }
735
737
 
736
738
  const truncated = truncateResult(result.result)
737
- console.error(`[AI Usage] execute: OK in ${result.durationMs}ms — apiCalls=${apiCallCount} — ${truncated.length} chars`)
739
+ logger.info('execute tool succeeded', { durationMs: result.durationMs, apiCalls: apiCallCount, resultChars: truncated.length })
738
740
 
739
741
  const memoryContext = ctx.sessionId ? buildMemoryContext(ctx.sessionId) : undefined
740
742
  return {
@@ -779,9 +781,7 @@ export function createApiRequestFn(
779
781
 
780
782
  if (!authorization.allowed) {
781
783
  const callDuration = Date.now() - callStart
782
- console.error(
783
- `[AI Usage] api.request: ${normalizedMethod} ${apiPath} → ${authorization.statusCode} in ${callDuration}ms (blocked by Code Mode RBAC)`
784
- )
784
+ logger.warn('api.request blocked by Code Mode RBAC', { method: normalizedMethod, path: apiPath, statusCode: authorization.statusCode, durationMs: callDuration })
785
785
  return {
786
786
  success: false,
787
787
  statusCode: authorization.statusCode,
@@ -834,7 +834,7 @@ export function createApiRequestFn(
834
834
  const callDuration = Date.now() - callStart
835
835
 
836
836
  if (!response.ok) {
837
- console.error(`[AI Usage] api.request: ${normalizedMethod} ${apiPath} → ${response.status} in ${callDuration}ms`)
837
+ logger.debug('api.request completed with error status', { method: normalizedMethod, path: apiPath, status: response.status, durationMs: callDuration })
838
838
 
839
839
  // Format 400 validation errors into a clear fix instruction for the LLM
840
840
  if (response.status === 400) {
@@ -853,7 +853,7 @@ export function createApiRequestFn(
853
853
  }
854
854
  }
855
855
 
856
- console.error(`[AI Usage] api.request: ${normalizedMethod} ${apiPath} → ${response.status} in ${callDuration}ms (${responseText.length} bytes)`)
856
+ logger.debug('api.request completed', { method: normalizedMethod, path: apiPath, status: response.status, durationMs: callDuration, bytes: responseText.length })
857
857
 
858
858
  // Add mutation warning for non-GET calls
859
859
  if (!['GET', 'HEAD', 'OPTIONS'].includes(normalizedMethod)) {
@@ -5,6 +5,7 @@
5
5
  * via the discover_schema MCP tool.
6
6
  */
7
7
 
8
+ import { createLogger } from '@open-mercato/shared/lib/logger'
8
9
  import type { SearchService } from '@open-mercato/search/service'
9
10
  import type { IndexableRecord } from '@open-mercato/search/types'
10
11
  import type { EntityGraph } from './entity-graph'
@@ -15,6 +16,8 @@ import {
15
16
  type IndexedEntity,
16
17
  } from './entity-index-config'
17
18
 
19
+ const logger = createLogger('ai_assistant')
20
+
18
21
  /**
19
22
  * Checksum from last indexing operation
20
23
  */
@@ -35,7 +38,7 @@ export async function indexEntitiesForSearch(
35
38
  force = false
36
39
  ): Promise<{ count: number }> {
37
40
  if (graph.nodes.length === 0) {
38
- console.error('[Entity Index] No entities to index')
41
+ logger.error('Entity Index — No entities to index')
39
42
  return { count: 0 }
40
43
  }
41
44
 
@@ -71,7 +74,7 @@ export async function indexEntitiesForSearch(
71
74
 
72
75
  // Skip if checksum matches and not forced
73
76
  if (!force && lastIndexChecksum === checksum) {
74
- console.error(`[Entity Index] Skipping indexing - ${indexedEntities.length} entities unchanged`)
77
+ logger.debug('Skipping entity indexing - entities unchanged', { count: indexedEntities.length })
75
78
  return { count: 0 }
76
79
  }
77
80
 
@@ -81,7 +84,7 @@ export async function indexEntitiesForSearch(
81
84
  )
82
85
 
83
86
  try {
84
- console.error(`[Entity Index] Starting bulk index of ${records.length} entities...`)
87
+ logger.info('Starting bulk index of entities', { count: records.length })
85
88
 
86
89
  // Bulk index using all available strategies (fulltext + vector)
87
90
  // Use Promise.race with timeout to prevent hanging
@@ -93,10 +96,10 @@ export async function indexEntitiesForSearch(
93
96
 
94
97
  await Promise.race([indexPromise, timeoutPromise])
95
98
  lastIndexChecksum = checksum
96
- console.error(`[Entity Index] Indexed ${records.length} entity schemas for hybrid search`)
99
+ logger.info('Indexed entity schemas for hybrid search', { count: records.length })
97
100
  return { count: records.length }
98
101
  } catch (error) {
99
- console.error('[Entity Index] Failed to index entities:', error)
102
+ logger.error('Entity Index — Failed to index entities', { err: error })
100
103
  // Still update checksum - some strategies may have succeeded
101
104
  lastIndexChecksum = checksum
102
105
  return { count: records.length }
@@ -14,11 +14,14 @@
14
14
  * `@open-mercato/shared/lib/bootstrap/dynamicLoader` and works in both the
15
15
  * monorepo and standalone apps.
16
16
  */
17
+ import { createLogger } from '@open-mercato/shared/lib/logger'
17
18
  import path from 'node:path'
18
19
  import fs from 'node:fs'
19
20
  import { createRequire } from 'node:module'
20
21
  import { fileURLToPath, pathToFileURL } from 'node:url'
21
22
 
23
+ const logger = createLogger('ai_assistant')
24
+
22
25
  const requireFromHere = createRequire(import.meta.url)
23
26
 
24
27
  /**
@@ -236,10 +239,7 @@ export async function ensureApiRouteManifestsRegistered(): Promise<number> {
236
239
  )
237
240
  return apiRoutes.length
238
241
  } catch (error) {
239
- console.warn(
240
- '[MCP Tools] Could not register api-routes manifest:',
241
- error instanceof Error ? error.message : error,
242
- )
242
+ logger.warn('Could not register api-routes manifest', { err: error })
243
243
  return 0
244
244
  }
245
245
  }
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
2
3
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
3
4
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
@@ -16,6 +17,8 @@ import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacS
16
17
  import type { ApiKey } from '@open-mercato/core/modules/api_keys/data/entities'
17
18
  import { findApiKeyBySecret, findSessionApiKeyWithSecret } from '@open-mercato/core/modules/api_keys/services/apiKeyService'
18
19
 
20
+ const logger = createLogger('ai_assistant').child({ component: 'mcp-http' })
21
+
19
22
  /**
20
23
  * Options for the HTTP MCP server.
21
24
  */
@@ -43,7 +46,7 @@ async function resolveSessionContext(
43
46
  const sessionResult = await findSessionApiKeyWithSecret(em, sessionToken)
44
47
  if (!sessionResult) {
45
48
  if (debug) {
46
- console.error(`[MCP HTTP] Session token not found, expired, or secret unavailable: ${redactSecretForLog(sessionToken)}`)
49
+ logger.debug('Session token not found, expired, or secret unavailable', { sessionToken: redactSecretForLog(sessionToken) })
47
50
  }
48
51
  return null
49
52
  }
@@ -54,7 +57,7 @@ async function resolveSessionContext(
54
57
  const userId = sessionKey.sessionUserId || sessionKey.createdBy
55
58
  if (!userId) {
56
59
  if (debug) {
57
- console.error(`[MCP HTTP] Session key has no associated user`)
60
+ logger.debug('Session key has no associated user')
58
61
  }
59
62
  return null
60
63
  }
@@ -65,7 +68,8 @@ async function resolveSessionContext(
65
68
  })
66
69
 
67
70
  if (debug) {
68
- console.error(`[MCP HTTP] Session context resolved for user ${userId}:`, {
71
+ logger.debug('Session context resolved', {
72
+ userId,
69
73
  tenantId: sessionKey.tenantId,
70
74
  organizationId: sessionKey.organizationId,
71
75
  features: acl.features.length,
@@ -86,7 +90,7 @@ async function resolveSessionContext(
86
90
  }
87
91
  } catch (error) {
88
92
  if (debug) {
89
- console.error(`[MCP HTTP] Error resolving session context:`, error)
93
+ logger.debug('Error resolving session context', { err: error })
90
94
  }
91
95
  return null
92
96
  }
@@ -106,7 +110,7 @@ async function resolveApiKeyContext(
106
110
  const userId = apiKeyRecord.sessionUserId ?? apiKeyRecord.createdBy
107
111
  if (!userId) {
108
112
  if (debug) {
109
- console.error(`[MCP HTTP] API key has no associated user`)
113
+ logger.debug('API key has no associated user')
110
114
  }
111
115
  return null
112
116
  }
@@ -117,7 +121,8 @@ async function resolveApiKeyContext(
117
121
  })
118
122
 
119
123
  if (debug) {
120
- console.error(`[MCP HTTP] API key context resolved for user ${userId}:`, {
124
+ logger.debug('API key context resolved', {
125
+ userId,
121
126
  tenantId: apiKeyRecord.tenantId,
122
127
  organizationId: apiKeyRecord.organizationId,
123
128
  features: acl.features.length,
@@ -136,7 +141,7 @@ async function resolveApiKeyContext(
136
141
  }
137
142
  } catch (error) {
138
143
  if (debug) {
139
- console.error(`[MCP HTTP] Error resolving API key context:`, error)
144
+ logger.debug('Error resolving API key context', { err: error })
140
145
  }
141
146
  return null
142
147
  }
@@ -161,13 +166,13 @@ function createMcpServerForRequest(
161
166
  const tools = Array.from(registry.getTools().values())
162
167
 
163
168
  if (config.debug) {
164
- console.error(`[MCP HTTP] Registering ${tools.length} tools (ACL checked per-call via session token)`)
169
+ logger.debug('Registering tools (ACL checked per-call via session token)', { toolCount: tools.length })
165
170
  }
166
171
 
167
172
  // Register ALL tools - permission checks happen at execution time via session token
168
173
  for (const tool of tools) {
169
174
  if (config.debug) {
170
- console.error(`[MCP HTTP] Registering tool: ${tool.name}`)
175
+ logger.debug('Registering tool', { toolName: tool.name })
171
176
  }
172
177
 
173
178
  // Convert Zod schema to a "safe" schema without Date types
@@ -193,10 +198,7 @@ function createMcpServerForRequest(
193
198
  safeSchema = (converted as z.ZodObject<any>).passthrough()
194
199
  } catch (error) {
195
200
  if (config.debug) {
196
- console.error(
197
- `[MCP HTTP] Skipping tool ${tool.name} - schema conversion failed:`,
198
- error instanceof Error ? error.message : error
199
- )
201
+ logger.debug('Skipping tool: schema conversion failed', { toolName: tool.name, err: error })
200
202
  }
201
203
  continue
202
204
  }
@@ -226,9 +228,10 @@ function createMcpServerForRequest(
226
228
  delete toolArgs._sessionToken // Remove before passing to tool handler
227
229
 
228
230
  // Always log tool calls for debugging
229
- console.error(`[MCP HTTP] ▶ Tool call: ${tool.name}`, {
231
+ logger.debug('Tool call received', {
232
+ toolName: tool.name,
230
233
  hasSessionToken: !!sessionToken,
231
- args: JSON.stringify(toolArgs).slice(0, 200),
234
+ argKeys: Object.keys(toolArgs ?? {}).join(','),
232
235
  })
233
236
 
234
237
  // Resolve user context from session token
@@ -312,7 +315,7 @@ function createMcpServerForRequest(
312
315
  const result = await executeTool(tool.name, toolArgs, effectiveContext)
313
316
 
314
317
  if (!result.success) {
315
- console.error(`[MCP HTTP] ✗ Tool error: ${tool.name}`, { error: result.error, code: result.errorCode })
318
+ logger.error('Tool call failed', { toolName: tool.name, err: result.error, code: result.errorCode })
316
319
  return {
317
320
  content: [
318
321
  {
@@ -324,9 +327,7 @@ function createMcpServerForRequest(
324
327
  }
325
328
  }
326
329
 
327
- console.error(`[MCP HTTP] ✓ Tool success: ${tool.name}`, {
328
- resultPreview: JSON.stringify(result.result).slice(0, 200)
329
- })
330
+ logger.debug('Tool call succeeded', { toolName: tool.name })
330
331
  return {
331
332
  content: [
332
333
  {
@@ -336,7 +337,7 @@ function createMcpServerForRequest(
336
337
  ],
337
338
  }
338
339
  } catch (err) {
339
- console.error(`[MCP HTTP] ✗ Tool exception: ${tool.name}`, err)
340
+ logger.error('Tool call threw', { toolName: tool.name, err })
340
341
  return {
341
342
  content: [
342
343
  {
@@ -352,10 +353,7 @@ function createMcpServerForRequest(
352
353
  } catch (error) {
353
354
  // Skip tools with schemas that can't be registered
354
355
  if (config.debug) {
355
- console.error(
356
- `[MCP HTTP] Skipping tool ${tool.name} - registration failed:`,
357
- error instanceof Error ? error.message : error
358
- )
356
+ logger.debug('Skipping tool: registration failed', { toolName: tool.name, err: error })
359
357
  }
360
358
  continue
361
359
  }
@@ -418,9 +416,9 @@ export async function runMcpHttpServer(options: McpHttpServerOptions): Promise<v
418
416
  const orm = await getOrm()
419
417
  const graph = await extractEntityGraph(orm)
420
418
  cacheEntityGraph(graph)
421
- console.error(`[MCP HTTP] Entity graph: ${graph.nodes.length} entities, ${graph.edges.length} relationships`)
419
+ logger.info('Entity graph generated', { entities: graph.nodes.length, relationships: graph.edges.length })
422
420
  } catch (error) {
423
- console.error('[MCP HTTP] Entity graph generation skipped:', error instanceof Error ? error.message : error)
421
+ logger.warn('Entity graph generation skipped', { err: error })
424
422
  }
425
423
 
426
424
  // Pre-cache rich OpenAPI spec for Code Mode search tool (prefers runtime module registry over static JSON)
@@ -428,12 +426,12 @@ export async function runMcpHttpServer(options: McpHttpServerOptions): Promise<v
428
426
  const { loadRichOpenApiSpec } = await import('./api-endpoint-index')
429
427
  const spec = await loadRichOpenApiSpec()
430
428
  if (spec) {
431
- console.error('[MCP HTTP] Rich OpenAPI spec cached for Code Mode (with requestBody schemas)')
429
+ logger.info('Rich OpenAPI spec cached for Code Mode (with requestBody schemas)')
432
430
  } else {
433
- console.error('[MCP HTTP] OpenAPI spec not available')
431
+ logger.warn('OpenAPI spec not available')
434
432
  }
435
433
  } catch (error) {
436
- console.error('[MCP HTTP] OpenAPI spec caching skipped:', error instanceof Error ? error.message : error)
434
+ logger.warn('OpenAPI spec caching skipped', { err: error })
437
435
  }
438
436
 
439
437
  // Index tools and entity schemas for hybrid search discovery (if search service available)
@@ -451,15 +449,15 @@ export async function runMcpHttpServer(options: McpHttpServerOptions): Promise<v
451
449
  if (graph) {
452
450
  const { count } = await indexEntitiesForSearch(searchService, graph)
453
451
  if (count > 0) {
454
- console.error(`[MCP HTTP] Indexed ${count} entity schemas for hybrid search`)
452
+ logger.info('Indexed entity schemas for hybrid search', { count })
455
453
  }
456
454
  }
457
455
  } catch (entityError) {
458
- console.error('[MCP HTTP] Entity schema indexing skipped:', entityError instanceof Error ? entityError.message : entityError)
456
+ logger.warn('Entity schema indexing skipped', { err: entityError })
459
457
  }
460
458
  } catch (error) {
461
459
  // Search service might not be configured - discovery will use fallback
462
- console.error('[MCP HTTP] Search indexing skipped (search service not available):', error)
460
+ logger.warn('Search indexing skipped (search service not available)', { err: error })
463
461
  }
464
462
 
465
463
  const httpServer = createServer(async (req: IncomingMessage, res: ServerResponse) => {
@@ -482,7 +480,7 @@ export async function runMcpHttpServer(options: McpHttpServerOptions): Promise<v
482
480
  return
483
481
  }
484
482
 
485
- console.error(`[MCP HTTP] ← Request: ${req.method} ${url.pathname}`)
483
+ logger.debug('Request received', { method: req.method, path: url.pathname })
486
484
 
487
485
  // Extract headers
488
486
  const headers: Record<string, string | undefined> = {}
@@ -508,7 +506,7 @@ export async function runMcpHttpServer(options: McpHttpServerOptions): Promise<v
508
506
  }
509
507
 
510
508
  if (config.debug) {
511
- console.error(`[MCP HTTP] Server-level auth passed (${req.method}) - API key: ${apiKeyRecord.keyPrefix}...`)
509
+ logger.debug('Server-level auth passed', { method: req.method, keyPrefix: apiKeyRecord.keyPrefix })
512
510
  }
513
511
 
514
512
  // Create base tool context using API key's tenant/org scope
@@ -536,8 +534,8 @@ export async function runMcpHttpServer(options: McpHttpServerOptions): Promise<v
536
534
  if (config.debug) {
537
535
  // Check registered tools on the server
538
536
  const registeredTools = (mcpServer as any)._registeredTools || {}
539
- console.error(`[MCP HTTP] Registered tools in McpServer:`, Object.keys(registeredTools))
540
- console.error(`[MCP HTTP] Tool handlers initialized:`, (mcpServer as any)._toolHandlersInitialized)
537
+ logger.debug('Registered tools in McpServer', { toolNames: Object.keys(registeredTools).join(',') })
538
+ logger.debug('Tool handlers initialized', { initialized: (mcpServer as any)._toolHandlersInitialized })
541
539
  }
542
540
 
543
541
  // Connect server to transport
@@ -556,11 +554,11 @@ export async function runMcpHttpServer(options: McpHttpServerOptions): Promise<v
556
554
  transport.close()
557
555
  mcpServer.close()
558
556
  if (config.debug) {
559
- console.error(`[MCP HTTP] Request completed, cleaned up`)
557
+ logger.debug('Request completed, cleaned up')
560
558
  }
561
559
  })
562
560
  } catch (error) {
563
- console.error('[MCP HTTP] Error handling request:', error)
561
+ logger.error('Error handling request', { err: error })
564
562
  if (!res.headersSent) {
565
563
  // Handle payload too large error
566
564
  if (error instanceof Error && error.message === 'Request payload too large') {
@@ -586,24 +584,24 @@ export async function runMcpHttpServer(options: McpHttpServerOptions): Promise<v
586
584
 
587
585
  const toolCount = getToolRegistry().listToolNames().length
588
586
 
589
- console.error(`[MCP HTTP] Starting ${config.name} v${config.version}`)
590
- console.error(`[MCP HTTP] Endpoint: http://localhost:${port}/mcp`)
591
- console.error(`[MCP HTTP] Health: http://localhost:${port}/health`)
592
- console.error(`[MCP HTTP] Tools registered: ${toolCount}`)
593
- console.error(`[MCP HTTP] Mode: Stateless (new server per request)`)
594
- console.error(`[MCP HTTP] Server Auth: API key validated against database (x-api-key header)`)
595
- console.error(`[MCP HTTP] User Auth: Session token (_sessionToken) preferred, falls back to API key roles`)
587
+ logger.info('Starting MCP HTTP server', { name: config.name, version: config.version })
588
+ logger.info('Endpoint ready', { endpoint: `http://localhost:${port}/mcp` })
589
+ logger.info('Health endpoint ready', { endpoint: `http://localhost:${port}/health` })
590
+ logger.info('Tools registered', { toolCount })
591
+ logger.info('Mode: stateless (new server per request)')
592
+ logger.info('Server auth: API key validated against database (x-api-key header)')
593
+ logger.info('User auth: session token (_sessionToken) preferred, falls back to API key roles')
596
594
 
597
595
  // Return a Promise that keeps the process alive until shutdown
598
596
  return new Promise<void>((resolve) => {
599
597
  httpServer.listen(port, () => {
600
- console.error(`[MCP HTTP] Server listening on port ${port}`)
598
+ logger.info('Server listening', { port })
601
599
  })
602
600
 
603
601
  const shutdown = async () => {
604
- console.error('[MCP HTTP] Shutting down...')
602
+ logger.info('Shutting down')
605
603
  httpServer.close(() => {
606
- console.error('[MCP HTTP] Server closed')
604
+ logger.info('Server closed')
607
605
  resolve()
608
606
  })
609
607
  }
@@ -8,18 +8,21 @@
8
8
  *
9
9
  * Adapter registration is wrapped in individual try/catch blocks. A
10
10
  * failing import (e.g. missing peer dependency) skips that adapter with a
11
- * `console.warn` but leaves the rest of the registry working.
11
+ * a logger warning but leaves the rest of the registry working.
12
12
  *
13
13
  * @see packages/shared/src/lib/ai/llm-provider-registry.ts
14
14
  * @see .ai/specs/implemented/2026-04-14-llm-provider-ports-and-adapters.md
15
15
  */
16
16
 
17
+ import { createLogger } from '@open-mercato/shared/lib/logger'
17
18
  import { llmProviderRegistry } from '@open-mercato/shared/lib/ai/llm-provider-registry'
18
19
  import { createAnthropicAdapter } from './llm-adapters/anthropic'
19
20
  import { createGoogleAdapter } from './llm-adapters/google'
20
21
  import { createOpenAICompatibleProvider } from './llm-adapters/openai'
21
22
  import { OPENAI_COMPATIBLE_PRESETS } from './openai-compatible-presets'
22
23
 
24
+ const logger = createLogger('ai_assistant')
25
+
23
26
  let bootstrapped = false
24
27
 
25
28
  /**
@@ -36,19 +39,13 @@ export function registerBuiltInLlmProviders(): void {
36
39
  try {
37
40
  llmProviderRegistry.register(createAnthropicAdapter())
38
41
  } catch (error) {
39
- console.warn(
40
- '[LlmBootstrap] Failed to register Anthropic adapter:',
41
- error instanceof Error ? error.message : error,
42
- )
42
+ logger.warn('Failed to register Anthropic adapter', { err: error })
43
43
  }
44
44
 
45
45
  try {
46
46
  llmProviderRegistry.register(createGoogleAdapter())
47
47
  } catch (error) {
48
- console.warn(
49
- '[LlmBootstrap] Failed to register Google adapter:',
50
- error instanceof Error ? error.message : error,
51
- )
48
+ logger.warn('Failed to register Google adapter', { err: error })
52
49
  }
53
50
 
54
51
  // OpenAI-compatible presets — all share one protocol adapter under the
@@ -57,10 +54,7 @@ export function registerBuiltInLlmProviders(): void {
57
54
  try {
58
55
  llmProviderRegistry.register(createOpenAICompatibleProvider(preset))
59
56
  } catch (error) {
60
- console.warn(
61
- `[LlmBootstrap] Failed to register OpenAI-compatible preset "${preset.id}":`,
62
- error instanceof Error ? error.message : error,
63
- )
57
+ logger.warn('Failed to register OpenAI-compatible preset', { presetId: preset.id, err: error })
64
58
  }
65
59
  }
66
60
 
@@ -1,8 +1,11 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { Client } from '@modelcontextprotocol/sdk/client/index.js'
2
3
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
3
4
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
4
5
  import type { McpClientInterface, ToolInfo, ToolResult } from './types'
5
6
 
7
+ const logger = createLogger('ai_assistant')
8
+
6
9
  /**
7
10
  * Options for stdio transport.
8
11
  */
@@ -95,7 +98,7 @@ export class McpClient implements McpClientInterface {
95
98
  transport.stderr?.on('data', (data) => {
96
99
  const message = data.toString().trim()
97
100
  if (message) {
98
- console.error(`[MCP Client] ${message}`)
101
+ logger.info('MCP server stderr output', { output: message })
99
102
  }
100
103
  })
101
104
 
@@ -1,5 +1,8 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { resolve, dirname } from 'node:path'
2
3
 
4
+ const logger = createLogger('ai_assistant')
5
+
3
6
  const MCP_CONFIG_FILENAME = '.mcp.json'
4
7
 
5
8
  // Markers that identify a project/repo root. The lookup stops at the first
@@ -8,7 +11,7 @@ const MCP_CONFIG_FILENAME = '.mcp.json'
8
11
  const PROJECT_ROOT_MARKERS = ['.git', 'yarn.lock', 'pnpm-lock.yaml', 'package-lock.json'] as const
9
12
 
10
13
  const log = (message: string, ...args: unknown[]) => {
11
- console.error(`[MCP Dev] ${message}`, ...args)
14
+ logger.info(message, args.length > 0 ? { details: args.map((arg) => String(arg)).join(' ') } : undefined)
12
15
  }
13
16
 
14
17
  type PermissionStat = { uid: number; mode: number }
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
2
3
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
3
4
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
@@ -12,10 +13,12 @@ import type { McpToolContext } from './types'
12
13
  import type { SearchService } from '@open-mercato/search/service'
13
14
  import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'
14
15
 
16
+ const logger = createLogger('ai_assistant')
17
+
15
18
  const DEFAULT_PORT = 3001
16
19
 
17
20
  const log = (message: string, ...args: unknown[]) => {
18
- console.error(`[MCP Dev] ${message}`, ...args)
21
+ logger.info(message, args.length > 0 ? { details: args.map((arg) => String(arg)).join(' ') } : undefined)
19
22
  }
20
23
 
21
24
  /**