ai-backend-performance-mcp
ai-backend-performance-mcp
Статический анализ MCP-сервера для проблем производительности Node.js backend. AI-агенты могут проверять проект на анти-паттерны запросов к базе данных, узкие места асинхронности, ошибки пула соединений и проблемы гигиены зависимостей — без изменения вашего кода.
Зачем этот проект?
Проблемы производительности backend часто скрыты на виду: N+1 запросы в циклах, клиенты, создаваемые на каждый запрос, последовательные await, которые можно выполнять параллельно, или зависимости, неправильно классифицированные в package.json. Этот MCP-сервер выявляет эти паттерны как структурированные, подтверждённые доказательствами находки, которые AI-ассистенты могут анализировать.
Что он делает
Статический анализ исходных файлов JavaScript/TypeScript только для чтения
Шесть специализированных MCP-инструментов для распространённых категорий производительности backend
Структурированные находки с серьёзностью, уверенностью, фрагментами кода и рекомендациями
Различает подтверждённые доказательства и потенциальные проблемы
Чего он не делает
Не выполняет ваш код приложения или репозитория
Не изменяет файлы, не устанавливает пакеты и не меняет индексы
Не заменяет профилирование, нагрузочное тестирование или анализ
EXPLAINбазы данных
Related MCP server: CodeMore MCP Server
Архитектура
flowchart TD
Client[MCP Client / AI Agent]
Server[MCP Server]
Tools[MCP Tools]
Engine[Analysis Engine]
Analyzers[Individual Analyzers]
Findings[Structured Findings]
Client --> Server
Server --> Tools
Tools --> Engine
Engine --> Analyzers
Analyzers --> Findings
Findings --> Tools
Tools --> Server
Server --> ClientПодробности слоёв см. в docs/architecture.md.
Анализаторы
Анализатор | Обнаруживает |
Запросы к базе данных | Паттерны N+1, неограниченные find/query |
Индексы MongoDB | Поля фильтрации/сортировки без соответствующего |
Асинхронные паттерны |
|
Пул соединений | Создание клиента/пула в обработчиках или циклах |
Зависимости | Неиспользуемые зависимости, неправильная классификация dev/prod, статистика lockfile |
MCP-инструменты
Инструмент | Описание |
| Полное сканирование с группированными находками и сводкой |
| Паттерны запросов MongoDB/PostgreSQL |
| Эвристики покрытия индексов MongoDB |
| Паттерны производительности async/await |
| Анти-паттерны жизненного цикла соединений |
| Гигиена |
Справочник инструментов: docs/tools.md
Установка
npm install ai-backend-performance-mcpИли запустите напрямую:
npx ai-backend-performance-mcpКонфигурация MCP
Добавьте в конфигурацию вашего MCP-клиента (пример для Cursor / Claude Desktop):
{
"mcpServers": {
"backend-performance": {
"command": "npx",
"args": ["-y", "ai-backend-performance-mcp"],
"env": {}
}
}
}Для локальной разработки:
{
"mcpServers": {
"backend-performance": {
"command": "node",
"args": ["/absolute/path/to/ai-backend-performance-mcp/dist/index.js"]
}
}
}Использование
Вызовите любой инструмент с projectPath, указывающим на репозиторий Node.js backend:
{
"projectPath": "/path/to/your/api"
}Пример вывода (сокращённый)
{
"projectPath": "/app/examples/sample-node-api",
"technologies": ["express", "mongodb"],
"metadata": {
"packageName": "sample-node-api",
"packageVersion": "1.0.0",
"sourceFileCount": 4
},
"findings": [
{
"category": "pooling",
"severity": "critical",
"title": "Connection or client created in request handler",
"evidence": {
"kind": "confirmed",
"snippet": "const client = await MongoClient.connect(...)"
},
"confidence": 0.9,
"recommendation": "Create a shared client/pool at module scope and reuse it."
}
],
"summary": {
"totalFindings": 6,
"confirmedCount": 3,
"potentialCount": 3
}
}Попробуйте включённый демонстрационный проект в examples/sample-node-api.
Безопасность
Только чтение: никогда не записывает в анализируемые проекты
Проверка путей: предотвращает выход за пределы
projectPathБез выполнения кода: анализирует только текст исходников; не запускает код репозитория
Недоверенный ввод: считайте анализируемые репозитории недоверенными
Ограничения
Только статический анализ; находки, зависящие от состояния кластера, остаются
potentialДинамические
require()/ запросы, генерируемые во время выполнения, отслеживаются не полностьюАнализ индексов сравнивает только вызовы
createIndexвнутри репозитория (не индексы Atlas/ops-managed) и молчит, если в репозитории их нетArray.find, пакетные$in/ANY(), поиск по_idи клиенты БД на уровне модуля не считаются проблемамиПоследовательные await помечаются только если они не используют предыдущие привязки;
Promise.allникогда не сообщается как находкаОбнаружение неиспользуемых зависимостей основано на сканировании импортов
Специфические правила для Redis запланированы, но не реализованы в v0.1.0
Разработка
git clone https://github.com/robinafaruqia/ai-backend-performance-mcp.git
cd ai-backend-performance-mcp
npm install
npm run typecheck
npm run lint
npm test
npm run buildСм. docs/development.md.
Тестирование
npm testФикстурные проекты в tests/fixtures/ объединяют проблемный и валидный код для N+1 запросов, индексов, асинхронности, пулов и зависимостей, чтобы анализаторы не срабатывали на каждый await, запрос, цикл или соединение.
Дорожная карта
Анализатор Redis/кэша
Специфические правила запросов для Prisma/TypeORM
Кэширование ProjectContext
Экспорт отчётов SARIF/JSON
Настраиваемые пороги серьёзности
Вклад в проект
Вклад приветствуется! См. CONTRIBUTING.md и CODE_OF_CONDUCT.md.
Лицензия
MIT — см. LICENSE.
Available Tools
6 toolsanalyze_async_patternsB
Detect async performance issues including await in loops, sequential awaits, and blocking operations.
| Name | Required | Description | Default |
|---|---|---|---|
| projectPath | Yes | Absolute or relative path to the Node.js project to analyze |
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 of behavioral disclosure. It states what the tool detects but does not clarify whether it is read-only, what it returns (e.g., a report, a list of issues), or whether it modifies the project. The verb 'Detect' implies analysis, but without explicit confirmation, the agent cannot be certain of side effects or output format.
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, focused sentence that front-loads the purpose with specific examples. It contains no filler or redundancy, and every word contributes to explaining the tool's function.
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?
For a tool with a single parameter and no output schema, the description is moderately complete. It explains what the tool detects but omits details about the return format, whether the analysis is non-destructive, and any prerequisites or limitations. Given the absence of annotations and output schema, additional context would improve agent confidence, but the simplicity of the tool mitigates the gap.
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 fully documents the single parameter (projectPath) with a clear description and minimal length constraint. The tool description adds no extra meaning about the parameter format, validation, or usage nuances, so it matches the baseline of 3 for high schema coverage.
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 clearly states a specific verb ('Detect') and resource ('async performance issues'), and enumerates concrete examples (await in loops, sequential awaits, blocking operations). This distinguishes it from sibling analyzers like analyze_database_queries or analyze_indexes, which target different problem domains.
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?
There is no explicit guidance on when to use this tool versus its siblings. The description does not mention alternatives or conditions for selection. While the name implies a focus on async patterns, the absence of any comparative context leaves the agent to infer usage, which may lead to choosing the wrong analyzer.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
analyze_connection_poolingB
Detect database client or pool creation inside request handlers, loops, or other hot paths.
| Name | Required | Description | Default |
|---|---|---|---|
| projectPath | Yes | Absolute or relative path to the Node.js project to analyze |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It states only the detection action but does not mention side effects, read-only nature, performance implications, or output format. The lack of behavioral detail is a significant gap for an analysis tool.
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, focused sentence that conveys the core purpose immediately. No unnecessary wording or redundancy, making it highly concise and well-structured.
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?
For a tool with a single parameter and no output schema, the description is adequate but incomplete. It does not mention expected output, return format, or how results are presented, nor does it provide guidance on alternatives. An agent might need additional context to use it effectively.
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 already fully describes the single parameter 'projectPath' with 100% description coverage. The tool description adds no extra meaning or context for the parameter, so baseline score of 3 is appropriate.
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 clearly states the verb 'detect' and specific resource 'database client or pool creation' within defined contexts ('request handlers, loops, or other hot paths'). It distinguishes itself from siblings like analyze_database_queries by focusing on connection pooling patterns, though it does not explicitly reference siblings.
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 when to use the tool (when you want to detect connection pooling issues in hot paths) but provides no explicit guidance on when not to use it or mention of alternative tools. Usage is implied but not fully elaborated.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
analyze_database_queriesA
Detect MongoDB/PostgreSQL query anti-patterns such as N+1 queries, unbounded finds, and sequential query calls.
| Name | Required | Description | Default |
|---|---|---|---|
| projectPath | Yes | Absolute or relative path to the Node.js project to analyze |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full disclosure burden. It states what is detected but not how the tool behaves — whether it performs static code scanning or connects to live databases, whether credentials or a running instance are required, or what the return format looks like. 'Detect' implies a read-only analysis, but the mechanism, prerequisites, and side-effect profile are undisclosed.
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?
A single, tightly-packed sentence that leads with the verb and detection scope, then supplies concrete anti-pattern examples. There is zero filler and the most important information is front-loaded. Efficient and well-structured.
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?
Adequate but gapped. The purpose and single parameter are fully covered, but for a detection tool with no output schema and no annotations, the agent is left without guidance on what the analysis returns, what prerequisites exist (a Node.js project using these databases), or what the tool's behavior is at runtime. These gaps matter more given the absence of structured annotations and an output schema.
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 100%, with projectPath fully documented as 'Absolute or relative path to the Node.js project to analyze'. The description adds no additional parameter meaning beyond what the schema provides, so the baseline of 3 applies — the schema carries the weight adequately.
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 ('Detect') plus a clear resource ('MongoDB/PostgreSQL query anti-patterns') and enumerates concrete examples (N+1 queries, unbounded finds, sequential query calls). This clearly differentiates it from its siblings — analyze_indexes targets indexes, analyze_connection_pooling targets connections, analyze_async_patterns targets async code — leaving no ambiguity about what this tool covers.
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 purpose implies the usage context (use when analyzing database access patterns in a Node.js project), but the description never explicitly states when to choose this tool over its overlapping siblings, particularly analyze_indexes which lives in the same database-performance domain. There is no when-not-to-use guidance or named alternative, leaving the agent to infer the boundary.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
analyze_dependenciesA
Analyze package.json and lockfile for dependency hygiene issues including unused and misclassified packages.
| Name | Required | Description | Default |
|---|---|---|---|
| projectPath | Yes | Absolute or relative path to the Node.js project to analyze |
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 of behavioral disclosure. It states the action ('Analyze') but does not explicitly disclose whether the operation is read-only or has side effects (e.g., modifies files, requires network access). For a tool that likely only reads files, this is a gap in transparency.
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?
A single, front-loaded sentence with no filler. It immediately states the target and the value, making it easy for an agent to grasp the tool's purpose at a glance.
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?
Given the tool's simplicity (one parameter, no nested objects, no output schema), the description adequately explains what the tool does and what it analyzes. It does not cover the output format, but since no output schema is provided, that is not required. The description alone is sufficient for an agent to decide when to call this tool.
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 input schema already provides a clear description for projectPath ('Absolute or relative path to the Node.js project to analyze'), and schema coverage is 100%. The description does not add extra meaning beyond the schema—it only contextualizes the parameter by mentioning the files that will be examined, which is marginal.
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 specifies a clear verb ('Analyze'), a precise resource ('package.json and lockfile'), and a concrete goal ('dependency hygiene issues including unused and misclassified packages'). It distinguishes itself from sibling tools like analyze_project or analyze_database_queries by naming the exact files and intent, leaving no ambiguity about scope.
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 clearly implies when to use this tool (when dependency hygiene is the concern), but it does not explicitly state exclusions or reference alternative tools. There is no 'use this instead of X when...' guidance, so usage context is 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.
analyze_indexesB
Analyze MongoDB query patterns against createIndex definitions to surface potential missing indexes.
| Name | Required | Description | Default |
|---|---|---|---|
| projectPath | Yes | Absolute or relative path to the Node.js project to analyze |
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 of disclosure. While 'Analyze' implies a read-only operation, the description does not explicitly state that no files are modified, whether a MongoDB connection is required, or what the output format looks like beyond 'surface potential missing indexes'. It fails to disclose any side effects or operational requirements, which is a significant gap given the lack of annotations.
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 with no filler. It front-loads the action ('Analyze') and immediately specifies the subject and intended outcome. Every word earns its place; there is no redundancy or irrelevant detail.
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 with one fully documented parameter and a clear outcome in the description. It explains what the tool does and what it surfaces, which is adequate for a read-only analysis tool. However, it does not mention any limitations, prerequisites, or how results are presented, which would improve completeness. Given the simplicity, a 4 is slightly generous but defensible as it covers the core use case.
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 100%, with projectPath fully described as 'Absolute or relative path to the Node.js project to analyze'. The description adds no additional meaning to the parameter – it merely mentions 'MongoDB query patterns' without tying it to the parameter. Per the rubric, a baseline of 3 is appropriate when the schema already covers the parameter.
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 ('Analyze'), a clear resource ('MongoDB query patterns against createIndex definitions'), and an explicit outcome ('surface potential missing indexes'). It clearly distinguishes itself from siblings by focusing specifically on index analysis, whereas siblings like analyze_database_queries cover broader query behavior.
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 provides no guidance on when to use this tool versus the alternatives. It does not mention any conditions, prerequisites, or scenarios where this tool is preferable to analyze_database_queries or analyze_project. Without this, an agent cannot confidently decide when to invoke it.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
analyze_projectB
Analyze a Node.js backend project for performance issues across database, async, pooling, and dependencies.
| Name | Required | Description | Default |
|---|---|---|---|
| projectPath | Yes | Absolute or relative path to the Node.js project to analyze |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of disclosing behavioral traits. It only says 'analyze' implying a read-only operation, but does not state whether it executes code, whether it requires network access, what output format is returned, or if any side effects occur. For a tool that ostensibly scans a codebase, this is a significant gap.
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, tight sentence that leads with the verb and scope, and enumerates the analysis dimensions. It contains no filler or redundancy, earning a high score for efficiency. A slight deduction because it is almost too terse, omitting useful details that would not hurt conciseness.
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?
Given the presence of five specialized sibling tools, the description should clarify the relationship (e.g., that this is an aggregate analysis and that more focused tools exist). It also does not mention what the output contains, how long it might take, or any prerequisites. The one-parameter input is simple, but the tool's purpose is broad, so the description is under-specified for an agent to confidently call it.
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 coverage is 100%: the single parameter, projectPath, already has a clear description ('Absolute or relative path to the Node.js project to analyze'). The tool description adds no further meaning about the parameter beyond what the schema provides, so the baseline score of 3 is appropriate.
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 ('Analyze') and resource ('Node.js backend project'), with a clear scope: performance issues across database, async, pooling, and dependencies. This distinguishes it from the specialized sibling tools, which each target a single concern. The purpose is unambiguous and immediately actionable.
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 is the broad, comprehensive analysis tool compared to siblings like analyze_database_queries or analyze_async_patterns, but it does not explicitly state when to use this versus those alternatives, nor does it provide any 'when not to use' guidance. The usage context is inferred from the scope listed rather than stated.
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.
6 tool updates
v0.1.0- First observed
analyze_async_patterns - First observed
analyze_connection_pooling - First observed
analyze_database_queries - First observed
analyze_dependencies - First observed
analyze_indexes - First observed
analyze_project
TDQS
Scored across 6 tools
Each tool targets a clearly distinct performance concern: project-wide analysis, database queries, indexes, async patterns, connection pooling, and dependencies. There is no overlap or ambiguity in their purposes.
All tool names follow the identical 'analyze_<topic>' pattern, making it predictable and easy to infer the function of each tool from its name. No mixed conventions or inconsistent verbs.
Six tools is well-scoped for a performance analysis server. Each tool addresses a distinct aspect of backend performance without redundancy, and the count feels neither thin nor overwhelming.
The tool covers major performance domains: database queries, indexes, async patterns, connection pooling, dependencies, and a project overview. Minor potential gaps like memory or caching analysis are absent, but the core performance concerns are well represented.
Maintenance
Related MCP Connectors
Provide AI-powered real-time analysis and intelligence on NPM packages, including security, depend…
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
Read-only AI coding tools for change verification, release readiness, capacity, and guidance.
AI-powered codebase analysis — call graphs, security, dead code, complexity. 150+ tools.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables MCP-compatible clients to inspect Next.js codebases, analyze App Router and Pages Router structure, discover API routes, and audit build performance through controlled tools.12 npmMIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to scan code for security and quality issues and receive machine-readable reports with suggested fixes and verification criteria.83 npm2MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to analyze code health in TypeScript/JavaScript projects, providing tools to run analysis, start a dashboard, and get summaries.11 npm3MIT
- FlicenseBqualityCmaintenanceEnables AI agents to perform comprehensive, zero-infrastructure codebase analysis through 24 MCP tools, covering security, quality, architecture, type safety, git history, and dead code detection with high precision and local privacy.45-