8000 fix: enforce attack rules and harden storage, from the engine audit (part 2) by Mnehmos · Pull Request #114 · Mnehmos/mnehmos.rpg.mcp · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ jobs:

strategy:
matrix:
node-version: [18.x, 20.x, 22.x]
node-version: [20.x, 22.x]

steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "npm"
Expand Down
6 changes: 3 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

## This Repository

The reference backend game engine. **35 MCP tools** (31 consolidated action-routed + 4 meta/event) for complete RPG mechanics, including LLM-driven NPCs via `agent_manage` and the Operator's constraint-perception lens via `perception_manage`.
The reference backend game engine. **36 MCP tools** (31 consolidated action-routed + 5 meta/event) for complete RPG mechanics, including LLM-driven NPCs via `agent_manage` and the Operator's constraint-perception lens via `perception_manage`.
**Philosophy:** "LLM describes, engine validates" - Database is source of truth.
**Status:** Alpha - 2216 tests passing (7 skipped), 141 test files, MCP Protocol fully integrated
**Status:** Alpha - 2373 tests passing (7 skipped), 161 test files, MCP Protocol fully integrated

## Who consumes this engine

Expand Down Expand Up @@ -60,7 +60,7 @@ src/
├── utils/ # Action router, fuzzy matching
└── math/ # Dice, algebra, physics

tests/ # Mirror of src/ structure (141 files)
tests/ # Mirror of src/ structure (161 files)
docs/ # White paper, ADRs, LLM spatial guide
```

Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ npm install mnehmos.rpg.mcp

### Option 2: Standalone Binaries

Download pre-built binaries from [Releases](https://github.com/Mnehmos/rpg-mcp/releases):
Download pre-built binaries from [Releases](https://github.com/Mnehmos/mnehmos.rpg.mcp/releases):

```bash
# Windows
Expand All @@ -220,8 +220,8 @@ chmod +x rpg-mcp-linux && ./rpg-mcp-linux
### Option 3: From Source

```bash
git clone https://github.com/Mnehmos/rpg-mcp.git
cd rpg-mcp
git clone https://github.com/Mnehmos/mnehmos.rpg.mcp.git
cd mnehmos.rpg.mcp
npm install
npm run build
npm test # 2214 tests should pass
Expand Down Expand Up @@ -374,7 +374,7 @@ the consolidated contracts, and the adapter matrix is enforced by

```bash
npm test
# 2252 tests passing, 7 skipped
# 2373 tests passing, 7 skipped
# 148 test files
# Coverage across all 36 tools (31 consolidated + 5 meta/event)
```
Expand Down
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/Mnehmos/rpg-mcp.git"
"url": "git+https://github.com/Mnehmos/mnehmos.rpg.mcp.git"
},
"keywords": [
"mcp",
Expand All @@ -42,10 +42,13 @@
],
"author": "Mnehmos",
"license": "MIT",
"engines": {
"node": ">=20"
},
"bugs": {
"url": "https://github.com/Mnehmos/rpg-mcp/issues"
"url": "https://github.com/Mnehmos/mnehmos.rpg.mcp/issues"
},
"homepage": "https://github.com/Mnehmos/rpg-mcp#readme",
"homepage": "https://github.com/Mnehmos/mnehmos.rpg.mcp#readme",
"description": "Complete tabletop RPG game engine via MCP - D&D 5e combat, procedural worldgen, NPC memory, 36 tools (31 consolidated + 5 meta/event)",
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
Expand Down
86 changes: 86 additions & 0 deletions src/engine/combat/attack-rules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { parseDiceTerms } from './rng.js';

/**
* Limits on the numbers a caller may supply for an attack.
*
* Attack bonus, target number and damage can be passed in by the caller, which
* is how monsters without a character sheet attack at all. They are still
* caller input: unbounded, `attackBonus: 999, damage: 9999` kills anything in
* one call. The bounds sit above anything in the rules (a +19 to hit and AC 30
* are already extreme) so no legitimate attack is refused.
*/
export const MIN_ATTACK_BONUS = -20;
export const MAX_ATTACK_BONUS = 30;
export const MIN_ATTACK_DC = 1;
export const MAX_ATTACK_DC = 40;
/** Largest damage one attack may deal before criticals and vulnerabilities. */
export const MAX_ATTACK_DAMAGE = 1000;

/** Reach of a melee attack when the caller states no range, in feet. */
export const DEFAULT_MELEE_REACH_FT = 5;
export const MAX_ATTACK_RANGE_FT = 600;
const FEET_PER_SQUARE = 5;

/** The most a damage value could come to: the number itself, or every die at its maximum. */
export function maxPossibleDamage(damage: number | string): number {
if (typeof damage === 'number') return damage;
let max = 0;
for (const term of parseDiceTerms(damage)) {
if (term.sign < 0) continue;
max += term.kind === 'dice' ? term.count * term.sides : term.value;
}
return max;
}

export function assertAttackNumbersWithinBounds(attackBonus: number, dc: number, damage: number | string): void {
if (!Number.isFinite(attackBonus) || attackBonus < MIN_ATTACK_BONUS || attackBonus > MAX_ATTACK_BONUS) {
throw new Error(
`attackBonus ${attackBonus} is out of bounds (${MIN_ATTACK_BONUS} to ${MAX_ATTACK_BONUS}). ` +
'Omit attackBonus to have it calculated from the attacker.'
);
}
if (!Number.isFinite(dc) || dc < MIN_ATTACK_DC || dc > MAX_ATTACK_DC) {
throw new Error(
`dc ${dc} is out of bounds (${MIN_ATTACK_DC} to ${MAX_ATTACK_DC}). ` +
"Omit dc to use the target's armor class."
);
}
const most = maxPossibleDamage(damage);
if (most > MAX_ATTACK_DAMAGE) {
throw new Error(
`damage ${damage} is out of bounds: one attack may deal at most ${MAX_ATTACK_DAMAGE}. ` +
'Omit damage to have it calculated from the attacker.'
);
}
}

type Position = { x: number; y: number };

/** Grid distance in feet; diagonals cost the same as orthogonals, as movement does. */
export function distanceInFeet(a: Position, b: Position): number {
return Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) * FEET_PER_SQUARE;
}

/**
* Refuse an attack on a target the attacker cannot reach.
*
* Only checked when both combatants have a position. `range` is the reach or
* range of the attack in feet; without it the attack is melee.
*/
export function assertTargetInRange(
attacker: { name: string; position?: Position },
target: { name: string; position?: Position },
range: number | undefined
): void {
if (!attacker.position || !target.position) return;

const reach = range ?? DEFAULT_MELEE_REACH_FT;
const distance = distanceInFeet(attacker.position, target.position);
if (distance <= reach) return;

throw new Error(
`${target.name} is ${distance}ft from ${attacker.name}, beyond this attack's ${reach}ft ` +
`${range === undefined ? 'melee reach' : 'range'}. Move closer, or for a ranged or reach attack ` +
'pass range (in feet) large enough to cover the distance.'
);
}
10 changes: 6 additions & 4 deletions src/engine/combat/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1458,10 +1458,12 @@ export class CombatEngine {
// Mark reaction as used
attacker.reactionUsed = true;

// Simple attack calculation: use initiative bonus as attack modifier
// AC approximation: 10 + initiative bonus (simple heuristic)
const attackBonus = attacker.initiativeBonus + 2; // Add a small bonus
const targetAC = 10 + (target.initiativeBonus > 0 ? Math.floor(target.initiativeBonus / 2) : 0);
// Use the combatants' real numbers when the encounter has them. The
// initiative-based estimate is only a fallback: on its own it turned
// a high or low initiative bonus into an absurd attack bonus or AC.
const attackBonus = attacker.attackBonus ?? attacker.initiativeBonus + 2;
const targetAC = target.ac
?? 10 + (target.initiativeBonus > 0 ? Math.floor(target.initiativeBonus / 2) : 0);

// Fixed damage for opportunity attacks: 1d6 + 2
const baseDamage = this.rng.roll('1d6') + 2;
Expand Down
2 changes: 1 addition & 1 deletion src/engine/combat/rng.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ export interface DamageResult {
total: number; // Final damage total
}

type DiceTerm =
export type DiceTerm =
| { kind: 'dice'; count: number; sides: number; sign: 1 | -1 }
| { kind: 'scalar'; value: number; sign: 1 | -1 };

Expand Down
10 changes: 8 additions & 2 deletions src/server/consolidated/combat-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ const AttackSchema = z.object({
attackBonus: z.number().int().optional(),
dc: z.number().int().optional(),
damage: z.union([z.number(), z.string()]).optional(),
damageType: z.string().optional()
damageType: z.string().optional(),
range: z.number().int().min(5).max(600).optional()
.describe('Reach or range of the attack in feet. Omit for melee (5ft). Required to attack a target farther than 5ft away.')
});

const HealSchema = z.object({
Expand Down Expand Up @@ -115,7 +117,8 @@ const definitions: Record<CombatAction, ActionDefinition> = {
attackBonus: params.attackBonus,
dc: params.dc,
damage: params.damage,
damageType: params.damageType
damageType: params.damageType,
range: params.range
}, ctx);
return extractResultData(result, 'attack');
},
Expand Down Expand Up @@ -359,6 +362,8 @@ DO NOT use math_manage for combat rolls - use this tool instead!
⚔️ ATTACK (minimal call):
{ action: "attack", encounterId, actorId, targetId }
Everything else auto-calculated. Returns: roll result, damage dealt, HP change.
Melee reaches 5ft. For a ranged or reach attack add range (feet), e.g. range: 150.
An attack outside the attacker's own turn uses its reaction (one per round).

🔮 CAST_SPELL (minimal call):
{ action: "cast_spell", encounterId, actorId, spellName, targetId }
Expand Down Expand Up @@ -390,6 +395,7 @@ Aliases: hit/strike→attack, cast/spell→cast_spell, sprint→dash, evade→do
dc: z.number().optional().describe('DC for the attack'),
damage: z.union([z.number(), z.string()]).optional().describe('Damage amount or dice'),
damageType: z.string().optional().describe('Damage type (fire, slashing, etc.)'),
range: z.number().optional().describe('Attack reach or range in feet. Omit for melee (5ft); required to attack a target farther than 5ft away'),
amount: z.number().optional().describe('Healing amount'),
spellName: z.string().optional().describe('Spell name'),
slotLevel: z.number().optional().describe('Spell slot level'),
Expand Down
33 changes: 29 additions & 4 deletions src/server/handlers/combat-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { startConcentration, checkConcentration, breakConcentration } from '../.
import type { Character } from '../../schema/character.js';
import { getPatternGenerator, PATTERN_DESCRIPTIONS } from '../terrain-patterns.js';
import { CREATURE_PRESETS } from '../../data/creature-presets.js';
import { assertAttackNumbersWithinBounds, assertTargetInRange, MAX_ATTACK_RANGE_FT } from '../../engine/combat/attack-rules.js';

// Global combat state (in-memory for MVP)
let pubsub: PubSub | null = null;
Expand Down Expand Up @@ -661,6 +662,8 @@ Examples:
damage: z.union([z.number(), z.string()]).optional().describe('Damage amount (number) or dice expression (e.g., "1d6+2")'),
damageType: z.string().optional()
.describe('HIGH-002: Damage type (e.g., "fire", "cold", "slashing") for resistance calculation'),
range: z.number().int().min(5).max(MAX_ATTACK_RANGE_FT).optional()
.describe('Reach or range of the attack in feet. Omit for a melee attack (5ft). Required to attack a target farther than 5ft away.'),
amount: z.number().int().optional(),
targetPosition: z.object({ x: z.number(), y: z.number() }).optional()
.describe('CRIT-003: Target position for move action'),
Expand Down Expand Up @@ -1270,6 +1273,7 @@ export async function handleExecuteCombatAction(args: unknown, ctx: SessionConte
// some legitimate flows could be disrupted. A stricter mode can be
// layered on top later.
let turnWarning: string | undefined;
let isOffTurn = false;
{
const liveState = engine.getState();
if (liveState) {
Expand All @@ -1288,6 +1292,7 @@ export async function handleExecuteCombatAction(args: unknown, ctx: SessionConte
? 'LAIR action'
: (liveState.participants.find((p) => p.id === activeId)?.name ?? activeId);
turnWarning = `off_turn_action: ${parsed.actorId} acting during ${activeLabel}'s turn`;
isOffTurn = true;
}
}
}
Expand Down Expand Up @@ -1388,9 +1393,26 @@ export async function handleExecuteCombatAction(args: unknown, ctx: SessionConte
throw new Error('Attack action requires targetId');
}

// Validate Action Economy
const validation = engine.validateActionEconomy(parsed.actorId, 'action');
// The numbers may come from the caller; keep them inside the rules.
assertAttackNumbersWithinBounds(attackBonus, dc, damage);

if (actor && target) {
assertTargetInRange(actor, target, parsed.range);
}

// Validate Action Economy. An attack outside the attacker's own turn
// can only be its reaction, and it has one per round — this used to
// be a warning, which let a combatant attack any number of times
// during someone else's turn.
const attackEconomy: 'action' | 'reaction' = isOffTurn ? 'reaction' : 'action';
const validation = engine.validateActionEconomy(parsed.actorId, attackEconomy);
if (!validation.valid) {
if (isOffTurn) {
throw new Error(
`It is not ${actor?.name ?? parsed.actorId}'s turn, and an off-turn attack needs a reaction: ${validation.error}. ` +
'Call advance_turn until it is their turn.'
);
}
throw new Error(validation.error);
}

Expand Down Expand Up @@ -1457,9 +1479,12 @@ export async function handleExecuteCombatAction(args: unknown, ctx: SessionConte
}

output = formatAttackResult(result);

// Commit Action Economy
engine.commitAction(parsed.actorId, 'action');
engine.commitAction(parsed.actorId, attackEconomy);
if (isOffTurn) {
turnWarning += ` (resolved as ${actor?.name ?? parsed.actorId}'s reaction for this round)`;
}

} else if (parsed.action === 'heal') {
if (parsed.amount === undefined) {
Expand Down
10 changes: 8 additions & 2 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ function setupShutdownHandlers(): void {
* `pubsub` and `auditLogger` are app-level singletons shared across calls —
* only the protocol-level McpServer/tool-registration wrapper is rebuilt.
*/
let registrationLogged = false;

function buildServer(
pubsub: PubSub,
auditLogger: AuditLogger,
Expand Down Expand Up @@ -174,8 +176,12 @@ function buildServer(
);
}

console.error(`[Server] Registered ${toolCount} tools with minimal schemas`);
console.error(`[Server] Meta-tools: search_tools, load_tool_schema`);
// The HTTP transport builds a server per request; say this once, not per call.
if (!registrationLogged) {
registrationLogged = true;
console.error(`[Server] Registered ${toolCount} tools with minimal schemas`);
console.error(`[Server] Meta-tools: search_tools, load_tool_schema`);
}

return server;
}
Expand Down
Loading
Loading
0