@rizom/brain 0.2.0-alpha.154 → 0.2.0-alpha.156

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.
@@ -376,7 +376,7 @@
376
376
  "import { ServicePlugin as RuntimeServicePlugin } from \"../service/service-plugin\";\nimport type { ServicePluginContext as RuntimeServicePluginContext } from \"../service/context\";\nimport type { PluginConfigSchema } from \"../config\";\nimport type {\n IShell,\n PluginCapabilities,\n PluginRegistrationContext,\n} from \"../interfaces\";\nimport type { Plugin, Resource, ServicePluginContext, Tool } from \"./types\";\n\ninterface ServicePluginHooks {\n onRegister(context: ServicePluginContext): Promise<void>;\n onReady(context: ServicePluginContext): Promise<void>;\n onShutdown(): Promise<void>;\n getTools(): Promise<Tool[]>;\n getResources(): Promise<Resource[]>;\n getInstructions(): Promise<string | undefined>;\n}\n\nclass ServicePluginDelegate<TConfig, TConfigInput> extends RuntimeServicePlugin<\n TConfig,\n TConfigInput\n> {\n private readonly hooks: ServicePluginHooks;\n constructor(\n id: string,\n packageJson: { name: string; version: string; description?: string },\n config: TConfigInput,\n configSchema: PluginConfigSchema<TConfig>,\n hooks: ServicePluginHooks,\n ) {\n super(id, packageJson, config, configSchema);\n this.hooks = hooks;\n }\n\n protected override onRegister(\n context: RuntimeServicePluginContext,\n ): Promise<void> {\n return this.hooks.onRegister(context);\n }\n\n protected override onReady(\n context: RuntimeServicePluginContext,\n ): Promise<void> {\n return this.hooks.onReady(context);\n }\n\n protected override onShutdown(): Promise<void> {\n return this.hooks.onShutdown();\n }\n\n protected override getTools(): Promise<never[]> {\n return this.hooks.getTools() as Promise<never[]>;\n }\n\n protected override getResources(): Promise<never[]> {\n return this.hooks.getResources() as Promise<never[]>;\n }\n\n protected override getInstructions(): Promise<string | undefined> {\n return this.hooks.getInstructions();\n }\n}\n\nexport abstract class ServicePlugin<TConfig, TConfigInput> implements Plugin {\n public readonly type = \"service\" as const;\n public readonly id: string;\n public readonly version: string;\n public readonly packageName: string;\n public readonly description?: string;\n private readonly delegate: ServicePluginDelegate<TConfig, TConfigInput>;\n\n protected constructor(\n id: string,\n packageJson: { name: string; version: string; description?: string },\n config: TConfigInput,\n configSchema: PluginConfigSchema<TConfig>,\n ) {\n this.id = id;\n this.version = packageJson.version;\n this.packageName = packageJson.name;\n if (packageJson.description !== undefined) {\n this.description = packageJson.description;\n }\n this.delegate = new ServicePluginDelegate(\n id,\n packageJson,\n config,\n configSchema,\n {\n onRegister: (context): Promise<void> => this.onRegister(context),\n onReady: (context): Promise<void> => this.onReady(context),\n onShutdown: (): Promise<void> => this.onShutdown(),\n getTools: (): Promise<Tool[]> => this.getTools(),\n getResources: (): Promise<Resource[]> => this.getResources(),\n getInstructions: (): Promise<string | undefined> =>\n this.getInstructions(),\n },\n );\n }\n\n /** @internal */\n register(\n shell: IShell,\n context?: PluginRegistrationContext,\n ): Promise<PluginCapabilities> {\n return this.delegate.register(shell, context);\n }\n\n protected async onRegister(_context: ServicePluginContext): Promise<void> {}\n protected async onReady(_context: ServicePluginContext): Promise<void> {}\n protected async onShutdown(): Promise<void> {}\n protected async getTools(): Promise<Tool[]> {\n return [];\n }\n protected async getResources(): Promise<Resource[]> {\n return [];\n }\n protected async getInstructions(): Promise<string | undefined> {\n return undefined;\n }\n\n ready(): Promise<void> {\n return this.delegate.ready();\n }\n\n shutdown(): Promise<void> {\n return this.delegate.shutdown?.() ?? Promise.resolve();\n }\n}\n",
377
377
  "import { z } from \"@brains/utils/zod\";\nimport {\n conversationMessageActorSchema,\n conversationMessageSourceSchema,\n} from \"@brains/conversation-service\";\nimport type { AgentResponse } from \"@brains/contracts\";\nexport {\n ActionsCardSchema,\n AgentResponseSchema,\n AttachmentCardDataSchema,\n AttachmentCardSchema,\n AttachmentCardSourceSchema,\n ChatActionSchema,\n EventChatActionSchema,\n PendingConfirmationSchema,\n PromptChatActionSchema,\n SourceCitationSchema,\n SourcesCardSchema,\n StructuredChatCardSchema,\n ToolApprovalCardSchema,\n ToolApprovalCardStateSchema,\n ToolResultDataSchema,\n} from \"@brains/contracts\";\nexport type {\n ActionsCard,\n AgentResponse,\n AttachmentCard,\n AttachmentCardData,\n AttachmentCardSource,\n ChatAction,\n EventChatAction,\n PendingConfirmation,\n PromptChatAction,\n SourceCitation,\n SourcesCard,\n StructuredChatCard,\n ToolApprovalCard,\n ToolApprovalCardState,\n ToolResultData,\n} from \"@brains/contracts\";\n\nexport const ChatAttachmentSourceSchema: z.ZodObject<{\n kind: z.ZodString;\n id: z.ZodString;\n}> = z.object({\n kind: z.string().min(1),\n id: z.string().min(1),\n});\n\nexport const TextChatAttachmentSchema: z.ZodObject<{\n kind: z.ZodLiteral<\"text\">;\n filename: z.ZodString;\n mediaType: z.ZodString;\n content: z.ZodString;\n sizeBytes: z.ZodOptional<z.ZodNumber>;\n source: z.ZodOptional<typeof ChatAttachmentSourceSchema>;\n}> = z.object({\n kind: z.literal(\"text\"),\n filename: z.string().min(1),\n mediaType: z.string().min(1),\n content: z.string(),\n sizeBytes: z.number().nonnegative().optional(),\n source: ChatAttachmentSourceSchema.optional(),\n});\n\nconst fileAttachmentDataSchema: z.ZodType<Uint8Array, unknown> =\n z.custom<Uint8Array>((value) => value instanceof Uint8Array);\n\nexport const FileChatAttachmentSchema: z.ZodObject<{\n kind: z.ZodLiteral<\"file\">;\n filename: z.ZodString;\n mediaType: z.ZodString;\n data: typeof fileAttachmentDataSchema;\n sizeBytes: z.ZodOptional<z.ZodNumber>;\n source: z.ZodOptional<typeof ChatAttachmentSourceSchema>;\n}> = z.object({\n kind: z.literal(\"file\"),\n filename: z.string().min(1),\n mediaType: z.string().min(1),\n data: fileAttachmentDataSchema,\n sizeBytes: z.number().nonnegative().optional(),\n source: ChatAttachmentSourceSchema.optional(),\n});\n\nexport const ChatAttachmentSchema: z.ZodDiscriminatedUnion<\n [typeof TextChatAttachmentSchema, typeof FileChatAttachmentSchema],\n \"kind\"\n> = z.discriminatedUnion(\"kind\", [\n TextChatAttachmentSchema,\n FileChatAttachmentSchema,\n]);\n\nexport type ChatAttachment = z.output<typeof ChatAttachmentSchema>;\n\nexport interface ChatContext {\n userPermissionLevel?: \"anchor\" | \"trusted\" | \"public\" | undefined;\n interfaceType?: string | undefined;\n channelId?: string | undefined;\n channelName?: string | undefined;\n actor?:\n | {\n actorId: string;\n canonicalId?: string | undefined;\n interfaceType: string;\n role: \"user\" | \"assistant\";\n displayName?: string | undefined;\n username?: string | undefined;\n isBot?: boolean | undefined;\n }\n | undefined;\n source?:\n | {\n messageId?: string | undefined;\n channelId?: string | undefined;\n channelName?: string | undefined;\n threadId?: string | undefined;\n metadata?: Record<string, unknown> | undefined;\n }\n | undefined;\n attachments?: ChatAttachment[] | undefined;\n}\n\nexport const ChatContextSchema: z.ZodType<ChatContext, unknown> = z.object({\n userPermissionLevel: z.enum([\"anchor\", \"trusted\", \"public\"]).optional(),\n interfaceType: z.string().optional(),\n channelId: z.string().optional(),\n channelName: z.string().optional(),\n actor: conversationMessageActorSchema.optional(),\n source: conversationMessageSourceSchema.optional(),\n attachments: z.array(ChatAttachmentSchema).optional(),\n});\n\nexport interface AgentNamespace {\n chat(\n message: string,\n conversationId: string,\n context?: ChatContext,\n ): Promise<AgentResponse>;\n confirmPendingAction(\n conversationId: string,\n confirmed: boolean,\n approvalId: string,\n context: ChatContext,\n ): Promise<AgentResponse>;\n invalidate(): void;\n}\n",
378
378
  "import { z } from \"@brains/utils/zod\";\n\n/**\n * Daemon health status schema\n */\nexport const DaemonHealthSchema: z.ZodObject<{\n status: z.ZodEnum<{\n healthy: \"healthy\";\n warning: \"warning\";\n error: \"error\";\n unknown: \"unknown\";\n }>;\n message: z.ZodOptional<z.ZodString>;\n lastCheck: z.ZodOptional<z.ZodDate>;\n details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;\n}> = z.object({\n status: z.enum([\"healthy\", \"warning\", \"error\", \"unknown\"]),\n message: z.string().optional(),\n lastCheck: z.date().optional(),\n details: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type DaemonHealth = z.output<typeof DaemonHealthSchema>;\n\n/**\n * Daemon status info schema for validation\n */\nexport const DaemonStatusInfoSchema: z.ZodObject<{\n name: z.ZodString;\n pluginId: z.ZodString;\n status: z.ZodString;\n health: z.ZodOptional<typeof DaemonHealthSchema>;\n}> = z.object({\n name: z.string(),\n pluginId: z.string(),\n status: z.string(),\n health: DaemonHealthSchema.optional(),\n});\n\nexport type DaemonStatusInfo = z.output<typeof DaemonStatusInfoSchema>;\n\n/**\n * Daemon interface for long-running interface processes\n */\nexport interface Daemon {\n /**\n * Start the daemon - called when plugin is initialized\n */\n start: () => Promise<void>;\n\n /**\n * Stop the daemon - called when plugin is unloaded/shutdown\n */\n stop: () => Promise<void>;\n\n /**\n * Optional health check - called periodically to monitor daemon health\n */\n healthCheck?: () => Promise<DaemonHealth>;\n}\n\n/**\n * Information about a registered daemon\n */\nexport interface DaemonInfo {\n name: string;\n daemon: Daemon;\n pluginId: string;\n status: \"stopped\" | \"starting\" | \"running\" | \"stopping\" | \"error\";\n health?: DaemonHealth;\n error?: Error;\n startedAt?: Date;\n stoppedAt?: Date;\n}\n\n/**\n * Interface for DaemonRegistry — used by plugins to avoid circular dep with core\n */\nexport interface IDaemonRegistry {\n register(name: string, daemon: Daemon, pluginId: string): void;\n has(name: string): boolean;\n get(name: string): DaemonInfo | undefined;\n start(name: string): Promise<void>;\n stop(name: string): Promise<void>;\n checkHealth(name: string): Promise<DaemonHealth | undefined>;\n getByPlugin(pluginId: string): DaemonInfo[];\n getAll(): string[];\n getAllInfo(): DaemonInfo[];\n getStatuses(): Promise<DaemonStatusInfo[]>;\n unregister(name: string): Promise<void>;\n startPlugin(pluginId: string): Promise<void>;\n stopPlugin(pluginId: string): Promise<void>;\n clear(): Promise<void>;\n}\n",
379
- "import type { IMessageBus, MessageResponse } from \"@brains/messaging-service\";\nimport { PermissionService, type UserPermissionLevel } from \"@brains/templates\";\nimport { type Logger } from \"@brains/utils/logger\";\nimport { z } from \"@brains/utils/zod\";\nimport {\n McpServer,\n ResourceTemplate as MCPResourceTemplate,\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ToolAnnotations } from \"@modelcontextprotocol/sdk/types.js\";\nimport type {\n MCPProtocolMode,\n Prompt,\n Resource,\n ResourceTemplate,\n Tool,\n} from \"./types\";\nimport { normalizeToolExecutionMessageResponse } from \"./tool-response-validation\";\n\nconst MCP_SERVER_INFO = {\n name: \"brain-mcp\",\n version: \"1.0.0\",\n};\n\nconst DEFAULT_TOOL_VISIBILITY: UserPermissionLevel = \"anchor\";\nconst RESOURCE_VISIBILITY: UserPermissionLevel = \"anchor\";\nconst DEFAULT_PROMPT_VISIBILITY: UserPermissionLevel = \"anchor\";\n\nexport interface RegisteredTool {\n pluginId: string;\n tool: Tool;\n}\n\nexport interface RegisteredResource {\n pluginId: string;\n resource: Resource;\n}\n\nexport interface RegisteredTemplate {\n pluginId: string;\n template: ResourceTemplate;\n}\n\nexport interface RegisteredPrompt {\n pluginId: string;\n prompt: Prompt;\n}\n\nexport function createMcpServerInstance(): McpServer {\n return new McpServer(MCP_SERVER_INFO);\n}\n\nexport function canExposeTool(\n permissionLevel: UserPermissionLevel,\n tool: Tool,\n): boolean {\n return PermissionService.hasPermission(\n permissionLevel,\n tool.visibility ?? DEFAULT_TOOL_VISIBILITY,\n );\n}\n\nexport function canExposeToolOnProtocol(\n permissionLevel: UserPermissionLevel,\n tool: Tool,\n mode: MCPProtocolMode,\n): boolean {\n if (!canExposeTool(permissionLevel, tool)) {\n return false;\n }\n\n if (mode === \"debug\") {\n return true;\n }\n\n return (\n isReadOnlyTool(tool) || tool.name === \"chat\" || tool.name === \"confirm\"\n );\n}\n\nexport function canExposeResource(\n permissionLevel: UserPermissionLevel,\n): boolean {\n return PermissionService.hasPermission(permissionLevel, RESOURCE_VISIBILITY);\n}\n\n/**\n * Resource templates expose entity listing/completion that can leak entity\n * existence even when handler output is filtered by visibility. Pin them to\n * the same anchor-only policy as plain resources.\n */\nexport function canExposeResourceTemplate(\n permissionLevel: UserPermissionLevel,\n): boolean {\n return PermissionService.hasPermission(permissionLevel, RESOURCE_VISIBILITY);\n}\n\n/**\n * Prompts ship as anchor-only by default because their bodies can reference\n * restricted workflows, entity names, or operator instructions. Plugins can\n * opt a prompt down to \"trusted\" / \"public\" if its template is safe to share.\n */\nexport function canExposePrompt(\n permissionLevel: UserPermissionLevel,\n prompt: Prompt,\n): boolean {\n return PermissionService.hasPermission(\n permissionLevel,\n prompt.visibility ?? DEFAULT_PROMPT_VISIBILITY,\n );\n}\n\nexport function filterToolsForPermission(\n tools: RegisteredTool[],\n userLevel: UserPermissionLevel,\n): RegisteredTool[] {\n return tools.filter(({ tool }) => canExposeTool(userLevel, tool));\n}\n\nexport function getToolAnnotations(tool: Tool): ToolAnnotations | undefined {\n if (tool.annotations) {\n return tool.annotations;\n }\n\n if (tool.sideEffects === \"none\") {\n return {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n };\n }\n\n if (tool.sideEffects === \"writes\") {\n return {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n };\n }\n\n if (tool.sideEffects === \"external\") {\n return {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n };\n }\n\n return undefined;\n}\n\nexport function isReadOnlyTool(tool: Tool): boolean {\n return getToolAnnotations(tool)?.readOnlyHint === true;\n}\n\nexport function serializeMessageResponse(response: MessageResponse): string {\n if (\"success\" in response && !response.success) {\n throw new Error(response.error ?? \"Operation failed\");\n }\n return JSON.stringify(\"data\" in response ? response.data : response, null, 2);\n}\n\nexport function registerToolOnServer(\n server: McpServer,\n pluginId: string,\n tool: Tool,\n messageBus: IMessageBus,\n logger: Logger,\n permissionLevel: UserPermissionLevel,\n): void {\n server.tool(\n tool.name,\n tool.description,\n tool.inputSchema,\n getToolAnnotations(tool) ?? {},\n async (params, extra) => {\n const interfaceType = extra._meta?.[\"interfaceType\"] ?? \"mcp\";\n const userId = extra._meta?.[\"userId\"] ?? \"mcp-user\";\n const conversationId = extra._meta?.[\"conversationId\"];\n const channelId = extra._meta?.[\"channelId\"];\n const channelName = extra._meta?.[\"channelName\"];\n const progressToken = extra._meta?.progressToken;\n\n logger.debug(\"MCP client metadata\", {\n tool: tool.name,\n pluginId,\n interfaceType,\n userId,\n conversationId,\n channelId,\n channelName,\n progressToken,\n userPermissionLevel: permissionLevel,\n });\n\n try {\n const response = await messageBus.send({\n type: `plugin:${pluginId}:tool:execute`,\n payload: {\n toolName: tool.name,\n args: params,\n progressToken,\n hasProgress: progressToken !== undefined,\n interfaceType,\n userId,\n conversationId,\n channelId,\n channelName,\n userPermissionLevel: permissionLevel,\n },\n sender: \"MCPService\",\n });\n const normalizedResponse = normalizeToolExecutionMessageResponse(\n response,\n {\n pluginId,\n toolName: tool.name,\n logger,\n },\n );\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: serializeMessageResponse(normalizedResponse),\n },\n ],\n };\n } catch (error) {\n logger.error(`Tool execution error for ${tool.name}`, error);\n throw error;\n }\n },\n );\n}\n\nexport function registerResourceOnServer(\n server: McpServer,\n resource: Resource,\n): void {\n server.resource(\n resource.name,\n resource.uri,\n { description: resource.description, mimeType: resource.mimeType },\n async () => resource.handler(),\n );\n}\n\nexport function registerResourceTemplateOnServer(\n server: McpServer,\n template: ResourceTemplate,\n): void {\n const listFn = template.list;\n\n const sdkTemplate = new MCPResourceTemplate(template.uriTemplate, {\n list: listFn\n ? async (): Promise<{\n resources: Array<{ uri: string; name: string }>;\n }> => ({\n resources: (await listFn()).map((r) => ({\n uri: r.uri,\n name: r.name,\n })),\n })\n : undefined,\n ...(template.complete && {\n complete: Object.fromEntries(\n Object.entries(template.complete).map(([k, fn]) => [\n k,\n (\n value: string,\n context?: { arguments?: Record<string, string> },\n ): string[] | Promise<string[]> => fn(value, context),\n ]),\n ),\n }),\n });\n\n server.registerResource(\n template.name,\n sdkTemplate,\n { description: template.description, mimeType: template.mimeType },\n async (_uri, vars) => {\n const flatVars: Record<string, string> = {};\n for (const [k, v] of Object.entries(vars)) {\n flatVars[k] = Array.isArray(v) ? (v[0] ?? \"\") : v;\n }\n return template.handler(flatVars);\n },\n );\n}\n\nexport function registerPromptOnServer(\n server: McpServer,\n prompt: Prompt,\n): void {\n const argsSchema = Object.fromEntries(\n Object.entries(prompt.args).map(([key, arg]) => [\n key,\n arg.required\n ? z.string().describe(arg.description)\n : z.string().optional().describe(arg.description),\n ]),\n );\n\n server.prompt(\n prompt.name,\n prompt.description ?? \"Prompt\",\n argsSchema,\n async (args) => prompt.handler(args as Record<string, string>),\n );\n}\n",
379
+ "import type { IMessageBus, MessageResponse } from \"@brains/messaging-service\";\nimport { PermissionService, type UserPermissionLevel } from \"@brains/templates\";\nimport { type Logger } from \"@brains/utils/logger\";\nimport { z } from \"@brains/utils/zod\";\nimport {\n McpServer,\n ResourceTemplate as MCPResourceTemplate,\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ToolAnnotations } from \"@modelcontextprotocol/sdk/types.js\";\nimport type {\n MCPProtocolMode,\n Prompt,\n Resource,\n ResourceTemplate,\n Tool,\n} from \"./types\";\nimport { normalizeToolExecutionMessageResponse } from \"./tool-response-validation\";\n\nconst MCP_SERVER_INFO = {\n name: \"brain-mcp\",\n version: \"1.0.0\",\n};\n\nconst DEFAULT_TOOL_VISIBILITY: UserPermissionLevel = \"anchor\";\nconst RESOURCE_VISIBILITY: UserPermissionLevel = \"anchor\";\nconst DEFAULT_PROMPT_VISIBILITY: UserPermissionLevel = \"anchor\";\n\nexport interface RegisteredTool {\n pluginId: string;\n tool: Tool;\n}\n\nexport interface RegisteredResource {\n pluginId: string;\n resource: Resource;\n}\n\nexport interface RegisteredTemplate {\n pluginId: string;\n template: ResourceTemplate;\n}\n\nexport interface RegisteredPrompt {\n pluginId: string;\n prompt: Prompt;\n}\n\nexport function createMcpServerInstance(): McpServer {\n return new McpServer(MCP_SERVER_INFO);\n}\n\nexport function canExposeTool(\n permissionLevel: UserPermissionLevel,\n tool: Tool,\n): boolean {\n return PermissionService.hasPermission(\n permissionLevel,\n tool.visibility ?? DEFAULT_TOOL_VISIBILITY,\n );\n}\n\nexport function canExposeToolOnProtocol(\n permissionLevel: UserPermissionLevel,\n tool: Tool,\n mode: MCPProtocolMode,\n): boolean {\n if (!canExposeTool(permissionLevel, tool)) {\n return false;\n }\n\n if (mode === \"debug\") {\n return true;\n }\n\n return (\n isReadOnlyTool(tool) || tool.name === \"chat\" || tool.name === \"confirm\"\n );\n}\n\nexport function canExposeResource(\n permissionLevel: UserPermissionLevel,\n): boolean {\n return PermissionService.hasPermission(permissionLevel, RESOURCE_VISIBILITY);\n}\n\n/**\n * Resource templates expose entity listing/completion that can leak entity\n * existence even when handler output is filtered by visibility. Pin them to\n * the same anchor-only policy as plain resources.\n */\nexport function canExposeResourceTemplate(\n permissionLevel: UserPermissionLevel,\n): boolean {\n return PermissionService.hasPermission(permissionLevel, RESOURCE_VISIBILITY);\n}\n\n/**\n * Prompts ship as anchor-only by default because their bodies can reference\n * restricted workflows, entity names, or operator instructions. Plugins can\n * opt a prompt down to \"trusted\" / \"public\" if its template is safe to share.\n */\nexport function canExposePrompt(\n permissionLevel: UserPermissionLevel,\n prompt: Prompt,\n): boolean {\n return PermissionService.hasPermission(\n permissionLevel,\n prompt.visibility ?? DEFAULT_PROMPT_VISIBILITY,\n );\n}\n\nexport function filterToolsForPermission(\n tools: RegisteredTool[],\n userLevel: UserPermissionLevel,\n): RegisteredTool[] {\n return tools.filter(({ tool }) => canExposeTool(userLevel, tool));\n}\n\nexport function getToolAnnotations(tool: Tool): ToolAnnotations | undefined {\n if (tool.annotations) {\n return tool.annotations;\n }\n\n if (tool.sideEffects === \"none\") {\n return {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n };\n }\n\n if (tool.sideEffects === \"writes\") {\n return {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n };\n }\n\n if (tool.sideEffects === \"external\") {\n return {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n };\n }\n\n return undefined;\n}\n\nexport function isReadOnlyTool(tool: Tool): boolean {\n return getToolAnnotations(tool)?.readOnlyHint === true;\n}\n\nexport function serializeMessageResponse(response: MessageResponse): string {\n if (\"success\" in response && !response.success) {\n throw new Error(response.error ?? \"Operation failed\");\n }\n return JSON.stringify(\"data\" in response ? response.data : response, null, 2);\n}\n\nexport function registerToolOnServer(\n server: McpServer,\n pluginId: string,\n tool: Tool,\n messageBus: IMessageBus,\n logger: Logger,\n permissionLevel: UserPermissionLevel,\n): void {\n server.tool(\n tool.name,\n tool.description,\n tool.inputSchema,\n getToolAnnotations(tool) ?? {},\n async (params, extra) => {\n const interfaceType = extra._meta?.[\"interfaceType\"] ?? \"mcp\";\n const verifiedSubject = extra.authInfo?.extra?.[\"subject\"];\n const userId =\n (typeof verifiedSubject === \"string\" && verifiedSubject.length > 0\n ? verifiedSubject\n : undefined) ??\n extra._meta?.[\"userId\"] ??\n \"mcp-user\";\n const conversationId = extra._meta?.[\"conversationId\"];\n const channelId = extra._meta?.[\"channelId\"];\n const channelName = extra._meta?.[\"channelName\"];\n const progressToken = extra._meta?.progressToken;\n\n logger.debug(\"MCP client metadata\", {\n tool: tool.name,\n pluginId,\n interfaceType,\n userId,\n conversationId,\n channelId,\n channelName,\n progressToken,\n userPermissionLevel: permissionLevel,\n });\n\n try {\n const response = await messageBus.send({\n type: `plugin:${pluginId}:tool:execute`,\n payload: {\n toolName: tool.name,\n args: params,\n progressToken,\n hasProgress: progressToken !== undefined,\n interfaceType,\n userId,\n conversationId,\n channelId,\n channelName,\n userPermissionLevel: permissionLevel,\n },\n sender: \"MCPService\",\n });\n const normalizedResponse = normalizeToolExecutionMessageResponse(\n response,\n {\n pluginId,\n toolName: tool.name,\n logger,\n },\n );\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: serializeMessageResponse(normalizedResponse),\n },\n ],\n };\n } catch (error) {\n logger.error(`Tool execution error for ${tool.name}`, error);\n throw error;\n }\n },\n );\n}\n\nexport function registerResourceOnServer(\n server: McpServer,\n resource: Resource,\n): void {\n server.resource(\n resource.name,\n resource.uri,\n { description: resource.description, mimeType: resource.mimeType },\n async () => resource.handler(),\n );\n}\n\nexport function registerResourceTemplateOnServer(\n server: McpServer,\n template: ResourceTemplate,\n): void {\n const listFn = template.list;\n\n const sdkTemplate = new MCPResourceTemplate(template.uriTemplate, {\n list: listFn\n ? async (): Promise<{\n resources: Array<{ uri: string; name: string }>;\n }> => ({\n resources: (await listFn()).map((r) => ({\n uri: r.uri,\n name: r.name,\n })),\n })\n : undefined,\n ...(template.complete && {\n complete: Object.fromEntries(\n Object.entries(template.complete).map(([k, fn]) => [\n k,\n (\n value: string,\n context?: { arguments?: Record<string, string> },\n ): string[] | Promise<string[]> => fn(value, context),\n ]),\n ),\n }),\n });\n\n server.registerResource(\n template.name,\n sdkTemplate,\n { description: template.description, mimeType: template.mimeType },\n async (_uri, vars) => {\n const flatVars: Record<string, string> = {};\n for (const [k, v] of Object.entries(vars)) {\n flatVars[k] = Array.isArray(v) ? (v[0] ?? \"\") : v;\n }\n return template.handler(flatVars);\n },\n );\n}\n\nexport function registerPromptOnServer(\n server: McpServer,\n prompt: Prompt,\n): void {\n const argsSchema = Object.fromEntries(\n Object.entries(prompt.args).map(([key, arg]) => [\n key,\n arg.required\n ? z.string().describe(arg.description)\n : z.string().optional().describe(arg.description),\n ]),\n );\n\n server.prompt(\n prompt.name,\n prompt.description ?? \"Prompt\",\n argsSchema,\n async (args) => prompt.handler(args as Record<string, string>),\n );\n}\n",
380
380
  "import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ToolAnnotations } from \"@modelcontextprotocol/sdk/types.js\";\nimport { type ProgressNotification } from \"@brains/utils/progress\";\nimport { z, type ZodRawShape } from \"@brains/utils/zod\";\nimport type { UserPermissionLevel } from \"@brains/templates\";\n\n/**\n * Tool visibility levels for permission control\n * Uses the same levels as UserPermissionLevel for consistency\n */\nexport type ToolVisibility = UserPermissionLevel;\n\n/**\n * Tool execution context\n * Provides progress reporting and routing metadata\n */\nexport interface ToolContext {\n // Progress reporting\n progressToken?: string | number;\n sendProgress?: (notification: ProgressNotification) => Promise<void>;\n\n // Routing metadata for job creation (required for proper context propagation)\n interfaceType: string; // Which interface called the tool (e.g., \"mcp\", \"cli\", \"matrix\")\n userId: string; // User who invoked the tool\n conversationId?: string; // Durable conversation/session id for conversation-scoped tools when available\n channelId?: string; // Transport channel/room context (for Matrix, etc.)\n channelName?: string; // Human-readable channel name (for display)\n runId?: string; // Runtime workflow/playbook run context when available\n toolCallId?: string; // AI SDK tool call id when invoked by an agent\n /** Caller's permission level. Tools that read/write entities use this to derive\n * the content-visibility scope they are allowed to see. */\n userPermissionLevel?: UserPermissionLevel;\n}\n\nexport interface ToolContextRouting {\n interfaceType: string;\n userId: string;\n conversationId?: string | undefined;\n channelId?: string | undefined;\n channelName?: string | undefined;\n runId?: string | undefined;\n toolCallId?: string | undefined;\n userPermissionLevel?: UserPermissionLevel | undefined;\n}\n\ninterface ToolContextRoutingSchemaShape extends ZodRawShape {\n interfaceType: z.ZodString;\n userId: z.ZodString;\n conversationId: z.ZodOptional<z.ZodString>;\n channelId: z.ZodOptional<z.ZodString>;\n channelName: z.ZodOptional<z.ZodString>;\n runId: z.ZodOptional<z.ZodString>;\n toolCallId: z.ZodOptional<z.ZodString>;\n userPermissionLevel: z.ZodOptional<\n z.ZodEnum<{\n anchor: \"anchor\";\n trusted: \"trusted\";\n public: \"public\";\n }>\n >;\n}\n\n/**\n * Schema for ToolContext routing metadata\n * Used to validate routing information in tool execution requests\n */\nexport const ToolContextRoutingSchema: z.ZodObject<ToolContextRoutingSchemaShape> =\n z.object({\n interfaceType: z.string(),\n userId: z.string(),\n conversationId: z.string().optional(),\n channelId: z.string().optional(),\n channelName: z.string().optional(),\n runId: z.string().optional(),\n toolCallId: z.string().optional(),\n userPermissionLevel: z.enum([\"anchor\", \"trusted\", \"public\"]).optional(),\n });\n\nexport interface ToolSuccessResponse {\n success: true;\n data?: unknown;\n message?: string | undefined;\n cached?: true | undefined;\n}\n\n/**\n * Success response schema\n */\nexport const toolSuccessSchema: z.ZodType<ToolSuccessResponse> = z.strictObject(\n {\n success: z.literal(true),\n data: z.unknown().optional(),\n message: z.string().optional(),\n cached: z.literal(true).optional(),\n },\n);\n\nexport interface ToolErrorResponse {\n success: false;\n error: string;\n code?: string | undefined;\n}\n\n/**\n * Error response schema\n */\nexport const toolErrorSchema: z.ZodType<ToolErrorResponse> = z.strictObject({\n success: z.literal(false),\n error: z.string(),\n code: z.string().optional(),\n});\n\n/**\n * Confirmation response schema\n * Tools return this when an operation needs user approval.\n * The agent service detects this shape and enters the confirmation flow.\n */\nexport interface ToolConfirmation {\n needsConfirmation: true;\n toolName: string;\n summary: string;\n completionSummary?: string | undefined;\n preview?: string | undefined;\n args: unknown;\n}\n\nexport const toolConfirmationSchema: z.ZodType<ToolConfirmation> =\n z.strictObject({\n needsConfirmation: z.literal(true),\n toolName: z.string(),\n summary: z.string(),\n completionSummary: z.string().optional(),\n preview: z.string().optional(),\n args: z.unknown(),\n });\n\n/**\n * Standardized tool response schema\n * All tools return one of: success, error, or confirmation request.\n */\nexport type ToolResponse =\n ToolSuccessResponse | ToolErrorResponse | ToolConfirmation;\n\nexport const toolResponseSchema: z.ZodType<ToolResponse> = z.union([\n toolSuccessSchema,\n toolErrorSchema,\n toolConfirmationSchema,\n]);\n\nexport type ToolSideEffects = \"none\" | \"writes\" | \"external\";\nexport type ToolInputSchema = ZodRawShape;\nexport type ToolOutputSchema = z.ZodType;\nexport type MCPProtocolMode = \"basic\" | \"debug\";\n\n/**\n * Tool definition\n * @template TOutput - The output type, defaults to ToolResponse for backward compatibility\n */\nexport interface Tool<TOutput = ToolResponse> {\n name: string;\n description: string;\n inputSchema: ToolInputSchema;\n outputSchema?: ToolOutputSchema; // Optional: Zod schema for type-safe outputs\n handler: (input: unknown, context: ToolContext) => Promise<TOutput>;\n visibility?: ToolVisibility; // Default: \"anchor\" for safety - only explicitly marked tools are public\n /** Declares whether this tool is safe to repeat/cache within one model turn. Undefined defaults to not cacheable. */\n sideEffects?: ToolSideEffects;\n /** MCP protocol annotations advertised to external clients. Derived from sideEffects when omitted. */\n annotations?: ToolAnnotations;\n /** Optional CLI metadata — makes this tool invocable as a brain CLI command */\n cli?: {\n /** CLI command name (e.g. \"list\", \"sync\", \"build\") */\n name: string;\n };\n}\n\n/**\n * Resource definition\n */\nexport interface Resource {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n handler: () => Promise<{\n contents: Array<{\n text: string;\n uri: string;\n mimeType?: string;\n }>;\n }>;\n}\n\n/**\n * Variables extracted from a URI template.\n * Generic parameter ensures handlers receive typed vars, not loose index signatures.\n */\nexport type ResourceVars<K extends string = string> = { [P in K]: string };\n\n/**\n * A parameterized resource with URI template (e.g. \"entity://{type}/{id}\")\n */\nexport interface ResourceTemplate<K extends string = string> {\n name: string;\n uriTemplate: string;\n description?: string;\n mimeType?: string;\n /** List all concrete resources matching this template (for resources/list) */\n list?: () => Promise<Array<{ uri: string; name: string }>>;\n /** Autocomplete values for template variables (populates client selectors) */\n complete?: Record<\n K,\n (\n value: string,\n context?: { arguments?: Partial<ResourceVars<K>> },\n ) => string[] | Promise<string[]>\n >;\n /** Read a single resource by resolved template variables */\n handler: (vars: ResourceVars<K>) => Promise<{\n contents: Array<{ text: string; uri: string; mimeType?: string }>;\n }>;\n}\n\n/**\n * An MCP prompt — parameterized message template for client prompt pickers\n */\nexport interface Prompt {\n name: string;\n description?: string;\n args: Record<string, { description: string; required?: boolean }>;\n handler: (args: Record<string, string>) => Promise<{\n messages: Array<{\n role: \"user\" | \"assistant\";\n content: { type: \"text\"; text: string };\n }>;\n }>;\n /** Default: \"anchor\" — prompt bodies can reference restricted workflows,\n * so they ship as anchor-only unless explicitly marked. */\n visibility?: ToolVisibility;\n}\n\n/**\n * Minimal interface exposed to transport layers\n * Only provides what's needed to connect transports to the MCP server\n */\nexport interface IMCPTransport {\n /**\n * Get the underlying MCP server for transport layers to connect to\n * Transport layers should import McpServer type from @modelcontextprotocol/sdk directly\n */\n getMcpServer(): McpServer;\n\n /**\n * Create a fresh MCP server instance with all registered tools/resources.\n * Required for Streamable HTTP where each session needs its own server.\n */\n createMcpServer(permissionLevel?: UserPermissionLevel): McpServer;\n\n /**\n * Set the permission level for this transport\n */\n setPermissionLevel(level: UserPermissionLevel): void;\n\n /** Select which registered tools are exposed on the external MCP protocol server. */\n setProtocolMode(mode: MCPProtocolMode): void;\n}\n\n/**\n * Full MCP Service interface for managing tool and resource registration\n * Extends the transport interface with registration capabilities\n */\nexport interface IMCPService extends IMCPTransport {\n /**\n * Register a tool with the MCP server\n */\n registerTool(pluginId: string, tool: Tool): void;\n\n /**\n * Register a resource with the MCP server\n */\n registerResource(pluginId: string, resource: Resource): void;\n\n /**\n * Register a resource template with parameterized URI\n */\n registerResourceTemplate<K extends string = string>(\n pluginId: string,\n template: ResourceTemplate<K>,\n ): void;\n\n /**\n * Register an MCP prompt\n */\n registerPrompt(pluginId: string, prompt: Prompt): void;\n\n /**\n * List all registered tools\n */\n listTools(): Array<{ pluginId: string; tool: Tool }>;\n\n /**\n * List tools that have CLI metadata (invocable as brain CLI commands)\n */\n getCliTools(): Array<{ pluginId: string; tool: Tool }>;\n\n /**\n * List tools filtered by user permission level\n */\n listToolsForPermissionLevel(\n userLevel: UserPermissionLevel,\n ): Array<{ pluginId: string; tool: Tool }>;\n\n /**\n * List all registered resources\n */\n listResources(): Array<{ pluginId: string; resource: Resource }>;\n\n /**\n * Register behavioral instructions from a plugin for the agent system prompt\n */\n registerInstructions(pluginId: string, instructions: string): void;\n\n /**\n * Get all registered plugin instructions\n */\n getInstructions(): string[];\n}\n\n/**\n * Tool registration info\n */\nexport interface ToolInfo {\n name: string;\n description: string;\n pluginId: string;\n}\n",
381
381
  "import type { MessageResponse } from \"@brains/messaging-service\";\nimport { type Logger } from \"@brains/utils/logger\";\nimport { z } from \"@brains/utils/zod\";\nimport { toolResponseSchema, type Tool, type ToolResponse } from \"./types\";\n\ninterface ToolResponseValidationContext {\n pluginId: string;\n toolName: string;\n logger: Logger;\n}\n\nfunction invalidToolResponse(toolName: string): ToolResponse {\n return {\n success: false,\n error: `Tool ${toolName} returned an invalid response shape`,\n };\n}\n\nfunction invalidEnvelopeResponse(\n toolName: string,\n): MessageResponse<ToolResponse> {\n return {\n success: false,\n error: `Tool ${toolName} returned an invalid message response envelope`,\n };\n}\n\n/**\n * Envelope shape returned by message-bus handlers for `plugin:*:tool:execute`.\n * Success branch carries the raw tool response in `data`; error branch is the\n * bus-level failure (e.g. tool not found, payload invalid). Anything else\n * (missing `success`, `noop`, wrong types) is rejected by the union.\n */\nconst toolExecutionEnvelopeSchema = z.union([\n z.looseObject({ success: z.literal(true) }),\n z.object({ success: z.literal(false), error: z.string() }),\n]);\n\nfunction hasEnvelopeData(value: {\n success: true;\n}): value is { success: true; data: unknown } {\n return Object.prototype.hasOwnProperty.call(value, \"data\");\n}\n\nexport function normalizeToolResponse(\n raw: unknown,\n context: ToolResponseValidationContext,\n): ToolResponse {\n const parsed = toolResponseSchema.safeParse(raw);\n\n if (\n parsed.success &&\n \"success\" in parsed.data &&\n parsed.data.success === true &&\n !Object.prototype.hasOwnProperty.call(parsed.data, \"data\")\n ) {\n context.logger.error(\"Tool returned non-compliant response\", {\n pluginId: context.pluginId,\n toolName: context.toolName,\n issues: [{ path: [\"data\"], message: \"Required\" }],\n });\n return invalidToolResponse(context.toolName);\n }\n\n if (parsed.success) {\n return parsed.data;\n }\n\n context.logger.error(\"Tool returned non-compliant response\", {\n pluginId: context.pluginId,\n toolName: context.toolName,\n issues: parsed.error.issues,\n });\n\n return invalidToolResponse(context.toolName);\n}\n\nexport function normalizeToolExecutionMessageResponse(\n response: unknown,\n context: ToolResponseValidationContext,\n): MessageResponse<ToolResponse> {\n const parsed = toolExecutionEnvelopeSchema.safeParse(response);\n\n if (!parsed.success) {\n context.logger.error(\"Tool returned non-compliant message response\", {\n pluginId: context.pluginId,\n toolName: context.toolName,\n response,\n });\n return invalidEnvelopeResponse(context.toolName);\n }\n\n if (!parsed.data.success) {\n return { success: false, error: parsed.data.error };\n }\n\n if (!hasEnvelopeData(parsed.data)) {\n context.logger.error(\"Tool returned non-compliant message response\", {\n pluginId: context.pluginId,\n toolName: context.toolName,\n response,\n });\n return invalidEnvelopeResponse(context.toolName);\n }\n\n return {\n success: true,\n data: normalizeToolResponse(parsed.data.data, context),\n };\n}\n\nexport function wrapToolWithResponseValidation(\n pluginId: string,\n tool: Tool,\n logger: Logger,\n): Tool {\n return {\n ...tool,\n handler: async (input, context): Promise<ToolResponse> => {\n const raw = await tool.handler(input, context);\n return normalizeToolResponse(raw, {\n pluginId,\n toolName: tool.name,\n logger,\n });\n },\n };\n}\n",
382
382
  "import type { Tool, Resource, ToolResponse, ToolContext } from \"./types\";\nimport { getErrorMessage } from \"@brains/utils/error\";\nimport { Logger } from \"@brains/utils/logger\";\nimport { z, type ZodRawShape } from \"@brains/utils/zod\";\n\nexport interface ToolSuccessResult<T = unknown> {\n success: true;\n data: T;\n message?: string | undefined;\n}\n\nexport interface ToolErrorResult {\n success: false;\n error: string;\n code?: string | undefined;\n}\n\n/**\n * Zod schema for tool result validation\n * Use this to parse/validate tool results at runtime\n */\nexport const toolResultSchema: z.ZodType<ToolSuccessResult | ToolErrorResult> =\n z.union([\n z.object({\n success: z.literal(true),\n data: z.unknown(),\n message: z.string().optional(),\n }),\n z.object({\n success: z.literal(false),\n error: z.string(),\n code: z.string().optional(),\n }),\n ]);\n\n/**\n * Standardized tool result type derived from schema\n * All tools should return this format for consistent handling\n *\n * @template T - The type of data returned on success (defaults to unknown)\n */\nexport type ToolResult<T = unknown> = ToolSuccessResult<T> | ToolErrorResult;\n\n/**\n * Helper to create a success result\n */\nexport function toolSuccess<T>(data: T, message?: string): ToolResult<T> {\n return message ? { success: true, data, message } : { success: true, data };\n}\n\n/**\n * Helper to create an error result\n */\nexport function toolError(error: string, code?: string): ToolResult<never> {\n return code ? { success: false, error, code } : { success: false, error };\n}\n\n/**\n * Create a tool with auto-validation and consistent response format.\n *\n * - Input is automatically validated against the schema\n * - Handler receives typed input (no manual parsing needed)\n * - Must return `ToolResult<T>` for consistent response format\n * - Validation errors are automatically caught and formatted\n *\n * @example\n * ```typescript\n * const captureSchema = z.object({\n * url: z.string().url(),\n * title: z.string().optional(),\n * });\n *\n * createTool(\n * pluginId,\n * \"capture\",\n * \"Capture a link\",\n * captureSchema,\n * async (input, ctx) => {\n * // input is typed as { url: string; title?: string }\n * const link = await captureLink(input.url);\n * return toolSuccess({ linkId: link.id });\n * }\n * );\n * ```\n */\nfunction formatZodError(error: z.ZodError): string {\n return error.issues\n .map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\";\n return `${path}: ${issue.message}`;\n })\n .join(\", \");\n}\n\nexport function createTool<\n TSchema extends z.ZodObject<ZodRawShape>,\n TOutput = unknown,\n>(\n pluginId: string,\n name: string,\n description: string,\n inputSchema: TSchema,\n handler: (\n input: z.output<TSchema>,\n context: ToolContext,\n ) => Promise<ToolResult<TOutput>>,\n options: {\n visibility?: Tool[\"visibility\"];\n sideEffects?: Tool[\"sideEffects\"];\n annotations?: Tool[\"annotations\"];\n debug?: boolean;\n cli?: Tool[\"cli\"];\n } = {},\n): Tool {\n const {\n visibility = \"anchor\",\n sideEffects,\n annotations,\n debug = false,\n cli,\n } = options;\n const logger = debug ? Logger.createFresh({ context: pluginId }) : null;\n const inputShape = inputSchema.shape;\n\n return {\n name: `${pluginId}_${name}`,\n description,\n inputSchema: inputShape,\n handler: async (input, context): Promise<ToolResponse> => {\n logger?.debug(`Tool ${name} started`);\n try {\n // Auto-validate input\n const parseResult = inputSchema.safeParse(input);\n if (!parseResult.success) {\n const errorMessage = formatZodError(parseResult.error);\n logger?.debug(`Tool ${name} validation failed: ${errorMessage}`);\n return {\n success: false,\n error: `Invalid input: ${errorMessage}`,\n };\n }\n\n // Call handler with validated, typed input\n const result = await handler(parseResult.data, context);\n logger?.debug(`Tool ${name} completed`);\n return result;\n } catch (error) {\n logger?.error(`Tool ${name} failed`, error);\n const errorMessage = getErrorMessage(error);\n return {\n success: false,\n error: errorMessage,\n };\n }\n },\n visibility,\n ...(sideEffects ? { sideEffects } : {}),\n ...(annotations ? { annotations } : {}),\n ...(cli ? { cli } : {}),\n };\n}\n\n/**\n * Create a resource with consistent structure and optional debug logging.\n *\n * Use this in resource factory functions instead of building resource objects manually.\n */\nexport function createResource(\n pluginId: string,\n uri: string,\n name: string,\n description: string,\n handler: Resource[\"handler\"],\n options: {\n mimeType?: string;\n debug?: boolean;\n } = {},\n): Resource {\n const { mimeType = \"text/plain\", debug = false } = options;\n const logger = debug ? Logger.createFresh({ context: pluginId }) : null;\n\n return {\n uri: `${pluginId}_${uri}`,\n name,\n description,\n mimeType,\n handler: async (): Promise<{\n contents: Array<{\n text: string;\n uri: string;\n mimeType?: string;\n }>;\n }> => {\n logger?.debug(`Resource ${uri} started`);\n try {\n const result = await handler();\n logger?.debug(`Resource ${uri} completed`);\n return result;\n } catch (error) {\n logger?.error(`Resource ${uri} failed`, error);\n throw error;\n }\n },\n };\n}\n",