dsh-ustc-campus 0.2.14 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp-host.mjs CHANGED
@@ -36,8 +36,9 @@ import { libraryPlanLink } from './result-links.mjs';
36
36
 
37
37
  const SOURCE_URL = 'https://jw.ustc.edu.cn/for-std/course-table';
38
38
  const IPC_MAX_REQUEST_BYTES = 16 * 1024;
39
- const IPC_TIMEOUT_MS = 70_000;
40
- const SUMMARY_TIMEOUT_MS = 45_000;
39
+ const IPC_CONNECTION_TIMEOUT_MS = 5_000;
40
+ const READ_TIMEOUT_MS = 25_000;
41
+ const BATCH_TIMEOUT_MS = 45_000;
41
42
  const UPLOAD_TIMEOUT_MS = 60_000;
42
43
  const MAX_COUNT = 1_000_000;
43
44
  const RANGE_LIMIT_DAYS = 31;
@@ -582,7 +583,8 @@ const bbStatusMessages = {
582
583
  stopped_before_write: '已取消本次提交。',
583
584
  uncertain: '提交状态暂未核实,请查看 Blackboard 官方记录或用 bb_submission_status 复查。'
584
585
  };
585
- export function bbFeedback({ id, assignment, preparation: p, busy }) {
586
+ export function bbFeedback({ id, assignment, preparation: p, busy, state: status, message }) {
587
+ if (status === 'not_found') return { state: status, id, message };
586
588
  const state = busy ? 'processing' : p?.state ?? 'awaiting_materials';
587
589
  return { id, assignment, state, message: bbStatusMessages[state], preparation: p ? {
588
590
  state: p.state,
@@ -700,6 +702,46 @@ export function createHostHandlers(ctx) {
700
702
  };
701
703
  }
702
704
  if (ctx?.ustcTransit) handlers['campus-shuttle'] = ({fromCampus,toCampus,date,scheduleType}) => ctx.ustcTransit.read({fromCampus,toCampus,date,scheduleType});
705
+ if (ctx?.ustcCampus && typeof ctx.ustcCampus.queryFeed === 'function') {
706
+ handlers['feed-query'] = async (args = {}) => {
707
+ const queryArgs = { source: args.source, category: args.category, intent: args.intent,
708
+ keyword: args.keyword, sort: args.sort, interests: args.interests };
709
+ let feed = ctx.ustcCampus.queryFeed(queryArgs);
710
+ if (feed.sources.length > 0 && feed.sources.every((entry) => entry.fetchedAt == null)) {
711
+ await ctx.ustcCampus.refresh();
712
+ feed = ctx.ustcCampus.queryFeed(queryArgs);
713
+ }
714
+ const limit = Math.min(30, Math.max(1, Math.trunc(Number(args.limit) || 10)));
715
+ const offset = Math.min(feed.items.length, Math.max(0, Math.trunc(Number(args.offset) || 0)));
716
+ const items = feed.items.slice(offset, offset + limit);
717
+ return {
718
+ items,
719
+ total: feed.items.length,
720
+ offset,
721
+ nextOffset: offset + items.length < feed.items.length ? offset + items.length : null,
722
+ truncated: offset + items.length < feed.items.length,
723
+ sources: feed.sources
724
+ };
725
+ };
726
+ }
727
+ if (ctx?.ustcCampus && typeof ctx.ustcCampus.recordFeedFeedback === 'function') {
728
+ handlers['feed-feedback'] = (args = {}) => ctx.ustcCampus.recordFeedFeedback(args);
729
+ }
730
+ if (ctx?.ustcCampus && typeof ctx.ustcCampus.feedProfile === 'function') {
731
+ handlers['feed-profile'] = () => ctx.ustcCampus.feedProfile();
732
+ }
733
+ if (ctx?.ustcCampus && typeof ctx.ustcCampus.listCustomFeeds === 'function') {
734
+ handlers['feed-custom-list'] = () => ctx.ustcCampus.listCustomFeeds();
735
+ handlers['feed-custom-add'] = async (args = {}) => {
736
+ const added = ctx.ustcCampus.addCustomFeed(args);
737
+ await ctx.ustcCampus.refresh?.({ force: false }).catch(() => {});
738
+ return { ...added, subscriptions: ctx.ustcCampus.listCustomFeeds() };
739
+ };
740
+ handlers['feed-custom-remove'] = (args = {}) => ({
741
+ ...ctx.ustcCampus.removeCustomFeed(args),
742
+ subscriptions: ctx.ustcCampus.listCustomFeeds()
743
+ });
744
+ }
703
745
  return handlers;
704
746
  }
705
747
 
@@ -745,7 +787,7 @@ export async function createCampusPipe({ handlers } = {}) {
745
787
  sockets.delete(socket);
746
788
  socket.destroy();
747
789
  };
748
- const timer = setTimeout(drop, IPC_TIMEOUT_MS);
790
+ let timer = setTimeout(drop, IPC_CONNECTION_TIMEOUT_MS);
749
791
  timer.unref?.();
750
792
 
751
793
  const reply = (payload) => {
@@ -800,15 +842,23 @@ export async function createCampusPipe({ handlers } = {}) {
800
842
  return;
801
843
  }
802
844
  processing = true;
845
+ clearTimeout(timer);
803
846
 
804
847
  let value;
805
848
  try {
806
- const opTimeout = request.op === 'bb-submit' ? UPLOAD_TIMEOUT_MS : SUMMARY_TIMEOUT_MS;
849
+ const opTimeout = request.op === 'bb-submit' ? UPLOAD_TIMEOUT_MS
850
+ : request.op === 'bb-assignments' && args.checkStatus === true ? BATCH_TIMEOUT_MS : READ_TIMEOUT_MS;
851
+ timer = setTimeout(drop, opTimeout + 1_000);
852
+ timer.unref?.();
807
853
  value = await withTimeout(
808
854
  Promise.resolve().then(() => table.get(request.op)({ ...args })),
809
855
  opTimeout
810
856
  );
811
857
  } catch (error) {
858
+ if (error?.code === 'IPC_TIMEOUT' && request.op !== 'school-status') {
859
+ reply({ v: 1, ok: false, error: 'timeout' });
860
+ return;
861
+ }
812
862
  if (request.op === 'school-status') {
813
863
  reply({ v: 1, ok: true, result: normalizeSchoolStatus({ status: error?.code === 'IPC_TIMEOUT' ? 'unavailable' : 'error' }) });
814
864
  return;
@@ -956,6 +1006,7 @@ export async function apply(ctx) {
956
1006
  if(handlers['youth-enroll-prepare']) registration.env.CAMPUS_MCP_YOUTH_ACTIONS='1';
957
1007
  if(handlers['school-exams']) registration.env.CAMPUS_MCP_EXAMS='1';
958
1008
  if(handlers['campus-shuttle']) registration.env.CAMPUS_MCP_TRANSIT='1';
1009
+ if(handlers['feed-feedback']) registration.env.CAMPUS_MCP_FEED_FEEDBACK='1';
959
1010
  ctx.mcpManager.register('ustc_campus', registration);
960
1011
  } catch (error) {
961
1012
  await pipe.close();
package/src/mcp.mjs CHANGED
@@ -24,14 +24,15 @@ import { z } from 'zod';
24
24
 
25
25
  import { DAY, localMidnight } from './calendar.mjs';
26
26
  import { openCampus } from './state.mjs';
27
- import { FEED_SOURCES } from './feed.mjs';
27
+ import { FEED_CATEGORIES, FEED_SOURCES } from './feed.mjs';
28
+ import { TOPIC_IDS } from './recommender.mjs';
28
29
  import { sanitizeText } from './public-fetch.mjs';
29
30
  import { bbMaterialsLink, bbResultLink, calendarReceiptLink, HS_LIBRARY_RESULT_LINK, localResultLink, LIBRARY_RESULT_LINK, YOUTH_ENROLLED_LINK, YOUTH_PORTAL_LINK } from './result-links.mjs';
30
31
 
31
32
  const SERVER_NAME = 'dsh-ustc-campus-mcp';
32
33
  const SERVER_VERSION = '0.3.0';
33
34
  const SOURCE_URL = 'https://jw.ustc.edu.cn/for-std/course-table';
34
- const IPC_TIMEOUT_MS = 50_000;
35
+ const IPC_TIMEOUT_MS = 26_000;
35
36
  const IPC_MAX_BYTES = 3 * 1024 * 1024;
36
37
  const MAX_COUNT = 1_000_000;
37
38
  const RANGE_LIMIT_DAYS = 31;
@@ -213,7 +214,7 @@ function requestHost(op, args = {}) {
213
214
  }
214
215
 
215
216
  socket.setEncoding('utf8');
216
- const timeoutMs = op === 'bb-submit' ? 65_000 : IPC_TIMEOUT_MS;
217
+ const timeoutMs = op === 'bb-submit' ? 61_000 : op === 'bb-assignments' && args?.checkStatus === true ? 46_000 : IPC_TIMEOUT_MS;
217
218
  timer = setTimeout(() => finish({ ok: false, code: 'unavailable', message: '请求超时,请稍后重试。' }), timeoutMs);
218
219
  timer.unref?.();
219
220
 
@@ -242,13 +243,13 @@ function requestHost(op, args = {}) {
242
243
  finish({ ok: true, value: reply.result });
243
244
  return;
244
245
  }
245
- const code = ['invalid', 'failed', 'forbidden', 'bad-request', 'too-large'].includes(reply.error)
246
+ const code = ['invalid', 'failed', 'forbidden', 'bad-request', 'too-large', 'timeout'].includes(reply.error)
246
247
  ? reply.error
247
248
  : 'failed';
248
249
  finish({
249
250
  ok: false,
250
251
  code,
251
- message: code === 'invalid' ? safePublicMessage(reply.message) : null
252
+ message: code === 'invalid' ? safePublicMessage(reply.message) : code === 'timeout' ? '请求超时,请稍后重试。' : null
252
253
  });
253
254
  });
254
255
  socket.on('error', () => finish({ ok: false, code: 'unavailable' }));
@@ -284,6 +285,9 @@ function feedItem(item) {
284
285
  return {
285
286
  id: item.id,
286
287
  source: item.source,
288
+ ...(item.category ? { category: item.category } : {}),
289
+ ...(item.intent ? { intent: item.intent } : {}),
290
+ ...(item.requiresRegistration !== undefined ? { requiresRegistration: item.requiresRegistration === true } : {}),
287
291
  title: item.title,
288
292
  url: clickableUrl(item.url),
289
293
  date: item.date ?? null,
@@ -292,7 +296,17 @@ function feedItem(item) {
292
296
  start: item.start ?? null,
293
297
  end: item.end ?? null,
294
298
  reason: item.reason ?? '',
295
- past: item.past === true
299
+ past: item.past === true,
300
+ ...(item.organizer ? { organizer: item.organizer } : {}),
301
+ ...(item.enrollmentRatio ? { enrollmentRatio: item.enrollmentRatio } : {}),
302
+ ...(item.remainingSlots !== undefined && item.remainingSlots !== null ? { remainingSlots: item.remainingSlots } : {}),
303
+ ...(item.hours !== undefined && item.hours !== null ? { hours: item.hours } : {}),
304
+ ...(item.youthItemId ? { youthItemId: item.youthItemId } : {}),
305
+ ...(item.registered !== undefined && item.registered !== null ? { registered: item.registered } : {}),
306
+ ...(Number.isFinite(item.score) ? { score: item.score } : {}),
307
+ ...(Array.isArray(item.topics) && item.topics.length ? { topics: item.topics } : {}),
308
+ ...(Array.isArray(item.channels) && item.channels.length ? { channels: item.channels } : {}),
309
+ ...(Array.isArray(item.alsoIn) && item.alsoIn.length ? { alsoIn: item.alsoIn } : {})
296
310
  };
297
311
  }
298
312
 
@@ -873,7 +887,7 @@ function registerTools(server) {
873
887
  {
874
888
  title: '科大公开资讯与资料',
875
889
  description:
876
- '检索科大公开资讯、校园活动及也西书架课程资料索引。查课程资料传 query,查校内通知/活动传 keyword/source/sort;可用 scope 只返回其中一类。',
890
+ '检索科大公开资讯(25 个官方来源,已登录时自动融合青春科大报名中二课活动及自定义订阅)、校园活动及也西书架课程资料索引。查课程资料传 query,查校内通知/活动传 keyword/source/category/intent/sort(推荐排序结合本地偏好与课表方向);可用 scope 只返回其中一类。',
877
891
  inputSchema: {
878
892
  scope: z.enum(['all', 'feed', 'materials']).optional().describe('查询范围:all、feed(仅校园资讯)或 materials(仅课程资料)'),
879
893
  query: z
@@ -882,8 +896,10 @@ function registerTools(server) {
882
896
  .optional()
883
897
  .describe('课程名或课号,用于查询也西书架公开资料索引'),
884
898
  keyword: z.string().max(120).optional().describe('资讯标题/地点关键词'),
885
- source: z.enum(Object.keys(FEED_SOURCES)).optional().describe('按具体来源筛选;省略则全部'),
886
- sort: z.enum(['time', 'recommended']).optional().describe('按时间或推荐排序'),
899
+ source: z.string().max(80).optional().describe('按具体来源筛选(如 news/teach/lug/youth-enrolling/custom:*);省略则全部'),
900
+ category: z.enum(FEED_CATEGORIES).optional().describe('按分类筛选(campus/academic/research/student/activity/lecture/tech/service/exchange/college)'),
901
+ intent: z.enum(['all', 'activity', 'notice']).optional().describe('按内容意图筛选:all(全部)、activity(活动/讲座/二课)或 notice(通知/新闻)'),
902
+ sort: z.enum(['time', 'recommended']).optional().describe('按时间或个性化推荐排序'),
887
903
  interests: z
888
904
  .array(z.string().max(64))
889
905
  .max(12)
@@ -898,35 +914,47 @@ function registerTools(server) {
898
914
  idempotentHint: true
899
915
  }
900
916
  },
901
- async ({ scope, query, keyword, source, sort, interests, offset = 0, limit = 10 }) => {
917
+ async ({ scope, query, keyword, source, category, intent, sort, interests, offset = 0, limit = 10 }) => {
902
918
  try {
903
- const store = getCampus();
904
919
  const hasQuery = typeof query === 'string' && Boolean(query.trim());
905
- const effectiveScope = scope ?? (hasQuery && !keyword && !source && !sort && !interests?.length ? 'materials' : 'all');
920
+ const effectiveScope = scope ?? (hasQuery && !keyword && !source && !category && !intent && !sort && !interests?.length ? 'materials' : 'all');
906
921
  const result = {
907
922
  timezone: 'Asia/Shanghai',
908
923
  feed: null,
909
924
  materials: null
910
925
  };
911
926
  if (effectiveScope !== 'materials') {
912
- let feed = store.queryFeed({ source, keyword, sort, interests });
913
- if (feed.sources.every(entry => entry.fetchedAt == null)) {
914
- await store.refresh();
915
- feed = store.queryFeed({ source, keyword, sort, interests });
927
+ const hostReply = await requestHost('feed-query', { source, category, intent, keyword, sort, interests, offset, limit });
928
+ if (hostReply.ok && hostReply.value && Array.isArray(hostReply.value.items)) {
929
+ result.feed = {
930
+ items: hostReply.value.items.map(feedItem),
931
+ total: hostReply.value.total,
932
+ offset: hostReply.value.offset,
933
+ nextOffset: hostReply.value.nextOffset,
934
+ truncated: hostReply.value.truncated,
935
+ sources: hostReply.value.sources
936
+ };
937
+ } else {
938
+ const store = getCampus();
939
+ let feed = store.queryFeed({ source, category, intent, keyword, sort, interests });
940
+ if (feed.sources.every(entry => entry.fetchedAt == null)) {
941
+ await store.refresh();
942
+ feed = store.queryFeed({ source, category, intent, keyword, sort, interests });
943
+ }
944
+ const from = Math.min(feed.items.length, Math.max(0, Math.trunc(offset)));
945
+ const items = feed.items.slice(from, from + limit).map(feedItem);
946
+ result.feed = {
947
+ items,
948
+ total: feed.items.length,
949
+ offset: from,
950
+ nextOffset: from + items.length < feed.items.length ? from + items.length : null,
951
+ truncated: from + items.length < feed.items.length,
952
+ sources: feed.sources
953
+ };
916
954
  }
917
- const from = Math.min(feed.items.length, Math.max(0, Math.trunc(offset)));
918
- const items = feed.items.slice(from, from + limit).map(feedItem);
919
- result.feed = {
920
- items,
921
- total: feed.items.length,
922
- offset: from,
923
- nextOffset: from + items.length < feed.items.length ? from + items.length : null,
924
- truncated: from + items.length < feed.items.length,
925
- sources: feed.sources
926
- };
927
955
  }
928
956
  if (effectiveScope !== 'feed' && hasQuery) {
929
- result.materials = materialsResult(await store.lookup(query.trim()));
957
+ result.materials = materialsResult(await getCampus().lookup(query.trim()));
930
958
  }
931
959
  return textResult(result);
932
960
  } catch {
@@ -934,6 +962,87 @@ function registerTools(server) {
934
962
  }
935
963
  }
936
964
  );
965
+
966
+ if (process.env.CAMPUS_MCP_FEED_FEEDBACK === '1') {
967
+ server.registerTool(
968
+ 'campus_feed_feedback',
969
+ {
970
+ title: '校园资讯推荐偏好与反馈',
971
+ description:
972
+ '记录对校园资讯的反馈(like/dislike/open/屏蔽或恢复来源或话题/设置兴趣词/重置)或查看当前学到的推荐偏好画像(action: profile)。',
973
+ inputSchema: {
974
+ action: z.enum([
975
+ 'like', 'dislike', 'open', 'impression',
976
+ 'mute_source', 'unmute_source',
977
+ 'mute_topic', 'unmute_topic',
978
+ 'set_interests', 'reset', 'profile'
979
+ ]).describe('操作类型'),
980
+ itemId: z.string().max(200).optional().describe('资讯 ID(用于 like/dislike/open)'),
981
+ itemIds: z.array(z.string().max(200)).max(30).optional().describe('批量曝光 ID(用于 impression)'),
982
+ dwellMs: z.number().int().min(0).max(3_600_000).optional().describe('阅读停留毫秒数(可选)'),
983
+ source: z.string().max(80).optional().describe('来源 ID(用于 mute_source/unmute_source)'),
984
+ topic: z.enum(TOPIC_IDS).optional().describe('话题 ID(用于 mute_topic/unmute_topic)'),
985
+ interests: z.array(z.string().max(64)).max(24).optional().describe('固定兴趣关键词列表(用于 set_interests)')
986
+ },
987
+ annotations: {
988
+ readOnlyHint: false,
989
+ openWorldHint: false,
990
+ idempotentHint: false
991
+ }
992
+ },
993
+ async (args) => {
994
+ if (args.action === 'profile') {
995
+ const reply = await requestHost('feed-profile', {});
996
+ if (reply.ok && reply.value) return textResult(reply.value);
997
+ return textResult(getCampus().feedProfile());
998
+ }
999
+ const reply = await requestHost('feed-feedback', args);
1000
+ if (reply.ok && reply.value) return textResult(reply.value);
1001
+ if (reply.code === 'invalid' && reply.message) return errorResult(reply.message);
1002
+ return textResult(getCampus().recordFeedFeedback(args));
1003
+ }
1004
+ );
1005
+
1006
+ server.registerTool(
1007
+ 'campus_custom_feeds',
1008
+ {
1009
+ title: '自定义校园 RSS / JSON 订阅源',
1010
+ description:
1011
+ '查看、添加或移除用户自定义的公开 RSS / Atom / 静态 JSON 订阅源(仅限 https:// 公开网址,可用于接入外部社团或公众号聚合源)。',
1012
+ inputSchema: {
1013
+ action: z.enum(['list', 'add', 'remove']).describe('操作类型'),
1014
+ id: z.string().max(100).optional().describe('订阅源 ID(用于 remove)'),
1015
+ label: z.string().max(80).optional().describe('显示名称(用于 add)'),
1016
+ url: z.string().max(500).optional().describe('订阅地址(必须 https:// 开头,用于 add)'),
1017
+ format: z.enum(['auto', 'xml', 'json']).optional().describe('订阅格式,默认 auto'),
1018
+ defaultIntent: z.enum(['auto', 'activity', 'notice']).optional().describe('默认意图分类,默认 auto'),
1019
+ category: z.string().max(32).optional().describe('分类名称,默认 activity')
1020
+ },
1021
+ annotations: {
1022
+ readOnlyHint: false,
1023
+ openWorldHint: true,
1024
+ idempotentHint: false
1025
+ }
1026
+ },
1027
+ async (args) => {
1028
+ if (args.action === 'list') {
1029
+ const reply = await requestHost('feed-custom-list', {});
1030
+ if (reply.ok) return textResult({ subscriptions: reply.value });
1031
+ return textResult({ subscriptions: getCampus().listCustomFeeds() });
1032
+ }
1033
+ if (args.action === 'add') {
1034
+ const reply = await requestHost('feed-custom-add', args);
1035
+ if (reply.ok) return textResult(reply.value);
1036
+ if (reply.code === 'invalid' && reply.message) return errorResult(reply.message);
1037
+ return textResult(getCampus().addCustomFeed(args));
1038
+ }
1039
+ const reply = await requestHost('feed-custom-remove', { id: args.id });
1040
+ if (reply.ok) return textResult(reply.value);
1041
+ if (reply.code === 'invalid' && reply.message) return errorResult(reply.message);
1042
+ return textResult(getCampus().removeCustomFeed({ id: args.id }));
1043
+ }
1044
+ );
1045
+ }
937
1046
  }
938
1047
 
939
1048
  async function main() {