8000 feat(character): clarify class-aware spell progression by Mnehmos · Pull Request #107 · 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: 6 additions & 0 deletions src/engine/magic/spell-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,12 @@ export function characterKnowsSpell(character: Character, spellName: string): {

// For classes that require preparation
if (config.preparationRequired) {
if (charClass === 'wizard' && !knownSpells.some(s => s.toLowerCase() === spellName.toLowerCase())) {
return {
knows: false,
reason: `${spell.name} is not in your spellbook`
};
}
if (!preparedSpells.some(s => s.toLowerCase() === spellName.toLowerCase())) {
if (knownSpells.some(s => s.toLowerCase() === spellName.toLowerCase())) {
return {
Expand Down
55 changes: 43 additions & 12 deletions src/server/consolidated/character-manage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ const CreateSchema = z.object({
hp: z.number().int().min(1).optional(),
maxHp: z.number().int().min(1).optional(),
ac: z.number().int().min(0).optional(),
level: z.number().int().min(1).optional().default(1),
level: z.number().int().min(1).max(20).optional().default(1)
.describe('Starting character level, from 1 through 20; determines class progression, features, and spell slots'),
characterType: CharacterTypeSchema.optional().default('pc'),
factionId: z.string().optional(),
behavior: z.string().optional(),
Expand Down Expand Up @@ -140,7 +141,8 @@ const UpdateSchema = z.object({
hp: z.number().int().min(0).optional(),
maxHp: z.number().int().min(1).optional(),
ac: z.number().int().min(0).optional(),
level: z.number().int().min(1).optional(),
level: z.number().int().min(1).max(20).optional()
.describe('Character level, from 1 through 20'),
characterType: CharacterTypeSchema.optional(),
stats: StatsSchema.partial().optional(),
cantripsKnown: z.array(z.string()).optional(),
Expand Down Expand Up @@ -238,6 +240,21 @@ function uniqueStrings(...groups: Array<readonly string[] | undefined>): string[
return [...values.values()];
}

function validateWizardPreparedSpells(
characterClass: string | null | undefined,
knownSpells: readonly string[] | undefined,
preparedSpells: readonly string[] | undefined,
): void {
if ((characterClass ?? '').trim().toLowerCase() !== 'wizard') return;

const spellbook = new Set((knownSpells ?? []).map((spell) => spell.trim().toLowerCase()));
const missing = [...new Set((preparedSpells ?? [])
.filter((spell) => !spellbook.has(spell.trim().toLowerCase())))];
if (missing.length > 0) {
throw new Error(`Wizard prepared spells must be present in knownSpells (spellbook): ${missing.join(', ')}`);
}
}

function validSkillProficiencies(values: readonly string[] | undefined): Array<z.infer<typeof SkillProficiencySchema>> {
return (values ?? []).flatMap((value) => {
const parsed = SkillProficiencySchema.safeParse(value);
Expand Down Expand Up @@ -498,6 +515,17 @@ async function handleGet(args: z.infer<typeof GetSchema>): Promise<object> {

async function handleUpdate(args: z.infer<typeof UpdateSchema>): Promise<object> {
const { characterRepo } = ensureDb();
const character = characterRepo.findById(args.characterId);
if (!character) {
throw new Error(`Character ${args.characterId} not found`);
}

validateWizardPreparedSpells(
args.class ?? character.characterClass,
args.knownSpells ?? character.knownSpells,
args.preparedSpells ?? character.preparedSpells,
);

const updateData: Record<string, unknown> = {};

// Map fields
Expand Down Expand Up @@ -528,13 +556,8 @@ async function handleUpdate(args: z.infer<typeof UpdateSchema>): Promise<object>
if (args.conditions !== undefined) {
updateData.conditions = args.conditions;
} else if (args.addConditions !== undefined || args.removeConditions !== undefined) {
const existing = characterRepo.findById(args.characterId);
if (!existing) {
throw new Error(`Character ${args.characterId} not found`);
}

let currentConditions: Array<{ name: string; duration?: number; source?: string }> =
(existing as any).conditions || [];
(character as any).conditions || [];

if (args.removeConditions?.length) {
const toRemove = new Set(args.removeConditions.map(n => n.toLowerCase()));
Expand Down Expand Up @@ -803,6 +826,14 @@ export const CharacterManageTool = {
- provisionEquipment: true (default) auto-grants starting equipment
- For custom items, create with item_manage first, then use inventory_manage

✨ SPELLCASTING:
- cantripsKnown, knownSpells, and preparedSpells are durable character fields.
- Bard, Ranger, Sorcerer, and Warlock cast leveled spells from knownSpells; daily preparation is not used.
- Cleric, Druid, and Paladin cast leveled spells from preparedSpells.
- Wizards keep leveled spells in knownSpells as their spellbook and cast only preparedSpells.
Comment thread
Mnehmos marked this conversation as resolved.
Resolved
- Class and level determine available spell levels and slot progression; spell casting validates the saved choices and consumes the authoritative slots.
- Use character_manage.update to change a character's durable spell choices. Do not invent spell names, slots, or class progression.

Actions: ${ACTIONS.join(', ')}
Aliases: new/add/spawn->create, fetch/find->get, modify/edit->update`,
actionSchemas: router.actionSchemas,
Expand All @@ -819,13 +850,13 @@ Aliases: new/add/spawn->create, fetch/find->get, modify/edit->update`,
hp: z.number().int().optional(),
maxHp: z.number().int().optional(),
ac: z.number().int().optional(),
level: z.number().int().optional(),
level: z.number().int().min(1).max(20).optional().describe('Character level from 1 through 20'),
characterType: CharacterTypeSchema.optional(),
factionId: z.string().optional(),
behavior: z.string().optional(),
cantripsKnown: z.array(z.string()).optional(),
knownSpells: z.array(z.string()).optional(),
preparedSpells: z.array(z.string()).optional(),
cantripsKnown: z.array(z.string()).optional().describe('Persisted cantrips the character knows'),
knownSpells: z.array(z.string()).optional().describe('Persisted known spells; for Wizards this is the spellbook'),
preparedSpells: z.array(z.string()).optional().describe('Persisted leveled spells currently prepared'),
skillProficiencies: z.array(SkillProficiencySchema).optional(),
saveProficiencies: z.array(SaveProficiencySchema).optional(),
expertise: z.array(z.string()).optional(),
Expand Down
2 changes: 1 addition & 1 deletion src/server/consolidated/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const TOOL_DESCRIPTORS: Readonly<Record<string, ToolDescriptor>> = {
concentration_manage: { category: 'concentration', keywords: ['concentration', 'spell', 'save', 'break', 'maintain'], capabilities: ['Concentration checks', 'Break concentration', 'Duration tracking'] },
narrative_manage: { category: 'narrative', keywords: ['narrative', 'story', 'note', 'journal', 'log'], capabilities: ['Story notes', 'Search history', 'Context retrieval'] },
scroll_manage: { category: 'scroll', keywords: ['scroll', 'spell', 'use', 'create', 'identify', 'arcana'], capabilities: ['Use scrolls', 'Create scrolls', 'Check usability'] },
character_manage: { category: 'character', keywords: ['character', 'pc', 'npc', 'create', 'update', 'stats', 'level'], capabilities: ['CRUD characters', 'Level up', 'Stats management'] },
character_manage: { category: 'character', keywords: ['character', 'pc', 'npc', 'create', 'update', 'stats', 'level', 'spell', 'spells', 'prepare', 'prepared', 'spellbook', 'cantrip', 'slots'], capabilities: ['CRUD characters', 'Level up', 'Stats management', 'Known/prepared spell management', 'Class spell-slot progression'] },
party_manage: { category: 'party', keywords: ['party', 'group', 'member', 'leader', 'formation', 'gold'], capabilities: ['Party management', 'Member operations', 'Treasury'] },
item_manage: { category: 'inventory', keywords: ['item', 'weapon', 'armor', 'gear', 'equipment', 'create'], capabilities: ['Item templates', 'CRUD items', 'Item search'] },
inventory_manage: { category: 'inventory', keywords: ['inventory', 'give', 'take', 'equip', 'use', 'transfer'], capabilities: ['Give/take items', 'Equip/use', 'Transfer between characters'] },
Expand Down
36 changes: 36 additions & 0 deletions tests/server/consolidated/character-manage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ describe('character_manage consolidated tool', () => {
expect(CharacterManageTool.description).toContain('level_up');
});

it('documents class-aware spell choices and exposes the D&D level range', () => {
expect(CharacterManageTool.description).toContain('knownSpells');
expect(CharacterManageTool.description).toContain('preparedSpells');
expect(CharacterManageTool.description).toContain('daily preparation is not used');
expect(CharacterManageTool.inputSchema.parse({ action: 'create', name: 'Level Seven', level: 7 }).level).toBe(7);
expect(() => CharacterManageTool.inputSchema.parse({ action: 'create', name: 'Too Powerful', level: 21 })).toThrow();
});

it('exposes cantripsKnown through the MCP registration schema', () => {
const parsed = CharacterManageTool.inputSchema.parse({
action: 'update',
Expand Down Expand Up @@ -125,6 +133,34 @@ describe('character_manage consolidated tool', () => {
expect(updated.cantripsKnown).toEqual(['Ray of Frost']);
});

it('rejects Wizard preparation outside the persisted spellbook', async () => {
const createdResult = await handleCharacterManage({
action: 'create',
name: 'Wizard Invariant Test',
class: 'Wizard',
knownSpells: ['Magic Missile'],
preparedSpells: ['Magic Missile'],
}, ctx);
const created = extractJson(createdResult.content[0].text);

const rejectedResult = await handleCharacterManage({
action: 'update',
characterId: created.id,
preparedSpells: ['Shield'],
}, ctx);
const rejected = extractJson(rejectedResult.content[0].text);

expect(rejected.error).toBe(true);
expect(rejected.message).toContain('spellbook');

const fetchedResult = await handleCharacterManage({
action: 'get',
characterId: created.id,
}, ctx);
const fetched = extractJson(fetchedResult.content[0].text);
expect(fetched.preparedSpells).toEqual(['Magic Missile']);
});

it('round-trips all character proficiency fields through get and update', async () => {
const createdResult = await handleCharacterManage({
action: 'create',
Expand Down
Loading
0