"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
const zod_1 = require("zod");
const promptsController_1 = require("./controllers/promptsController");
const toolsController_1 = require("./controllers/toolsController");
const resourceService_1 = require("./services/resourceService");
// ==========================================
// 初始化 MCP Server
// ==========================================
const server = new mcp_js_1.McpServer({
    name: 'Project-Caffeine-S2-Prompt-Strategy',
    version: '2.0.0'
});
// ==========================================
// 注册 Prompts 原语（多维思维框架模板）
// ==========================================
server.prompt('scqa', // 示例：SCQA 框架
{
    situation: zod_1.z.string().describe('情境'),
    complication: zod_1.z.string().describe('复杂性'),
    question: zod_1.z.string().describe('问题'),
    answer: zod_1.z.string().describe('答案')
}, async (args, extra) => {
    const result = await (0, promptsController_1.handlePromptsGet)('scqa', args);
    return {
        ...result,
        messages: Array.isArray(result.messages)
            ? result.messages
                .filter((msg) => msg.role === "user" || msg.role === "assistant")
                .map((msg) => ({
                ...msg,
                // Optionally ensure content has required structure
                content: {
                    ...msg.content,
                    // Add default annotations/_meta if missing
                    annotations: msg.content.annotations ?? undefined,
                    _meta: msg.content._meta ?? undefined
                }
            }))
            : []
    };
});
server.prompt('5whys', // 5 Whys 框架
{ problem: zod_1.z.string().describe('需要分析的问题或现象') }, async (args) => {
    const result = await (0, promptsController_1.handlePromptsGet)('5whys', args);
    return {
        ...result,
        messages: Array.isArray(result.messages)
            ? result.messages
                .filter((msg) => msg.role === "user" || msg.role === "assistant")
                .map((msg) => ({
                ...msg,
                content: {
                    ...msg.content,
                    annotations: msg.content.annotations ?? undefined,
                    _meta: msg.content._meta ?? undefined
                }
            }))
            : []
    };
});
server.prompt('5w3h', // 5W3H 框架
{ topic: zod_1.z.string().describe('需要分析的主题') }, async (args) => {
    const result = await (0, promptsController_1.handlePromptsGet)('5w3h', args);
    return {
        ...result,
        messages: Array.isArray(result.messages)
            ? result.messages
                .filter((msg) => msg.role === "user" || msg.role === "assistant")
                .map((msg) => ({
                ...msg,
                content: {
                    ...msg.content,
                    annotations: msg.content.annotations ?? undefined,
                    _meta: msg.content._meta ?? undefined
                }
            }))
            : []
    };
});
server.prompt('swot', // SWOT 框架
{ entity: zod_1.z.string().describe('分析对象（企业、项目等）') }, async (args) => {
    const result = await (0, promptsController_1.handlePromptsGet)('swot', args);
    return {
        ...result,
        messages: Array.isArray(result.messages)
            ? result.messages
                .filter((msg) => msg.role === "user" || msg.role === "assistant")
                .map((msg) => ({
                ...msg,
                content: {
                    ...msg.content,
                    annotations: msg.content.annotations ?? undefined,
                    _meta: msg.content._meta ?? undefined
                }
            }))
            : []
    };
});
server.prompt('pestle', // PESTLE 框架
{ domain: zod_1.z.string().describe('行业或领域') }, async (args) => {
    const result = await (0, promptsController_1.handlePromptsGet)('pestle', args);
    return {
        ...result,
        messages: Array.isArray(result.messages)
            ? result.messages
                .filter((msg) => msg.role === "user" || msg.role === "assistant")
                .map((msg) => ({
                ...msg,
                content: {
                    ...msg.content,
                    annotations: msg.content.annotations ?? undefined,
                    _meta: msg.content._meta ?? undefined
                }
            }))
            : []
    };
});
// ==========================================
// 注册工具：generate_search_queries
// ==========================================
server.tool('generate_search_queries', { query: zod_1.z.string().describe('用户的原始查询语句') }, async (args, extra) => {
    const result = await (0, toolsController_1.handleToolCall)('generate_search_queries', args);
    // Ensure each content item has type: "text" (not a generic string)
    return {
        ...result,
        content: result.content.map((item) => ({
            ...item,
            type: "text"
        }))
    };
});
// =====================================================
// 注册工具：list_local_notes, read_local_note, save_note
// =====================================================
// 工具：列出本地笔记
server.tool('list_local_notes', {}, async (args) => {
    const result = await (0, toolsController_1.handleToolCall)('list_local_notes', args);
    return {
        ...result,
        content: result.content.map((item) => ({
            type: 'text',
            text: item.text
        }))
    };
});
// 工具：读取本地笔记
server.tool('read_local_note', { filename: zod_1.z.string().describe('需要读取的笔记文件名，必须包含 .md 后缀') }, async (args) => {
    const result = await (0, toolsController_1.handleToolCall)('read_local_note', args);
    return {
        ...result,
        content: result.content.map((item) => ({
            type: 'text',
            text: item.text
        }))
    };
});
// 工具：保存笔记到本地知识库
server.tool('save_note', {
    filename: zod_1.z.string().describe('笔记文件名，必须以 .md 结尾'),
    content: zod_1.z.string().describe('笔记内容（Markdown 格式）')
}, async (args) => {
    const result = await (0, toolsController_1.handleToolCall)('save_note', args);
    return {
        ...result,
        content: result.content.map((item) => ({
            type: 'text',
            text: item.text
        }))
    };
});
// ==========================================
// 注册 Resources 原语（暴露本地笔记供客户端勾选）
// ==========================================
// 使用 ResourceTemplate 注册动态资源
server.resource("local-notes", // 资源名称
new mcp_js_1.ResourceTemplate("note://local/{filename}", {
    // 实现列表功能：返回所有可用的笔记资源
    list: async () => {
        try {
            const notes = await (0, resourceService_1.listObsidianNotes)();
            return {
                resources: notes.map(filename => ({
                    name: filename,
                    uri: `note://local/${encodeURIComponent(filename)}`,
                    mimeType: "text/markdown",
                    description: `本地笔记: ${filename}`
                }))
            };
        }
        catch (error) {
            console.error('[Resources] 列出资源失败:', error);
            return { resources: [] };
        }
    }
}), 
// 处理资源读取：根据 URI 中的 filename 参数读取笔记内容
async (uri, { filename }) => {
    try {
        // filename 参数由 ResourceTemplate 自动从 URI 中提取
        const filenameStr = Array.isArray(filename) ? filename[0] : filename;
        const decodedFilename = decodeURIComponent(filenameStr);
        const content = await (0, resourceService_1.readObsidianNote)(decodedFilename);
        return {
            contents: [{
                    uri: uri.href,
                    mimeType: "text/markdown",
                    text: content
                }]
        };
    }
    catch (error) {
        // 错误处理：返回错误信息
        throw new Error(`读取笔记失败: ${error.message}`);
    }
});
// ==========================================
// 启动 STDIO 传输层
// ==========================================
async function start() {
    console.error('[S2] 正在启动 MCP Server (Prompts + 检索词工具)...');
    const transport = new stdio_js_1.StdioServerTransport();
    await server.connect(transport);
    console.error('[S2] MCP Server 已就绪，等待 Cherry Studio 连接');
}
start().catch((err) => {
    console.error('[S2] 服务器启动失败:', err);
    process.exit(1);
});
//# sourceMappingURL=app.js.map