mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-21 22:41:05 +08:00
Compare commits
65 Commits
codex/add-
...
codex/add-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d98c3644a6 | ||
|
|
dbb63a4039 | ||
|
|
8db928b9a8 | ||
|
|
46f6ccb3a8 | ||
|
|
87dcebf052 | ||
|
|
0ad4f4feff | ||
|
|
a227ac77fb | ||
|
|
ef53a40ed5 | ||
|
|
7d8c9b68bd | ||
|
|
dbc3d54fa1 | ||
|
|
4c0b9e744a | ||
|
|
4b4d1a2a86 | ||
|
|
6990aa93ed | ||
|
|
421b8b6b4f | ||
|
|
e55acc6dc4 | ||
|
|
33ce56aa31 | ||
|
|
339c39c6ca | ||
|
|
389961c922 | ||
|
|
6db53274fb | ||
|
|
a413c0be35 | ||
|
|
06ecd39c8b | ||
|
|
f0ba00b7e8 | ||
|
|
092c4c36c2 | ||
|
|
db13f8145d | ||
|
|
3be396976a | ||
|
|
3fbaa332fc | ||
|
|
4e6cb59753 | ||
|
|
1c6c17e577 | ||
|
|
c968efa42a | ||
|
|
0cd5ded39b | ||
|
|
7a2cf829c7 | ||
|
|
12329b43d1 | ||
|
|
1a45603e0f | ||
|
|
4a73503399 | ||
|
|
83bf8c1d5e | ||
|
|
34e206f05d | ||
|
|
dc349923e9 | ||
|
|
0d44c9a823 | ||
|
|
02645af321 | ||
|
|
c3a175f13f | ||
|
|
0821d447f7 | ||
|
|
257794ca00 | ||
|
|
6a527de3eb | ||
|
|
2313f90eb3 | ||
|
|
7fde984e7d | ||
|
|
fc41e605e4 | ||
|
|
042e5fdbe6 | ||
|
|
629442bff6 | ||
|
|
7798910be0 | ||
|
|
6f036eb4fe | ||
|
|
56fc05cb3c | ||
|
|
a55a15659b | ||
|
|
ccf6e0c7ce | ||
|
|
87677f5968 | ||
|
|
fd93a2dc61 | ||
|
|
80f862a226 | ||
|
|
26bb85f4d4 | ||
|
|
398b4b482f | ||
|
|
2cfb302981 | ||
|
|
e75bd76b71 | ||
|
|
99c3ac1837 | ||
|
|
749ab560ff | ||
|
|
541ad4d149 | ||
|
|
03eb027ea4 | ||
|
|
4194b2be91 |
30
.github/workflows/coffee-bot.yml
vendored
Normal file
30
.github/workflows/coffee-bot.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
name: Coffee Bot
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 1 * * 1-5"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
run-coffee-bot:
|
||||||
|
environment: Bots
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: "20"
|
||||||
|
cache: "npm"
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm install --no-save @openai/agents tsx typescript
|
||||||
|
|
||||||
|
- name: Run coffee bot
|
||||||
|
env:
|
||||||
|
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||||
|
OPENISLE_TOKEN: ${{ secrets.OPENISLE_TOKEN }}
|
||||||
|
APIFY_API_TOKEN: ${{ secrets.APIFY_API_TOKEN }}
|
||||||
|
run: npx tsx bots/instance/coffee_bot.ts
|
||||||
30
.github/workflows/open_source_reply_bot.yml
vendored
Normal file
30
.github/workflows/open_source_reply_bot.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
name: Open Source Reply Bot
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "*/30 * * * *"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
run-open-source-reply-bot:
|
||||||
|
environment: Bots
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: "20"
|
||||||
|
cache: "npm"
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm install --no-save @openai/agents tsx typescript
|
||||||
|
|
||||||
|
- name: Run open source reply bot
|
||||||
|
env:
|
||||||
|
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||||
|
OPENISLE_TOKEN: ${{ secrets.OPENISLE_TOKEN_BOT_1 }}
|
||||||
|
APIFY_API_TOKEN: ${{ secrets.APIFY_API_TOKEN }}
|
||||||
|
run: npx tsx bots/instance/open_source_reply_bot.ts
|
||||||
30
.github/workflows/reply-bots.yml
vendored
Normal file
30
.github/workflows/reply-bots.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
name: Reply Bots
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "*/30 * * * *"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
run-reply-bot:
|
||||||
|
environment: Bots
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: "20"
|
||||||
|
cache: "npm"
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm install --no-save @openai/agents tsx typescript
|
||||||
|
|
||||||
|
- name: Run reply bot
|
||||||
|
env:
|
||||||
|
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||||
|
OPENISLE_TOKEN: ${{ secrets.OPENISLE_TOKEN }}
|
||||||
|
APIFY_API_TOKEN: ${{ secrets.APIFY_API_TOKEN }}
|
||||||
|
run: npx tsx bots/instance/reply_bot.ts
|
||||||
164
bots/bot_father.ts
Normal file
164
bots/bot_father.ts
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
import { Agent, Runner, hostedMcpTool, withTrace } from "@openai/agents";
|
||||||
|
|
||||||
|
export type WorkflowInput = { input_as_text: string };
|
||||||
|
|
||||||
|
export abstract class BotFather {
|
||||||
|
protected readonly openisleToken = (process.env.OPENISLE_TOKEN ?? "").trim();
|
||||||
|
protected readonly weatherToken = (process.env.APIFY_API_TOKEN ?? "").trim();
|
||||||
|
|
||||||
|
protected readonly mcp = this.createHostedMcpTool();
|
||||||
|
protected readonly weatherMcp = this.createWeatherMcpTool();
|
||||||
|
protected readonly agent: Agent;
|
||||||
|
|
||||||
|
constructor(protected readonly name: string) {
|
||||||
|
console.log(`✅ ${this.name} starting...`);
|
||||||
|
console.log(
|
||||||
|
this.openisleToken
|
||||||
|
? "🔑 OPENISLE_TOKEN detected in environment; it will be attached to MCP requests."
|
||||||
|
: "🔓 OPENISLE_TOKEN not set; authenticated MCP tools may be unavailable."
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
this.weatherToken
|
||||||
|
? "☁️ APIFY_API_TOKEN detected; weather MCP server will be available."
|
||||||
|
: "🌥️ APIFY_API_TOKEN not set; weather updates will be unavailable."
|
||||||
|
);
|
||||||
|
|
||||||
|
this.agent = new Agent({
|
||||||
|
name: this.name,
|
||||||
|
instructions: this.buildInstructions(),
|
||||||
|
tools: [this.mcp, this.weatherMcp],
|
||||||
|
model: "gpt-4o",
|
||||||
|
modelSettings: {
|
||||||
|
temperature: 0.7,
|
||||||
|
topP: 1,
|
||||||
|
maxTokens: 2048,
|
||||||
|
toolChoice: "auto",
|
||||||
|
store: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected buildInstructions(): string {
|
||||||
|
const instructions = [
|
||||||
|
...this.getBaseInstructions(),
|
||||||
|
...this.getAdditionalInstructions(),
|
||||||
|
].filter(Boolean);
|
||||||
|
return instructions.join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getBaseInstructions(): string[] {
|
||||||
|
return [
|
||||||
|
"You are a helpful assistant for https://www.open-isle.com.",
|
||||||
|
"Finish tasks end-to-end before replying. If multiple MCP tools are needed, call them sequentially until the task is truly done.",
|
||||||
|
"When presenting the result, reply in Chinese with a concise summary and include any important URLs or IDs.",
|
||||||
|
"After finishing replies, call mark_notifications_read with all processed notification IDs to keep the inbox clean.",
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private createHostedMcpTool() {
|
||||||
|
const token = this.openisleToken;
|
||||||
|
const authConfig = token
|
||||||
|
? {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {};
|
||||||
|
|
||||||
|
return hostedMcpTool({
|
||||||
|
serverLabel: "openisle_mcp",
|
||||||
|
serverUrl: "https://www.open-isle.com/mcp",
|
||||||
|
allowedTools: [
|
||||||
|
"search", // 用于搜索帖子、内容等
|
||||||
|
"create_post", // 创建新帖子
|
||||||
|
"reply_to_post", // 回复帖子
|
||||||
|
"reply_to_comment", // 回复评论
|
||||||
|
"recent_posts", // 获取最新帖子
|
||||||
|
"get_post", // 获取特定帖子的详细信息
|
||||||
|
"list_unread_messages", // 列出未读消息或通知
|
||||||
|
"mark_notifications_read", // 标记通知为已读
|
||||||
|
],
|
||||||
|
requireApproval: "never",
|
||||||
|
...authConfig,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private createWeatherMcpTool(): ReturnType<typeof hostedMcpTool> {
|
||||||
|
return hostedMcpTool({
|
||||||
|
serverLabel: "weather_mcp_server",
|
||||||
|
serverUrl: "https://jiri-spilka--weather-mcp-server.apify.actor/mcp",
|
||||||
|
requireApproval: "never",
|
||||||
|
allowedTools: [
|
||||||
|
"get_current_weather", // 天气 MCP 工具
|
||||||
|
],
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${this.weatherToken || ""}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getAdditionalInstructions(): string[] {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected createRunner(): Runner {
|
||||||
|
return new Runner({
|
||||||
|
workflowName: this.name,
|
||||||
|
traceMetadata: {
|
||||||
|
__trace_source__: "agent-builder",
|
||||||
|
workflow_id: "wf_69003cbd47e08190928745d3c806c0b50d1a01cfae052be8",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async runWorkflow(workflow: WorkflowInput) {
|
||||||
|
if (!process.env.OPENAI_API_KEY) {
|
||||||
|
throw new Error("Missing OPENAI_API_KEY");
|
||||||
|
}
|
||||||
|
|
||||||
|
const runner = this.createRunner();
|
||||||
|
|
||||||
|
return await withTrace(`${this.name} run`, async () => {
|
||||||
|
const preview = workflow.input_as_text.trim();
|
||||||
|
console.log(
|
||||||
|
"📝 Received workflow input (preview):",
|
||||||
|
preview.length > 200 ? `${preview.slice(0, 200)}…` : preview
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log("🚦 Starting agent run with maxTurns=16...");
|
||||||
|
const result = await runner.run(this.agent, workflow.input_as_text, {
|
||||||
|
maxTurns: 16,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("📬 Agent run completed. Result keys:", Object.keys(result));
|
||||||
|
|
||||||
|
if (!result.finalOutput) {
|
||||||
|
throw new Error("Agent result is undefined (no final output).");
|
||||||
|
}
|
||||||
|
|
||||||
|
const openisleBotResult = { output_text: String(result.finalOutput) };
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
"🤖 Agent result (length=%d):\n%s",
|
||||||
|
openisleBotResult.output_text.length,
|
||||||
|
openisleBotResult.output_text
|
||||||
|
);
|
||||||
|
return openisleBotResult;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract getCliQuery(): string;
|
||||||
|
|
||||||
|
public async runCli(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const query = this.getCliQuery();
|
||||||
|
console.log("🔍 Running workflow...");
|
||||||
|
await this.runWorkflow({ input_as_text: query });
|
||||||
|
process.exit(0);
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error("❌ Agent failed:", err?.stack || err);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
55
bots/instance/coffee_bot.ts
Normal file
55
bots/instance/coffee_bot.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { BotFather, WorkflowInput } from "../bot_father";
|
||||||
|
|
||||||
|
const WEEKDAY_NAMES = ["日", "一", "二", "三", "四", "五", "六"] as const;
|
||||||
|
|
||||||
|
class CoffeeBot extends BotFather {
|
||||||
|
constructor() {
|
||||||
|
super("Coffee Bot");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override getAdditionalInstructions(): string[] {
|
||||||
|
return [
|
||||||
|
"You are responsible for 发布每日抽奖早安贴。",
|
||||||
|
"创建帖子时,确保标题、奖品信息、开奖时间以及领奖方式完全符合 CLI 查询提供的细节。",
|
||||||
|
"正文需亲切友好,简洁明了,鼓励社区成员互动。",
|
||||||
|
"开奖说明需明确告知中奖者需私聊站长 @nagisa 领取奖励。",
|
||||||
|
"确保只发布一个帖子,避免重复调用 create_post。",
|
||||||
|
"使用标签为 weather_mcp_server 的 MCP 工具获取北京、上海、广州、深圳当天的天气信息,并把结果写入早安问候之后。",
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override getCliQuery(): string {
|
||||||
|
const now = new Date(Date.now() + 8 * 60 * 60 * 1000);
|
||||||
|
const weekday = WEEKDAY_NAMES[now.getDay()];
|
||||||
|
const drawTime = new Date(now);
|
||||||
|
drawTime.setHours(15, 0, 0, 0);
|
||||||
|
|
||||||
|
return `
|
||||||
|
请立即在 https://www.open-isle.com 使用 create_post 发表一篇帖子,遵循以下要求:
|
||||||
|
1. 标题固定为「大家星期${weekday}早安--抽一杯咖啡」。
|
||||||
|
2. 正文包含:
|
||||||
|
- 亲切的早安问候;
|
||||||
|
- 早安问候后立即列出北京、上海、广州、深圳当天的天气信息,每行格式为“城市:天气描述,最低温~最高温”;天气需调用 weather_mcp_server 获取;
|
||||||
|
- 标注“领奖请私聊站长 @[nagisa]”;
|
||||||
|
- 鼓励大家留言互动。
|
||||||
|
3. 奖品信息
|
||||||
|
- 明确奖品写作“Coffee”;
|
||||||
|
- 帖子类型必须为 LOTTERY;
|
||||||
|
- 奖品图片链接:https://openisle-1307107697.cos.accelerate.myqcloud.com/dynamic_assert/0d6a9b33e9ca4fe5a90540187d3f9ecb.png;
|
||||||
|
- 公布开奖时间为 ${drawTime}, 直接传UTC时间给接口,不要考虑时区问题
|
||||||
|
- categoryId 固定为 10,tagIds 设为 [36]。
|
||||||
|
4. 帖子语言使用简体中文。
|
||||||
|
`.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const coffeeBot = new CoffeeBot();
|
||||||
|
|
||||||
|
export const runWorkflow = async (workflow: WorkflowInput) => {
|
||||||
|
return coffeeBot.runWorkflow(workflow);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
coffeeBot.runCli();
|
||||||
|
}
|
||||||
|
|
||||||
65
bots/instance/open_source_reply_bot.ts
Normal file
65
bots/instance/open_source_reply_bot.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { BotFather, WorkflowInput } from "../bot_father";
|
||||||
|
|
||||||
|
class OpenSourceReplyBot extends BotFather {
|
||||||
|
constructor() {
|
||||||
|
super("OpenSource Reply Bot");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override getAdditionalInstructions(): string[] {
|
||||||
|
const knowledgeBase = this.loadKnowledgeBase();
|
||||||
|
|
||||||
|
return [
|
||||||
|
"You are OpenSourceReplyBot, a professional helper who focuses on answering open-source development and code-related questions for the OpenIsle community.",
|
||||||
|
"Respond in Chinese using well-structured Markdown sections such as 标题、列表、代码块等,让回复清晰易读。",
|
||||||
|
"保持语气专业、耐心、详尽,绝不使用表情符号或颜文字,也不要卖萌。",
|
||||||
|
"优先解答与项目代码、贡献流程、架构设计或排错相关的问题;如果消息与此无关,请礼貌说明并跳过。",
|
||||||
|
"在需要时引用 README.md 与 CONTRIBUTING.md 中的要点,帮助用户快速定位文档位置。",
|
||||||
|
knowledgeBase,
|
||||||
|
].filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override getCliQuery(): string {
|
||||||
|
return `
|
||||||
|
【AUTO】每30分钟自动巡检未读提及与评论,严格遵守以下流程:
|
||||||
|
1)调用 list_unread_messages 获取待处理的“提及/评论”;
|
||||||
|
2)按时间从新到旧逐条处理(最多10条);如需上下文请调用 get_post;
|
||||||
|
3)仅对与开源项目、代码实现或贡献流程直接相关的问题生成详尽的 Markdown 中文回复,
|
||||||
|
若与主题无关则礼貌说明并跳过;
|
||||||
|
4)回复时引用 README 或 CONTRIBUTING 中的要点(如适用),并优先给出可执行的排查步骤或代码建议;
|
||||||
|
5)回复评论使用 reply_to_comment,回复帖子使用 reply_to_post;
|
||||||
|
6)若某通知最后一条已由本 bot 回复,则跳过避免重复;
|
||||||
|
7)整理已处理通知 ID 调用 mark_notifications_read;
|
||||||
|
8)结束时输出包含处理条目概览(URL或ID)的总结。`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadKnowledgeBase(): string {
|
||||||
|
const docs = ["../../README.md", "../../CONTRIBUTING.md"];
|
||||||
|
const sections: string[] = [];
|
||||||
|
|
||||||
|
for (const relativePath of docs) {
|
||||||
|
try {
|
||||||
|
const absolutePath = path.resolve(__dirname, relativePath);
|
||||||
|
const content = readFileSync(absolutePath, "utf-8").trim();
|
||||||
|
if (content) {
|
||||||
|
sections.push(`以下是 ${path.basename(absolutePath)} 的内容:\n${content}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
sections.push(`未能加载 ${relativePath},请检查文件路径或权限。`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sections.join("\n\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const openSourceReplyBot = new OpenSourceReplyBot();
|
||||||
|
|
||||||
|
export const runWorkflow = async (workflow: WorkflowInput) => {
|
||||||
|
return openSourceReplyBot.runWorkflow(workflow);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
openSourceReplyBot.runCli();
|
||||||
|
}
|
||||||
39
bots/instance/reply_bot.ts
Normal file
39
bots/instance/reply_bot.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
// reply_bot.ts
|
||||||
|
import { BotFather, WorkflowInput } from "../bot_father";
|
||||||
|
|
||||||
|
class ReplyBot extends BotFather {
|
||||||
|
constructor() {
|
||||||
|
super("OpenIsle Bot");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override getAdditionalInstructions(): string[] {
|
||||||
|
return [
|
||||||
|
"You are a helpful and cute assistant for https://www.open-isle.com. Keep the lovable tone with plentiful kawaii kaomoji (颜表情) such as (๑˃ᴗ˂)ﻭ, (•̀ω•́)✧, (。•ᴗ-)_♡, (⁎⁍̴̛ᴗ⁍̴̛⁎), etc., while staying professional and informative.",
|
||||||
|
"OpenIsle 是一个由 Spring Boot + Vue 3 打造的开源社区平台,提供注册登录、OAuth 登录(Google/GitHub/Discord/Twitter)、帖子与评论互动、标签分类、草稿、统计分析、通知消息、全局搜索、Markdown 支持、图片上传(默认腾讯云 COS)、浏览器推送、DiceBear 头像等功能,旨在帮助团队快速搭建属于自己的技术社区。",
|
||||||
|
"回复时请主动结合上述站点背景,为用户提供有洞察力、可执行的建议或答案,并在需要时引用官网 https://www.open-isle.com、GitHub 仓库 https://github.com/nagisa77/OpenIsle 或相关文档链接,避免空泛的安慰或套话。",
|
||||||
|
"When presenting the result, reply in Chinese with a concise yet content-rich summary filled with kaomoji,并清晰列出关键结论、操作步骤、重要 URL 或 ID,确保用户能直接采取行动。",
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override getCliQuery(): string {
|
||||||
|
return `
|
||||||
|
【AUTO】无需确认,自动处理所有未读的提及与评论:
|
||||||
|
1)调用 list_unread_messages;
|
||||||
|
2)依次处理每条“提及/评论”:如需上下文则使用 get_post 获取,生成简明中文回复;如有 commentId 则用 reply_to_comment,否则用 reply_to_post;
|
||||||
|
3)跳过关注和系统事件;
|
||||||
|
4)保证幂等性:如该贴最后一条是你自己发的回复,则跳过;
|
||||||
|
5)调用 mark_notifications_read,传入本次已处理的通知 ID 清理已读;
|
||||||
|
6)最多只处理最新10条;结束时仅输出简要摘要(包含URL或ID)。
|
||||||
|
`.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const replyBot = new ReplyBot();
|
||||||
|
|
||||||
|
export const runWorkflow = async (workflow: WorkflowInput) => {
|
||||||
|
return replyBot.runWorkflow(workflow);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
replyBot.runCli();
|
||||||
|
}
|
||||||
@@ -31,6 +31,7 @@ By default the server listens on port `8085` and serves MCP over Streamable HTTP
|
|||||||
| Tool | Description |
|
| Tool | Description |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `search` | Perform a global search against the OpenIsle backend. |
|
| `search` | Perform a global search against the OpenIsle backend. |
|
||||||
|
| `create_post` | Publish a new post using a JWT token. |
|
||||||
| `reply_to_post` | Create a new comment on a post using a JWT token. |
|
| `reply_to_post` | Create a new comment on a post using a JWT token. |
|
||||||
| `reply_to_comment` | Reply to an existing comment using a JWT token. |
|
| `reply_to_comment` | Reply to an existing comment using a JWT token. |
|
||||||
| `recent_posts` | Retrieve posts created within the last *N* minutes. |
|
| `recent_posts` | Retrieve posts created within the last *N* minutes. |
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional
|
||||||
|
|
||||||
from pydantic import BaseModel, Field, ConfigDict
|
from pydantic import BaseModel, Field, ConfigDict, field_validator
|
||||||
|
|
||||||
|
|
||||||
class SearchResultItem(BaseModel):
|
class SearchResultItem(BaseModel):
|
||||||
@@ -170,6 +170,15 @@ class CommentData(BaseModel):
|
|||||||
|
|
||||||
model_config = ConfigDict(populate_by_name=True, extra="allow")
|
model_config = ConfigDict(populate_by_name=True, extra="allow")
|
||||||
|
|
||||||
|
@field_validator("replies", "reactions", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _ensure_comment_lists(cls, value: Any) -> list[Any]:
|
||||||
|
"""Convert ``None`` payloads to empty lists for comment collections."""
|
||||||
|
|
||||||
|
if value is None:
|
||||||
|
return []
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
class CommentReplyResult(BaseModel):
|
class CommentReplyResult(BaseModel):
|
||||||
"""Structured response returned when replying to a comment."""
|
"""Structured response returned when replying to a comment."""
|
||||||
@@ -183,6 +192,12 @@ class CommentCreateResult(BaseModel):
|
|||||||
comment: CommentData = Field(description="Comment returned by the backend.")
|
comment: CommentData = Field(description="Comment returned by the backend.")
|
||||||
|
|
||||||
|
|
||||||
|
class PostCreateResult(BaseModel):
|
||||||
|
"""Structured response returned when creating a new post."""
|
||||||
|
|
||||||
|
post: PostDetail = Field(description="Detailed post payload returned by the backend.")
|
||||||
|
|
||||||
|
|
||||||
class PostSummary(BaseModel):
|
class PostSummary(BaseModel):
|
||||||
"""Summary information for a post."""
|
"""Summary information for a post."""
|
||||||
|
|
||||||
@@ -253,6 +268,15 @@ class PostSummary(BaseModel):
|
|||||||
|
|
||||||
model_config = ConfigDict(populate_by_name=True, extra="allow")
|
model_config = ConfigDict(populate_by_name=True, extra="allow")
|
||||||
|
|
||||||
|
@field_validator("tags", "reactions", "participants", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _ensure_post_lists(cls, value: Any) -> list[Any]:
|
||||||
|
"""Normalize ``None`` values returned by the backend to empty lists."""
|
||||||
|
|
||||||
|
if value is None:
|
||||||
|
return []
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
class RecentPostsResponse(BaseModel):
|
class RecentPostsResponse(BaseModel):
|
||||||
"""Structured response for the recent posts tool."""
|
"""Structured response for the recent posts tool."""
|
||||||
@@ -278,6 +302,15 @@ class PostDetail(PostSummary):
|
|||||||
|
|
||||||
model_config = ConfigDict(populate_by_name=True, extra="allow")
|
model_config = ConfigDict(populate_by_name=True, extra="allow")
|
||||||
|
|
||||||
|
@field_validator("comments", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _ensure_comments_list(cls, value: Any) -> list[Any]:
|
||||||
|
"""Treat ``None`` comments payloads as empty lists."""
|
||||||
|
|
||||||
|
if value is None:
|
||||||
|
return []
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
class NotificationData(BaseModel):
|
class NotificationData(BaseModel):
|
||||||
"""Unread notification payload returned by the backend."""
|
"""Unread notification payload returned by the backend."""
|
||||||
@@ -331,3 +364,15 @@ class UnreadNotificationsResponse(BaseModel):
|
|||||||
default_factory=list,
|
default_factory=list,
|
||||||
description="Unread notifications returned by the backend.",
|
description="Unread notifications returned by the backend.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class NotificationCleanupResult(BaseModel):
|
||||||
|
"""Structured response returned after marking notifications as read."""
|
||||||
|
|
||||||
|
processed_ids: list[int] = Field(
|
||||||
|
default_factory=list,
|
||||||
|
description="Identifiers that were marked as read in the backend.",
|
||||||
|
)
|
||||||
|
total_marked: int = Field(
|
||||||
|
description="Total number of notifications successfully marked as read.",
|
||||||
|
)
|
||||||
|
|||||||
@@ -66,14 +66,15 @@ class SearchClient:
|
|||||||
resolved = self._resolve_token(token)
|
resolved = self._resolve_token(token)
|
||||||
if resolved is None:
|
if resolved is None:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"Authenticated request requires an access token but none was provided."
|
"Authenticated request requires an access token. Provide a Bearer token "
|
||||||
|
"via the MCP Authorization header or configure a default token for the server."
|
||||||
)
|
)
|
||||||
return resolved
|
return resolved
|
||||||
|
|
||||||
def _build_headers(
|
def _build_headers(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
token: str | None = None,
|
token: str,
|
||||||
accept: str = "application/json",
|
accept: str = "application/json",
|
||||||
include_json: bool = False,
|
include_json: bool = False,
|
||||||
) -> dict[str, str]:
|
) -> dict[str, str]:
|
||||||
@@ -173,6 +174,33 @@ class SearchClient:
|
|||||||
logger.info("Reply to post_id=%s succeeded with id=%s", post_id, body.get("id"))
|
logger.info("Reply to post_id=%s succeeded with id=%s", post_id, body.get("id"))
|
||||||
return body
|
return body
|
||||||
|
|
||||||
|
async def create_post(
|
||||||
|
self,
|
||||||
|
payload: dict[str, Any],
|
||||||
|
*,
|
||||||
|
token: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Create a new post and return the detailed backend payload."""
|
||||||
|
|
||||||
|
client = self._get_client()
|
||||||
|
resolved_token = self._require_token(token)
|
||||||
|
headers = self._build_headers(token=resolved_token, include_json=True)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
"Creating post with category_id=%s and %d tag(s)",
|
||||||
|
payload.get("categoryId"),
|
||||||
|
len(payload.get("tagIds", []) if isinstance(payload.get("tagIds"), list) else []),
|
||||||
|
)
|
||||||
|
response = await client.post(
|
||||||
|
"/api/posts",
|
||||||
|
json=payload,
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
body = self._ensure_dict(response.json())
|
||||||
|
logger.info("Post creation succeeded with id=%s, token=%s", body.get("id"), token)
|
||||||
|
return body
|
||||||
|
|
||||||
async def recent_posts(self, minutes: int) -> list[dict[str, Any]]:
|
async def recent_posts(self, minutes: int) -> list[dict[str, Any]]:
|
||||||
"""Return posts created within the given timeframe."""
|
"""Return posts created within the given timeframe."""
|
||||||
|
|
||||||
@@ -221,7 +249,7 @@ class SearchClient:
|
|||||||
*,
|
*,
|
||||||
page: int = 0,
|
page: int = 0,
|
||||||
size: int = 30,
|
size: int = 30,
|
||||||
token: str | None = None,
|
token: str,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
"""Return unread notifications for the authenticated user."""
|
"""Return unread notifications for the authenticated user."""
|
||||||
|
|
||||||
@@ -253,6 +281,53 @@ class SearchClient:
|
|||||||
)
|
)
|
||||||
return [self._ensure_dict(entry) for entry in payload]
|
return [self._ensure_dict(entry) for entry in payload]
|
||||||
|
|
||||||
|
async def mark_notifications_read(
|
||||||
|
self,
|
||||||
|
ids: list[int],
|
||||||
|
*,
|
||||||
|
token: str
|
||||||
|
) -> None:
|
||||||
|
"""Mark the provided notifications as read for the authenticated user."""
|
||||||
|
|
||||||
|
if not ids:
|
||||||
|
raise ValueError(
|
||||||
|
"At least one notification identifier must be provided to mark as read."
|
||||||
|
)
|
||||||
|
|
||||||
|
sanitized_ids: list[int] = []
|
||||||
|
for value in ids:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
raise ValueError("Notification identifiers must be integers, not booleans.")
|
||||||
|
try:
|
||||||
|
converted = int(value)
|
||||||
|
except (TypeError, ValueError) as exc: # pragma: no cover - defensive
|
||||||
|
raise ValueError(
|
||||||
|
"Notification identifiers must be integers."
|
||||||
|
) from exc
|
||||||
|
if converted <= 0:
|
||||||
|
raise ValueError(
|
||||||
|
"Notification identifiers must be positive integers."
|
||||||
|
)
|
||||||
|
sanitized_ids.append(converted)
|
||||||
|
|
||||||
|
client = self._get_client()
|
||||||
|
resolved_token = self._require_token(token)
|
||||||
|
logger.debug(
|
||||||
|
"Marking %d notifications as read: ids=%s",
|
||||||
|
len(sanitized_ids),
|
||||||
|
sanitized_ids,
|
||||||
|
)
|
||||||
|
response = await client.post(
|
||||||
|
"/api/notifications/read",
|
||||||
|
json={"ids": sanitized_ids},
|
||||||
|
headers=self._build_headers(token=resolved_token, include_json=True),
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
logger.info(
|
||||||
|
"Successfully marked %d notifications as read.",
|
||||||
|
len(sanitized_ids),
|
||||||
|
)
|
||||||
|
|
||||||
async def aclose(self) -> None:
|
async def aclose(self) -> None:
|
||||||
"""Dispose of the underlying HTTP client."""
|
"""Dispose of the underlying HTTP client."""
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,12 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from typing import Annotated, Any
|
from typing import Annotated
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from mcp.server.fastmcp import Context, FastMCP
|
from mcp.server.fastmcp import Context, FastMCP
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
from pydantic import Field as PydanticField
|
from pydantic import Field as PydanticField
|
||||||
from weakref import WeakKeyDictionary
|
|
||||||
|
|
||||||
from .config import get_settings
|
from .config import get_settings
|
||||||
from .schemas import (
|
from .schemas import (
|
||||||
@@ -18,8 +17,10 @@ from .schemas import (
|
|||||||
CommentData,
|
CommentData,
|
||||||
CommentReplyResult,
|
CommentReplyResult,
|
||||||
NotificationData,
|
NotificationData,
|
||||||
|
NotificationCleanupResult,
|
||||||
UnreadNotificationsResponse,
|
UnreadNotificationsResponse,
|
||||||
PostDetail,
|
PostDetail,
|
||||||
|
PostCreateResult,
|
||||||
PostSummary,
|
PostSummary,
|
||||||
RecentPostsResponse,
|
RecentPostsResponse,
|
||||||
SearchResponse,
|
SearchResponse,
|
||||||
@@ -51,67 +52,35 @@ search_client = SearchClient(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class SessionTokenManager:
|
def _extract_authorization_token(ctx: Context | None) -> str | None:
|
||||||
"""Cache JWT access tokens on a per-session basis."""
|
"""Return the Bearer token from the incoming MCP request headers."""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self._tokens: WeakKeyDictionary[Any, str] = WeakKeyDictionary()
|
|
||||||
|
|
||||||
def resolve(
|
|
||||||
self, ctx: Context | None, token: str | None = None
|
|
||||||
) -> str | None:
|
|
||||||
"""Resolve and optionally persist the token for the current session."""
|
|
||||||
|
|
||||||
session = self._get_session(ctx)
|
|
||||||
|
|
||||||
if isinstance(token, str):
|
|
||||||
stripped = token.strip()
|
|
||||||
if stripped:
|
|
||||||
if session is not None:
|
|
||||||
self._tokens[session] = stripped
|
|
||||||
logger.debug(
|
|
||||||
"Stored JWT token for session %s.",
|
|
||||||
self._describe_session(session),
|
|
||||||
)
|
|
||||||
return stripped
|
|
||||||
|
|
||||||
if session is not None and session in self._tokens:
|
|
||||||
logger.debug(
|
|
||||||
"Clearing stored JWT token for session %s due to empty input.",
|
|
||||||
self._describe_session(session),
|
|
||||||
)
|
|
||||||
del self._tokens[session]
|
|
||||||
return None
|
|
||||||
|
|
||||||
if session is not None:
|
|
||||||
cached = self._tokens.get(session)
|
|
||||||
if cached:
|
|
||||||
logger.debug(
|
|
||||||
"Reusing cached JWT token for session %s.",
|
|
||||||
self._describe_session(session),
|
|
||||||
)
|
|
||||||
return cached
|
|
||||||
|
|
||||||
|
if ctx is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@staticmethod
|
try:
|
||||||
def _get_session(ctx: Context | None) -> Any | None:
|
request_context = ctx.request_context
|
||||||
if ctx is None:
|
except ValueError:
|
||||||
return None
|
return None
|
||||||
try:
|
|
||||||
return ctx.session
|
|
||||||
except Exception: # pragma: no cover - defensive guard
|
|
||||||
return None
|
|
||||||
|
|
||||||
@staticmethod
|
request = getattr(request_context, "request", None)
|
||||||
def _describe_session(session: Any) -> str:
|
if request is None:
|
||||||
identifier = getattr(session, "mcp_session_id", None)
|
return None
|
||||||
if isinstance(identifier, str) and identifier:
|
|
||||||
return identifier
|
|
||||||
return hex(id(session))
|
|
||||||
|
|
||||||
|
headers = getattr(request, "headers", None)
|
||||||
|
if headers is None:
|
||||||
|
return None
|
||||||
|
|
||||||
session_token_manager = SessionTokenManager()
|
authorization = headers.get("authorization")
|
||||||
|
if not authorization:
|
||||||
|
return None
|
||||||
|
|
||||||
|
scheme, _, token = authorization.partition(" ")
|
||||||
|
if scheme.lower() != "bearer":
|
||||||
|
return None
|
||||||
|
|
||||||
|
stripped = token.strip()
|
||||||
|
return stripped or None
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -129,9 +98,10 @@ async def lifespan(_: FastMCP):
|
|||||||
app = FastMCP(
|
app = FastMCP(
|
||||||
name="openisle-mcp",
|
name="openisle-mcp",
|
||||||
instructions=(
|
instructions=(
|
||||||
"Use this server to search OpenIsle content, reply to posts and comments with "
|
"Use this server to search OpenIsle content, create new posts, reply to posts and "
|
||||||
"session-managed authentication, retrieve details for a specific post, list posts created "
|
"comments using the Authorization header or configured access token, retrieve details "
|
||||||
"within a recent time window, and review unread notification messages."
|
"for a specific post, list posts created within a recent time window, and review "
|
||||||
|
"unread notification messages."
|
||||||
),
|
),
|
||||||
host=settings.host,
|
host=settings.host,
|
||||||
port=settings.port,
|
port=settings.port,
|
||||||
@@ -139,25 +109,6 @@ app = FastMCP(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.tool(
|
|
||||||
name="set_token",
|
|
||||||
description=(
|
|
||||||
"Set JWT token for the current session to be reused by other tools."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
async def set_token(
|
|
||||||
token: Annotated[
|
|
||||||
str,
|
|
||||||
PydanticField(description="JWT token string."),
|
|
||||||
],
|
|
||||||
ctx: Context | None = None,
|
|
||||||
) -> str:
|
|
||||||
"""Persist a JWT token for the active MCP session."""
|
|
||||||
|
|
||||||
session_token_manager.resolve(ctx, token)
|
|
||||||
return "Token stored successfully."
|
|
||||||
|
|
||||||
|
|
||||||
@app.tool(
|
@app.tool(
|
||||||
name="search",
|
name="search",
|
||||||
description="Perform a global search across OpenIsle resources.",
|
description="Perform a global search across OpenIsle resources.",
|
||||||
@@ -211,7 +162,10 @@ async def search(
|
|||||||
|
|
||||||
@app.tool(
|
@app.tool(
|
||||||
name="reply_to_post",
|
name="reply_to_post",
|
||||||
description="Create a comment on a post using session authentication.",
|
description=(
|
||||||
|
"Create a comment on a post using the request Authorization header or the configured "
|
||||||
|
"access token."
|
||||||
|
),
|
||||||
structured_output=True,
|
structured_output=True,
|
||||||
)
|
)
|
||||||
async def reply_to_post(
|
async def reply_to_post(
|
||||||
@@ -240,7 +194,7 @@ async def reply_to_post(
|
|||||||
|
|
||||||
sanitized_captcha = captcha.strip() if isinstance(captcha, str) else None
|
sanitized_captcha = captcha.strip() if isinstance(captcha, str) else None
|
||||||
|
|
||||||
resolved_token = session_token_manager.resolve(ctx)
|
request_token = _extract_authorization_token(ctx)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info(
|
logger.info(
|
||||||
@@ -250,20 +204,20 @@ async def reply_to_post(
|
|||||||
)
|
)
|
||||||
raw_comment = await search_client.reply_to_post(
|
raw_comment = await search_client.reply_to_post(
|
||||||
post_id,
|
post_id,
|
||||||
resolved_token,
|
token=request_token,
|
||||||
sanitized_content,
|
content=sanitized_content,
|
||||||
sanitized_captcha,
|
captcha=sanitized_captcha,
|
||||||
)
|
)
|
||||||
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
||||||
status_code = exc.response.status_code
|
status_code = exc.response.status_code
|
||||||
if status_code == 401:
|
if status_code == 401:
|
||||||
message = (
|
message = (
|
||||||
"Authentication failed while replying to post "
|
"Authentication failed while replying to post "
|
||||||
f"{post_id}. Please verify the token."
|
f"{post_id}. Please verify the Authorization header or configured token."
|
||||||
)
|
)
|
||||||
elif status_code == 403:
|
elif status_code == 403:
|
||||||
message = (
|
message = (
|
||||||
"The provided token is not authorized to reply to post "
|
"The provided Authorization token is not authorized to reply to post "
|
||||||
f"{post_id}."
|
f"{post_id}."
|
||||||
)
|
)
|
||||||
elif status_code == 404:
|
elif status_code == 404:
|
||||||
@@ -309,7 +263,10 @@ async def reply_to_post(
|
|||||||
|
|
||||||
@app.tool(
|
@app.tool(
|
||||||
name="reply_to_comment",
|
name="reply_to_comment",
|
||||||
description="Reply to an existing comment using session authentication.",
|
description=(
|
||||||
|
"Reply to an existing comment using the request Authorization header or the configured "
|
||||||
|
"access token."
|
||||||
|
),
|
||||||
structured_output=True,
|
structured_output=True,
|
||||||
)
|
)
|
||||||
async def reply_to_comment(
|
async def reply_to_comment(
|
||||||
@@ -338,7 +295,7 @@ async def reply_to_comment(
|
|||||||
|
|
||||||
sanitized_captcha = captcha.strip() if isinstance(captcha, str) else None
|
sanitized_captcha = captcha.strip() if isinstance(captcha, str) else None
|
||||||
|
|
||||||
resolved_token = session_token_manager.resolve(ctx)
|
request_token = _extract_authorization_token(ctx)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info(
|
logger.info(
|
||||||
@@ -348,20 +305,20 @@ async def reply_to_comment(
|
|||||||
)
|
)
|
||||||
raw_comment = await search_client.reply_to_comment(
|
raw_comment = await search_client.reply_to_comment(
|
||||||
comment_id,
|
comment_id,
|
||||||
resolved_token,
|
token=request_token,
|
||||||
sanitized_content,
|
content=sanitized_content,
|
||||||
sanitized_captcha,
|
captcha=sanitized_captcha,
|
||||||
)
|
)
|
||||||
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
||||||
status_code = exc.response.status_code
|
status_code = exc.response.status_code
|
||||||
if status_code == 401:
|
if status_code == 401:
|
||||||
message = (
|
message = (
|
||||||
"Authentication failed while replying to comment "
|
"Authentication failed while replying to comment "
|
||||||
f"{comment_id}. Please verify the token."
|
f"{comment_id}. Please verify the Authorization header or configured token."
|
||||||
)
|
)
|
||||||
elif status_code == 403:
|
elif status_code == 403:
|
||||||
message = (
|
message = (
|
||||||
"The provided token is not authorized to reply to comment "
|
"The provided Authorization token is not authorized to reply to comment "
|
||||||
f"{comment_id}."
|
f"{comment_id}."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -403,6 +360,342 @@ async def reply_to_comment(
|
|||||||
return CommentReplyResult(comment=comment)
|
return CommentReplyResult(comment=comment)
|
||||||
|
|
||||||
|
|
||||||
|
@app.tool(
|
||||||
|
name="create_post",
|
||||||
|
description=(
|
||||||
|
"Publish a new post using the request Authorization header or the configured access "
|
||||||
|
"token."
|
||||||
|
),
|
||||||
|
structured_output=True,
|
||||||
|
)
|
||||||
|
async def create_post(
|
||||||
|
title: Annotated[
|
||||||
|
str,
|
||||||
|
PydanticField(description="Title of the post to be created."),
|
||||||
|
],
|
||||||
|
content: Annotated[
|
||||||
|
str,
|
||||||
|
PydanticField(description="Markdown content of the post."),
|
||||||
|
],
|
||||||
|
category_id: Annotated[
|
||||||
|
int | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
ge=1,
|
||||||
|
description="Optional category identifier for the post.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
tag_ids: Annotated[
|
||||||
|
list[int] | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
min_length=1,
|
||||||
|
description="Optional list of tag identifiers to assign to the post.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
post_type: Annotated[
|
||||||
|
str | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="Optional post type value (e.g. LOTTERY, POLL).",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
visible_scope: Annotated[
|
||||||
|
str | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="Optional visibility scope for the post.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
prize_description: Annotated[
|
||||||
|
str | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="Description of the prize for lottery posts.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
prize_icon: Annotated[
|
||||||
|
str | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="Icon URL for the lottery prize.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
prize_count: Annotated[
|
||||||
|
int | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
ge=1,
|
||||||
|
description="Total number of prizes available for lottery posts.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
point_cost: Annotated[
|
||||||
|
int | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
ge=0,
|
||||||
|
description="Point cost required to participate in the post, when applicable.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
start_time: Annotated[
|
||||||
|
str | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="ISO 8601 start time for lottery or poll posts.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
end_time: Annotated[
|
||||||
|
str | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="ISO 8601 end time for lottery or poll posts.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
options: Annotated[
|
||||||
|
list[str] | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
min_length=1,
|
||||||
|
description="Poll options when creating a poll post.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
multiple: Annotated[
|
||||||
|
bool | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="Whether the poll allows selecting multiple options.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
proposed_name: Annotated[
|
||||||
|
str | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="Proposed category name for suggestion posts.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
proposal_description: Annotated[
|
||||||
|
str | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="Supporting description for the proposed category.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
captcha: Annotated[
|
||||||
|
str | None,
|
||||||
|
PydanticField(
|
||||||
|
default=None,
|
||||||
|
description="Captcha solution if the backend requires one to create posts.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
ctx: Context | None = None,
|
||||||
|
) -> PostCreateResult:
|
||||||
|
"""Create a new post in OpenIsle and return the detailed backend payload."""
|
||||||
|
|
||||||
|
sanitized_title = title.strip()
|
||||||
|
if not sanitized_title:
|
||||||
|
raise ValueError("Post title must not be empty.")
|
||||||
|
|
||||||
|
sanitized_content = content.strip()
|
||||||
|
if not sanitized_content:
|
||||||
|
raise ValueError("Post content must not be empty.")
|
||||||
|
|
||||||
|
sanitized_category_id: int | None = None
|
||||||
|
if category_id is not None:
|
||||||
|
if isinstance(category_id, bool):
|
||||||
|
raise ValueError("Category identifier must be an integer, not a boolean.")
|
||||||
|
try:
|
||||||
|
sanitized_category_id = int(category_id)
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ValueError("Category identifier must be an integer.") from exc
|
||||||
|
if sanitized_category_id <= 0:
|
||||||
|
raise ValueError("Category identifier must be a positive integer.")
|
||||||
|
if sanitized_category_id is None:
|
||||||
|
raise ValueError("A category identifier is required to create a post.")
|
||||||
|
|
||||||
|
sanitized_tag_ids: list[int] | None = None
|
||||||
|
if tag_ids is not None:
|
||||||
|
sanitized_tag_ids = []
|
||||||
|
for value in tag_ids:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
raise ValueError("Tag identifiers must be integers, not booleans.")
|
||||||
|
try:
|
||||||
|
converted = int(value)
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ValueError("Tag identifiers must be integers.") from exc
|
||||||
|
if converted <= 0:
|
||||||
|
raise ValueError("Tag identifiers must be positive integers.")
|
||||||
|
sanitized_tag_ids.append(converted)
|
||||||
|
if not sanitized_tag_ids:
|
||||||
|
sanitized_tag_ids = None
|
||||||
|
if not sanitized_tag_ids:
|
||||||
|
raise ValueError("At least one tag identifier is required to create a post.")
|
||||||
|
if len(sanitized_tag_ids) > 2:
|
||||||
|
raise ValueError("At most two tag identifiers can be provided for a post.")
|
||||||
|
|
||||||
|
sanitized_post_type = post_type.strip() if isinstance(post_type, str) else None
|
||||||
|
if sanitized_post_type == "":
|
||||||
|
sanitized_post_type = None
|
||||||
|
|
||||||
|
sanitized_visible_scope = (
|
||||||
|
visible_scope.strip() if isinstance(visible_scope, str) else None
|
||||||
|
)
|
||||||
|
if sanitized_visible_scope == "":
|
||||||
|
sanitized_visible_scope = None
|
||||||
|
|
||||||
|
sanitized_prize_description = (
|
||||||
|
prize_description.strip() if isinstance(prize_description, str) else None
|
||||||
|
)
|
||||||
|
if sanitized_prize_description == "":
|
||||||
|
sanitized_prize_description = None
|
||||||
|
|
||||||
|
sanitized_prize_icon = prize_icon.strip() if isinstance(prize_icon, str) else None
|
||||||
|
if sanitized_prize_icon == "":
|
||||||
|
sanitized_prize_icon = None
|
||||||
|
|
||||||
|
sanitized_prize_count: int | None = None
|
||||||
|
if prize_count is not None:
|
||||||
|
if isinstance(prize_count, bool):
|
||||||
|
raise ValueError("Prize count must be an integer, not a boolean.")
|
||||||
|
try:
|
||||||
|
sanitized_prize_count = int(prize_count)
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ValueError("Prize count must be an integer.") from exc
|
||||||
|
if sanitized_prize_count <= 0:
|
||||||
|
raise ValueError("Prize count must be a positive integer.")
|
||||||
|
|
||||||
|
sanitized_point_cost: int | None = None
|
||||||
|
if point_cost is not None:
|
||||||
|
if isinstance(point_cost, bool):
|
||||||
|
raise ValueError("Point cost must be an integer, not a boolean.")
|
||||||
|
try:
|
||||||
|
sanitized_point_cost = int(point_cost)
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ValueError("Point cost must be an integer.") from exc
|
||||||
|
if sanitized_point_cost < 0:
|
||||||
|
raise ValueError("Point cost cannot be negative.")
|
||||||
|
|
||||||
|
sanitized_start_time = start_time.strip() if isinstance(start_time, str) else None
|
||||||
|
if sanitized_start_time == "":
|
||||||
|
sanitized_start_time = None
|
||||||
|
|
||||||
|
sanitized_end_time = end_time.strip() if isinstance(end_time, str) else None
|
||||||
|
if sanitized_end_time == "":
|
||||||
|
sanitized_end_time = None
|
||||||
|
|
||||||
|
sanitized_options: list[str] | None = None
|
||||||
|
if options is not None:
|
||||||
|
sanitized_options = []
|
||||||
|
for option in options:
|
||||||
|
if option is None:
|
||||||
|
continue
|
||||||
|
stripped_option = option.strip()
|
||||||
|
if stripped_option:
|
||||||
|
sanitized_options.append(stripped_option)
|
||||||
|
if not sanitized_options:
|
||||||
|
sanitized_options = None
|
||||||
|
|
||||||
|
sanitized_multiple = bool(multiple) if isinstance(multiple, bool) else None
|
||||||
|
|
||||||
|
sanitized_proposed_name = (
|
||||||
|
proposed_name.strip() if isinstance(proposed_name, str) else None
|
||||||
|
)
|
||||||
|
if sanitized_proposed_name == "":
|
||||||
|
sanitized_proposed_name = None
|
||||||
|
|
||||||
|
sanitized_proposal_description = (
|
||||||
|
proposal_description.strip() if isinstance(proposal_description, str) else None
|
||||||
|
)
|
||||||
|
if sanitized_proposal_description == "":
|
||||||
|
sanitized_proposal_description = None
|
||||||
|
|
||||||
|
sanitized_captcha = captcha.strip() if isinstance(captcha, str) else None
|
||||||
|
if sanitized_captcha == "":
|
||||||
|
sanitized_captcha = None
|
||||||
|
|
||||||
|
payload: dict[str, object] = {
|
||||||
|
"title": sanitized_title,
|
||||||
|
"content": sanitized_content,
|
||||||
|
}
|
||||||
|
if sanitized_category_id is not None:
|
||||||
|
payload["categoryId"] = sanitized_category_id
|
||||||
|
if sanitized_tag_ids is not None:
|
||||||
|
payload["tagIds"] = sanitized_tag_ids
|
||||||
|
if sanitized_post_type is not None:
|
||||||
|
payload["type"] = sanitized_post_type
|
||||||
|
if sanitized_visible_scope is not None:
|
||||||
|
payload["postVisibleScopeType"] = sanitized_visible_scope
|
||||||
|
if sanitized_prize_description is not None:
|
||||||
|
payload["prizeDescription"] = sanitized_prize_description
|
||||||
|
if sanitized_prize_icon is not None:
|
||||||
|
payload["prizeIcon"] = sanitized_prize_icon
|
||||||
|
if sanitized_prize_count is not None:
|
||||||
|
payload["prizeCount"] = sanitized_prize_count
|
||||||
|
if sanitized_point_cost is not None:
|
||||||
|
payload["pointCost"] = sanitized_point_cost
|
||||||
|
if sanitized_start_time is not None:
|
||||||
|
payload["startTime"] = sanitized_start_time
|
||||||
|
if sanitized_end_time is not None:
|
||||||
|
payload["endTime"] = sanitized_end_time
|
||||||
|
if sanitized_options is not None:
|
||||||
|
payload["options"] = sanitized_options
|
||||||
|
if sanitized_multiple is not None:
|
||||||
|
payload["multiple"] = sanitized_multiple
|
||||||
|
if sanitized_proposed_name is not None:
|
||||||
|
payload["proposedName"] = sanitized_proposed_name
|
||||||
|
if sanitized_proposal_description is not None:
|
||||||
|
payload["proposalDescription"] = sanitized_proposal_description
|
||||||
|
if sanitized_captcha is not None:
|
||||||
|
payload["captcha"] = sanitized_captcha
|
||||||
|
|
||||||
|
try:
|
||||||
|
logger.info("Creating post with title='%s'", sanitized_title)
|
||||||
|
raw_post = await search_client.create_post(payload, token=_extract_authorization_token(ctx))
|
||||||
|
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
||||||
|
status_code = exc.response.status_code
|
||||||
|
if status_code == 400:
|
||||||
|
message = (
|
||||||
|
"Post creation failed due to invalid input or captcha verification errors."
|
||||||
|
)
|
||||||
|
elif status_code == 401:
|
||||||
|
message = (
|
||||||
|
"Authentication failed while creating the post. Please verify the "
|
||||||
|
"Authorization header or configured token."
|
||||||
|
)
|
||||||
|
elif status_code == 403:
|
||||||
|
message = "The provided Authorization token is not authorized to create posts."
|
||||||
|
else:
|
||||||
|
message = (
|
||||||
|
"OpenIsle backend returned HTTP "
|
||||||
|
f"{status_code} while creating the post."
|
||||||
|
)
|
||||||
|
if ctx is not None:
|
||||||
|
await ctx.error(message)
|
||||||
|
raise ValueError(message) from exc
|
||||||
|
except httpx.RequestError as exc: # pragma: no cover - network errors
|
||||||
|
message = f"Unable to reach OpenIsle backend post service: {exc}."
|
||||||
|
if ctx is not None:
|
||||||
|
await ctx.error(message)
|
||||||
|
raise ValueError(message) from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
post = PostDetail.model_validate(raw_post)
|
||||||
|
except ValidationError as exc:
|
||||||
|
message = "Received malformed data from the post creation endpoint."
|
||||||
|
if ctx is not None:
|
||||||
|
await ctx.error(message)
|
||||||
|
raise ValueError(message) from exc
|
||||||
|
|
||||||
|
if ctx is not None:
|
||||||
|
await ctx.info(f"Post '{post.title}' created successfully.")
|
||||||
|
logger.debug(
|
||||||
|
"Validated created post payload with id=%s and title='%s'",
|
||||||
|
post.id,
|
||||||
|
post.title,
|
||||||
|
)
|
||||||
|
|
||||||
|
return PostCreateResult(post=post)
|
||||||
|
|
||||||
|
|
||||||
@app.tool(
|
@app.tool(
|
||||||
name="recent_posts",
|
name="recent_posts",
|
||||||
description="Retrieve posts created in the last N minutes.",
|
description="Retrieve posts created in the last N minutes.",
|
||||||
@@ -469,11 +762,11 @@ async def get_post(
|
|||||||
) -> PostDetail:
|
) -> PostDetail:
|
||||||
"""Fetch post details from the backend and validate the response."""
|
"""Fetch post details from the backend and validate the response."""
|
||||||
|
|
||||||
resolved_token = session_token_manager.resolve(ctx)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info("Fetching post details for post_id=%s", post_id)
|
logger.info("Fetching post details for post_id=%s", post_id)
|
||||||
raw_post = await search_client.get_post(post_id, resolved_token)
|
raw_post = await search_client.get_post(
|
||||||
|
post_id, _extract_authorization_token(ctx)
|
||||||
|
)
|
||||||
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
||||||
status_code = exc.response.status_code
|
status_code = exc.response.status_code
|
||||||
if status_code == 404:
|
if status_code == 404:
|
||||||
@@ -481,7 +774,7 @@ async def get_post(
|
|||||||
elif status_code == 401:
|
elif status_code == 401:
|
||||||
message = "Authentication failed while retrieving the post."
|
message = "Authentication failed while retrieving the post."
|
||||||
elif status_code == 403:
|
elif status_code == 403:
|
||||||
message = "The provided token is not authorized to view this post."
|
message = "The provided Authorization token is not authorized to view this post."
|
||||||
else:
|
else:
|
||||||
message = (
|
message = (
|
||||||
"OpenIsle backend returned HTTP "
|
"OpenIsle backend returned HTTP "
|
||||||
@@ -542,8 +835,6 @@ async def list_unread_messages(
|
|||||||
) -> UnreadNotificationsResponse:
|
) -> UnreadNotificationsResponse:
|
||||||
"""Retrieve unread notifications and return structured data."""
|
"""Retrieve unread notifications and return structured data."""
|
||||||
|
|
||||||
resolved_token = session_token_manager.resolve(ctx)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info(
|
logger.info(
|
||||||
"Fetching unread notifications (page=%s, size=%s)",
|
"Fetching unread notifications (page=%s, size=%s)",
|
||||||
@@ -553,7 +844,7 @@ async def list_unread_messages(
|
|||||||
raw_notifications = await search_client.list_unread_notifications(
|
raw_notifications = await search_client.list_unread_notifications(
|
||||||
page=page,
|
page=page,
|
||||||
size=size,
|
size=size,
|
||||||
token=resolved_token,
|
token=_extract_authorization_token(ctx),
|
||||||
)
|
)
|
||||||
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
||||||
message = (
|
message = (
|
||||||
@@ -599,6 +890,68 @@ async def list_unread_messages(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.tool(
|
||||||
|
name="mark_notifications_read",
|
||||||
|
description="Mark specific notification messages as read to remove them from the unread list.",
|
||||||
|
structured_output=True,
|
||||||
|
)
|
||||||
|
async def mark_notifications_read(
|
||||||
|
ids: Annotated[
|
||||||
|
list[int],
|
||||||
|
PydanticField(
|
||||||
|
min_length=1,
|
||||||
|
description="Notification identifiers that should be marked as read.",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
ctx: Context | None = None,
|
||||||
|
) -> NotificationCleanupResult:
|
||||||
|
"""Mark the supplied notifications as read and report the processed identifiers."""
|
||||||
|
|
||||||
|
try:
|
||||||
|
logger.info(
|
||||||
|
"Marking %d notifications as read", # pragma: no branch - logging
|
||||||
|
len(ids),
|
||||||
|
)
|
||||||
|
await search_client.mark_notifications_read(
|
||||||
|
ids, token=_extract_authorization_token(ctx)
|
||||||
|
)
|
||||||
|
except httpx.HTTPStatusError as exc: # pragma: no cover - network errors
|
||||||
|
message = (
|
||||||
|
"OpenIsle backend returned HTTP "
|
||||||
|
f"{exc.response.status_code} while marking notifications as read."
|
||||||
|
)
|
||||||
|
if ctx is not None:
|
||||||
|
await ctx.error(message)
|
||||||
|
raise ValueError(message) from exc
|
||||||
|
except httpx.RequestError as exc: # pragma: no cover - network errors
|
||||||
|
message = f"Unable to reach OpenIsle backend notification service: {exc}."
|
||||||
|
if ctx is not None:
|
||||||
|
await ctx.error(message)
|
||||||
|
raise ValueError(message) from exc
|
||||||
|
|
||||||
|
processed_ids: list[int] = []
|
||||||
|
for value in ids:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
raise ValueError("Notification identifiers must be integers, not booleans.")
|
||||||
|
converted = int(value)
|
||||||
|
if converted <= 0:
|
||||||
|
raise ValueError("Notification identifiers must be positive integers.")
|
||||||
|
processed_ids.append(converted)
|
||||||
|
if ctx is not None:
|
||||||
|
await ctx.info(
|
||||||
|
f"Marked {len(processed_ids)} notifications as read.",
|
||||||
|
)
|
||||||
|
logger.debug(
|
||||||
|
"Successfully marked notifications as read: ids=%s",
|
||||||
|
processed_ids,
|
||||||
|
)
|
||||||
|
|
||||||
|
return NotificationCleanupResult(
|
||||||
|
processed_ids=processed_ids,
|
||||||
|
total_marked=len(processed_ids),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
"""Run the MCP server using the configured transport."""
|
"""Run the MCP server using the configured transport."""
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user