PR Guardian MCP
Analyzes GitHub Pull Request diffs for security vulnerabilities and data leakage, with deterministic filtering for non-code changes to save costs.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@PR Guardian MCPanalyze PR #42 diff for security issues"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
PR Guardian MCP
Servidor Model Context Protocol (MCP) open-source que analisa diffs de Pull Requests do GitHub com foco em segurança e vazamento de dados.
A arquitetura prioriza economia de tokens: a maioria dos PRs (docs, CSS, formatação) é aprovada por lógica nativa TypeScript, sem chamar a LLM. Apenas mudanças em arquivos de lógica disparam análise via LangGraph + Claude 3.5 Haiku.
Arquitetura
flowchart TD
A[MCP Tool: analyze_pr_diff] --> B[LangGraph: classify]
B --> C{Filtro Determinístico}
C -->|docs / css / formatação| D[auto_approve]
C -->|.ts / .tsx / outros riscos| E[ai_analyze]
E --> F[Claude 3.5 Haiku]
F --> G[Zod Validation]
D --> G
G --> H[Resposta MCP estruturada]
subgraph Observabilidade
F -.->|trace| LS[LangSmith]
end1. Filtro Determinístico (custo zero)
Antes de qualquer chamada à API da Anthropic, o nó classify executa regras nativas em TypeScript:
Condição | Ação |
Apenas | Aprovação automática |
Diff altera somente whitespace (formatação) | Aprovação automática |
Presença de | Encaminha para IA |
Outros arquivos fora do escopo seguro | Encaminha para IA |
Por que isso importa? Em repositórios reais, uma parcela significativa dos PRs altera apenas documentação, estilos ou formatação. Enviar esses diffs para uma LLM gera:
Custo desnecessário — tokens de entrada/saída cobrados sem valor de segurança
Latência — 1–3s adicionais por PR trivial
Ruído — falsos positivos em conteúdo que não executa código
O filtro determinístico responde em microssegundos, com custo $0.00.
2. Filtro de IA (LangGraph)
Quando arquivos de lógica são detectados, o grafo aciona o nó ai_analyze:
Modelo: Claude 3.5 Haiku (
claude-3-5-haiku-20241022)Escopo: apenas riscos de segurança e vazamento de dados
Saída: JSON estruturado via
withStructuredOutput
Categorias analisadas: secret_leak, injection, auth_bypass, data_exposure, dependency_risk.
3. Validação (Zod)
Toda resposta — determinística ou da LLM — passa pelo nó validate_result e é parseada com PrAnalysisResultSchema antes de retornar ao cliente MCP. Respostas malformadas da LLM são rejeitadas com erro explícito.
4. Observabilidade (LangSmith)
Chamadas LLM são rastreadas automaticamente quando:
LANGCHAIN_TRACING_V2=true
LANGCHAIN_API_KEY=lsv2_...
LANGCHAIN_PROJECT=pr-guardian-mcpNo dashboard do LangSmith você visualiza latência, tokens consumidos e custo estimado por execução do grafo.
Related MCP server: CodePeel MCP Server
Estrutura do Projeto
pr-guardian-mcp/
├── src/
│ ├── index.ts # Servidor MCP (stdio)
│ ├── graph.ts # LangGraph: classify → auto_approve | ai_analyze → validate
│ ├── schema.ts # Schemas Zod (input, output, LLM)
│ ├── deterministic-filter.ts # Lógica de filtro nativo (custo zero)
│ └── langsmith.ts # Configuração de observabilidade
├── Dockerfile
├── docker-compose.yml
├── .env.example
├── package.json
└── tsconfig.jsonPré-requisitos
Node.js ≥ 20
Chave da API Anthropic (apenas para PRs com arquivos de lógica)
Chave do LangSmith (opcional, recomendado)
Instalação
git clone https://github.com/seu-usuario/pr-guardian-mcp.git
cd pr-guardian-mcp
npm install
cp .env.example .env
# Edite .env com suas chavesUso Local
# Desenvolvimento
npm run dev
# Build + produção
npm run build
npm startConfiguração no Cursor / Claude Desktop
Adicione ao arquivo de configuração MCP:
{
"mcpServers": {
"pr-guardian-mcp": {
"command": "node",
"args": ["/caminho/absoluto/pr-guardian-mcp/dist/index.js"],
"env": {
"ANTHROPIC_API_KEY": "sk-ant-...",
"LANGCHAIN_TRACING_V2": "true",
"LANGCHAIN_API_KEY": "lsv2_...",
"LANGCHAIN_PROJECT": "pr-guardian-mcp"
}
}
}
}Ferramenta MCP
analyze_pr_diff
Parâmetro | Tipo | Obrigatório | Descrição |
|
| Sim | Diff unified do PR (formato git) |
|
| Não | Título do PR para contexto |
|
| Não | Número do PR |
Exemplo de resposta:
{
"approved": true,
"path": "deterministic",
"reason": "Alterações exclusivas em documentação (.md) ou estilos (.css) — aprovado sem chamada à LLM.",
"findings": [],
"metadata": {
"analyzedAt": "2026-07-15T18:00:00.000Z",
"filesChanged": ["README.md", "docs/guide.md"],
"tokenCostSaved": true
}
}Docker
Build e execução
docker build -t pr-guardian-mcp .
docker run -i --rm \
-e ANTHROPIC_API_KEY=sk-ant-... \
-e LANGCHAIN_TRACING_V2=true \
-e LANGCHAIN_API_KEY=lsv2_... \
-e LANGCHAIN_PROJECT=pr-guardian-mcp \
pr-guardian-mcpDocker Compose
cp .env.example .env
docker compose up --buildO container expõe o servidor via stdio (-i), compatível com clientes MCP que lançam processos filhos.
Stack
Pacote | Papel |
| Servidor MCP |
| Orquestração do fluxo Determinístico vs IA |
| Integração Claude 3.5 Haiku |
| Validação estrita de input/output |
| Tracing de custo e latência |
Licença
MIT
Available Tools
1 toolanalyze_pr_diffAnalisar diff de Pull RequestA
Analisa um diff de PR do GitHub focando em riscos de segurança e vazamento de dados. Aplica filtro determinístico (custo zero) para docs/estilos/formatação antes de acionar a LLM.
| Name | Required | Description | Default |
|---|---|---|---|
| diff | Yes | ||
| prTitle | No | ||
| prNumber | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| path | Yes | |
| reason | Yes | |
| approved | Yes | |
| findings | Yes | |
| metadata | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The description discloses a behavioral detail: applying a deterministic filter before calling the LLM. However, it does not mention any side effects, authentication needs, or whether it is read-only. With no annotations provided, this leaves gaps 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?
Two concise sentences front-load the purpose and add a key behavioral detail. Every part earns its place with no filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
An output schema exists, so return values are covered. However, parameter descriptions are missing, and usage context is vague. The description could better prepare the agent for parameter semantics and boundaries.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0% (no descriptions in input schema), so the description must explain parameters. It mentions 'diff' indirectly but does not describe 'prTitle' or 'prNumber', leaving their purpose unclear.
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 action ('analisa um diff de PR do GitHub') with a focused purpose ('riscos de segurança e vazamento de dados'). It distinguishes itself as a security analysis tool, and since there are no sibling tools, differentiation is not required.
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 usage for security analysis of PR diffs and mentions a filter for non-code files, but it does not explicitly specify when to use the tool, when not to, or provide alternatives. The guidance is implied but not explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
1 tool update
v0.1.0- First observed
analyze_pr_diff
TDQS
Scored across 1 tool
Only one tool exists, so there is no ambiguity in tool selection.
With a single tool, naming consistency is perfect as there is no pattern to compare.
The server has only one tool, which is on the low end for typical MCP servers. However, the narrow focus on PR diff analysis justifies the minimal count.
The single tool fully covers its stated purpose of analyzing PR diffs for security risks, but the server lacks additional tools for follow-up actions like reporting or issue creation.
Maintenance
Related MCP Connectors
Screens public GitHub repos and PRs to generate risk maps, findings, and merge-readiness signals.
Risk-scan a diff, flag AI-generated-code tells, find secrets. 5 of 7 tools need no account.
Security reviews for coding agents: diffs checked against your org policy and live infrastructure.
- VulX WatchOAuthai.vulx
Independent security review for AI-built apps. Watch a GitHub repo. Never a patch.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceAnalyzes GitHub Pull Requests using AI via MCP, providing detailed feedback and approve/reject decisions.7 npm1MIT

CodePeel MCP Serverofficial
FlicenseAqualityDmaintenanceEnables AI agents to review code diffs for bugs, security issues, and bad patterns, and generate fixes.4-- FlicenseNot gradedqualityDmaintenanceScans GitHub repositories for security vulnerabilities by cloning, performing static analysis, secret detection, build verification, and AI-powered OWASP-aligned code review, producing a scored SECURITY.md report.-

gitlumen-mcpofficial
FlicenseAqualityDmaintenanceEnables AI agents to screen GitHub repositories and pull requests for risk analysis, generating risk scores, findings, and merge-readiness signals.5-