rfcxml-mcp
Servidor MCP para compreensão estrutural de documentos RFC.
Documentação
Servidor MCP RFCXML
README em japonês · Documentação
Um servidor Model Context Protocol (MCP) para compreensão estruturada de documentos RFC.
Propósito
Diferente dos servidores MCP de RFC baseados em texto, este servidor aproveita a estrutura semântica do RFCXML para permitir:
- Extração de requisitos normativos (MUST/SHOULD/MAY) com saída estruturada
- Construção de grafo de dependências de RFC
- Gerenciamento de escopo de definições
- Geração de listas de verificação de implementação
Arquitetura
┌─────────────────────────┐
│ Markdown / PDF │ Display & Sharing
├─────────────────────────┤
│ Translation │ Explanation & Verification
├─────────────────────────┤
│ RFCXML MCP │ Common Understanding for AI & Humans
├─────────────────────────┤
│ RFCXML │ Single Source of Truth
└─────────────────────────┘
Comparação com MCPs Existentes
| Recurso | mcp-rfc existente | RFCXML MCP |
|---|---|---|
| Recuperação de texto de RFC | ✅ | ✅ |
| Extração de seções | ✅ (baseado em texto) | ✅ (baseado em estrutura) |
| Extração de MUST/SHOULD/MAY | ❌ | ✅ |
| Estruturação de condições/exceções | ❌ | ✅ |
| Grafo de dependências de RFC | ❌ | ✅ |
| Gerenciamento de escopo de definições | ❌ | ✅ |
| Lista de verificação de implementação | ❌ | ✅ |
Início Rápido
Uso com Claude Desktop / Claude Code
Adicione o seguinte ao seu arquivo de configuração do MCP:
{
"mcpServers": {
"rfcxml": {
"command": "npx",
"args": ["-y", "@shuji-bonji/rfcxml-mcp"]
}
}
}
Para fixar uma versão (a 0.6.x lança correções com frequência), escreva a versão na especificação do pacote:
{
"mcpServers": {
"rfcxml": {
"command": "npx",
"args": ["-y", "@shuji-bonji/rfcxml-mcp@0.6.53"]
}
}
}
Para manter os RFCs baixados em disco entre reinicializações, passe RFCXML_CACHE_DIR (veja Cache em disco e rfcxml-prefetch):
{
"mcpServers": {
"rfcxml": {
"command": "npx",
"args": ["-y", "@shuji-bonji/rfcxml-mcp@0.6.53"],
"env": { "RFCXML_CACHE_DIR": "/home/you/.cache/rfcxml-mcp" }
}
}
}
Locais dos arquivos de configuração:
- Claude Desktop (macOS):
~/Library/Application Support/Claude/claude_desktop_config.json - Claude Desktop (Windows):
%APPDATA%\Claude\claude_desktop_config.json - Claude Code (escopo do projeto):
.mcp.jsonna raiz do projeto - Claude Code (escopo do usuário):
~/.claude.json - Claude Code (CLI):
claude mcp add rfcxml -- npx -y @shuji-bonji/rfcxml-mcp
Instalação (Opcional)
Para instalação global:
npm install -g @shuji-bonji/rfcxml-mcp
Em seguida, configure o MCP:
{
"mcpServers": {
"rfcxml": {
"command": "rfcxml-mcp"
}
}
}
Ferramentas Disponíveis
Fase 1: Estrutura Básica
get_rfc_structure- Obter hierarquia de seções e metadadosget_requirements- Extrair requisitos normativos (MUST/SHOULD/MAY) com estruturaget_definitions- Obter definições de termos e seu escopo
Fase 2: Relacionamentos
get_rfc_dependencies- Obter RFCs referenciados (normativos/informativos)get_related_sections- Obter seções relacionadas dentro do mesmo RFC
Fase 3: Suporte à Verificação
validate_statement- Encontrar os requisitos do RFC que incidem sobre uma declaração e relatar contradições detectadas. Isso não é um julgamento de conformidade:isValidtem três valores (null= nada correspondeu com força suficiente para julgar,false= uma contradição foi detectada,true= nenhuma contradição foi detectada entre as correspondências). O veredito é seu.generate_checklist- Gerar lista de verificação de implementação
Suporte a RFCs Legados
RFCs publicados após o RFC 8650 (dezembro de 2019) estão disponíveis no formato oficial RFCXML v3. RFCs anteriores podem não ter XML disponível.
Este servidor inclui funcionalidade de fallback automático — quando o XML não está disponível, ele analisa o formato de texto.
Informações de Origem
Todas as respostas incluem informações de origem:
{
"rfc": 6455,
"sections": [...],
"_source": "text",
"_sourceNote": "Warning: Parsed from text format. Accuracy may be limited."
}
_source | Descrição |
|---|---|
xml | Analisado do RFCXML (alta precisão) |
text | Analisado do texto (precisão média) |
Compatibilidade
| RFC | Formato | Observações |
|---|---|---|
| RFC 8650+ | XML | Suporte oficial RFCXML v3 |
| Antes do RFC 8650 | Texto | Fallback automático |
Exemplos de Saída
Cada exemplo abaixo é extraído da saída real da versão atual (npm run build, depois a chamada de ferramenta listada por meio de um cliente MCP). Nomes de campos e valores são verbatim; arrays longos são cortados com ....
get_rfc_structure - Obter Estrutura do RFC
get_rfc_structure { "rfc": 9293 }
{
"metadata": {
"title": "Transmission Control Protocol (TCP)",
"docName": "draft-ietf-tcpm-rfc793bis-28",
"number": 9293,
"date": "2022-08",
"category": "std",
"stream": "IETF",
"abstract": "This document specifies the Transmission Control Protocol (TCP). ..."
},
"sections": [
{ "number": "1", "title": "Purpose and Scope" },
{ "number": "2", "title": "Introduction" },
{
"number": "3",
"title": "Functional Specification",
"subsections": [
{ "number": "3.1", "title": "Header Format" },
{
"number": "3.5",
"title": "Establishing a Connection",
"subsections": [
{ "number": "3.5.1", "title": "Half-Open Connections and Other Anomalies" },
{ "number": "3.5.2", "title": "Reset Generation" },
{ "number": "3.5.3", "title": "Reset Processing" }
]
}
]
}
],
"referenceCount": { "normative": 15, "informative": 85 },
"_source": "xml"
}
number é o número da seção como impresso no RFC (3.5, A.2), não o pn do RFCXML (section-3.5). category / stream / abstract vêm da API do IETF Datatracker e são omitidos quando a API está inacessível ou relata um valor fora do mapeamento (por exemplo, RFC 1 é unkn / legacy); nesse caso, _sourceNote informa isso.
get_requirements - Extrair Requisitos Normativos
get_requirements { "rfc": 9293, "level": "MUST" }
{
"rfc": 9293,
"filter": { "section": "all", "level": "MUST" },
"stats": { "total": 55, "byLevel": { "MUST": 55 } },
"requirements": [
{
"id": "R-3.5-1",
"level": "MUST",
"text": "A TCP implementation MUST support simultaneous open attempts (MUST-10).",
"section": "3.5",
"sectionTitle": "Establishing a Connection",
"fullContext": "A TCP implementation MUST support simultaneous open attempts (MUST-10).",
"subject": "tcp implementation",
"action": "support simultaneous open attempts (MUST-10)"
},
{
"id": "R-3.7.1-1",
"level": "MUST",
"text": "TCP endpoints MUST implement both sending and receiving the MSS Option (MUST-14).",
"section": "3.7.1",
"sectionTitle": "Maximum Segment Size Option",
"fullContext": "TCP endpoints MUST implement both sending and receiving the MSS Option (MUST-14).",
"subject": "tcp endpoints",
"action": "implement both sending and receiving the MSS Option (MUST-14)"
}
],
"_source": "xml"
}
id é R-<section>-<n> com n numerado por seção, para que o identificador permaneça estável quando requisitos são adicionados em outro lugar do documento.
get_rfc_dependencies - Obter Dependências do RFC
get_rfc_dependencies { "rfc": 9293 }
{
"rfc": 9293,
"normative": [
{ "rfcNumber": 791, "title": "Internet Protocol", "anchor": "RFC0791" },
{ "rfcNumber": 1191, "title": "Path MTU discovery", "anchor": "RFC1191" },
{
"rfcNumber": 2119,
"title": "Key words for use in RFCs to Indicate Requirement Levels",
"anchor": "RFC2119"
}
],
"informative": [
{ "rfcNumber": 793, "title": "Transmission Control Protocol", "anchor": "RFC0793" },
{ "rfcNumber": 896, "title": "Congestion Control in IP/TCP Internetworks", "anchor": "RFC0896" }
],
"_source": "xml",
"_referencesSource": "xml"
}
_referencesSource informa de onde veio a lista de referências: xml (RFCXML <references>), text (a seção References do texto simples) ou api (Datatracker relateddocument, com títulos provisórios).
generate_checklist - Gerar Lista de Verificação de Implementação
generate_checklist { "rfc": 9293, "role": "client", "sections": ["3.5", "3.7.1"] } — o campo markdown:
# RFC 9293 Implementation Checklist
**Transmission Control Protocol (TCP)**
Role: client
Generated: 2026-09-04T17:09:37.833Z
## Mandatory Requirements (MUST / REQUIRED / SHALL)
- [ ] **MUST** A TCP implementation MUST support simultaneous open attempts (MUST-10). (§3.5)
- [ ] **MUST** TCP endpoints MUST implement both sending and receiving the MSS Option (MUST-14). (§3.7.1)
- [ ] **MUST** If an MSS Option is not received at connection setup, TCP implementations MUST assume a default send MSS of 536 (576 - 40) for IPv4 or 1220 (1280 - 60) for IPv6 (MUST-15). (§3.7.1)
## Recommended Requirements (SHOULD / RECOMMENDED)
- [ ] **SHOULD** TCP implementations SHOULD allow a received RST segment to include data (SHLD-2). (§3.5.3)
A mesma chamada também retorna "stats": { "must": 6, "should": 2, "may": 1, "total": 9 }.
validate_statement - Encontrar Requisitos Incidentes
validate_statement { "rfc": 6455, "statement": "The client MUST mask all frames sent to the server." }
{
"rfc": 6455,
"statement": "The client MUST mask all frames sent to the server.",
"analysis": { "detectedLevel": "MUST", "detectedSubject": "client" },
"isValid": true,
"matchingRequirements": [
{
"id": "R-5.3-2",
"level": "MUST",
"text": "When preparing a masked frame, the client MUST pick a fresh masking key from the set of allowed 32-bit values.",
"section": "5.3",
"sectionTitle": "Client-to-Server Masking",
"_matchScore": 17,
"_matchedKeywords": ["client", "mask", "frames"],
"_subjectMatch": true,
"_levelMatch": true
}
],
"conflicts": [],
"_source": "text",
"_sourceNote": "Warning: Parsed from text format. Validation accuracy may be limited."
}
isValid: true significa apenas que nenhuma contradição foi detectada entre os requisitos correspondentes. Quando nada corresponde com força suficiente, isValid é null e _verdictNote explica o motivo.
Saída de Fallback de Texto (RFCs Legados)
get_rfc_structure { "rfc": 6455 } — o RFC 6455 é anterior ao RFCXML v3, então o texto simples é analisado:
{
"metadata": {
"title": "The WebSocket Protocol",
"number": 6455,
"date": "2011-12",
"category": "std",
"stream": "IETF",
"abstract": "The WebSocket Protocol enables two-way communication ..."
},
"sections": [
{ "number": "1", "title": "Introduction" },
{ "number": "2", "title": "Conformance Requirements" },
{ "number": "5", "title": "Data Framing" }
],
"referenceCount": { "normative": 18, "informative": 9 },
"_source": "text",
"_sourceNote": "Warning: Parsed from text format. Accuracy may be limited."
}
Para RFCs 8650 e posteriores, o XML é tentado primeiro. Se todas as fontes de XML retornarem 404, a chamada falha ("Nenhum RFC com esse número foi publicado"). Se a busca de XML falhar por outro motivo (5xx, timeout), o texto é usado e _sourceNote informa que a busca de XML falhou e pode ser temporária.
Cache em disco e rfcxml-prefetch
Por padrão, os RFCs baixados ficam apenas em um cache LRU em memória e são baixados novamente após cada reinicialização. Defina RFCXML_CACHE_DIR para mantê-los em disco:
$RFCXML_CACHE_DIR/
├── xml/rfc9293.xml # RFCXML (RFC 8650 and later)
└── text/rfc6455.txt # plain text (older RFCs, or XML fetch failures)
O pacote também inclui um CLI rfcxml-prefetch que preenche o mesmo layout antecipadamente, para uso offline ou em CI:
# Fetch a range into $RFCXML_CACHE_DIR (or ~/.cache/rfcxml-mcp when unset)
npx -y -p @shuji-bonji/rfcxml-mcp rfcxml-prefetch --range 9110-9114
# Individual RFCs, explicit directory, re-download even if cached
npx -y -p @shuji-bonji/rfcxml-mcp rfcxml-prefetch --rfc 6455 --rfc 9293 --cache-dir ./rfc-cache --force
Opções: --range A-B, --rfc N (repetível), --cache-dir DIR, --concurrency N (padrão 3), --force. RFCs já em disco (XML ou texto) são ignorados, a menos que --force seja fornecido. Os números de RFC devem conter apenas dígitos; --rfc 9110abc sai com código 1.
Exemplos
Veja o diretório examples/ para exemplos completos de listas de verificação:
| RFC | Protocolo | Origem |
|---|---|---|
| RFC 6455 | WebSocket | Texto (fallback) |
| RFC 9293 | TCP | RFCXML |
| RFC 7540 | HTTP/2 | Texto (fallback) |
Exemplo de prompt para Claude:
Generate an implementation checklist for RFC 9293 (TCP).
Arquitetura Interna
Estrutura de Módulos
src/
├── index.ts # MCP server entry point
├── config.ts # Centralized configuration
├── constants.ts # BCP 14 keyword definitions + RFC number limits
├── services/
│ ├── rfc-fetcher.ts # RFC fetching (parallel)
│ ├── rfc-service.ts # RFC parse & cache management
│ ├── rfcxml-parser.ts # RFCXML parser
│ ├── rfc-text-parser.ts # Text fallback parser
│ └── checklist-generator.ts # Checklist generation service
├── tools/
│ ├── definitions.ts # MCP tool definitions
│ └── handlers.ts # Tool handlers (toolHandlers map)
├── types/
│ └── index.ts # Type definitions
└── utils/
├── cache.ts # LRU cache
├── fetch.ts # Parallel fetch utility
├── logger.ts # Logger abstraction
├── requirement-extractor.ts # Shared requirement extraction
├── section.ts # Section search utilities
├── statement-matcher.ts # Weighted statement matching
├── text.ts # Text processing utility
└── validation.ts # Input validation
Otimização de Busca de RFC
Envia requisições paralelas para as duas fontes de XML (RFC Editor, Datatracker) e usa a primeira resposta bem-sucedida. tools.ietf.org foi descontinuado em 2021 e não é usado. Não há nova tentativa; a corrida paralela é a única redundância.
┌─────────────────┐
│ fetchRFCXML() │
└────────┬────────┘
│ Parallel requests
┌────┴─────────┐
▼ ▼
┌────────┐ ┌────────┐
│RFC │ │Data- │
│Editor │ │tracker │
└────┬───┘ └────┬───┘
│ │
└──────┬──────┘
│ Promise.any (first success)
▼
┌───────────┐
│ Successful│ → Cancel other requests via AbortController
│ Response │
└───────────┘
Chamadas concorrentes para o mesmo RFC (por exemplo, get_rfc_structure e get_requirements emitidas em paralelo) compartilham uma única busca em andamento e uma única análise.
Estratégia de Cache
Cache LRU (Least Recently Used) com limites de memória, além do cache em disco opcional (RFCXML_CACHE_DIR) abaixo dos caches de XML / texto:
| Cache | Máx. de Entradas | Conteúdo |
|---|---|---|
| Cache de XML | 20 | RFCXML bruto |
| Cache de Texto | 20 | Texto bruto |
| Cache de Metadados | 100 | Metadados de RFC |
| Cache de Análise | 50 | Estrutura analisada |
Desenvolvimento
# Install dependencies
npm install
# Development mode
npm run dev
# Build
npm run build
# Unit tests (single run) / watch mode
npm test
npm run test:watch
# E2E test (MCP client integration; fetches a few real RFCs)
npm run test:e2e
# Audit against real RFCs, tool-to-tool crosscheck, output snapshots
# (see tests/audit/README.md; run weekly by .github/workflows/audit.yml)
npm run audit
npm run crosscheck
npm run snapshot
# Lint
npm run lint
# Format
npm run format
Licença
MIT
Projetos Relacionados
- mjpitz/mcp-rfc - MCP de RFC baseado em texto
- ietf-tools/RFCXML - Esquema RFCXML
- xml2rfc - Ferramenta oficial do IETF