Token导航 LogoToken导航TokenDH.com
code trm MCP logo
开发工具未说明官方级别未说明来源级核验

code trm MCP

MCP Server

一个基于测试时递归记忆(TRM)的MCP服务器,用于通过LLM开发工具进行递归代码优化和评估。

工具数

18

提示词数

0

GitHub Stars

2

资源数

0
安全分析TypeScriptClaude测试自动化ClaudeCursor

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

andreahaku

提供方

andreahaku

最后核验

2026/5/17 20:21

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

详细介绍

MCP TRM服务器

A. TRM启发(测试时递归存储器)MCP服务器 使用LLM开发工具进行递归代码优化。

此服务器实现了递归改进循环,其中:

  • LLM(Claude Code、Cursor、Codex CLI)充当 优化器 建议代码更改
  • 此MCP服务器充当 评论家/评价者 具有状态跟踪功能
  • 评估包括:构建、测试、lint和基准测试
  • 使用EMA(指数移动平均线)跟踪分数
  • 停止策略(简化的ACT-自适应计算时间)决定何时停止

特性

  • 多信号评估:构建、测试、lint和性能基准测试
  • 加权评分:不同评估信号的可配置权重
  • EMA跟踪:跨迭代平滑跟踪分数
  • 智能停机:当测试通过+分数阈值、无改善或最大步数时停止
  • 灵活的候选人提交:支持多种模式(文件、补丁、差异、修改、创建)
  • 安全执行:命令在具有可配置超时的隔离目录中运行
  • 可操作的反馈:紧凑、LLM友好的错误消息,带有TypeScript解析和相关性
  • 高级功能:快速撤消、增量文件读取、AI驱动的修复建议

安装

npm install
npm run build

与MCP客户端一起使用

克劳德码(VS码)

  1. 打开VS代码设置
  2. 导航到“模型上下文协议”
  3. 添加新的MCP服务器:

- 命令: node /absolute/path/to/code_trm_mcp/dist/server.js - 参数: *(留空)*

光标

  1. 打开设置→ MCP/“自定义MCP服务器”
  2. 添加服务器:

- 命令: node /absolute/path/to/code_trm_mcp/dist/server.js

Codex CLI

{
  "command": "node",
  "args": ["/absolute/path/to/code_trm_mcp/dist/server.js"]
}

可用工具(共18个)

核心工具

trm.startSession

在本地存储库上初始化TRM会话。

参数:

  • repoPath (必填):项目的绝对路径
  • buildCmd, testCmd, lintCmd, benchCmd:评估命令
  • timeoutSec:每个命令超时(默认值:120)
  • weights:评分权重(构建:0.3,测试:0.5,皮棉:0.1,性能:0.1)
  • halt:停止策略(最大步数、通过阈值、患者无改善、最小步数)
  • emaAlpha:EMA平滑系数(默认值:0.9)
  • zNotes:可选的初始推理说明
  • preflight:运行验证检查(默认值:false)

退货: sessionId, message,可选 preflight 结果

trm.submitCandidate

应用候选人变更,运行评估,返回反馈。

参数:

  • sessionId (必填)
  • candidate (必填):其中一种模式:

- 文件:完整的文件内容 - 补丁:统一的差异格式 - 差异: 每个文件的差异 - 修改:语义编辑操作 - 创造:仅限新文件

  • rationale:法学硕士推理笔记

退货: step, score, emaScore, bestScore, tests, okBuild, okLint, shouldHalt, reasons, feedback, modeSuggestion

主要特点:

  • 错误相关性,显示哪个迭代导致了错误
  • 基于变化模式的智能模式建议
  • 带有可操作建议的TypeScript错误解析

trm.getFileContent

使用元数据读取当前文件状态。

参数:

  • sessionId, paths (必填)
  • offset, limit:可选线路范围

退货: 带元数据的文件内容(行数、大小字节、lastModified)

trm.getState

返回当前会话状态快照。

退货: sessionId, step, emaScore, bestScore, noImproveStreak, last, zNotes

trm.shouldHalt

检查停止决定。

退货: shouldHalt, reasons

trm.endSession

清理会议。

退货: ok

增强工具

trm.validateCandidate

在应用更改之前进行详细预览的模拟运行验证。

参数: sessionId, candidate

退货: valid, errors, warnings, preview (文件受影响,行添加/删除/修改,预览之前/之后)

优点:

  • 提交前捕获错误(无效行号、重复)
  • 查看上下文前后会发生什么变化
  • 显著减少失败的迭代

trm.getSuggestions

基于评估结果和代码分析,获取基于AI的改进建议。

退货: 按优先级排序的前5条建议(关键→ high → 中等→ low)

trm.saveCheckpoint, trm.restoreCheckpoint, trm.listCheckpoints

保存/恢复基于快照的工作流的会话状态。

trm.resetToBaseline

将存储库重置为初始git提交状态。

高级工具

trm.undoLastCandidate

快速撤消并完全恢复状态。

退货: message, currentStep, score, emaScore, filesRestored

它是如何工作的:

  • 在应用每个候选人之前捕获文件内容
  • 撤消时:恢复文件,回滚步数计数器,重新计算分数/EMA/连胜
  • 无需git命令-使用内部快照

例子:

// Submit fails badly (score drops from 0.85 to 0.25)
await trm.submitCandidate({ sessionId: "...", candidate: {...} });

// Immediately undo - back to previous state
await trm.undoLastCandidate({ sessionId: "..." });
// Session restored to previous step with score 0.85 ✅

trm.getFileLines

从带有行号的文件中读取特定的行范围。

参数: sessionId, file, startLine, endLine

退货: 带格式化行号的行,总行数

优点:

  • 在大文件上节省10-15%的代币
  • 包含行号,便于参考
  • 非常适合针对错误位置进行有针对性的修复

例子:

// Error at line 50 - read context (lines 45-56)
const context = await trm.getFileLines({
  sessionId: "...",
  file: "src/parser.ts",
  startLine: 45,
  endLine: 56
});
// Returns: ["45: export function...", "46:   try {", ...]

trm.suggestFix

基于错误分析的人工智能修复候选生成。

支持的错误: TS2304(缺少导入)、TS7006(隐式任何)、TS2339(无效属性访问)

退货: 一系列建议 priority, issue, candidateToFix, rationale

例子:

// Iteration fails with TypeScript errors
const result = await trm.submitCandidate({ /* ... */ });

// Get AI-generated fixes
const fixes = await trm.suggestFix({ sessionId: "..." });

// Apply suggested fix (or validate first)
await trm.submitCandidate({
  sessionId: "...",
  candidate: fixes.suggestions[0].candidateToFix,
  rationale: fixes.suggestions[0].rationale
});

trm.reviewPR

结合风格检查的全面代码审查, 安全分析,以及 代码质量分析 在pull请求上。

参数:

  • prUrl:GitHub PR URL(例如。, https://github.com/owner/repo/pull/123)
  • diff:直接统一差异内容
  • files:包含以下内容的文件数组 path, content,可选 originalContent
  • focus:筛选评论类别的可选数组

重点类别:

  • type-safety:检测的使用情况 any 类型
  • logging:标记控制台语句
  • todos:识别TODO/FIXME评论
  • code-quality:魔术数字,长线
  • formatting:行长度验证(>120个字符)
  • error-handling:异步函数中缺少try-catch
  • testing:建议添加测试
  • size:标记大型变更集

综合分析:

  • 安全扫描:OWASP漏洞、机密、注入、XSS、身份验证问题(来自 trm.security)
  • 代码质量:大文件检测、代码拆分建议(来自 trm.codeQuality)

退货:

{
  summary: {
    filesChanged: number,
    linesAdded: number,
    linesRemoved: number,
    commentsCount: number,
    criticalCount: number,
    warningCount: number,
    infoCount: number,
    assessment: "approved" | "needs-changes" | "comments",
    highlights: string[],
    // Security summary
    securityIssues: {
      critical: number,
      high: number,
      medium: number,
      low: number,
      total: number
    },
    // Code quality summary
    codeQualityIssues: {
      largeFiles: number,
      highSeverity: number
    }
  },
  comments: [{
    file: string,
    line: number,
    severity: "error" | "warning" | "info",
    category: string,
    message: string,
    suggestion?: string
  }],
  issues: string[],
  suggestions: string[],
  prInfo?: { title?: string, url?: string },
  // Security analysis results
  security?: {
    vulnerabilities: SecurityVulnerability[],
    positives: string[]
  },
  // Code quality results
  codeQuality?: {
    largeFiles: LargeFileIssue[],
    recommendations: string[]
  }
}

评估逻辑:

  • needs-changes:严重/高安全问题,或>5个警告,或>2个中等安全问题
  • comments:检测到任何安全问题或大文件
  • approved:未发现重大问题

例子:

// Review from GitHub URL - includes security + code quality
const review = await trm.reviewPR({
  prUrl: "https://github.com/owner/repo/pull/123"
});

console.log(`Assessment: ${review.summary.assessment}`);
console.log(`Security issues: ${review.summary.securityIssues.total}`);
console.log(`Large files: ${review.summary.codeQualityIssues.largeFiles}`);

// Check for critical security issues
if (review.security?.vulnerabilities.some(v => v.severity === "critical")) {
  console.log("⚠️ Critical security vulnerabilities found!");
}

// Review from direct diff
const review2 = await trm.reviewPR({
  diff: "diff --git a/file.ts...",
  focus: ["type-safety", "error-handling"]
});

trm.security

全面的安全分析,检测OWASP Top 10漏洞、秘密和安全反模式。

参数:

  • path (必填):要分析的目录
  • include:球状图案包括(例如。, ["src/**/*.ts"])
  • exclude:要排除的球状图案(例如。, ["**/test/**"])
  • focus:按类别筛选- secrets, injection, xss, auth, crypto, config, mobile
  • severity:报告的最低严重程度- critical, high, medium, low

漏洞类别:

类别检测
secrets硬编码API密钥、密码、AWS证书、JWT机密
injectionSQL/NoSQL注入、命令注入、eval()、模板注入
xss危险SetInnerHTML、innerHTML、v-html、document.write
auth不安全的令牌存储(localStorage)、缺少身份验证检查、JWT问题、弱Cookie
crypto禁用SSL、弱哈希(MD5/SHA1)、Math.random()以确保安全
configCORS通配符、调试模式、堆栈跟踪暴露、日志中的敏感数据
mobileAsyncStorage用于秘密、深度链接验证、明文流量、WebView风险

检测到的积极做法:

  • 安全存储(世博会安全存储、钥匙扣)
  • 参数化SQL查询
  • 输入净化(DOMPurify)
  • JWT与受众/发行人的验证
  • 模式验证(Joi、Yup、Zod)
  • 速率限制、CSRF保护、安全标头
  • 证书固定

退货:

{
  vulnerabilities: [{
    id: number,
    title: string,
    severity: "critical" | "high" | "medium" | "low",
    owasp: "A01:2021-Broken Access Control" | ...,
    status: "needs-fix" | "review",
    location: { file: string, line?: number, snippet?: string },
    issue: string,
    risk: string[],
    solution: string[]
  }],
  positivePractices: [{
    title: string,
    description: string,
    location?: { file: string, line?: number }
  }],
  metrics: {
    totalFilesAnalyzed: number,
    securityRelatedFiles: number,
    errorBoundaries: number,
    secureStorageOps: number,
    totalPatternsDetected: number,
    antiPatternsFound: number
  },
  summary: { critical: number, high: number, medium: number, low: number, total: number },
  recommendations: [{ priority: "immediate" | "high" | "medium" | "ongoing", description: string }]
}

例子:

// Full security audit
const audit = await trm.security({
  path: "/path/to/project"
});

console.log(`Found ${audit.summary.total} issues`);
console.log(`Critical: ${audit.summary.critical}, High: ${audit.summary.high}`);

// Focused analysis on auth and secrets
const authAudit = await trm.security({
  path: "/path/to/project",
  focus: ["auth", "secrets"],
  severity: "high"  // Only high and critical
});

// Mobile app security check
const mobileAudit = await trm.security({
  path: "/path/to/mobile-app",
  focus: ["mobile", "auth", "crypto"],
  exclude: ["**/node_modules/**", "**/__tests__/**"]
});

输出格式:

该工具返回格式化的markdown报告和结构化的JSON数据:

## Security Analysis Summary

| Severity | Count | Action Required |
|----------|-------|-----------------|
| CRITICAL | 2     | Immediate remediation |
| High     | 3     | Immediate remediation |
| Medium   | 5     | Address in next sprint |

---
## Positive Security Practices Observed

1. **Secure Token Storage** (src/utils/secureStorage.ts)
   Uses secure storage for sensitive tokens (iOS Keychain, Android Keystore)

2. **Parameterized SQL Queries** (src/db/queries.ts)
   Uses parameterized queries to prevent SQL injection

---
## Vulnerabilities Found

### CRITICAL Severity

#### 1. Hardcoded Secret/API Key
**Severity:** CRITICAL
**Location:** `src/config.ts:15`
**OWASP:** A02:2021-Cryptographic Failures

**Issue:** Hardcoded secret or API key detected

**Risk:**
- Secrets exposed in source control
- Credential theft if code is leaked

**Solution:**
- Use environment variables
- Use secrets manager (AWS Secrets Manager, HashiCorp Vault)

---
## Recommended Next Steps

1. **Immediate (Critical):** Fix 2 critical issues: Hardcoded Secret/API Key, Command Injection
2. **High Priority:** Address 3 high-severity issues
3. **Ongoing:** Implement automated security scanning in CI/CD pipeline

安全分析提示示例:

对Claude Code、Cursor或其他启用MCP的LLM使用这些提示:

# Full security audit
"Run a security analysis on this project and show me all vulnerabilities"

# Pre-release security check
"Before we deploy, scan the codebase for any hardcoded secrets or API keys"

# Mobile app security
"Analyze this React Native app for mobile security issues - focus on token storage and deep links"

# Auth system review
"Check our authentication code for security vulnerabilities - look at JWT handling, cookies, and session management"

# OWASP compliance check
"Scan for OWASP Top 10 vulnerabilities in the src directory"

# Quick secrets scan
"Do a quick scan for any hardcoded credentials or API keys that shouldn't be in the code"

# Production readiness
"Is this codebase secure enough for production? Check for critical and high severity issues only"

安全第一开发工作流程:

// 1. Run security scan before starting work
const initialAudit = await trm.security({
  path: "/path/to/project",
  severity: "high"  // Focus on critical issues first
});

if (initialAudit.summary.critical > 0) {
  console.log("Fix critical security issues before proceeding:");
  initialAudit.vulnerabilities
    .filter(v => v.severity === "critical")
    .forEach(v => console.log(`- ${v.title}: ${v.location?.file}`));
}

// 2. After implementing features, re-scan
const postFeatureAudit = await trm.security({
  path: "/path/to/project",
  include: ["src/features/newFeature/**"]  // Scan only new code
});

// 3. Pre-commit security gate
const preCommitAudit = await trm.security({
  path: "/path/to/project",
  focus: ["secrets", "injection"],  // Quick scan for worst issues
  severity: "critical"
});

if (preCommitAudit.summary.total > 0) {
  throw new Error("Cannot commit: critical security issues found");
}

将安全分析与TRM迭代相结合:

// Start TRM session
const session = await trm.startSession({
  repoPath: "/path/to/project",
  buildCmd: "tsc --noEmit",
  testCmd: "npm test",
  halt: { maxSteps: 10, passThreshold: 0.95, patienceNoImprove: 3 }
});

// Run security scan to identify issues to fix
const securityIssues = await trm.security({
  path: "/path/to/project",
  severity: "high"
});

// Iterate through security fixes
for (const vuln of securityIssues.vulnerabilities) {
  console.log(`Fixing: ${vuln.title} in ${vuln.location?.file}`);

  // Read the problematic file
  const { files } = await trm.getFileContent({
    sessionId: session.sessionId,
    paths: [vuln.location.file]
  });

  // Get context around the issue
  if (vuln.location?.line) {
    const context = await trm.getFileLines({
      sessionId: session.sessionId,
      file: vuln.location.file,
      startLine: Math.max(1, vuln.location.line - 5),
      endLine: vuln.location.line + 10
    });
    console.log("Context:", context.lines.join("\n"));
  }

  // Apply fix (LLM generates the actual fix based on vuln.solution)
  // ... submit candidate with security fix ...

  // Verify fix didn't break anything
  const state = await trm.getState({ sessionId: session.sessionId });
  if (state.last?.okBuild && state.last?.tests?.failed === 0) {
    console.log(`✓ Fixed ${vuln.title} without breaking tests`);
  }
}

// Final security verification
const finalAudit = await trm.security({
  path: "/path/to/project",
  severity: "high"
});
console.log(`Security issues remaining: ${finalAudit.summary.total}`);

CI/CD集成示例:

# .github/workflows/security.yml
name: Security Scan

on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Run MCP Security Scan
        run: |
          # Use the MCP server for security analysis
          node -e "
            import('./dist/analyzer/security-analyzer.js').then(async (mod) => {
              const result = await mod.analyzeSecurityComprehensive('./src', {
                minSeverity: 'high'
              });

              console.log('Security Scan Results:');
              console.log('Critical:', result.summary.critical);
              console.log('High:', result.summary.high);

              if (result.summary.critical > 0) {
                console.error('CRITICAL security issues found!');
                process.exit(1);
              }
            });
          "

______________________________________________________________________

trm.codeQuality -大文件检测和代码拆分

分析可能受益于拆分的大型文件的代码库,以提高可维护性、可测试性和关注点分离。

参数:

参数类型必填说明
pathstring要分析的目录
threshold编号行数阈值(默认值:500)
includestring\[\]球状图案包括(例如。, ["**/*.ts"])
excludestring\[\]要排除的球状图案(例如。, ["**/node_modules/**"])

严重级别:

严重性线路范围操作
🔴 高>1000行需要立即关注
🟠 中等700-1000行应该重构
🟡 低500-700行考虑拆分

分析指标:

  • 行数:总计、代码、注释、空白行
  • 复杂性:类、函数、导出、导入
  • 功能指标:最大长度、平均长度
  • 嵌套深度:最大嵌套级别

建议类型:

类型描述
📦 提取类将类和相关方法移动到新文件
⚡ 提取函数组相关实用函数
📁 拆分模块将关注点拆分为模块
🔧 提取常量将常量移动到专用文件
📝 提取类型将类型定义移动到类型文件

示例用法:

// Basic analysis with default threshold (500 lines)
const result = await trm.codeQuality({
  path: "/path/to/project/src"
});

// Custom threshold and filters
const result = await trm.codeQuality({
  path: "/path/to/project",
  threshold: 300,
  include: ["**/*.ts", "**/*.tsx"],
  exclude: ["**/*.test.ts", "**/generated/**"]
});

输出示例:

## Code Quality Analysis - Large File Detection

**Threshold:** 500 lines

### Summary

| Severity | Count | Line Range |
|----------|-------|------------|
| HIGH | 1 | >1000 lines |
| Medium | 2 | 700-1000 lines |
| Low | 3 | 500-700 lines |

**Total files over threshold:** 6 of 44 analyzed

### Codebase Metrics

| Metric | Value |
|--------|-------|
| Total Files Analyzed | 44 |
| Files Over Threshold | 6 |
| Average File Size | 192 lines |
| Largest File | 910 lines |
| Total Code Lines | 8,450 |

---
### Large Files Requiring Attention

#### 1. 🔴 `src/analyzer/security-analyzer.ts`
**Severity:** HIGH | **Lines:** 910

**File Composition:**
- Code: 750 lines | Comments: 85 | Blank: 75
- Classes: 0 | Functions: 25 | Exports: 5 | Imports: 8

**Impact:**
- Difficult to test individual security patterns
- Changes risk unintended side effects
- Code review overhead increased

**Suggested Splits:**
- **📦 Extract Class:** Create SecurityPatternMatcher class
  - Items: `detectSecrets`, `detectInjection`, `detectXSS`
  - Estimated reduction: ~300 lines
- **📁 Split Module:** Separate patterns by category
  - Items: `secrets-patterns.ts`, `injection-patterns.ts`
  - Estimated reduction: ~400 lines

示例提示:

"Analyze my codebase for large files that should be split"

"Find all files over 300 lines and suggest how to refactor them"

"Check src/services for maintainability issues"

"What files in my project are too complex and need splitting?"

与开发工作流集成:

// Pre-commit check for file size
const quality = await trm.codeQuality({
  path: "./src",
  threshold: 500
});

if (quality.summary.high > 0) {
  console.error("Files over 1000 lines need refactoring before commit");
  process.exit(1);
}

推荐工作流程

1.使用Preflight开始会话

const session = await trm.startSession({
  repoPath: "/absolute/path/to/project",
  buildCmd: "tsc -p . --noEmit",
  testCmd: "npm test --silent -- --reporter=json",
  preflight: true, // Validate setup before iterating
  halt: { maxSteps: 12, passThreshold: 0.97, patienceNoImprove: 3 }
});

if (!session.preflight.initialBuild.success) {
  console.log("Fix build before iterating");
  return;
}

2.迭代改进循环

关键原则:

  • 保留补丁 小而专注 (一次一个问题)
  • 最大化 每步增量信息 (TRM哲学)
  • 使用 rationale 跨步骤维护上下文
  • 相信分数/反馈信号作为指导

图案:

  1. 获取文件元数据以避免行号错误
  2. 提交前验证更改
  3. 提交候选人并说明理由
  4. 如果失败:使用 suggestFixundoLastCandidate
  5. 重复直到 shouldHalt=true

3.具有高级功能的示例

// 1. Get file metadata
const { files } = await trm.getFileContent({
  sessionId: session.sessionId,
  paths: ["src/parser.ts"]
});
const lineCount = files["src/parser.ts"].metadata.lineCount;

// 2. Validate before submitting
const validation = await trm.validateCandidate({
  sessionId: session.sessionId,
  candidate: {
    mode: "modify",
    changes: [{
      file: "src/parser.ts",
      edits: [{ type: "insertAfter", line: lineCount, content: "..." }]
    }]
  }
});

if (!validation.valid) {
  console.log("Fix errors:", validation.errors);
  return;
}

// 3. Submit
const result = await trm.submitCandidate({
  sessionId: session.sessionId,
  candidate: validation.preview.candidate,
  rationale: "Adding error handling"
});

// 4. Handle failures
if (!result.okBuild) {
  // Try AI-generated fixes
  const fixes = await trm.suggestFix({ sessionId: session.sessionId });

  if (fixes.suggestions.length > 0) {
    await trm.submitCandidate({
      sessionId: session.sessionId,
      candidate: fixes.suggestions[0].candidateToFix,
      rationale: `Auto-fix: ${fixes.suggestions[0].rationale}`
    });
  } else {
    // Or undo and try different approach
    await trm.undoLastCandidate({ sessionId: session.sessionId });
  }
}

// 5. For targeted fixes, read just relevant lines
if (result.feedback.includes("line 145")) {
  const context = await trm.getFileLines({
    sessionId: session.sessionId,
    file: "src/parser.ts",
    startLine: 135,
    endLine: 155
  });
  // Use context with line numbers for precise fix
}

提交方式

推荐(新):

  • create:仅新文件(验证文件不存在)
  • modify:语义编辑操作(替换、insertBefore、insertAfter、replaceLine、deleteRange等)

修改模式示例:

{
  mode: "modify",
  changes: [{
    file: "src/server.ts",
    edits: [
      { type: "replace", oldText: "err: any", newText: "err: unknown", all: true },
      { type: "insertAfter", line: 150, content: "const NEW_CONSTANT = 42;" }
    ]
  }]
}

传统(仍受支持):

  • diff:每个文件的统一差异(使用自定义模糊匹配修补程序)
  • patch:多个文件的单个统一差异
  • files:完整的文件内容(用于重写)

性能优势

功能节省时间节省代币用例
快速撤消5-10%-从失败的迭代中立即恢复
增量文件读取10-15%30-50%大文件,重点编辑
自动建议修复1-20%-TypeScript错误,常见模式
预应用验证20-30%-提交前发现错误
错误相关性10-15%-根据上下文更快地进行调试
安全分析--OWASP漏洞、秘密检测
综合效益高达40%30-50%整体效率提升

现实世界影响:

  • 在错误繁重的工作负载上显著加快迭代会话
  • 处理大文件时减少令牌使用
  • 由于验证和错误相关性,浪费的迭代更少

令牌优化

MCP工具模式已经过优化,以最大限度地减少令牌使用,同时保留完整功能:

优化结果:

  • 减少4% MCP令牌总使用量(节省384个令牌)
  • 17工具 使用简洁的模式进行优化
  • 无功能损失 -所有参数、类型和功能均保持不变

优化内容:

  • 简洁的工具描述,没有冗长的解释
  • 删除了冗余的属性描述
  • 从模式中删除内联示例
  • 简化文本,同时保持清晰

影响:

  • 在上下文窗口中释放384个令牌
  • 相当于约100行额外的代码上下文
  • MCP协议开销(约7200个令牌)仍然是主要瓶颈

实施: 超优化模式处于活动状态。有关分析和更大的代币节省策略,请参阅 TOKEN_OPTIMIZATION.mdtoken-comparison.md.

分数计算

分数是\[0,1\]中的加权平均值:

score = (w.build * sBuild + w.test * sTests + w.lint * sLint + w.perf * sPerf) / sumWeights

where:
  sBuild = 1 if build succeeds, 0 otherwise
  sTests = passed / total (0 if tests fail to parse)
  sLint = 1 if lint succeeds, 0 otherwise
  sPerf = normalized performance score (best/current, lower is better)

停机条件

迭代在以下情况下停止:

  1. 成功: step >= minSteps 所有测试均已通过 score >= passThreshold
  2. 高原:没有改善 patienceNoImprove 连续步骤
  3. 限制:已到达 maxSteps

设计哲学(TRM→ MCP)

  • y(当前解决方案):The 回购状态 LLM应用每个补丁后
  • z(潜在推理): rationalezNotes 保持我们如何/为什么达到当前状态的上下文
  • 深度监督:每个 submitCandidate 是一个 精炼步骤;评分/EMA提供客观反馈
  • ACT停止: shouldHalt 使用明确的规则(测试通过+阈值,耐心耗尽,最大步数)
  • 小补丁:每一步信息最大化(TRM原则)
  • 无需培训:使用现有开发工具进行纯测试时间优化

实用技巧

  1. 启用JSON测试报告器 (Jest/Vitest)用于精确计算分数
  2. 保持补丁较小 使每一步的信息最大化(TRM原理)
  3. 调整 weights 基于目标(例如,增加权重 perf 当测试为绿色时)
  4. 使用 benchCmd 输出一个数字(例如毫秒)用于性能跟踪
  5. 对于TypeScript:使用 tsc --noEmitbuildCmd 用于快速类型错误检测
  6. 使用飞行前验证 在迭代之前捕捉设置问题
  7. 验证候选人 在提交之前减少失败的迭代
  8. 使用 getFileLines 用于保存令牌的大文件
  9. 尝试 suggestFix 当遇到TypeScript错误时
  10. 使用 undoLastCandidate 从错误的更改中快速恢复
  11. 运行安全扫描 在部署之前捕获硬编码的秘密和漏洞
  12. 重点安全分析 使用 focus 用于更快的目标扫描的参数(例如。, ["secrets", "auth"])
  13. 使用严重性过滤器 (severity: "high")优先考虑关键问题
  14. 结合安全+TRM 修复漏洞,同时确保测试仍然通过

建筑

┌─────────────────────────────────────────────────────────────┐
│                      LLM Client                              │
│         (Claude Code / Cursor / Codex CLI)                  │
│                                                              │
│  • Proposes code changes (optimizer role)                   │
│  • Submits candidates via MCP tools                         │
│  • Interprets feedback and iterates                         │
└────────────────────┬────────────────────────────────────────┘
                     │ MCP Protocol
                     ▼
┌─────────────────────────────────────────────────────────────┐
│                   MCP TRM Server                            │
│                                                              │
│  Session State:                                             │
│  • Current score, EMA, best score                           │
│  • Test results, build status                               │
│  • Improvement streak tracking                              │
│  • History of evaluations                                   │
│  • Candidate snapshots (for undo)                           │
│                                                              │
│  Evaluation Pipeline:                                       │
│  1. Apply candidate changes                                 │
│  2. Run: build → test → lint → bench                        │
│  3. Parse outputs, extract signals                          │
│  4. Compute weighted score                                  │
│  5. Update EMA and improvement tracking                     │
│  6. Check halting policy                                    │
│  7. Return structured feedback                              │
└────────────────────┬────────────────────────────────────────┘
                     │ Shell Commands
                     ▼
┌─────────────────────────────────────────────────────────────┐
│                  Target Repository                          │
│                                                              │
│  • Source code files                                        │
│  • Build system (tsc, webpack, etc.)                        │
│  • Test framework (jest, vitest, etc.)                      │
│  • Linter (eslint, etc.)                                    │
│  • Benchmark scripts (optional)                             │
└─────────────────────────────────────────────────────────────┘

基于

这一实施的灵感来自 测试时间递归存储器(TRM) 论文中的方法:

“递归反思:教授语言模型代理如何自我提升” (arXiv:2510.4871v1)

MCP/LLM开发的关键调整:

  • TRM的递归精化→ 使用LLM提案进行迭代代码改进
  • 潜在推理(z)→ 迭代之间传递的基本原理/注释
  • ACT停止→ 基于分数+改进的可配置停止策略
  • 深度监督→ 构建/测试/lint/perf信号作为无需培训的反馈

许可证

麻省理工学院

贡献

项目存储库欢迎问题和拉取请求。

目录标签

目录标签

安全分析TypeScriptClaude测试自动化代码优化本地部署LLM开发工具递归评估性能基准测试

支持客户端

ClaudeCursor

接入字段

传输方式(transport,传输协议)

未说明

鉴权方式(authType,认证方式)

api-key

工具数量(toolCount,工具数)

18

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

未说明api-key部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

仍需确认:installCommand

来源信息

继续浏览同类 MCP