nwafu-mcp
nwafu-mcp · Набор MCP-инструментов для информации о кампусе Северо-Западного университета сельского и лесного хозяйства
Предоставляет агентам, развёрнутым на любой платформе ИИ-агентов, набор инструментов, совместимых с протоколом MCP, охватывающий три ключевых возможности:
Сводка популярного в кампусном канале: собирает недавние популярные посты официального QQ-канала Северо-Западного университета сельского и лесного хозяйства (pd.qq.com/g/inwafu1934), сортирует их по уровню вовлечённости и автоматически распределяет по категориям «Мероприятия / Конкурсы / Уведомления / Рекомендации / Советы / Помощь». Каждая важная запись содержит заголовок и ссылку на исходный пост, что гарантирует прослеживаемость.
Быстрый поиск по официальному сайту: использует полнотекстовый индекс официального сайта университета (www.nwafu.edu.cn) и новостного портала для быстрого поиска последних мероприятий, конкурсов, уведомлений и вакансий. Поддерживается передача таких ключевых слов, как «Факультет защиты растений», «Учебный отдел», для сужения области поиска.
Пользовательский поиск по нескольким сайтам: автоматически разбивает вопрос пользователя на поисковые слова, одновременно ищет по полнотекстовому индексу официального сайта и недавним постам кампусного канала, объединяет результаты и выводит их в удобочитаемом Markdown со ссылками на оригиналы.
Функциональные возможности
Стандартная реализация MCP: на базе официального Python SDK
mcp(FastMCP), транспорт stdio; можно напрямую подключать Claude Desktop, Cursor, Windsurf и любые платформы ИИ-агентов, поддерживающие MCP.Проверяемость информации: каждый итоговый пункт содержит заголовок источника и ссылку на оригинал; важная информация выносится в отдельные блоки «Ключевые замечания / Замечания об актуальности».
Умная категоризация: движок правил автоматически относит посты канала к категориям «Рекомендации / Советы / Мероприятия / Конкурсы / Уведомления / Помощь»; внутри групп сортировка по популярности (взвешенные лайки + комментарии).
Точный поиск по ключевым словам: поиск по официальному сайту поддерживает произвольные ключевые слова для сужения области (например, название факультета, отдела или события).
Устойчивость и отказоустойчивость: таймауты запросов, повторы, случайные задержки для ограничения частоты, предупреждения об истечении Cookie; сбой одного инструмента не влияет на остальные.
Конфиденциальность и соответствие: собирается только публично доступный контент, без обхода проверок входа или прав доступа; Cookie передаются через переменные окружения и не сохраняются в репозитории.
Related MCP server: zju-mcp
Список инструментов
Инструмент | Назначение | Ключевые параметры |
| Интеллектуальная сводка недавних популярных постов QQ-канала кампуса (рейтинг популярности + категории + ключевая информация) |
|
| Быстрый поиск и сводка последних уведомлений/мероприятий/конкурсов/вакансий с официального сайта |
|
| Полнотекстовый поиск по официальному сайту (произвольные ключевые слова) |
|
| Пользовательский поиск по «официальный сайт + кампусный канал» |
|
Все инструменты возвращают текст в формате Markdown со следующей структурой: источник данных, время сбора, условие запроса, список результатов (заголовок / дата / источник / аннотация / ссылка) и ключевые замечания.
Принцип работы
QQ-канал кампуса
Веб-версия канала Tencent полностью рендерится на стороне клиента; публичные данные поступают через шлюз protobuf-over-JSON:
POST https://pd.qq.com/qunng/guild/gotrpc/noauth/trpc.qchannel.commreader.ComReader/<Method>
x-oidb: {"uint32_service_type": 11 时间线 | 5 评论}Анонимно можно читать публичный контент, но шлюз требует браузерный сессионный Cookie (p_uin + uuid + EO-Bot-Js-Token). Инструмент:
по умолчанию загружает N последних постов (по времени публикации) из подраздела «Постовая площадь» (
670126629);оценивает популярность как
число лайков + 2 × число комментариеви выбирает самые горячие посты в окне;автоматически классифицирует посты с помощью правил; важная информация (уведомления/объявления/регистрация/дедлайны/экзамены и т. п.) выделяется отдельно;
опционально собирает популярные комментарии для постов из рейтинга (
GetFeedComments).
Примечание: интерфейс «сортировка по популярности» у
GetGuildFeedsпо факту возвращает пустые данные, поэтому рейтинг строится по схеме «недавние посты × вовлечённость», что больше соответствует смыслу «недавнее и популярное».
Официальный сайт университета
Главный сайт и новостной портал используют полнотекстовый поиск 通元 CMS:
GET https://www.nwsuaf.edu.cn/cms/web/search/index.jsp
?query=<关键词>&siteID=<站点ID>&searchScope=0&channelID=&matchType=0
&sortField=publishDate&order=1&date=<3|6|12>&page=<页码>siteID=32e6d9be...— индекс главного сайта (охватывает все факультеты и отделы университета);для каждой категории формируются поисковые запросы (уведомления/объявления, мероприятия/лекции/форумы, конкурсы/соревнования, вакансии и т. д.); после объединения с ключевыми словами пользователя выполняется постраничная загрузка с разбором заголовков, дат, источников, аннотаций и ссылок на оригиналы;
временной диапазон по умолчанию — последние 90 дней (соответствует фильтрам индекса на 3/6/12 месяцев).
Быстрый старт (локальный запуск)
cd nwafu-mcp
uv sync --extra dev1. Настройка Cookie канала (необязательно, нужно только для инструментов канала)
uv run nwafu-export-cookies --out cookies.jsonСкрипт откроет страницу канала в локальном Edge/Chrome, создаст сеанс и экспортирует Cookie. Затем значение cookie_header из cookies.json нужно записать в переменную окружения:
$env:PDQQ_COOKIES = "p_uin=xxx; uuid=xxx; EO-Bot-Js-Token=xxx"
# 或
$env:NWAFU_COOKIE_FILE = "F:\path\to\cookies.json"Cookie со временем истекают (анти-бот токен привязан к экземпляру браузера); при облачном развёртывании рекомендуется периодически их обновлять.
2. Прямое тестирование функций инструмента (без MCP-клиента)
uv run python -c "
import os
os.environ['NWAFU_COOKIE_FILE'] = 'cookies.json'
from nwafu_mcp.server import official_site_recent
print(official_site_recent(category='通知', keyword='植保学院'))
"3. Запуск в качестве MCP-сервера
uv run nwafu-mcpПодключение к MCP-клиентам
Claude Desktop (claude_desktop_config.json)
{
"mcpServers": {
"nwafu-campus": {
"command": "uvx",
"args": [
"--from",
"git+https://github.com/unielevotor/nwafu-AgentPlatformMCP",
"nwafu-mcp"
],
"env": {
"PDQQ_COOKIES": "p_uin=xxx; uuid=xxx; EO-Bot-Js-Token=xxx"
}
}
}
}Cursor / Windsurf / универсальные платформы (в формате JSON)
{
"mcpServers": {
"nwafu-campus": {
"command": "uvx",
"args": ["--from", "git+https://github.com/unielevotor/nwafu-AgentPlatformMCP", "nwafu-mcp"],
"env": {
"PDQQ_COOKIES": "p_uin=xxx; uuid=xxx; EO-Bot-Js-Token=xxx",
"PDQQ_GUILD_ID": "inwafu1934",
"PDQQ_CHANNEL_ID": "670126629"
}
}
}
}Также можно установить пакет через pip install git+https://github.com/unielevotor/nwafu-AgentPlatformMCP и запускать его напрямую командой nwafu-mcp.
Шаги развёртывания на GitHub
Отправьте в GitHub-репозиторий (
unielevotor/nwafu-AgentPlatformMCP):
git remote add origin https://github.com/unielevotor/nwafu-AgentPlatformMCP.git
git push -u origin mainУбедитесь, что репозиторий имеет статус Public (для частного репозитория целевая платформа агентов должна иметь доступ к учётным данным GitHub).
В конфигурации MCP на платформе агентов укажите приведённую выше команду запуска
uvx --from git+...и передайте переменные окружения, напримерPDQQ_COOKIES.
Переменные окружения
Переменная | Требуется | Описание |
| нужно для инструментов канала | браузерный сессионный Cookie QQ-канала |
| нужно для инструментов канала | путь к JSON, экспортированному |
| нет | ID гильдии, по умолчанию |
| нет | ID подраздела, по умолчанию |
| нет | интервал между запросами к каналу (сек), по умолчанию 0.3–0.8 |
| нет | таймаут одного запроса (сек), по умолчанию 30 |
См. .env.example.
Пример вывода (фрагмент)
# 🎓 西农校园频道 · 近期热门总结
> 数据来源:西北农林科技大学官方 QQ 频道 | 时间窗口:近 72 小时 | 帖子数:48
## 🔥 热度榜
1. **中元节鬼是真的多啊…**(👍7 · 💬1 · 08-27)
来源:[中元节鬼是真的多啊](https://pd.qq.com/g/inwafu1934/post/...)
## 🏆 竞赛(2)
- **关于举办2026年创新创业大赛的通知**(👍5 · 💬2 · 08-26)
来源:[…](https://pd.qq.com/g/inwafu1934/post/...)
## ⚠️ 重点信息(建议优先查看)
- [关于选课时间安排的通知](https://pd.qq.com/g/inwafu1934/post/...)# 📢 西北农林科技大学官网 · 近期信息查询
> 查询条件:分类=通知 | 关键词=植保学院 | 时间范围:近 90 天 | 结果数:12
1. **关于举办2026年植保论坛系列学术报告会(十七)的通知**(2026-08-26 · 植物保护学院)
[查看原文](https://ppc.nwafu.edu.cn/xzbg/...)Соответствие требованиям и рекомендации
Собирайте только публично видимый контент, не обходите проверки входа, оплаты или прав доступа.
Уже встроены случайный User-Agent, случайные задержки и повторы при сбоях; при развёртывании не уменьшайте задержки для высокочастотного сбора данных и соблюдайте условия обслуживания целевых платформ и применимые законы, включая Закон о защите персональной информации.
Для важной информации (дедлайны регистрации, расписания экзаменов и т. п.) ориентируйтесь на официальные источники; вывод инструмента предназначен только для быстрого просмотра.
Cookie канала содержат идентификаторы сессии; не загружайте их в публичный репозиторий, обязательно передавайте через переменные окружения.
Часто задаваемые вопросы
Симптом | Решение |
Инструмент канала сообщает «Cookie не настроены» | выполните локально |
Инструмент канала возвращает | Cookie истекли или отсутствует анти-бот токен; экспортируйте их заново |
Пустые результаты поиска по официальному сайту | увеличьте |
Нет Edge/Chrome в облаке | установите |
Структура каталога
src/nwafu_mcp/
server.py MCP 服务器与四个工具定义
qq_channel.py QQ 频道数据层(时间线/热评)
official_site.py 官网全文检索数据层
classify.py 帖子分类与热度评分
format.py Markdown 报告排版
config.py 环境变量与默认配置
export_cookies.py 本地导出频道 Cookie 的 CLI
tests/ 单元测试
scripts/mcp_smoke.py 端到端 MCP 冒烟测试(连接 stdio server 并调用全部工具)Available Tools
4 toolscampus_channel_summaryA
抓取西北农林科技大学官方 QQ 频道(https://pd.qq.com/g/inwafu1934)近期帖子,按互动量(点赞+评论)排名出热度榜,并自动归类为活动/竞赛/通知/推荐/贴士/求助/其他,输出 Markdown 总结;每条重要信息都附来源帖子标题与链接。
| Name | Required | Description | Default |
|---|---|---|---|
| top_n | No | ||
| max_posts | No | ||
| window_hours | No | ||
| comment_top_n | No | ||
| include_comments | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It transparently discloses the source URL, ranking formula, automatic categorization, Markdown output, and source attribution. It does not mention failure modes or rate limits, but the core behavior is clearly described.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single dense sentence that front-loads the fetch action, source, ranking, categorization, and output format. Every clause is relevant, though a more structured breakdown of parameters would improve readability.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The output schema covers return structure, and the description explains source, ranking, categories, and citations. However, with five parameters and no explicit guidance on when to invoke this tool versus siblings, the description is not fully complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, and the description does not explain any of the five parameters. Terms like 'top_n' and 'window_hours' are only indirectly related to '热度榜' and '近期帖子', while max_posts, comment_top_n, and include_comments receive no clarification.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific action: fetch recent posts from a named QQ channel, rank them by likes+comments, categorize them into seven types, and output a Markdown summary with source links. It clearly identifies the resource and unique behavior, distinguishing it from a plain recent-posts or search tool.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies this tool is for obtaining a ranked, categorized summary of QQ-channel posts rather than raw retrieval or search. It does not explicitly state when to use this tool versus the sibling tools or describe exclusions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
campus_question_searchA
对“学校官网 + 校园 QQ 频道”两个信息源做自定义问题检索:先自动从问题中提取关键词,在官网全文索引与频道近期帖子中检索,合并输出 Markdown 结果,每条均附来源标题与链接。
| Name | Required | Description | Default |
|---|---|---|---|
| days | No | ||
| keywords | No | ||
| question | Yes | ||
| max_results | No | ||
| include_channel | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations exist, so the description carries the full transparency burden. It does disclose the full search pipeline: auto keyword extraction, dual-source search, and merged Markdown output with source titles and links. It does not, however, explain the days recency window, the include_channel toggle, or behavior with zero results.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
One dense sentence that front-loads the action and sources, then follows with the pipeline steps and output format. Every clause adds information and there is no filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description is sufficient for a default invocation using only the required question, and an output schema covers the return structure. However, with 0% schema coverage, no annotations, and three sibling tools, the missing parameter semantics and lack of alternative routing keep it from being fully complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
With schema description coverage at 0%, the description needed to compensate, but it only clarifies the question parameter through the auto-extraction behavior. The parameters days, keywords, max_results, and include_channel are left unexplained, so an agent cannot reliably customize the call beyond the required question.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description names the action (检索), the exact sources (学校官网 + 校园 QQ 频道), and the concrete pipeline: keyword extraction, searching both sources, and merging Markdown results with titles and links. This clearly distinguishes it from siblings like official_site_search, which are single-source or summary tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies use for natural-language questions covering both campus sources, but it never states explicit when-not conditions or names sibling tools as alternatives. The '自定义问题' phrasing provides context without exclusions, so the agent must infer the boundary with official_site_search.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
official_site_recentA
查询西北农林科技大学官网(https://www.nwafu.edu.cn/)最近的活动、竞赛、通知、招聘等官方信息并输出 Markdown 总结。支持传入关键词(如学院名)缩小检索范围,例如 keyword='植保学院' 只返回植保学院相关通知。
| Name | Required | Description | Default |
|---|---|---|---|
| days | No | ||
| keyword | No | ||
| category | No | 全部 | |
| max_results | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the behavioral burden; it discloses that this is a read-only query of the official site and that output is a Markdown summary, plus that keyword narrows the results. It does not mention rate limits, freshness boundaries, or failure modes, but for a simple read tool the key behavioral traits are disclosed.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two sentences with no filler: the first establishes tool, source URL, content scope, and output format; the second gives the key parameter example. The most load-bearing information is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple and the output schema is present, which covers return structure. However, the description does not explain three of the four parameters, nor does it position the tool against official_site_search, so an agent still has meaningful uncertainty about how to set days/category/max_results and when to choose this over its siblings.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate, but only keyword is given real meaning (with the '植保学院' example). days, category, and max_results are left to inference from their names and defaults, which is insufficient with no schema descriptions.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific verb–resource pair: query the NWAFU official website for recent activities, competitions, notices, and recruitment information, then output a Markdown summary. It does not explicitly distinguish itself from official_site_search or the other siblings, so it loses a point for lacking sibling differentiation.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The intended use—retrieving recent official-site news—is implied and there is a concrete keyword example, but no alternative tools are named and no when-not-to-use conditions are given. Sibling tools like official_site_search could overlap, yet the description does not route the agent between them.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
official_site_searchB
对西北农林科技大学官网(含新闻网)执行关键词全文检索,返回 Markdown 排版的结果列表(标题/日期/来源/摘要/原文链接)。
| Name | Required | Description | Default |
|---|---|---|---|
| days | No | ||
| query | Yes | ||
| keyword | No | ||
| max_results | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The description clearly states that this is a full-text keyword search and details the returned fields, which is useful given that no annotations are provided. However, it does not disclose behavioral specifics such as the default 90-day time window, the maximum number of results, or how the optional keyword parameter interacts with query.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single front-loaded sentence with no filler. It efficiently conveys the operation, scope, and output contract in one pass.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
While the output contract is covered, the description is incomplete for a tool with four parameters and no annotations. An agent can make a minimal call using the required query, but it cannot confidently determine when to prefer this tool over siblings or how to correctly use keyword, days, and max_results without additional inference.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema has 0% description coverage, and the description does not explain the relationship between query and keyword or the meaning of days and max_results. The phrase '关键词全文检索' partially clarifies that query is the search term, but the remaining parameters remain semantically underspecified.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('执行关键词全文检索'), names the exact resource ('西北农林科技大学官网(含新闻网)'), and states the output format (Markdown list with title/date/source/abstract/link). This makes the tool clearly distinguishable from siblings like official_site_recent or campus_question_search.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives no guidance on when to use this tool versus its siblings. It does not mention that official_site_recent is for recency-based browsing or that campus_question_search targets Q&A content, so the selection criteria are entirely implied rather than explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
4 tool updates
v0.1.0- First observed
campus_channel_summary - First observed
campus_question_search - First observed
official_site_recent - First observed
official_site_search
TDQS
Scored across 4 tools
Each tool targets a fairly distinct retrieval need: QQ channel hot summaries, official-site recent info, official-site full-text search, and cross-source question search. The only mild overlap is between official_site_recent and official_site_search, but their descriptions make the difference clear enough.
Tool names are consistently lowercase snake_case and follow recognizable source prefixes like campus_* and official_site_*. However, suffixes mix result-oriented terms (summary, recent) with action terms (search), so they do not follow a strict verb_noun pattern throughout.
Four tools is well-scoped for a campus information retrieval server. Each tool covers a distinct retrieval workflow without redundancy, and the set is neither too thin nor overloaded for its stated purpose.
The set covers recent official announcements, full-text official-site search, QQ channel hot content, and a combined question-based search across both sources. A dedicated channel-only keyword search is missing, but campus_question_search partially fills that gap, so the surface is reasonably complete.
Maintenance
Related MCP Connectors
MCP server aggregating hot-search boards from 8 Chinese platforms (Weibo, Zhihu, Bilibili, Douyin).
Search MCP servers, agent skills and coding-agent plugins: trending tools and best-of lists.
Search and inspect source-pinned agent skills, plugins and tools through a free public MCP.
Read-only MCP tools for AI agent discovery, structured resources, and NIULAI information.
Related MCP Servers
- FlicenseNot gradedqualityBmaintenanceMCP server that aggregates department notices and provides structured answers to queries about courses, schedules, and academic dates via tool calling.-
- FlicenseAqualityDmaintenanceEnables interaction with Zhejiang University's learning platform (学在浙大 / 智云课堂) via MCP tools, allowing natural language commands to check todos, view schedules, fetch lecture transcripts, and submit homework.78-
- AlicenseAqualityBmaintenanceProvides Google search, URL extraction, and academic paper inline extraction without API keys, enabling search and content retrieval from a single MCP server.5104 npmMIT
- FlicenseNot gradedqualityBmaintenanceEnables searching the Xiangtan University Computer Science College official website, retrieving article content and attachments, and listing common sections through a Cloudflare-hosted MCP server.-