@g33ks/foundryvtt-mcp 0.0.0-stage → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +457 -2
- package/dist/character/manager.js +208 -0
- package/dist/cli/checks.js +307 -0
- package/dist/cli/config-file.js +120 -0
- package/dist/cli/init.js +414 -0
- package/dist/cli/prompt.js +117 -0
- package/dist/cli/snippets.js +64 -0
- package/dist/combat/manager.js +371 -0
- package/dist/config/env-layers.js +49 -0
- package/dist/config/index.js +298 -0
- package/dist/config/sources.js +201 -0
- package/dist/core.js +481 -0
- package/dist/diagnostics/client.js +291 -0
- package/dist/diagnostics/types.js +94 -0
- package/dist/foundry/auth.js +224 -0
- package/dist/foundry/browser-detect.js +170 -0
- package/dist/foundry/client.js +5874 -0
- package/dist/foundry/dice-formula.js +154 -0
- package/dist/foundry/event-log.js +298 -0
- package/dist/foundry/headless-gm-session.js +857 -0
- package/dist/foundry/journal-conflicts.js +141 -0
- package/dist/foundry/journal-history.js +90 -0
- package/dist/foundry/journal-integrity.js +322 -0
- package/dist/foundry/message-author.js +19 -0
- package/dist/foundry/module-bridge.js +441 -0
- package/dist/foundry/types.js +52 -0
- package/dist/foundry/world-cache.js +386 -0
- package/dist/index.js +107 -0
- package/dist/mcp-server.js +65 -0
- package/dist/server.js +159 -0
- package/dist/shared/build-order.js +134 -0
- package/dist/shared/config-hash.js +62 -0
- package/dist/shared/config-notice.js +55 -0
- package/dist/shared/control.js +291 -0
- package/dist/shared/daemon-link.js +135 -0
- package/dist/shared/daemon.js +311 -0
- package/dist/shared/ipc-client.js +200 -0
- package/dist/shared/ipc-server.js +316 -0
- package/dist/shared/paths.js +79 -0
- package/dist/shared/protocol.js +230 -0
- package/dist/shared/relay-config.js +65 -0
- package/dist/shared/relay.js +120 -0
- package/dist/shared/rotating-log.js +57 -0
- package/dist/shared/spawn.js +39 -0
- package/dist/shared/state-file.js +33 -0
- package/dist/shared/token.js +62 -0
- package/dist/shared/version.js +57 -0
- package/dist/tools/base.js +74 -0
- package/dist/tools/definitions.js +3109 -0
- package/dist/tools/handlers/actor-mutations.js +128 -0
- package/dist/tools/handlers/actors.js +114 -0
- package/dist/tools/handlers/chat-mutations.js +49 -0
- package/dist/tools/handlers/chat.js +38 -0
- package/dist/tools/handlers/combat-mutations.js +215 -0
- package/dist/tools/handlers/combat-order.js +94 -0
- package/dist/tools/handlers/combat.js +51 -0
- package/dist/tools/handlers/compendium.js +83 -0
- package/dist/tools/handlers/diagnostics.js +450 -0
- package/dist/tools/handlers/dice.js +54 -0
- package/dist/tools/handlers/effects.js +103 -0
- package/dist/tools/handlers/events.js +50 -0
- package/dist/tools/handlers/generation.js +258 -0
- package/dist/tools/handlers/item-mutations.js +132 -0
- package/dist/tools/handlers/items.js +53 -0
- package/dist/tools/handlers/journal-mutations.js +230 -0
- package/dist/tools/handlers/journals.js +80 -0
- package/dist/tools/handlers/module-bridge.js +421 -0
- package/dist/tools/handlers/placeable-mutations.js +272 -0
- package/dist/tools/handlers/resources.js +203 -0
- package/dist/tools/handlers/roll-tables.js +97 -0
- package/dist/tools/handlers/scene-mutations.js +159 -0
- package/dist/tools/handlers/scenes.js +355 -0
- package/dist/tools/handlers/settings.js +53 -0
- package/dist/tools/handlers/tile-mutations.js +56 -0
- package/dist/tools/handlers/token-mutations.js +356 -0
- package/dist/tools/handlers/users.js +59 -0
- package/dist/tools/handlers/utils.js +48 -0
- package/dist/tools/handlers/wall-mutations.js +98 -0
- package/dist/tools/handlers/world-documents.js +222 -0
- package/dist/tools/handlers/world.js +92 -0
- package/dist/tools/index.js +25 -0
- package/dist/tools/new-router.js +97 -0
- package/dist/tools/registry.js +79 -0
- package/dist/tools/resources.js +63 -0
- package/dist/tools/router.js +688 -0
- package/dist/tools/tool-dependencies.js +194 -0
- package/dist/tools/write-tools.js +97 -0
- package/dist/utils/cache-instance.js +30 -0
- package/dist/utils/cache.js +205 -0
- package/dist/utils/diagnostics.js +332 -0
- package/dist/utils/guards.js +17 -0
- package/dist/utils/image-size.js +160 -0
- package/dist/utils/log-args.js +47 -0
- package/dist/utils/logger.js +203 -0
- package/dist/utils/mcp-errors.js +47 -0
- package/dist/utils/refusal.js +30 -0
- package/dist/utils/sanitize.js +22 -0
- package/dist/utils/serial-queue.js +22 -0
- package/package.json +124 -4
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Actor attribute mutation tool handlers (laurigates/foundryvtt-mcp#143)
|
|
3
|
+
*
|
|
4
|
+
* Handles patching attributes on an actor's `system` object via dot-paths.
|
|
5
|
+
* WRITE operation — requires FOUNDRY_WRITE_ENABLED=true and an active Socket.IO
|
|
6
|
+
* connection (mutations use the core `modifyDocument` protocol).
|
|
7
|
+
*/
|
|
8
|
+
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
9
|
+
import { withToolError } from './utils.js';
|
|
10
|
+
/**
|
|
11
|
+
* Handles actor attribute update requests.
|
|
12
|
+
*
|
|
13
|
+
* `patch` keys are dot-paths into the actor's `system` object — e.g.
|
|
14
|
+
* `attributes.hp.value`, `attributes.hp.temp`, `currency.gp`,
|
|
15
|
+
* `resources.primary.value`, `spells.spell1.value`, `attributes.exhaustion`.
|
|
16
|
+
* The post-update value of every patched path is echoed back.
|
|
17
|
+
*/
|
|
18
|
+
export async function handleUpdateActorAttribute(args, foundryClient) {
|
|
19
|
+
const { actorId, patch } = args;
|
|
20
|
+
if (!actorId || typeof actorId !== 'string') {
|
|
21
|
+
throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
|
|
22
|
+
}
|
|
23
|
+
if (patch === null ||
|
|
24
|
+
typeof patch !== 'object' ||
|
|
25
|
+
Array.isArray(patch) ||
|
|
26
|
+
Object.keys(patch).length === 0) {
|
|
27
|
+
throw new McpError(ErrorCode.InvalidParams, 'patch is required and must be a non-empty object of dot-path attributes');
|
|
28
|
+
}
|
|
29
|
+
return withToolError('update actor attributes', async () => {
|
|
30
|
+
const result = await foundryClient.updateActorAttribute(actorId, patch);
|
|
31
|
+
const updatedList = Object.entries(result.updatedAttributes)
|
|
32
|
+
.map(([path, value]) => `- **${path}** → ${String(value)}`)
|
|
33
|
+
.join('\n');
|
|
34
|
+
return {
|
|
35
|
+
content: [
|
|
36
|
+
{
|
|
37
|
+
type: 'text',
|
|
38
|
+
text: `⚔️ **Actor Attributes Updated**
|
|
39
|
+
**Actor ID:** ${actorId}
|
|
40
|
+
**Status:** ${result.success ? 'Success' : 'Failed'}
|
|
41
|
+
|
|
42
|
+
**Updated attributes** (dot-paths into actor.system):
|
|
43
|
+
${updatedList}`,
|
|
44
|
+
},
|
|
45
|
+
],
|
|
46
|
+
};
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Handles creating a new top-level Actor document (NPC/character sheet).
|
|
51
|
+
*/
|
|
52
|
+
export async function handleCreateWorldActor(args, foundryClient) {
|
|
53
|
+
const { name, type, system, folder } = args;
|
|
54
|
+
if (!name || typeof name !== 'string') {
|
|
55
|
+
throw new McpError(ErrorCode.InvalidParams, 'name is required and must be a string');
|
|
56
|
+
}
|
|
57
|
+
if (!type || typeof type !== 'string') {
|
|
58
|
+
throw new McpError(ErrorCode.InvalidParams, 'type is required and must be a string');
|
|
59
|
+
}
|
|
60
|
+
return withToolError('create world actor', async () => {
|
|
61
|
+
const actor = await foundryClient.createWorldActor(name, type, system, folder);
|
|
62
|
+
return {
|
|
63
|
+
content: [
|
|
64
|
+
{
|
|
65
|
+
type: 'text',
|
|
66
|
+
text: `🎭 **Actor Created**
|
|
67
|
+
**Name:** ${actor.name}
|
|
68
|
+
**Type:** ${actor.type}
|
|
69
|
+
**ID:** ${actor._id}`,
|
|
70
|
+
},
|
|
71
|
+
],
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Handles creating a new top-level Actor document AND seeding it with
|
|
77
|
+
* starting items (skills, gear, weapons, …) in one call.
|
|
78
|
+
*/
|
|
79
|
+
export async function handleCreateFullActor(args, foundryClient) {
|
|
80
|
+
const { name, type, ...options } = args;
|
|
81
|
+
if (!name || typeof name !== 'string') {
|
|
82
|
+
throw new McpError(ErrorCode.InvalidParams, 'name is required and must be a string');
|
|
83
|
+
}
|
|
84
|
+
if (!type || typeof type !== 'string') {
|
|
85
|
+
throw new McpError(ErrorCode.InvalidParams, 'type is required and must be a string');
|
|
86
|
+
}
|
|
87
|
+
if (options.items !== undefined && !Array.isArray(options.items)) {
|
|
88
|
+
throw new McpError(ErrorCode.InvalidParams, 'items must be an array when provided');
|
|
89
|
+
}
|
|
90
|
+
return withToolError('create full actor', async () => {
|
|
91
|
+
const { actor, items, itemErrors } = await foundryClient.createFullActor(name, type, options);
|
|
92
|
+
const itemLines = items.length > 0
|
|
93
|
+
? items.map((i) => `- ${i.name} (${i.type}) — ID: ${i._id}`).join('\n')
|
|
94
|
+
: '_none_';
|
|
95
|
+
const errorLines = itemErrors.length > 0
|
|
96
|
+
? `\n\n**Item Failures (${itemErrors.length}):**\n${itemErrors.map((e) => `- ${e.name}: ${e.error}`).join('\n')}`
|
|
97
|
+
: '';
|
|
98
|
+
return {
|
|
99
|
+
content: [
|
|
100
|
+
{
|
|
101
|
+
type: 'text',
|
|
102
|
+
text: `🎭 **Full Actor Created**
|
|
103
|
+
**Name:** ${actor.name}
|
|
104
|
+
**Type:** ${actor.type}
|
|
105
|
+
**ID:** ${actor._id}
|
|
106
|
+
**Items Created (${items.length}):**
|
|
107
|
+
${itemLines}${errorLines}`,
|
|
108
|
+
},
|
|
109
|
+
],
|
|
110
|
+
};
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Handles permanently deleting a top-level Actor document.
|
|
115
|
+
*/
|
|
116
|
+
export async function handleDeleteWorldActor(args, foundryClient) {
|
|
117
|
+
const { actorId } = args;
|
|
118
|
+
if (!actorId || typeof actorId !== 'string') {
|
|
119
|
+
throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
|
|
120
|
+
}
|
|
121
|
+
return withToolError('delete actor', async () => {
|
|
122
|
+
await foundryClient.deleteWorldActor(actorId);
|
|
123
|
+
return {
|
|
124
|
+
content: [{ type: 'text', text: `🗑️ **Actor Deleted**\n**ID:** ${actorId}` }],
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=actor-mutations.js.map
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Actor management tool handlers
|
|
3
|
+
*
|
|
4
|
+
* Handles searching for actors and retrieving detailed actor information.
|
|
5
|
+
*/
|
|
6
|
+
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
7
|
+
import { withToolError } from './utils.js';
|
|
8
|
+
/**
|
|
9
|
+
* Handles actor search requests
|
|
10
|
+
*/
|
|
11
|
+
export async function handleSearchActors(args, foundryClient) {
|
|
12
|
+
const { query, type, limit = 10, cursor } = args;
|
|
13
|
+
return withToolError('search actors', async () => {
|
|
14
|
+
const searchParams = {
|
|
15
|
+
query: query || '',
|
|
16
|
+
limit,
|
|
17
|
+
};
|
|
18
|
+
if (type) {
|
|
19
|
+
searchParams.type = type;
|
|
20
|
+
}
|
|
21
|
+
if (cursor) {
|
|
22
|
+
searchParams.cursor = cursor;
|
|
23
|
+
}
|
|
24
|
+
const result = await foundryClient.searchActors(searchParams);
|
|
25
|
+
const actorList = result.actors
|
|
26
|
+
.map((actor) => `- **${actor.name}** (${actor.type}) - Level ${actor.level || 'Unknown'} - HP: ${actor.hp?.value || 'Unknown'}/${actor.hp?.max || 'Unknown'}`)
|
|
27
|
+
.join('\n');
|
|
28
|
+
return {
|
|
29
|
+
content: [
|
|
30
|
+
{
|
|
31
|
+
type: 'text',
|
|
32
|
+
text: `🎭 **Actor Search Results**
|
|
33
|
+
**Query:** ${query || 'All actors'}
|
|
34
|
+
**Type Filter:** ${type || 'All types'}
|
|
35
|
+
**Results:** ${result.actors.length}/${result.total} total
|
|
36
|
+
|
|
37
|
+
${actorList || 'No actors found matching the criteria.'}
|
|
38
|
+
|
|
39
|
+
**Page:** ${result.page} | **Limit:** ${result.limit}${result.nextCursor ? `\n\n_More results available. Pass cursor: "${result.nextCursor}" to retrieve the next page._` : ''}`,
|
|
40
|
+
},
|
|
41
|
+
],
|
|
42
|
+
};
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Handles detailed actor information requests
|
|
47
|
+
*/
|
|
48
|
+
export async function handleGetActorDetails(args, foundryClient) {
|
|
49
|
+
const { actorId } = args;
|
|
50
|
+
if (!actorId || typeof actorId !== 'string') {
|
|
51
|
+
throw new McpError(ErrorCode.InvalidParams, 'Actor ID is required and must be a string');
|
|
52
|
+
}
|
|
53
|
+
return withToolError('get actor details', async () => {
|
|
54
|
+
const actor = await foundryClient.getActor(actorId);
|
|
55
|
+
const abilities = actor.abilities
|
|
56
|
+
? Object.entries(actor.abilities)
|
|
57
|
+
.map(([key, ability]) => `**${key.toUpperCase()}:** ${ability.value} (${ability.mod >= 0 ? '+' : ''}${ability.mod})`)
|
|
58
|
+
.join('\n')
|
|
59
|
+
: 'No ability scores available';
|
|
60
|
+
return {
|
|
61
|
+
content: [
|
|
62
|
+
{
|
|
63
|
+
type: 'text',
|
|
64
|
+
text: `🎭 **Actor Details: ${actor.name}**
|
|
65
|
+
**Type:** ${actor.type}
|
|
66
|
+
**Level:** ${actor.level || 'Unknown'}
|
|
67
|
+
**Hit Points:** ${actor.hp?.value || 'Unknown'}/${actor.hp?.max || 'Unknown'}
|
|
68
|
+
**Armor Class:** ${actor.ac?.value || 'Unknown'}
|
|
69
|
+
|
|
70
|
+
**Ability Scores:**
|
|
71
|
+
${abilities}
|
|
72
|
+
|
|
73
|
+
**Description:** ${actor.description || 'No description available.'}`,
|
|
74
|
+
},
|
|
75
|
+
],
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Handles listing an actor's owned items (equipment, spells, features).
|
|
81
|
+
*
|
|
82
|
+
* Reads full `system` data from the cached worldData, unlike
|
|
83
|
+
* `get_actor_details`, which only reports the actor's own top-level stats.
|
|
84
|
+
*/
|
|
85
|
+
export async function handleGetActorInventory(args, foundryClient) {
|
|
86
|
+
const { actorId } = args;
|
|
87
|
+
if (!actorId || typeof actorId !== 'string') {
|
|
88
|
+
throw new McpError(ErrorCode.InvalidParams, 'actorId is required and must be a string');
|
|
89
|
+
}
|
|
90
|
+
return withToolError('get actor inventory', async () => {
|
|
91
|
+
const items = foundryClient.getActorItems(actorId);
|
|
92
|
+
if (items.length === 0) {
|
|
93
|
+
return {
|
|
94
|
+
content: [{ type: 'text', text: `Actor ${actorId} owns no items.` }],
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
const formatted = items
|
|
98
|
+
.map((item) => {
|
|
99
|
+
const qty = item.system.quantity;
|
|
100
|
+
const qtySuffix = typeof qty === 'number' ? ` x${qty}` : '';
|
|
101
|
+
return `- **${item.name}**${qtySuffix} (${item.type}) — ID: ${item._id}`;
|
|
102
|
+
})
|
|
103
|
+
.join('\n');
|
|
104
|
+
return {
|
|
105
|
+
content: [
|
|
106
|
+
{
|
|
107
|
+
type: 'text',
|
|
108
|
+
text: `🎒 **Actor Inventory** (${items.length} item${items.length !== 1 ? 's' : ''})\n\n${formatted}`,
|
|
109
|
+
},
|
|
110
|
+
],
|
|
111
|
+
};
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=actors.js.map
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Chat message mutation tool handler
|
|
3
|
+
*
|
|
4
|
+
* WRITE operation — requires FOUNDRY_WRITE_ENABLED=true and an active
|
|
5
|
+
* Socket.IO connection (mutations use the core `modifyDocument` protocol).
|
|
6
|
+
*/
|
|
7
|
+
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
8
|
+
import { withToolError } from './utils.js';
|
|
9
|
+
/**
|
|
10
|
+
* Handles posting a message to the FoundryVTT chat log, optionally as a
|
|
11
|
+
* named speaker, whispered to specific users, and/or styled as in-character
|
|
12
|
+
* or an emote.
|
|
13
|
+
*/
|
|
14
|
+
export async function handleSendChatMessage(args, foundryClient) {
|
|
15
|
+
const { content, speaker, whisperTo, style } = args;
|
|
16
|
+
if (!content || typeof content !== 'string') {
|
|
17
|
+
throw new McpError(ErrorCode.InvalidParams, 'content is required and must be a string');
|
|
18
|
+
}
|
|
19
|
+
if (whisperTo !== undefined && !Array.isArray(whisperTo)) {
|
|
20
|
+
throw new McpError(ErrorCode.InvalidParams, 'whisperTo must be an array of user ids');
|
|
21
|
+
}
|
|
22
|
+
return withToolError('send chat message', async () => {
|
|
23
|
+
const options = {};
|
|
24
|
+
if (speaker) {
|
|
25
|
+
options.speaker = speaker;
|
|
26
|
+
}
|
|
27
|
+
if (whisperTo && whisperTo.length > 0) {
|
|
28
|
+
options.whisperTo = whisperTo;
|
|
29
|
+
}
|
|
30
|
+
if (style) {
|
|
31
|
+
options.style = style;
|
|
32
|
+
}
|
|
33
|
+
const message = await foundryClient.sendChatMessage(content, options);
|
|
34
|
+
const audience = whisperTo && whisperTo.length > 0 ? `whispered to ${whisperTo.length} user(s)` : 'public';
|
|
35
|
+
return {
|
|
36
|
+
content: [
|
|
37
|
+
{
|
|
38
|
+
type: 'text',
|
|
39
|
+
text: `💬 **Chat Message Sent**
|
|
40
|
+
**Speaker:** ${speaker ?? '(default)'}
|
|
41
|
+
**Audience:** ${audience}
|
|
42
|
+
**Style:** ${style ?? 'other'}
|
|
43
|
+
**ID:** ${message._id}`,
|
|
44
|
+
},
|
|
45
|
+
],
|
|
46
|
+
};
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=chat-mutations.js.map
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chat message tool handler
|
|
3
|
+
*/
|
|
4
|
+
import { messageAuthorId } from '../../foundry/message-author.js';
|
|
5
|
+
import { stripHtml } from '../../utils/sanitize.js';
|
|
6
|
+
import { withToolError } from './utils.js';
|
|
7
|
+
export async function handleGetChatMessages(args, foundryClient) {
|
|
8
|
+
return withToolError('get chat messages', async () => {
|
|
9
|
+
const limit = Math.min(args.limit ?? 20, 100);
|
|
10
|
+
const messages = foundryClient.getChatMessages(limit);
|
|
11
|
+
if (messages.length === 0) {
|
|
12
|
+
return {
|
|
13
|
+
content: [{ type: 'text', text: 'No chat messages found.' }],
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
// Resolve user names from worldData
|
|
17
|
+
const { users } = foundryClient.getUsers();
|
|
18
|
+
const userMap = new Map(users.map((u) => [u._id, u.name]));
|
|
19
|
+
const formatted = messages
|
|
20
|
+
.map((m) => {
|
|
21
|
+
const authorId = messageAuthorId(m);
|
|
22
|
+
const speaker = m.speaker?.alias || (authorId ? userMap.get(authorId) : undefined) || 'Unknown';
|
|
23
|
+
const time = new Date(m.timestamp).toLocaleTimeString();
|
|
24
|
+
const content = stripHtml(m.content).trim().slice(0, 200);
|
|
25
|
+
return `[${time}] **${speaker}**: ${content}`;
|
|
26
|
+
})
|
|
27
|
+
.join('\n');
|
|
28
|
+
return {
|
|
29
|
+
content: [
|
|
30
|
+
{
|
|
31
|
+
type: 'text',
|
|
32
|
+
text: `**Recent Chat Messages** (${messages.length})\n\n${formatted}`,
|
|
33
|
+
},
|
|
34
|
+
],
|
|
35
|
+
};
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=chat.js.map
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Combat control mutation tool handlers (FR-018)
|
|
3
|
+
*
|
|
4
|
+
* Provides GM-gated combat-control tools that operate on the *active* combat:
|
|
5
|
+
* advancing the turn, ending the encounter, and setting a combatant's
|
|
6
|
+
* initiative. All are WRITE operations — they require FOUNDRY_WRITE_ENABLED=true
|
|
7
|
+
* and an active Socket.IO connection (mutations use the core `modifyDocument`
|
|
8
|
+
* protocol), and the connected user needs GM/owner permission.
|
|
9
|
+
*/
|
|
10
|
+
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
11
|
+
import { getCurrentCombatant, getTurnOrder, turnIndexAfterInitiativeChange, } from './combat-order.js';
|
|
12
|
+
import { withToolError } from './utils.js';
|
|
13
|
+
/**
|
|
14
|
+
* Computes the next `{ turn, round }` for an active combat.
|
|
15
|
+
*
|
|
16
|
+
* Advances to the next combatant in order; wrapping past the last combatant
|
|
17
|
+
* rolls over to turn 0 of the next round.
|
|
18
|
+
*
|
|
19
|
+
* `Combat#turn` is an index into the **initiative-sorted** turn order (see
|
|
20
|
+
* `combat-order.ts`), *not* into the stored/creation order of
|
|
21
|
+
* `combat.combatants` — the same order `get_combat_state` renders (laurigates/foundryvtt-mcp#214).
|
|
22
|
+
*
|
|
23
|
+
* When `skipDefeated` is true, `defeated` combatants are skipped — mirroring
|
|
24
|
+
* Foundry's `Combat#nextTurn`/`nextRound` with the `skipDefeated` setting. If
|
|
25
|
+
* every combatant is defeated, the round still advances (turn 0), matching
|
|
26
|
+
* Foundry's "none remaining" fallback rather than hanging.
|
|
27
|
+
*
|
|
28
|
+
* @throws if the combat has no combatants (cannot advance an empty encounter).
|
|
29
|
+
*/
|
|
30
|
+
export function computeNextTurn(combat, skipDefeated = false) {
|
|
31
|
+
const combatants = getTurnOrder(combat);
|
|
32
|
+
const n = combatants.length;
|
|
33
|
+
if (n === 0) {
|
|
34
|
+
throw new Error('Cannot advance turn: active combat has no combatants');
|
|
35
|
+
}
|
|
36
|
+
const cur = combat.turn ?? 0;
|
|
37
|
+
// Scan forward within the current round for the next eligible combatant.
|
|
38
|
+
for (let i = cur + 1; i < n; i++) {
|
|
39
|
+
if (skipDefeated && combatants[i]?.defeated) {
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
return { turn: i, round: combat.round };
|
|
43
|
+
}
|
|
44
|
+
// No eligible combatant left this round — advance to the next round.
|
|
45
|
+
const round = combat.round + 1;
|
|
46
|
+
if (!skipDefeated) {
|
|
47
|
+
return { turn: 0, round };
|
|
48
|
+
}
|
|
49
|
+
const firstAlive = combatants.findIndex((c) => !c.defeated);
|
|
50
|
+
return { turn: firstAlive === -1 ? 0 : firstAlive, round };
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Advances the active combat to the next turn (FR-018).
|
|
54
|
+
*
|
|
55
|
+
* Accepts an optional `skipDefeated` argument; when omitted it falls back to the
|
|
56
|
+
* combat's `settings.skipDefeated` (if present in the worldData snapshot), then
|
|
57
|
+
* to `false`.
|
|
58
|
+
*/
|
|
59
|
+
export async function handleNextTurn(args, foundryClient) {
|
|
60
|
+
const combat = foundryClient.getCombatState();
|
|
61
|
+
if (!combat) {
|
|
62
|
+
throw new McpError(ErrorCode.InvalidRequest, 'No active combat to advance.');
|
|
63
|
+
}
|
|
64
|
+
const skipDefeated = args?.skipDefeated ?? combat.settings?.skipDefeated ?? false;
|
|
65
|
+
return withToolError('advance combat turn', async () => {
|
|
66
|
+
const { turn, round } = computeNextTurn(combat, skipDefeated);
|
|
67
|
+
await foundryClient.updateCombat(combat._id, { turn, round });
|
|
68
|
+
const current = getTurnOrder(combat)[turn];
|
|
69
|
+
const currentName = current ? current.name : 'unknown';
|
|
70
|
+
return {
|
|
71
|
+
content: [
|
|
72
|
+
{
|
|
73
|
+
type: 'text',
|
|
74
|
+
text: `⚔️ **Combat Turn Advanced**
|
|
75
|
+
**Round:** ${round}
|
|
76
|
+
**Turn:** ${turn + 1} of ${combat.combatants.length}
|
|
77
|
+
**Now acting:** ${currentName}`,
|
|
78
|
+
},
|
|
79
|
+
],
|
|
80
|
+
};
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Ends (deletes) the active combat encounter (FR-018).
|
|
85
|
+
*/
|
|
86
|
+
export async function handleEndCombat(_args, foundryClient) {
|
|
87
|
+
const combat = foundryClient.getCombatState();
|
|
88
|
+
if (!combat) {
|
|
89
|
+
throw new McpError(ErrorCode.InvalidRequest, 'No active combat to end.');
|
|
90
|
+
}
|
|
91
|
+
return withToolError('end combat', async () => {
|
|
92
|
+
await foundryClient.endCombat(combat._id);
|
|
93
|
+
return {
|
|
94
|
+
content: [
|
|
95
|
+
{
|
|
96
|
+
type: 'text',
|
|
97
|
+
text: `⚔️ **Combat Ended**
|
|
98
|
+
**Encounter:** ${combat._id}
|
|
99
|
+
The active combat encounter has been removed.`,
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
};
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Sets a combatant's initiative in the active combat (FR-018).
|
|
107
|
+
*
|
|
108
|
+
* `combatId` defaults to the active combat when omitted.
|
|
109
|
+
*
|
|
110
|
+
* Writing an initiative re-sorts the turn order underneath the stored
|
|
111
|
+
* `Combat#turn`, which indexes that order (laurigates/foundryvtt-mcp#214) — so a different combatant can
|
|
112
|
+
* slide under the stored index. FoundryVTT's `Combat#setupTurns` re-finds the
|
|
113
|
+
* combatant that was acting and re-points `turn` at its new index; this handler
|
|
114
|
+
* mirrors that, so the MCP and Foundry never disagree about whose turn it is
|
|
115
|
+
* after an initiative correction. The re-anchor is skipped when there is
|
|
116
|
+
* nothing to anchor: no combatant is acting yet (round-0 setup, `turn` null, or
|
|
117
|
+
* a stale index), the acting combatant's index is unchanged, or the write
|
|
118
|
+
* targets a combat other than the active one (the only one readable here).
|
|
119
|
+
*/
|
|
120
|
+
export async function handleSetInitiative(args, foundryClient) {
|
|
121
|
+
const { combatantId, initiative, combatId } = args;
|
|
122
|
+
if (!combatantId || typeof combatantId !== 'string') {
|
|
123
|
+
throw new McpError(ErrorCode.InvalidParams, 'combatantId is required and must be a string');
|
|
124
|
+
}
|
|
125
|
+
if (typeof initiative !== 'number' || !Number.isFinite(initiative)) {
|
|
126
|
+
throw new McpError(ErrorCode.InvalidParams, 'initiative is required and must be a finite number');
|
|
127
|
+
}
|
|
128
|
+
const activeCombat = foundryClient.getCombatState();
|
|
129
|
+
const resolvedCombatId = combatId ?? activeCombat?._id;
|
|
130
|
+
if (!resolvedCombatId) {
|
|
131
|
+
throw new McpError(ErrorCode.InvalidRequest, 'No active combat and no combatId provided; cannot set initiative.');
|
|
132
|
+
}
|
|
133
|
+
// Only the active combat is readable from the world-data cache, so only its
|
|
134
|
+
// turn order can be recomputed. Capture who is acting BEFORE the write.
|
|
135
|
+
const combat = activeCombat?._id === resolvedCombatId ? activeCombat : undefined;
|
|
136
|
+
const acting = combat ? getCurrentCombatant(combat) : undefined;
|
|
137
|
+
return withToolError('set combatant initiative', async () => {
|
|
138
|
+
await foundryClient.setCombatantInitiative(resolvedCombatId, combatantId, initiative);
|
|
139
|
+
let reanchored = '';
|
|
140
|
+
if (combat && acting) {
|
|
141
|
+
const turn = turnIndexAfterInitiativeChange(combat, { combatantId, initiative }, acting._id);
|
|
142
|
+
if (turn !== undefined && turn !== combat.turn) {
|
|
143
|
+
await foundryClient.updateCombat(resolvedCombatId, { turn });
|
|
144
|
+
reanchored = `
|
|
145
|
+
**Still acting:** ${acting.name} (turn ${turn + 1} of ${combat.combatants.length})`;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
content: [
|
|
150
|
+
{
|
|
151
|
+
type: 'text',
|
|
152
|
+
text: `⚔️ **Initiative Set**
|
|
153
|
+
**Combat:** ${resolvedCombatId}
|
|
154
|
+
**Combatant:** ${combatantId}
|
|
155
|
+
**Initiative:** ${initiative}${reanchored}`,
|
|
156
|
+
},
|
|
157
|
+
],
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Starts a new combat encounter, seeding combatants from tokens (FR-018, laurigates/foundryvtt-mcp#172).
|
|
163
|
+
*
|
|
164
|
+
* Resolves the target scene (explicit `sceneId`, else the active scene), then
|
|
165
|
+
* builds combatant seeds from the requested `tokenIds` (or every token on the
|
|
166
|
+
* scene when none are given) and delegates the two-step create to the client.
|
|
167
|
+
*/
|
|
168
|
+
export async function handleStartCombat(args, foundryClient) {
|
|
169
|
+
const { tokenIds, sceneId } = args ?? {};
|
|
170
|
+
const scenes = foundryClient.getScenes();
|
|
171
|
+
const scene = sceneId
|
|
172
|
+
? scenes.find((s) => s._id === sceneId)
|
|
173
|
+
: scenes.find((s) => s.active);
|
|
174
|
+
if (!scene) {
|
|
175
|
+
throw new McpError(ErrorCode.InvalidRequest, sceneId
|
|
176
|
+
? `Scene not found: ${sceneId}`
|
|
177
|
+
: 'No active scene to start combat on; provide a sceneId.');
|
|
178
|
+
}
|
|
179
|
+
const sceneTokens = scene.tokens ?? [];
|
|
180
|
+
const tokenIdOf = (t) => typeof t._id === 'string' ? t._id : undefined;
|
|
181
|
+
const actorIdOf = (t) => typeof t.actorId === 'string' ? t.actorId : undefined;
|
|
182
|
+
const seeds = [];
|
|
183
|
+
if (tokenIds && tokenIds.length > 0) {
|
|
184
|
+
for (const id of tokenIds) {
|
|
185
|
+
const token = sceneTokens.find((t) => tokenIdOf(t) === id);
|
|
186
|
+
if (!token) {
|
|
187
|
+
throw new McpError(ErrorCode.InvalidParams, `Token not found on scene ${scene._id}: ${id}`);
|
|
188
|
+
}
|
|
189
|
+
seeds.push({ tokenId: id, sceneId: scene._id, actorId: actorIdOf(token) });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
for (const t of sceneTokens) {
|
|
194
|
+
const id = tokenIdOf(t);
|
|
195
|
+
if (id) {
|
|
196
|
+
seeds.push({ tokenId: id, sceneId: scene._id, actorId: actorIdOf(t) });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return withToolError('start combat', async () => {
|
|
201
|
+
const { combatId, combatantCount } = await foundryClient.startCombat(scene._id, seeds);
|
|
202
|
+
return {
|
|
203
|
+
content: [
|
|
204
|
+
{
|
|
205
|
+
type: 'text',
|
|
206
|
+
text: `⚔️ **Combat Started**
|
|
207
|
+
**Encounter:** ${combatId}
|
|
208
|
+
**Scene:** ${scene.name} (${scene._id})
|
|
209
|
+
**Combatants:** ${combatantCount}`,
|
|
210
|
+
},
|
|
211
|
+
],
|
|
212
|
+
};
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
//# sourceMappingURL=combat-mutations.js.map
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Shared combatant turn-order helper (laurigates/foundryvtt-mcp#214).
|
|
3
|
+
*
|
|
4
|
+
* FoundryVTT resolves `Combat#turn` against the **initiative-sorted** turn
|
|
5
|
+
* order, not the stored (creation) order of `Combat#combatants`. Every handler
|
|
6
|
+
* that maps a `turn` index onto a combatant — the read path
|
|
7
|
+
* (`get_combat_state`) and the write path (`next_turn`) alike — must therefore
|
|
8
|
+
* derive that list here, so the two can never drift apart through slightly
|
|
9
|
+
* different comparators.
|
|
10
|
+
*
|
|
11
|
+
* The comparator mirrors core's `Combat._sortCombatants`: initiative
|
|
12
|
+
* descending, non-numeric (un-rolled) initiative last, ties broken by document
|
|
13
|
+
* id so the order is deterministic and stable.
|
|
14
|
+
*/
|
|
15
|
+
/** Un-rolled / malformed initiative sorts to the very end of the order. */
|
|
16
|
+
function initiativeOf(c) {
|
|
17
|
+
return typeof c.initiative === 'number' && Number.isFinite(c.initiative)
|
|
18
|
+
? c.initiative
|
|
19
|
+
: Number.NEGATIVE_INFINITY;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Compares two combatants by Foundry's turn-order rules.
|
|
23
|
+
*
|
|
24
|
+
* Initiative descending; combatants without a rolled initiative go last; ties
|
|
25
|
+
* (including two un-rolled combatants, whose difference is `NaN`) fall back to
|
|
26
|
+
* the document id so the ordering is total and deterministic.
|
|
27
|
+
*/
|
|
28
|
+
export function compareCombatants(a, b) {
|
|
29
|
+
const byInitiative = initiativeOf(b) - initiativeOf(a);
|
|
30
|
+
if (byInitiative && !Number.isNaN(byInitiative)) {
|
|
31
|
+
return byInitiative;
|
|
32
|
+
}
|
|
33
|
+
if (a._id === b._id) {
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
return a._id > b._id ? 1 : -1;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Returns the combatants of `combat` in turn order.
|
|
40
|
+
*
|
|
41
|
+
* Sorts a **copy** — `combat` is a live reference into the world-data cache, so
|
|
42
|
+
* sorting in place would silently reorder cached state as a side effect of a
|
|
43
|
+
* read.
|
|
44
|
+
*/
|
|
45
|
+
export function getTurnOrder(combat) {
|
|
46
|
+
return [...combat.combatants].sort(compareCombatants);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Whether the encounter is under way, derived the way core derives it.
|
|
50
|
+
*
|
|
51
|
+
* `Combat#started` is a **client-side getter** (`turns.length > 0 && round >
|
|
52
|
+
* 0`), not schema data: `BaseCombat.defineSchema()` does not declare it, so a
|
|
53
|
+
* Combat document read out of `worldData` never carries the key. Reading
|
|
54
|
+
* `combat.started` therefore evaluates to `undefined` on every real world —
|
|
55
|
+
* only hand-written fixtures have it — so started-ness is computed here from
|
|
56
|
+
* the two fields the transport does deliver.
|
|
57
|
+
*/
|
|
58
|
+
export function isCombatStarted(combat) {
|
|
59
|
+
return combat.round > 0 && combat.combatants.length > 0;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Returns the combatant `combat.turn` currently points at, if any.
|
|
63
|
+
*
|
|
64
|
+
* Yields `undefined` when nobody is acting yet — the encounter has not been
|
|
65
|
+
* started (initiatives are commonly assigned during round 0 setup), `turn` is
|
|
66
|
+
* null, or the stored index no longer resolves to a combatant.
|
|
67
|
+
*/
|
|
68
|
+
export function getCurrentCombatant(combat) {
|
|
69
|
+
if (!isCombatStarted(combat) || combat.turn === null || combat.turn === undefined) {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
return getTurnOrder(combat)[combat.turn];
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Computes where `actingCombatantId` lands in the turn order once `change` is
|
|
76
|
+
* applied — i.e. the `turn` index that keeps the same combatant acting.
|
|
77
|
+
*
|
|
78
|
+
* The change is projected onto a copy rather than read back from the cache:
|
|
79
|
+
* `setCombatantInitiative` resolves on the `modifyDocument` ack, while the
|
|
80
|
+
* cache is updated by the separate broadcast, so the cached initiative may or
|
|
81
|
+
* may not have caught up by the time this runs. Projecting is correct either
|
|
82
|
+
* way (re-applying the same value is a no-op).
|
|
83
|
+
*
|
|
84
|
+
* @returns the new index, or `undefined` if the acting combatant is gone.
|
|
85
|
+
*/
|
|
86
|
+
export function turnIndexAfterInitiativeChange(combat, change, actingCombatantId) {
|
|
87
|
+
const projected = {
|
|
88
|
+
...combat,
|
|
89
|
+
combatants: combat.combatants.map((c) => c._id === change.combatantId ? { ...c, initiative: change.initiative } : c),
|
|
90
|
+
};
|
|
91
|
+
const index = getTurnOrder(projected).findIndex((c) => c._id === actingCombatantId);
|
|
92
|
+
return index === -1 ? undefined : index;
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=combat-order.js.map
|