@lorrylurui/code-intelligence-mcp 1.0.6 → 1.0.8
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/README.md +324 -5
- package/dist/config/env.js +23 -6
- package/dist/indexer/indexProject.js +1 -0
- package/dist/prompts/reusableCodeAdvisorPrompt.js +6 -6
- package/dist/server/createServer.js +0 -5
- package/dist/services/embeddingClient.js +8 -9
- package/dist/services/vectorMath.js +1 -1
- package/dist/tools/recommendComponent.js +17 -1
- package/dist/tools/searchByStructure.js +15 -15
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -156,11 +156,11 @@ npm run index
|
|
|
156
156
|
|
|
157
157
|
可选环境变量(见 `.env.example`):
|
|
158
158
|
|
|
159
|
-
| 变量 | 含义
|
|
160
|
-
| -------------- |
|
|
161
|
-
| `INDEX_ROOT` | 工程根目录,默认当前工作目录
|
|
162
|
-
| `INDEX_GLOB` | 空格分隔 glob,默认 `src/**/*.{ts,tsx}`
|
|
163
|
-
| `INDEX_IGNORE` | 额外忽略的 glob 片段(空格分隔)
|
|
159
|
+
| 变量 | 含义 |
|
|
160
|
+
| -------------- | --------------------------------------- |
|
|
161
|
+
| `INDEX_ROOT` | 工程根目录,默认当前工作目录 |
|
|
162
|
+
| `INDEX_GLOB` | 空格分隔 glob,默认 `src/**/*.{ts,tsx}` |
|
|
163
|
+
| `INDEX_IGNORE` | 额外忽略的 glob 片段(空格分隔) |
|
|
164
164
|
|
|
165
165
|
**分类规则(首版启发式)**:`interface` / `type` → `type`;`.tsx` 且函数体含 JSX → `component`;路径或导出名含 `selector` → `selector`;其余导出函数 → `util`;`class` → `util`(可后续细化)。
|
|
166
166
|
|
|
@@ -293,3 +293,322 @@ Run with:
|
|
|
293
293
|
- recommend-component
|
|
294
294
|
- reusable-code-advisor
|
|
295
295
|
````
|
|
296
|
+
|
|
297
|
+
---
|
|
298
|
+
|
|
299
|
+
Code Intelligence 功能完整总结
|
|
300
|
+
|
|
301
|
+
项目定位
|
|
302
|
+
|
|
303
|
+
智能代码推荐系统:解决日常团队开发中可复用逻辑(组件、样式、selectors、类型声明等)重复开发问题,提高代码复
|
|
304
|
+
用率。
|
|
305
|
+
|
|
306
|
+
一、系统架构
|
|
307
|
+
|
|
308
|
+
┌─────────────────────────────────────────────────────────────────┐
|
|
309
|
+
│ MCP Client (Claude/Cursor) │
|
|
310
|
+
│ 用户提问 → 模型分析 → 返回结果 │
|
|
311
|
+
└─────────────────────────────────────────────────────────────────┘
|
|
312
|
+
│
|
|
313
|
+
▼
|
|
314
|
+
┌─────────────────────────────────────────────────────────────────┐
|
|
315
|
+
│ MCP Server (Node.js) │
|
|
316
|
+
├─────────────────────────────────────────────────────────────────┤
|
|
317
|
+
│ Tools (4个) │ Prompts (1个) │ DB Layer │
|
|
318
|
+
│ - search_symbols │ - reusable-code- │ - MySQL │
|
|
319
|
+
│ - get_symbol_detail │ advisor │ - embedding │
|
|
320
|
+
│ - search_by_struct │ │ │
|
|
321
|
+
│ - reindex │ │ │
|
|
322
|
+
└─────────────────────────────────────────────────────────────────┘
|
|
323
|
+
│
|
|
324
|
+
▼
|
|
325
|
+
┌─────────────────────────────────────────────────────────────────┐
|
|
326
|
+
│ Indexer (源码解析) │
|
|
327
|
+
│ ts-ormorph (TS/TSX) + Babel (JS/JSX) │
|
|
328
|
+
└─────────────────────────────────────────────────────────────────┘
|
|
329
|
+
│
|
|
330
|
+
▼
|
|
331
|
+
┌─────────────────────────────────────────────────────────────────┐
|
|
332
|
+
│ Embedding Service (Python FastAPI) │
|
|
333
|
+
│ 向量化 + 语义检索 │
|
|
334
|
+
└─────────────────────────────────────────────────────────────────┘
|
|
335
|
+
|
|
336
|
+
二、MCP Server Tools(4个)
|
|
337
|
+
|
|
338
|
+
1. search_symbols 通用检索
|
|
339
|
+
|
|
340
|
+
功能:根据 query 和 type 进行语义搜索,对结果进行权重排序
|
|
341
|
+
|
|
342
|
+
入参:
|
|
343
|
+
{
|
|
344
|
+
query: string, // 搜索关键词
|
|
345
|
+
type?: 'component' | 'util' | 'selector' | 'type', // 可选
|
|
346
|
+
semantic?: boolean, // 是否启用语义搜索(需 embedding 服务)
|
|
347
|
+
ranked?: boolean, // 是否排序,默认 true
|
|
348
|
+
limit?: number, // 返回数量,默认 20
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
权重排序算法(RANK_WEIGHTS):
|
|
352
|
+
const RANK_WEIGHTS = {
|
|
353
|
+
textMatch: 0.4, // 文本匹配度
|
|
354
|
+
usage: 0.3, // 使用频率
|
|
355
|
+
recency: 0.15, // 最近更新时间
|
|
356
|
+
commonPath: 0.15, // common 路径偏好
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
score = textScore _ 0.4 + usage _ 0.3 + recency _ 0.15 + commonPath _ 0.15
|
|
360
|
+
|
|
361
|
+
难点:
|
|
362
|
+
|
|
363
|
+
- 多维度权重调优
|
|
364
|
+
- 文本匹配算法(模糊匹配 + 语义匹配)
|
|
365
|
+
- 冷启动时无 embedding 向量fallback 到文本匹配
|
|
366
|
+
|
|
367
|
+
---
|
|
368
|
+
|
|
369
|
+
2. get_symbol_detail 获取详情
|
|
370
|
+
|
|
371
|
+
功能:根据 name 获取代码块的完整信息
|
|
372
|
+
|
|
373
|
+
入参:
|
|
374
|
+
{
|
|
375
|
+
name: string, // 代码块名称
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
返回:完整代码块信息包括 meta(props/params/properties/hooks)
|
|
379
|
+
|
|
380
|
+
难点:需要从 MySQL 解析 JSON 格式的 meta 字段
|
|
381
|
+
|
|
382
|
+
---
|
|
383
|
+
|
|
384
|
+
3. search_by_structure 结构化搜索
|
|
385
|
+
|
|
386
|
+
功能:通过结构化字段搜索代码块,适用于 API 形态查询
|
|
387
|
+
|
|
388
|
+
入参:
|
|
389
|
+
{
|
|
390
|
+
fields: string[], // 结构字段,如 ['onChange', 'value']
|
|
391
|
+
type?: 'component' | 'util' | 'selector' | 'type',
|
|
392
|
+
category?: string, // 业务分类
|
|
393
|
+
limit?: number,
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
匹配逻辑:匹配 symbol.meta 中的:
|
|
397
|
+
|
|
398
|
+
- props - 组件 props
|
|
399
|
+
- params - 函数参数
|
|
400
|
+
- properties - 对象属性
|
|
401
|
+
- hooks - React hooks
|
|
402
|
+
|
|
403
|
+
难点:
|
|
404
|
+
|
|
405
|
+
- 不支持 LLM 向量检索,需全表扫描 + 内存过滤
|
|
406
|
+
- 需要在 MySQL 中存储 JSON 格式的 meta
|
|
407
|
+
|
|
408
|
+
---
|
|
409
|
+
|
|
410
|
+
4. reindex 重建索引
|
|
411
|
+
|
|
412
|
+
功能:扫描源码目录,解析并写入 MySQL + 向量
|
|
413
|
+
|
|
414
|
+
入参:
|
|
415
|
+
{
|
|
416
|
+
projectRoot?: string, // 项目根目录,默认 cwd
|
|
417
|
+
globPatterns?: string[], // glob 模式,默认 ['**/*.{ts,tsx}']
|
|
418
|
+
ignore?: string[], // 忽略目录
|
|
419
|
+
dryRun?: boolean, // 仅预览不写入
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
处理流程:
|
|
423
|
+
|
|
424
|
+
1. 收集文件(fast-glob)
|
|
425
|
+
↓
|
|
426
|
+
2. 分离 TS/TSX 和 JS/JSX
|
|
427
|
+
↓
|
|
428
|
+
3. TS/TSX:ts-ormorph 解析
|
|
429
|
+
JS/JSX:Babel 解析
|
|
430
|
+
↓
|
|
431
|
+
4. 提取 meta(props/params/properties/hooks)
|
|
432
|
+
↓
|
|
433
|
+
5. 写入 MySQL
|
|
434
|
+
↓
|
|
435
|
+
6. 写入 embedding 向量(可选)
|
|
436
|
+
|
|
437
|
+
难点:
|
|
438
|
+
|
|
439
|
+
- ts-ormorph:需要 tsconfig.json,不存在时用默认配置
|
|
440
|
+
- Babel 解析:支持 JSX、TypeScript、装饰器等语法
|
|
441
|
+
- meta 提取:
|
|
442
|
+
- extractFunctionMeta:提取函数参数、返回值类型
|
|
443
|
+
- extractHooksFromBody:提取 useState/useEffect 等
|
|
444
|
+
- extractInterfaceOrTypeMeta:提取接口属性
|
|
445
|
+
- 路径推断 category:从路径智能推断业务分类(如 src/components/form/\* → form)
|
|
446
|
+
- 忽略规则:node_modules、dist、build、.git、coverage、.next、.nuxt、.venv 等
|
|
447
|
+
|
|
448
|
+
---
|
|
449
|
+
|
|
450
|
+
三、MCP Prompt(1个)
|
|
451
|
+
|
|
452
|
+
reusable-code-advisor 多工具编排
|
|
453
|
+
|
|
454
|
+
功能:在实现需求时检索并推荐最合适的可复用代码
|
|
455
|
+
|
|
456
|
+
工作流:
|
|
457
|
+
|
|
458
|
+
1. 调用 search_symbols 检索候选,type 根据用户需求传(component/util/selector/type)
|
|
459
|
+
2. 如果用户指定了结构过滤条件(props/params/properties/hooks),额外调用 search_by_structure 做结构匹配
|
|
460
|
+
3. 先 search_symbols(limit=20) 拉候选,再对 Top 3 调用 get_symbol_detail 做深度判断
|
|
461
|
+
4. 若仅凭签名/摘要无法判断,调用 get_symbol_detail 获取详情
|
|
462
|
+
5. 从以下维度对比候选:
|
|
463
|
+
- 功能匹配度
|
|
464
|
+
- API 是否简单、入参是否合适
|
|
465
|
+
- 依赖与副作用风险
|
|
466
|
+
- 复用安全性(稳定性、耦合度、是否便于扩展)
|
|
467
|
+
6. 给出唯一首选推荐,并说明理由
|
|
468
|
+
|
|
469
|
+
返回格式:
|
|
470
|
+
|
|
471
|
+
- 首选:<代码块名>
|
|
472
|
+
- 理由:1~3 条要点
|
|
473
|
+
- 其他候选:简要列出及取舍
|
|
474
|
+
- 用法提示:结合用户场景的最小集成说明
|
|
475
|
+
|
|
476
|
+
难点:多工具组合调用逻辑、意图判断
|
|
477
|
+
|
|
478
|
+
---
|
|
479
|
+
|
|
480
|
+
四、GitHub Actions(CI/CD 检测评论)
|
|
481
|
+
|
|
482
|
+
1. duplicate-check 工作流
|
|
483
|
+
|
|
484
|
+
功能:检测代码重复实现,在 PR/Commit 上自动评论
|
|
485
|
+
|
|
486
|
+
触发条件:
|
|
487
|
+
|
|
488
|
+
- push 到 main 分支
|
|
489
|
+
- PR opened/synchronize/reopened
|
|
490
|
+
|
|
491
|
+
工作流:
|
|
492
|
+
|
|
493
|
+
1. 计算变更文件列表(git diff)
|
|
494
|
+
2. 运行 detect-duplicates 脚本
|
|
495
|
+
3. 生成报告(JSON + Markdown)
|
|
496
|
+
4. 上传 artifact
|
|
497
|
+
5. 评论到 PR 或 Commit
|
|
498
|
+
|
|
499
|
+
评论逻辑:
|
|
500
|
+
|
|
501
|
+
- PR 事件:直接评论到 PR
|
|
502
|
+
- Push 事件:查找关联 PR 并评论,无关联则评论到 Commit
|
|
503
|
+
|
|
504
|
+
发布为 GitHub Action:
|
|
505
|
+
|
|
506
|
+
- 仓库:lorrylurui/code-intelligence-check
|
|
507
|
+
- 第三方使用:
|
|
508
|
+
- uses: lorrylurui/code-intelligence-check@v1
|
|
509
|
+
with:
|
|
510
|
+
is-mock-mode: 'true' # 无需 MySQL
|
|
511
|
+
|
|
512
|
+
---
|
|
513
|
+
|
|
514
|
+
五、Embedding Service(Python FastAPI)
|
|
515
|
+
|
|
516
|
+
功能
|
|
517
|
+
|
|
518
|
+
- 文本向量化:将查询和代码块转为向量(384维 MiniLM)
|
|
519
|
+
- 语义检索:余弦相似度计算
|
|
520
|
+
|
|
521
|
+
API
|
|
522
|
+
|
|
523
|
+
POST /embed
|
|
524
|
+
Body: { "texts": ["查询文本"] }
|
|
525
|
+
Response: { "embeddings": [[0.1, 0.2, ...]] }
|
|
526
|
+
|
|
527
|
+
GET /health
|
|
528
|
+
|
|
529
|
+
---
|
|
530
|
+
|
|
531
|
+
六、数据库设计
|
|
532
|
+
|
|
533
|
+
symbols 表
|
|
534
|
+
|
|
535
|
+
CREATE TABLE symbols (
|
|
536
|
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
537
|
+
name VARCHAR(255) NOT NULL COMMENT '代码块名称',
|
|
538
|
+
type ENUM('component', 'util', 'selector', 'type') NOT NULL COMMENT '类型',
|
|
539
|
+
category VARCHAR(100) COMMENT '业务分类',
|
|
540
|
+
path VARCHAR(500) NOT NULL COMMENT '文件路径',
|
|
541
|
+
description TEXT COMMENT '描述/文档',
|
|
542
|
+
content LONGTEXT COMMENT '完整代码内容',
|
|
543
|
+
meta JSON COMMENT '结构化元信息:props/params/properties/hooks',
|
|
544
|
+
usage_count INT DEFAULT 0 COMMENT '使用频率',
|
|
545
|
+
embedding JSON NULL COMMENT '向量',
|
|
546
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
547
|
+
INDEX idx_type (type),
|
|
548
|
+
INDEX idx_category (category),
|
|
549
|
+
INDEX idx_usage (usage_count DESC)
|
|
550
|
+
);
|
|
551
|
+
|
|
552
|
+
---
|
|
553
|
+
|
|
554
|
+
七、环境配置
|
|
555
|
+
|
|
556
|
+
环境变量
|
|
557
|
+
|
|
558
|
+
┌───────────────────────┬──────────────┬───────────────────┐
|
|
559
|
+
│ 变量 │ 说明 │ 默认值 │
|
|
560
|
+
├───────────────────────┼──────────────┼───────────────────┤
|
|
561
|
+
│ MYSQL_ENABLED │ 启用 MySQL │ false │
|
|
562
|
+
├───────────────────────┼──────────────┼───────────────────┤
|
|
563
|
+
│ MYSQL_HOST │ MySQL 主机 │ - │
|
|
564
|
+
├───────────────────────┼──────────────┼───────────────────┤
|
|
565
|
+
│ MYSQL_PORT │ MySQL 端口 │ 3306 │
|
|
566
|
+
├───────────────────────┼──────────────┼───────────────────┤
|
|
567
|
+
│ MYSQL_USER │ MySQL 用户 │ - │
|
|
568
|
+
├───────────────────────┼──────────────┼───────────────────┤
|
|
569
|
+
│ MYSQL_PASSWORD │ MySQL 密码 │ - │
|
|
570
|
+
├───────────────────────┼──────────────┼───────────────────┤
|
|
571
|
+
│ MYSQL_DATABASE │ 数据库名 │ code_intelligence │
|
|
572
|
+
├───────────────────────┼──────────────┼───────────────────┤
|
|
573
|
+
│ MYSQL_SYMBOLS_TABLE │ 表名 │ symbols │
|
|
574
|
+
├───────────────────────┼──────────────┼───────────────────┤
|
|
575
|
+
│ EMBEDDING_SERVICE_URL │ 向量服务 URL │ - │
|
|
576
|
+
└───────────────────────┴──────────────┴───────────────────┘
|
|
577
|
+
|
|
578
|
+
环境变量加载逻辑
|
|
579
|
+
|
|
580
|
+
1. 加载本地 .env
|
|
581
|
+
2. 加载第三方 .env(按变量维度覆盖,只覆盖第三方明确配置的变量)
|
|
582
|
+
3. 命令行参数 --KEY=VALUE 优先级最高
|
|
583
|
+
|
|
584
|
+
---
|
|
585
|
+
|
|
586
|
+
八、技术难点总结
|
|
587
|
+
|
|
588
|
+
┌────────────┬───────────────────────────────────────────────────┐
|
|
589
|
+
│ 模块 │ 难点 │
|
|
590
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
591
|
+
│ 权重排序 │ textMatch/usage/recency/commonPath 四维权重调优 │
|
|
592
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
593
|
+
│ TS 解析 │ ts-ormorph 需要 tsconfig.json,不存在时用默认配置 │
|
|
594
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
595
|
+
│ JS 解析 │ Babel 支持 JSX/TS/装饰器等复杂语法 │
|
|
596
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
597
|
+
│ Meta 提取 │ 函数/接口/类/hooks 的参数、返回值、类型解析 │
|
|
598
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
599
|
+
│ 路径推断 │ 从文件路径智能推断业务分类(category) │
|
|
600
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
601
|
+
│ 结构搜索 │ meta 存储为 JSON,全表扫描 + 内存过滤 │
|
|
602
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
603
|
+
│ 向量检索 │ 向量生成、存储、余弦相似度计算 │
|
|
604
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
605
|
+
│ 多工具编排 │ Prompt 中多 Tool 组合调用逻辑 │
|
|
606
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
607
|
+
│ 环境加载 │ 本地/第三方 .env 按变量维度合并 │
|
|
608
|
+
├────────────┼───────────────────────────────────────────────────┤
|
|
609
|
+
│ CI 评论 │ PR/Commit 评论逻辑、关联 PR 查找 │
|
|
610
|
+
└────────────┴───────────────────────────────────────────────────┘
|
|
611
|
+
|
|
612
|
+
---
|
|
613
|
+
|
|
614
|
+
这就是完整详细的功能总结。如需补充其他细节请告诉我。
|
package/dist/config/env.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import dotenv from 'dotenv';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
5
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
5
6
|
const projectRoot = path.resolve(__dirname, '../../');
|
|
6
7
|
// 解析命令行参数 --key=value 格式,注入到 process.env
|
|
@@ -15,13 +16,29 @@ dotenv.config({
|
|
|
15
16
|
path: path.resolve(projectRoot, '.env'),
|
|
16
17
|
override: false,
|
|
17
18
|
});
|
|
18
|
-
// 尝试从第三方项目目录加载 .env
|
|
19
|
+
// 尝试从第三方项目目录加载 .env,按变量维度覆盖(只覆盖第三方明确配置的变量)
|
|
19
20
|
const clientProjectRoot = process.env.INDEX_ROOT || process.cwd();
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
const clientEnvPath = path.resolve(clientProjectRoot, '.env');
|
|
22
|
+
if (existsSync(clientEnvPath)) {
|
|
23
|
+
console.error(`[Config] Merging .env from client project root: ${clientProjectRoot}`);
|
|
24
|
+
// 手动解析第三方 .env,只覆盖其明确配置的变量
|
|
25
|
+
const clientEnvContent = readFileSync(clientEnvPath, 'utf-8');
|
|
26
|
+
for (const line of clientEnvContent.split('\n')) {
|
|
27
|
+
const trimmed = line.trim();
|
|
28
|
+
if (!trimmed || trimmed.startsWith('#'))
|
|
29
|
+
continue;
|
|
30
|
+
const eqIdx = trimmed.indexOf('=');
|
|
31
|
+
if (eqIdx === -1)
|
|
32
|
+
continue;
|
|
33
|
+
const key = trimmed.slice(0, eqIdx).trim();
|
|
34
|
+
const value = trimmed.slice(eqIdx + 1).trim();
|
|
35
|
+
// 移除引号
|
|
36
|
+
const cleanValue = value.replace(/^["']|["']$/g, '');
|
|
37
|
+
if (key) {
|
|
38
|
+
process.env[key] = cleanValue;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
25
42
|
// 外部传入的 env 已在上一步保留,这里确保环境变量已正确设置
|
|
26
43
|
for (const arg of process.argv) {
|
|
27
44
|
const match = arg.match(/^--([A-Z_][A-Z0-9_]*)=(.+)$/);
|
|
@@ -167,6 +167,7 @@ export async function indexProject(opts) {
|
|
|
167
167
|
const ignore = [...DEFAULT_IGNORE, ...(opts.ignore ?? [])];
|
|
168
168
|
console.error(`[indexProject] patterns: ${patterns.join(', ')}`);
|
|
169
169
|
const files = await fg(patterns, {
|
|
170
|
+
// 根据pattern收集文件列表,支持绝对路径和相对路径(相对于projectRoot),并自动排除node_modules、dist等常见目录。
|
|
170
171
|
absolute: true,
|
|
171
172
|
ignore,
|
|
172
173
|
onlyFiles: true,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
const REUSABLE_CODE_ADVISOR_DESCRIPTION = '
|
|
2
|
+
const REUSABLE_CODE_ADVISOR_DESCRIPTION = '在实现需求时检索并推荐最合适的可复用代码代码块(组件/函数/类/模块等)。在用户要求复用现有代码、询问是否已有组件/函数/服务、或要在多个代码块中选最优时使用。';
|
|
3
3
|
/** 与 SKILL.md 中 `# 可复用代码推荐` 起至约束、示例说明为止的正文一致(无 YAML frontmatter)。 */
|
|
4
4
|
const REUSABLE_CODE_ADVISOR_MARKDOWN = `# 可复用代码推荐
|
|
5
5
|
|
|
@@ -7,16 +7,16 @@ const REUSABLE_CODE_ADVISOR_MARKDOWN = `# 可复用代码推荐
|
|
|
7
7
|
|
|
8
8
|
当用户需要可复用代码或实现类需求时,按顺序执行:
|
|
9
9
|
|
|
10
|
-
1.
|
|
11
|
-
2.
|
|
12
|
-
3.
|
|
13
|
-
4. 若仅凭签名/摘要无法判断,对最相关的若干候选调用
|
|
10
|
+
1. 调用 search_symbols 检索候选,type 根据用户需求传(component/util/selector/type)
|
|
11
|
+
2. 如果用户指定了结构过滤条件(props/params/properties/hooks),额外调用 search_by_structure 做结构匹配
|
|
12
|
+
3. 先 search_symbols(limit=20) 拉候选,再对 Top 3 调用 get_symbol_detail 做深度判断
|
|
13
|
+
4. 若仅凭签名/摘要无法判断,对最相关的若干候选调用 get_symbol_detail 获取详情
|
|
14
14
|
5. 从以下维度对比候选:
|
|
15
15
|
- 与用户需求的**功能匹配度**
|
|
16
16
|
- **API 是否简单**、入参是否合适
|
|
17
17
|
- **依赖与副作用**风险
|
|
18
18
|
- **复用安全性**(稳定性、耦合度、是否便于扩展)
|
|
19
|
-
6.
|
|
19
|
+
6. 给出**唯一首选**推荐,并说明理由
|
|
20
20
|
|
|
21
21
|
## 回复结构
|
|
22
22
|
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
-
import { registerRecommendComponentPrompt } from "../prompts/recommendComponentPrompt.js";
|
|
3
2
|
import { registerReusableCodeAdvisorPrompt } from "../prompts/reusableCodeAdvisorPrompt.js";
|
|
4
3
|
import { SymbolRepository } from "../repositories/symbolRepository.js";
|
|
5
4
|
import { createSearchSymbolsTool } from "../tools/searchSymbols.js";
|
|
6
5
|
import { createGetSymbolDetailTool } from "../tools/getSymbolDetail.js";
|
|
7
|
-
import { createRecommendComponentTool } from "../tools/recommendComponent.js";
|
|
8
6
|
import { createReindexTool } from "../tools/reindex.js";
|
|
9
7
|
import { createSearchByStructureTool } from "../tools/searchByStructure.js";
|
|
10
8
|
export function createServer() {
|
|
@@ -19,11 +17,8 @@ export function createServer() {
|
|
|
19
17
|
server.tool(detailTool.name, detailTool.description, detailTool.inputSchema, detailTool.handler);
|
|
20
18
|
const structureTool = createSearchByStructureTool(repository);
|
|
21
19
|
server.tool(structureTool.name, structureTool.description, structureTool.inputSchema, structureTool.handler);
|
|
22
|
-
const recommendTool = createRecommendComponentTool(repository);
|
|
23
|
-
server.tool(recommendTool.name, recommendTool.description, recommendTool.inputSchema, recommendTool.handler);
|
|
24
20
|
const reindexTool = createReindexTool();
|
|
25
21
|
server.tool(reindexTool.name, reindexTool.description, reindexTool.inputSchema, reindexTool.handler);
|
|
26
|
-
registerRecommendComponentPrompt(server);
|
|
27
22
|
registerReusableCodeAdvisorPrompt(server);
|
|
28
23
|
return server;
|
|
29
24
|
}
|
|
@@ -1,28 +1,27 @@
|
|
|
1
1
|
export function createEmbeddingClient(baseUrl) {
|
|
2
|
-
const root = baseUrl.replace(/\/$/,
|
|
2
|
+
const root = baseUrl.replace(/\/$/, '');
|
|
3
3
|
return {
|
|
4
4
|
async embed(texts) {
|
|
5
5
|
if (texts.length === 0)
|
|
6
6
|
return [];
|
|
7
7
|
const res = await fetch(`${root}/embed`, {
|
|
8
|
-
method:
|
|
9
|
-
headers: {
|
|
8
|
+
method: 'POST',
|
|
9
|
+
headers: { 'Content-Type': 'application/json' },
|
|
10
10
|
body: JSON.stringify({ texts }),
|
|
11
|
-
signal: AbortSignal.timeout(180_000)
|
|
11
|
+
signal: AbortSignal.timeout(180_000),
|
|
12
12
|
});
|
|
13
13
|
if (!res.ok) {
|
|
14
|
-
const t = await res.text().catch(() =>
|
|
15
|
-
throw new Error(`embedding service HTTP ${res.status}${t ? `: ${t.slice(0, 200)}` :
|
|
14
|
+
const t = await res.text().catch(() => '');
|
|
15
|
+
throw new Error(`embedding service HTTP ${res.status}${t ? `: ${t.slice(0, 200)}` : ''}`);
|
|
16
16
|
}
|
|
17
17
|
const data = (await res.json());
|
|
18
18
|
if (!data.embeddings || !Array.isArray(data.embeddings)) {
|
|
19
|
-
throw new Error(
|
|
19
|
+
throw new Error('embedding service returned invalid JSON (missing embeddings)');
|
|
20
20
|
}
|
|
21
21
|
return data.embeddings;
|
|
22
|
-
}
|
|
22
|
+
},
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
-
/** Chunked embed to avoid huge request bodies. */
|
|
26
25
|
export async function embedAll(client, texts, chunkSize = 48) {
|
|
27
26
|
const out = [];
|
|
28
27
|
for (let i = 0; i < texts.length; i += chunkSize) {
|
|
@@ -8,7 +8,23 @@ export const recommendComponentInput = z.object({
|
|
|
8
8
|
export function createRecommendComponentTool(repository) {
|
|
9
9
|
return {
|
|
10
10
|
name: "recommend_component",
|
|
11
|
-
description:
|
|
11
|
+
description: `推荐最合适的可复用组件。
|
|
12
|
+
|
|
13
|
+
工作流(自动完成,无需关心内部细节):
|
|
14
|
+
1. 关键词检索:根据 query 在 component 类型中搜索候选
|
|
15
|
+
2. 结构过滤:如果传了 props 参数,按结构匹配进一步过滤
|
|
16
|
+
3. 语义排序:对候选进行语义相似度排序
|
|
17
|
+
4. 详情补全:获取 Top 结果的完整代码详情
|
|
18
|
+
5. 返回推荐:输出 Top N 结果及评分、理由
|
|
19
|
+
|
|
20
|
+
输入参数:
|
|
21
|
+
- query:搜索关键词,如 "form"、"modal"、"table"
|
|
22
|
+
- props(可选):结构过滤所需的 props,如 ["onChange", "value"]
|
|
23
|
+
- limit(可选):返回数量,默认 3,最大 20
|
|
24
|
+
|
|
25
|
+
输出:
|
|
26
|
+
- results 数组,每项包含 name、path、score、reason、detail
|
|
27
|
+
- 如果没有合适结果,会返回最接近的候选并说明差距`,
|
|
12
28
|
inputSchema: recommendComponentInput.shape,
|
|
13
29
|
handler: async (input) => {
|
|
14
30
|
const result = await recommendComponent(input.query, repository, {
|
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
// 按结构字段检索(匹配 meta.props / meta.params / meta.properties / meta.hooks)
|
|
2
|
-
import { z } from
|
|
3
|
-
import { rankSymbols } from
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { rankSymbols } from '../services/ranking.js';
|
|
4
4
|
export const searchByStructureInput = z.object({
|
|
5
5
|
fields: z.array(z.string().min(1)).min(1),
|
|
6
|
-
type: z.enum([
|
|
6
|
+
type: z.enum(['component', 'util', 'selector', 'type']).optional(),
|
|
7
7
|
category: z.string().optional(),
|
|
8
8
|
limit: z.number().int().min(1).max(100).optional().default(20),
|
|
9
|
-
ranked: z.boolean().optional().default(true)
|
|
9
|
+
ranked: z.boolean().optional().default(true),
|
|
10
10
|
});
|
|
11
11
|
export function createSearchByStructureTool(repository) {
|
|
12
12
|
return {
|
|
13
|
-
name:
|
|
14
|
-
description:
|
|
13
|
+
name: 'search_by_structure',
|
|
14
|
+
description: '通过结构化字段(如 props/params/properties/hooks)搜索代码块,适用于 API 形态的查询。',
|
|
15
15
|
inputSchema: searchByStructureInput.shape,
|
|
16
16
|
handler: async (input) => {
|
|
17
17
|
const rows = await repository.searchByStructure(input.fields, {
|
|
18
18
|
type: input.type,
|
|
19
19
|
category: input.category,
|
|
20
|
-
limit: input.limit
|
|
20
|
+
limit: input.limit,
|
|
21
21
|
});
|
|
22
|
-
const query = input.fields.join(
|
|
22
|
+
const query = input.fields.join(' ');
|
|
23
23
|
const resultRows = input.ranked
|
|
24
24
|
? rankSymbols(query, rows).map((item) => ({
|
|
25
25
|
name: item.symbol.name,
|
|
@@ -31,7 +31,7 @@ export function createSearchByStructureTool(repository) {
|
|
|
31
31
|
score: item.score,
|
|
32
32
|
reason: item.reason.summary,
|
|
33
33
|
reasonDetail: item.reason,
|
|
34
|
-
meta: item.symbol.meta
|
|
34
|
+
meta: item.symbol.meta,
|
|
35
35
|
}))
|
|
36
36
|
: rows.map((r) => ({
|
|
37
37
|
name: r.name,
|
|
@@ -40,16 +40,16 @@ export function createSearchByStructureTool(repository) {
|
|
|
40
40
|
path: r.path,
|
|
41
41
|
description: r.description,
|
|
42
42
|
usageCount: r.usageCount,
|
|
43
|
-
meta: r.meta
|
|
43
|
+
meta: r.meta,
|
|
44
44
|
}));
|
|
45
45
|
return {
|
|
46
46
|
content: [
|
|
47
47
|
{
|
|
48
|
-
type:
|
|
49
|
-
text: JSON.stringify(resultRows, null, 2)
|
|
50
|
-
}
|
|
51
|
-
]
|
|
48
|
+
type: 'text',
|
|
49
|
+
text: JSON.stringify(resultRows, null, 2),
|
|
50
|
+
},
|
|
51
|
+
],
|
|
52
52
|
};
|
|
53
|
-
}
|
|
53
|
+
},
|
|
54
54
|
};
|
|
55
55
|
}
|