convez.ai
MCP ServerDados & AnalyticsAvançado
sinan-ozel

Motor de Consulta de Campanhas RPG com Grafo de Conhecimento

sinan-ozel/campaign-setting-query-engine

Consultas de lore sem alucinações para Mestres de Dungeon

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP que indexa sourcebooks de RPG de mesa em um grafo de conhecimento OWL, permitindo consultas de lore precisas via SPARQL sem alucinações. Construído para Eberron, cada resposta cita as páginas de origem. Processa PDFs automaticamente, extrai entidades (NPCs, locais, facções) e expõe ferramentas MCP para agentes Claude consultarem a base de conhecimento.

Instalação

$npx convez-ai sinan-ozel/campaign-setting-query-engine

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
57%
Último commit
há 3 semanas
Versão
v0.2.0
Issues abertas
1
Contribuidores
1

Casos de uso

  • Mestres de RPG consultando lore canônica durante sessões
  • Agentes Claude extraindo informações de campanhas tabulares
  • Engenheiros de conhecimento indexando domínios especializados em grafos OWL

Veredito

Implementação técnica sólida com arquitetura de produção (Fuseki, Redis, MinIO, workers distribuídos). Serve bem casos específicos de retrieval com garantia de rastreabilidade — ideal para domínios onde alucinações são inaceitáveis. Nicho especializado: não é para consultas gerais.

README

A tradução para o português deste README ainda está na fila.

CI/CD License

Campaign Setting Query Engine

A knowledge graph–backed MCP server for precision lore retrieval from tabletop RPG campaign settings. Built for Eberron. Zero hallucinations — every answer cites a sourcebook page.

Canonical evaluation query: "List me the rivers of Eberron." Scored on precision + recall + F1 against ground truth extracted from the sourcebooks.


What it does

  1. Ingests PDF sourcebooks — submits a PDF + metadata YAML; a pdf-worker converts it to Markdown page-by-page (with OCR fallback and JPX error handling).
  2. Extracts entities — a graph-worker chunks the Markdown, classifies sections, and runs a single combined LLM call per chunk to extract NPCs, locations, factions, religions, deities, races, classes, and skills.
  3. Builds a knowledge graph — extracted entities are mapped to an OWL ontology and written to Apache Jena Fuseki as named-graph triples. OWL transitivity on cs:contains means "list everything in Xen'drik" returns all descendants automatically.
  4. Serves MCP tools — a FastMCP server exposes 6 tools that translate natural-language lore queries into SPARQL. Agents get structured answers with page references. No LLM at query time.

Architecture

Client / Agent
     │  MCP tools (/mcp)
     ▼
mcp-server  ──SPARQL──▶  Fuseki (OWL graph)
     │
     │  Admin HTTP (/ingest, /status, /admin/*)
     ▼
Streamlit dashboard

MinIO (/raw-pdfs, /markdown)
     │
     ├── pdf-worker   (PDF → Markdown, no LLM)
     └── graph-worker (Markdown → triples, LLM via LiteLLM)

Redis  (pipeline state, entity dedup index)
LLM    (external: llama.cpp / Ollama / OpenAI / Anthropic via config/llm.yaml)

Services:

ServiceImageDescription
mcp-serverDockerfileFastMCP tools + admin HTTP API
pdf-workerpdf_worker/DockerfilePDF → Markdown conversion
graph-workergraph_worker/DockerfileMarkdown → knowledge graph triples
dashboarddashboard/DockerfileStreamlit ingestion monitor
Fuseki 5.1.0stain/jena-fuseki:5.1.0SPARQL 1.1 graph store, OWL inference
Redis 7redis:7-alpinePipeline state, persistent (AOF)
MinIOminio/minioPDF and Markdown object storage

Quickstart

The only requirement is Docker.

1. Configure the LLM

Copy .env.example to .env and set your LLM endpoint:

cp .env.example .env
# Edit .env:
LLAMA_CPP_HOST=http://your-gpu-host:8080/v1

The LLM provider config lives in config/llm.yaml. The default is llama.cpp (OpenAI-compatible). Swap to Ollama, Mistral, OpenAI, or Anthropic by editing that file — no code changes needed:

# config/llm.yaml — llama.cpp (default)
api_base: ${LLAMA_CPP_HOST}
model: openai/gemma4:e2b
api_key: dummy
timeout: 150
# Ollama example
api_base: http://ollama:11434
model: ollama/gemma3:27b
# OpenAI example
model: gpt-4o
api_key: ${OPENAI_API_KEY}

2. Start the full stack

docker compose up --build

Services start in dependency order. Fuseki takes ~30 seconds on first boot (OWL reasoner init).

3. Submit a sourcebook

Via the dashboard at http://localhost:8501, or via the API:

curl -X POST http://localhost:8000/ingest \
  -F "pdf=@eberron_campaign_setting_3e.pdf" \
  -F 'metadata=document_id: eberron_campaign_setting_3e
title: "Eberron Campaign Setting (3.5e)"
edition: 3e
canon_type: canon
publisher: "Wizards of the Coast"
tags: [core-rulebook, setting-lore]'

Poll for progress:

curl http://localhost:8000/status/eberron_campaign_setting_3e

4. Query the graph

Connect any MCP client to http://localhost:8000/mcp. Available tools:

ToolExample
list_entitiesList all rivers, all factions, all NPCs in Breland
get_entityFull profile for "Lady Vol"
get_relationshipsAllies of "The Emerald Claw"
get_location_hierarchyEverything Xen'drik contains (transitive)
search_by_propertyNPCs with nationality "Karrnath"
get_ingestion_statusCurrent pipeline state per document

Configuration files

All live in config/ — version-controlled, mounted as ConfigMaps in Kubernetes:

FilePurpose
config/ontology.ttlOWL schema: classes, properties, cs:contains owl:TransitiveProperty
config/ingestion_config.yamlCoreference thresholds, chunking parameters
config/llm.yamlLiteLLM provider config — swap providers here
config/fuseki-config.ttlFuseki Assembler: wires OWL reasoner to TDB2 store

Development

VS Code tasks

Open Terminal → Run Task (Ctrl+Shift+P → Tasks: Run Task):

TaskWhat it runs
test: mcp-servermcp-server black-box tests (default)
test: pdf-workerpdf-worker black-box tests
test: graph-workergraph-worker black-box tests (needs LLM)
test: integrationFull pipeline: PDF in → graph query out
test: allAll four suites in series, stops on first failure
dev: startFull stack via docker-compose.yaml
dev: stopTear down the full stack
lintruff check on server/ and tests/
reformatblack + docformatter + isort
inspectorMCP Inspector at http://localhost:6274

Run a specific test suite

# mcp-server (no LLM needed)
docker compose -f tests/mcp_server/docker-compose.yml up --build --abort-on-container-exit --exit-code-from test-runner

# pdf-worker (no LLM needed)
docker compose -f tests/pdf_worker/docker-compose.yml up --build --abort-on-container-exit --exit-code-from test-runner

# graph-worker (needs LLAMA_CPP_HOST in .env)
docker compose -f tests/graph_worker/docker-compose.yml up --build --abort-on-container-exit --exit-code-from test-runner

# Full integration (needs LLAMA_CPP_HOST in .env)
docker compose -f tests/integration/docker-compose.yml up --build --abort-on-container-exit --exit-code-from test-runner

Lint and reformat

docker compose -f lint/docker-compose.yaml up --build --abort-on-container-exit
docker compose -f reformat/docker-compose.yaml up --build --abort-on-container-exit

Project structure

.
├── Dockerfile                   # mcp-server image
├── docker-compose.yaml          # full local dev stack
├── .env.example                 # copy to .env, set LLAMA_CPP_HOST
│
├── config/
│   ├── ontology.ttl             # OWL schema
│   ├── ingestion_config.yaml    # pipeline parameters
│   ├── llm.yaml                 # LiteLLM provider config ← edit this to swap LLMs
│   └── fuseki-config.ttl        # Fuseki Assembler (OWL inference)
│
├── server/                      # mcp-server: FastMCP tools + admin HTTP
│   ├── main.py                  # 6 MCP tools + /ingest /status /admin/* /health
│   ├── sparql.py                # SPARQL query builders
│   └── status.py                # Redis pipeline-state helpers
│
├── pdf_worker/
│   ├── Dockerfile
│   └── src/main.py              # PDF → Markdown, page-by-page, JPX fallback
│
├── graph_worker/
│   ├── Dockerfile
│   └── src/
│       ├── main.py              # poll loop, Redis lock, per-chunk progress
│       ├── chunker.py           # semantic heading-based Markdown chunker
│       ├── extractor.py         # LiteLLM classifier + combined entity extractor
│       └── mapper.py            # ontology mapper, coreference, triple writer
│
├── dashboard/
│   ├── Dockerfile
│   └── src/app.py               # Streamlit status monitor + submission form
│
├── tests/
│   ├── mcp_server/              # black-box: MCP tools, admin endpoints
│   ├── pdf_worker/              # black-box: PDF → Markdown pipeline
│   ├── graph_worker/            # black-box: Markdown → triples
│   └── integration/             # end-to-end: PDF in → query out
│
├── design/
│   ├── DESIGN.md                # architecture, ontology, pipeline design
│   └── EVALUATION.md            # evaluation queries and scoring
│
└── .github/workflows/ci.yaml    # CI/CD pipeline

Ontology

Namespace: http://campaignsetting.io/ontology# (prefix: cs:)

Key classes: NPC, Location (→ City, River, Nation, Region, Dungeon, Sea, Mountain, Forest, Ruin, Plane), Faction, Religion, Deity, Race, CharacterClass, Skill, PotentialMotive, SourceBook.

Key properties: cs:contains (owl:TransitiveProperty) for spatial containment, cs:mentionedIn linking entities to SourceBook nodes that carry cs:edition and cs:canonType.

Every result includes page_reference and source_book. Filtering by edition (3e, 4e, 5e) and canonicity (canon, kanon, community) works on all tools.


CI/CD

The workflow in .github/workflows/ci.yaml runs on every push:

reformat → lint
reformat → test (mcp-server suite)
         → detect-changes
              └── publish (main only)
                   └── publish-docs

Versioning is driven by server/__init__.py. Bump __version__ above the last git tag to trigger a stable Docker Hub release on the next main push.

Ver o original no GitHub

Bom para

Relacionados