cwtools-mcp 0.2.9 → 0.5.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.
@@ -33,6 +33,9 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.fallbackBridgeTools = fallbackBridgeTools;
37
+ exports.fallbackBridgeResources = fallbackBridgeResources;
38
+ exports.localBridgeToolDenied = localBridgeToolDenied;
36
39
  exports.createBridgeProxyMcpServer = createBridgeProxyMcpServer;
37
40
  exports.assertBridgeWorkspaceMatches = assertBridgeWorkspaceMatches;
38
41
  const fs = __importStar(require("fs"));
@@ -40,12 +43,45 @@ const path = __importStar(require("path"));
40
43
  const url_1 = require("url");
41
44
  const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
42
45
  const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
46
+ const cwtools_shared_1 = require("cwtools-shared");
43
47
  const vscodeCache_1 = require("../hosts/vscodeCache");
44
48
  const resources_1 = require("./resources");
45
49
  const toolRegistrar_1 = require("./toolRegistrar");
46
50
  const toolHandlers_1 = require("./toolHandlers");
47
51
  const BRIDGE_MANIFEST_FILE = 'bridge-manifest.json';
48
52
  const BRIDGE_PROTOCOL_VERSION = 1;
53
+ function fallbackBridgeTools(project, includeWrites) {
54
+ if (project.kind === 'unsupported' || project.kind === 'ambiguous')
55
+ return [];
56
+ return (0, toolRegistrar_1.listRegisteredTools)({ includeWrites, cwtOnly: project.kind === 'cwt-only' });
57
+ }
58
+ function fallbackBridgeResources(project) {
59
+ if (project.kind === 'unsupported' || project.kind === 'ambiguous')
60
+ return [];
61
+ const resources = (0, resources_1.listResources)();
62
+ return project.kind === 'cwt-only'
63
+ ? resources.filter(resource => resource.uri === 'cwtools://knowledge/diagnostic-routing')
64
+ : resources;
65
+ }
66
+ function localBridgeToolDenied(project, name) {
67
+ if (project.kind !== 'unsupported' && project.kind !== 'ambiguous'
68
+ && (project.kind !== 'cwt-only'
69
+ || fallbackBridgeTools(project, true).some(tool => tool.name === name)))
70
+ return undefined;
71
+ return {
72
+ ok: false,
73
+ status: 'denied',
74
+ source: 'cwtools-mcp-bridge-proxy',
75
+ error: {
76
+ code: project.kind === 'ambiguous'
77
+ ? 'project_ambiguous'
78
+ : project.kind === 'unsupported' ? 'project_not_supported' : 'tool_not_available_in_cwt_only',
79
+ message: project.kind === 'cwt-only'
80
+ ? `Tool '${name}' requires a full Paradox game model and is not available in a CWT-only workspace.`
81
+ : project.reason,
82
+ },
83
+ };
84
+ }
49
85
  function createBridgeProxyMcpServer(config) {
50
86
  const server = new index_js_1.Server({
51
87
  name: 'cwtools-mcp',
@@ -64,27 +100,68 @@ function createBridgeProxyMcpServer(config) {
64
100
  });
65
101
  server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
66
102
  try {
103
+ const manifest = await readBridgeManifest(config, server);
104
+ if (!manifest.project) {
105
+ const project = await detectProxyWorkspace(config, server);
106
+ return { tools: fallbackBridgeTools(project, config.enableWrites) };
107
+ }
67
108
  return await bridgeRpc(config, server, 'tools/list', {
68
109
  allowDomainWrites: config.enableWrites,
69
- });
110
+ }, manifest);
70
111
  }
71
112
  catch {
72
- return { tools: (0, toolRegistrar_1.listRegisteredTools)({ includeWrites: config.enableWrites }) };
113
+ try {
114
+ const project = await detectProxyWorkspace(config, server);
115
+ return { tools: fallbackBridgeTools(project, config.enableWrites) };
116
+ }
117
+ catch {
118
+ return { tools: [] };
119
+ }
73
120
  }
74
121
  });
75
122
  server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => {
76
123
  try {
77
- return await bridgeRpc(config, server, 'resources/list', {});
124
+ const manifest = await readBridgeManifest(config, server);
125
+ if (!manifest.project) {
126
+ const project = await detectProxyWorkspace(config, server);
127
+ return { resources: fallbackBridgeResources(project) };
128
+ }
129
+ return await bridgeRpc(config, server, 'resources/list', {}, manifest);
78
130
  }
79
131
  catch {
80
- return { resources: (0, resources_1.listResources)() };
132
+ try {
133
+ const project = await detectProxyWorkspace(config, server);
134
+ return { resources: fallbackBridgeResources(project) };
135
+ }
136
+ catch {
137
+ return { resources: [] };
138
+ }
81
139
  }
82
140
  });
83
141
  server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
84
142
  try {
143
+ const manifest = await readBridgeManifest(config, server);
144
+ if (!manifest.project) {
145
+ const project = await detectProxyWorkspace(config, server);
146
+ if (!fallbackBridgeResources(project).some(resource => resource.uri === request.params.uri)) {
147
+ return {
148
+ contents: [{
149
+ uri: request.params.uri,
150
+ mimeType: 'application/json',
151
+ text: `${JSON.stringify({
152
+ status: 'error',
153
+ error: {
154
+ code: project.kind === 'ambiguous' ? 'project_ambiguous' : project.kind === 'unsupported' ? 'project_not_supported' : 'resource_not_available_in_cwt_only',
155
+ message: project.reason,
156
+ },
157
+ }, null, 2)}\n`,
158
+ }],
159
+ };
160
+ }
161
+ }
85
162
  return await bridgeRpc(config, server, 'resources/read', {
86
163
  uri: request.params.uri,
87
- });
164
+ }, manifest);
88
165
  }
89
166
  catch (error) {
90
167
  return {
@@ -103,21 +180,37 @@ function createBridgeProxyMcpServer(config) {
103
180
  const args = request.params.arguments && typeof request.params.arguments === 'object'
104
181
  ? request.params.arguments
105
182
  : {};
183
+ const manifest = await readBridgeManifest(config, server);
184
+ if (!manifest.project) {
185
+ const project = await detectProxyWorkspace(config, server);
186
+ const denied = localBridgeToolDenied(project, request.params.name);
187
+ if (denied)
188
+ return (0, toolHandlers_1.toMcpCallToolResult)(denied);
189
+ }
106
190
  const result = await bridgeRpc(config, server, 'tools/call', {
107
191
  name: request.params.name,
108
192
  arguments: args,
109
193
  allowDomainWrites: config.enableWrites,
110
- });
194
+ }, manifest);
111
195
  return normalizeCallToolResult(result);
112
196
  }
113
197
  catch (error) {
198
+ try {
199
+ const project = await detectProxyWorkspace(config, server);
200
+ const denied = localBridgeToolDenied(project, request.params.name);
201
+ if (denied)
202
+ return (0, toolHandlers_1.toMcpCallToolResult)(denied);
203
+ }
204
+ catch {
205
+ // Preserve the original bridge error when local fallback detection fails.
206
+ }
114
207
  return (0, toolHandlers_1.toMcpCallToolResult)(unavailableResult(error));
115
208
  }
116
209
  });
117
210
  return server;
118
211
  }
119
- async function bridgeRpc(config, server, method, params) {
120
- const manifest = await readBridgeManifest(config, server);
212
+ async function bridgeRpc(config, server, method, params, knownManifest) {
213
+ const manifest = knownManifest ?? await readBridgeManifest(config, server);
121
214
  const controller = new AbortController();
122
215
  const timer = setTimeout(() => controller.abort(), 30000);
123
216
  try {
@@ -184,6 +277,19 @@ async function resolveExpectedWorkspace(config, server) {
184
277
  }
185
278
  return { roots: [config.workspaceRoot], source: 'MCP process cwd' };
186
279
  }
280
+ async function detectProxyWorkspace(config, server) {
281
+ const expected = await resolveExpectedWorkspace(config, server);
282
+ if (expected.roots.length > 1) {
283
+ return {
284
+ kind: 'ambiguous',
285
+ strength: 'none',
286
+ evidence: [],
287
+ candidates: [...expected.roots].sort(),
288
+ reason: `Multiple MCP workspace roots are ambiguous for the CWTools bridge: ${expected.roots.join(', ')}`,
289
+ };
290
+ }
291
+ return (0, cwtools_shared_1.detectWorkspaceProject)(expected.roots[0] ?? config.workspaceRoot, () => undefined);
292
+ }
187
293
  async function readClientWorkspaceRoots(server) {
188
294
  if (!server.getClientCapabilities()?.roots)
189
295
  return [];
@@ -0,0 +1,2 @@
1
+ export { bindToolCallHandler, createToolCallHandler } from 'cwtools-shared';
2
+ export type { SharedToolHandler, ToolCallContext } from 'cwtools-shared';
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createToolCallHandler = exports.bindToolCallHandler = void 0;
4
+ // Compatibility re-export: the transport-neutral call handler moved to
5
+ // `cwtools-shared` so hosts without an MCP dependency can route tools.
6
+ var cwtools_shared_1 = require("cwtools-shared");
7
+ Object.defineProperty(exports, "bindToolCallHandler", { enumerable: true, get: function () { return cwtools_shared_1.bindToolCallHandler; } });
8
+ Object.defineProperty(exports, "createToolCallHandler", { enumerable: true, get: function () { return cwtools_shared_1.createToolCallHandler; } });
@@ -77,7 +77,7 @@ function listResources(host) {
77
77
  {
78
78
  uri: 'cwtools://project/knowledge-manifest',
79
79
  name: 'CWTools project knowledge manifest',
80
- description: 'Freshness, domains, counts, and fingerprints for the /init-generated semantic knowledge pack.',
80
+ description: 'Freshness, domains, counts, and fingerprints for the initialize_project semantic knowledge pack.',
81
81
  mimeType: 'application/json',
82
82
  },
83
83
  {
@@ -87,6 +87,11 @@ function listResources(host) {
87
87
  mimeType: 'application/json',
88
88
  },
89
89
  ];
90
+ if (host?.projectSupported === false)
91
+ return [];
92
+ if (host?.projectKind === 'cwt-only') {
93
+ return base.filter(resource => resource.uri === 'cwtools://knowledge/diagnostic-routing');
94
+ }
90
95
  if (host?.workspaceRoot) {
91
96
  for (const skill of discoverSkills(host.workspaceRoot)) {
92
97
  base.push({
@@ -100,6 +105,19 @@ function listResources(host) {
100
105
  return base;
101
106
  }
102
107
  async function readResource(host, uri) {
108
+ if (host.projectSupported === false
109
+ || (host.projectKind === 'cwt-only' && uri !== 'cwtools://knowledge/diagnostic-routing')) {
110
+ const code = host.projectKind === 'ambiguous'
111
+ ? 'project_ambiguous'
112
+ : host.projectSupported === false ? 'project_not_supported' : 'resource_not_available_in_cwt_only';
113
+ return {
114
+ contents: [{
115
+ uri,
116
+ mimeType: 'application/json',
117
+ text: `${JSON.stringify({ status: 'error', error: { code, message: host.projectSupportReason ?? 'Resource is not available for this workspace.' } }, null, 2)}\n`,
118
+ }],
119
+ };
120
+ }
103
121
  if (uri.startsWith('cwtools://skills/') && uri !== 'cwtools://skills/catalog') {
104
122
  const skillName = decodeURIComponent(uri.slice('cwtools://skills/'.length));
105
123
  const found = discoverSkills(host.workspaceRoot).find(entry => entry.name === skillName);
@@ -212,7 +230,7 @@ async function readResourceData(host, uri) {
212
230
  : {
213
231
  status: 'missing',
214
232
  profilePath,
215
- _hint: 'Run /init in the VS Code extension or create .cwtools/project/profile.json.',
233
+ _hint: 'Call initialize_project to generate the profile, then read this resource again.',
216
234
  };
217
235
  }
218
236
  case 'cwtools://project/knowledge-manifest': {
@@ -223,7 +241,7 @@ async function readResourceData(host, uri) {
223
241
  : {
224
242
  status: 'missing',
225
243
  manifestPath,
226
- _hint: 'Run /init in the VS Code extension and wait for the deep semantic phase.',
244
+ _hint: 'Call initialize_project and wait for the knowledge export to complete.',
227
245
  };
228
246
  }
229
247
  case 'cwtools://skills/catalog': {
@@ -1,5 +1,6 @@
1
- import { type HostServices, type SharedToolDispatcher, type SharedToolResult } from 'cwtools-shared';
2
- export declare function createToolCallHandler(host: HostServices, dispatcher?: SharedToolDispatcher): (name: string, args?: Record<string, unknown>) => Promise<SharedToolResult>;
1
+ import type { SharedToolResult } from 'cwtools-shared';
2
+ export { createToolCallHandler, bindToolCallHandler } from 'cwtools-shared';
3
+ export type { SharedToolHandler, ToolCallContext } from 'cwtools-shared';
3
4
  export declare function toMcpCallToolResult(result: SharedToolResult): {
4
5
  content: Array<{
5
6
  type: 'text';
@@ -1,49 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createToolCallHandler = createToolCallHandler;
3
+ exports.bindToolCallHandler = exports.createToolCallHandler = void 0;
4
4
  exports.toMcpCallToolResult = toMcpCallToolResult;
5
- const cwtools_shared_1 = require("cwtools-shared");
6
- function createToolCallHandler(host, dispatcher = cwtools_shared_1.defaultSharedToolDispatcher) {
7
- // The game stays loaded once ready, so probe readiness only until it flips true.
8
- let ready = false;
9
- const probeReadiness = async () => {
10
- if (ready)
11
- return { ready: true };
12
- try {
13
- const status = await host.lsp.executeCommand('cwtools.ai.getValidationStatus', [], { timeoutMs: 8000 });
14
- const verdict = (0, cwtools_shared_1.parseReadiness)(status);
15
- if (verdict.ready)
16
- ready = true;
17
- return verdict;
18
- }
19
- catch {
20
- return { ready: false, reason: 'lsp_unavailable' };
21
- }
22
- };
23
- return async (name, args = {}) => {
24
- const writesEnabled = host.writesEnabled === true && host.readonlyMode === false;
25
- if (!(0, cwtools_shared_1.isMcpToolName)(name, { includeWrites: writesEnabled })) {
26
- return {
27
- ok: false,
28
- status: 'denied',
29
- source: 'cwtools-mcp',
30
- error: {
31
- code: 'tool_not_available',
32
- message: `Tool '${name}' is not available: this MCP server is read-only unless started with --allow-domain-writes (or --enable-writes).`,
33
- },
34
- };
35
- }
36
- const result = await dispatcher(host, name, args);
37
- // Tag vanilla-dependent results with cache provenance so clients never read a
38
- // mod-only answer as complete.
39
- const withVanilla = (0, cwtools_shared_1.annotateVanillaCache)(name, result, host.vanillaCache);
40
- // For load-dependent tools, mark results produced before the game is ready as
41
- // `loading` so clients retry instead of trusting an empty answer.
42
- if (!cwtools_shared_1.LOAD_DEPENDENT_TOOLS.has(name))
43
- return withVanilla;
44
- return (0, cwtools_shared_1.annotateReadiness)(name, withVanilla, await probeReadiness());
45
- };
46
- }
5
+ // MCP-specific adapter. The transport-neutral handler lives in
6
+ // `cwtools-shared` (tools/callHandler) and is re-exported here for compatibility.
7
+ var cwtools_shared_1 = require("cwtools-shared");
8
+ Object.defineProperty(exports, "createToolCallHandler", { enumerable: true, get: function () { return cwtools_shared_1.createToolCallHandler; } });
9
+ Object.defineProperty(exports, "bindToolCallHandler", { enumerable: true, get: function () { return cwtools_shared_1.bindToolCallHandler; } });
47
10
  function toMcpCallToolResult(result) {
48
11
  return {
49
12
  content: [
@@ -1,4 +1,2 @@
1
- import { type McpToolSchema } from 'cwtools-shared';
2
- export declare function listRegisteredTools(options?: {
3
- includeWrites?: boolean;
4
- }): McpToolSchema[];
1
+ import { type McpToolSchema, type ToolSurfaceOptions } from 'cwtools-shared';
2
+ export declare function listRegisteredTools(options?: ToolSurfaceOptions): McpToolSchema[];
package/dist/server.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
2
  import type { HostServices, SharedToolDispatcher } from 'cwtools-shared';
3
+ export declare function listServerTools(host: HostServices): import("cwtools-shared").McpToolSchema[];
3
4
  export declare function createCwtoolsMcpServer(host: HostServices, options?: {
4
5
  dispatcher?: SharedToolDispatcher;
5
6
  }): Server;
package/dist/server.js CHANGED
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listServerTools = listServerTools;
3
4
  exports.createCwtoolsMcpServer = createCwtoolsMcpServer;
4
5
  const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
5
6
  const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
@@ -8,8 +9,8 @@ const toolHandlers_1 = require("./mcp/toolHandlers");
8
9
  const resources_1 = require("./mcp/resources");
9
10
  // Server-level guidance surfaced to the model at connect time (MCP `instructions`).
10
11
  // Tells a Paradox coding agent to ground every claim in these tools.
11
- const SERVER_INSTRUCTIONS = [
12
- 'CWTools is a read-only semantic service for Paradox mods. Ground every',
12
+ const FULL_SERVER_INSTRUCTIONS = [
13
+ 'CWTools provides semantic and whitelisted domain-write tools for Paradox mods. Ground every',
13
14
  'claim about the mod in these tools instead of memory — PDX identifiers and syntax',
14
15
  'are routinely hallucinated.',
15
16
  '',
@@ -32,9 +33,30 @@ const SERVER_INSTRUCTIONS = [
32
33
  '- Results carry vanillaCache metadata: if available is false, vanilla IDs are missing',
33
34
  ' and references to them may show as false errors.',
34
35
  '',
35
- 'This server never writes files — perform edits with your own environment, then',
36
- 're-check with get_diagnostics.',
36
+ 'Use only the exposed whitelisted domain-write tools for writes, then re-check',
37
+ 'with get_diagnostics. Non-whitelisted writes remain unavailable.',
37
38
  ].join('\n');
39
+ function serverInstructions(host) {
40
+ if (host.projectSupported === false) {
41
+ return `CWTools is unavailable for this workspace: ${host.projectSupportReason ?? 'not a Paradox/CWT project.'}`;
42
+ }
43
+ if (host.projectKind === 'cwt-only') {
44
+ return 'CWTools is running in CWT-only mode. Use the exposed document, navigation, and diagnostics tools for CWT rules; no game model is loaded.';
45
+ }
46
+ if (host.projectGameId === 'paradox') {
47
+ return `${FULL_SERVER_INSTRUCTIONS}\n\nThe exact game is unknown. Generic Paradox mode is active; no game-specific rules or vanilla cache are assumed. Pass --game to enable a specific game model.`;
48
+ }
49
+ return FULL_SERVER_INSTRUCTIONS;
50
+ }
51
+ function listServerTools(host) {
52
+ if (host.projectSupported === false || host.projectKind === 'unsupported' || host.projectKind === 'ambiguous')
53
+ return [];
54
+ return (0, toolRegistrar_1.listRegisteredTools)({
55
+ includeWrites: host.writesEnabled === true && host.readonlyMode === false,
56
+ cwtOnly: host.projectKind === 'cwt-only',
57
+ capabilities: host.capabilities,
58
+ });
59
+ }
38
60
  function createCwtoolsMcpServer(host, options = {}) {
39
61
  // Undefined => treat as supported (e.g. the in-extension host never sets it).
40
62
  const supported = host.projectSupported !== false;
@@ -46,15 +68,12 @@ function createCwtoolsMcpServer(host, options = {}) {
46
68
  resources: {},
47
69
  tools: {},
48
70
  },
49
- instructions: SERVER_INSTRUCTIONS,
71
+ instructions: serverInstructions(host),
50
72
  });
51
73
  const callTool = (0, toolHandlers_1.createToolCallHandler)(host, options.dispatcher);
52
- // Tools stay listed even on unsupported workspaces so the model can always see
53
- // CWTools exists (instead of falling back to hunting for a CLI). The heavy work
54
- // is gated at call time below, not by hiding the toolset.
55
- server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
56
- tools: (0, toolRegistrar_1.listRegisteredTools)({ includeWrites: host.writesEnabled === true && host.readonlyMode === false }),
57
- }));
74
+ // Unsupported projects disclose no schemas. Calls are still gated below for
75
+ // clients holding a cached tool list from a previous workspace/session.
76
+ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({ tools: listServerTools(host) }));
58
77
  server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => ({
59
78
  resources: (0, resources_1.listResources)(host),
60
79
  }));
@@ -69,8 +88,8 @@ function createCwtoolsMcpServer(host, options = {}) {
69
88
  status: 'denied',
70
89
  source: 'cwtools-mcp',
71
90
  error: {
72
- code: 'project_not_supported',
73
- message: `CWTools is disabled for this workspace (${host.workspaceRoot}): ${host.projectSupportReason ?? 'not a Paradox mod.'} ` +
91
+ code: host.projectKind === 'ambiguous' ? 'project_ambiguous' : 'project_not_supported',
92
+ message: `CWTools is disabled for this workspace (${host.workspaceRoot}): ${host.projectSupportReason ?? 'not a Paradox/CWT project.'} ` +
74
93
  'If this IS a mod, point the server at the mod root — set the working directory (or pass --workspace <mod>) — or pass --force-start to override.',
75
94
  },
76
95
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cwtools-mcp",
3
- "version": "0.2.9",
4
- "description": "Read-only MCP server exposing CWTools Paradox/Stellaris semantic tools to external agents",
3
+ "version": "0.5.0",
4
+ "description": "MCP server exposing CWTools semantic tools and default-on whitelisted domain writes",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -36,11 +36,10 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@modelcontextprotocol/sdk": "^1.29.0",
39
- "chokidar": "^4.0.3",
40
- "cwtools-shared": "0.2.9",
41
- "vscode-jsonrpc": "^8.2.0"
39
+ "cwtools-node": "0.3.0",
40
+ "cwtools-shared": "0.4.0"
42
41
  },
43
42
  "devDependencies": {
44
43
  "esbuild": "^0.28.1"
45
44
  }
46
- }
45
+ }