@terpomosoft/pmitz-mcp 0.0.0-stage → 0.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.
Files changed (3) hide show
  1. package/README.md +19 -2
  2. package/package.json +24 -4
  3. package/pmitz-mcp.mjs +672 -0
package/README.md CHANGED
@@ -1,3 +1,20 @@
1
- # Temporary Holding Version
1
+ # Pmitz MCP server (local)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A local MCP server that lets a coding assistant read and change your own [Pmitz](https://github.com/terpomo-io/pmitz) server through its REST API. It needs Node.js 18 or newer and has no dependencies.
4
+
5
+ ```bash
6
+ codex mcp add pmitz -- npx -y @terpomosoft/pmitz-mcp@0.1.0
7
+ claude mcp add pmitz -- npx -y @terpomosoft/pmitz-mcp@0.1.0
8
+ ```
9
+
10
+ Set these in the environment the assistant starts from:
11
+
12
+ | Variable | Meaning |
13
+ |---|---|
14
+ | `PMITZ_BASE_URL` | Base URL of your Pmitz server, for example `http://127.0.0.1:8080` |
15
+ | `PMITZ_API_KEY` | API key of that server. It is sent only to that URL, in the `X-Api-Key` header. |
16
+ | `PMITZ_MCP_READ_ONLY` | Optional. Set to `true` to offer only the tools that read. |
17
+
18
+ The server offers eleven tools: it checks entitlements and limits, reads subscriptions, creates and removes products and subscriptions, and records or reduces usage. A Pmitz API key has full authority over its server, so connect a development server, or use read-only mode.
19
+
20
+ The tools and settings are described in the [Pmitz plugin README](https://github.com/terpomo-io/pmitz/tree/main/plugins/pmitz#your-own-server-the-local-connector). The plugin bundles this server for Claude Code and Codex, together with a skill and a hosted MCP server that creates an instant Pmitz server for trying the product.
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@terpomosoft/pmitz-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Local MCP server for Pmitz: lets a coding assistant read and change your own Pmitz server.",
5
+ "keywords": ["mcp", "pmitz", "subscriptions", "entitlements", "usage-limits"],
6
+ "license": "Apache-2.0",
7
+ "author": "Terpomo Software (https://terpomosoft.com/)",
8
+ "homepage": "https://github.com/terpomo-io/pmitz/tree/main/plugins/pmitz#your-own-server-the-local-connector",
9
+ "bugs": "https://github.com/terpomo-io/pmitz/issues",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/terpomo-io/pmitz.git",
13
+ "directory": "plugins/pmitz/server"
14
+ },
15
+ "type": "module",
16
+ "bin": {
17
+ "pmitz-mcp": "pmitz-mcp.mjs"
18
+ },
19
+ "files": ["pmitz-mcp.mjs"],
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ }
26
+ }
package/pmitz-mcp.mjs ADDED
@@ -0,0 +1,672 @@
1
+ #!/usr/bin/env node
2
+ // Pmitz MCP connector.
3
+ //
4
+ // A local MCP server (stdio, JSON-RPC 2.0) that lets a coding assistant inspect and change a
5
+ // Pmitz server through its REST API. It has no dependencies and needs Node.js 18 or newer.
6
+ //
7
+ // Configuration comes from environment variables only. Tool arguments can never change the
8
+ // destination, supply a credential, or leave read-only mode.
9
+ //
10
+ // PMITZ_BASE_URL Base URL of the Pmitz server, for example http://127.0.0.1:8080
11
+ // PMITZ_API_KEY API key of that server. Sent only in the X-Api-Key header to PMITZ_BASE_URL.
12
+ // PMITZ_MCP_READ_ONLY Optional. Set to "true" to offer only the tools that read.
13
+
14
+ import { realpathSync } from 'node:fs';
15
+ import { createInterface } from 'node:readline';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ const SERVER_NAME = 'pmitz';
19
+ const SERVER_VERSION = '0.1.0';
20
+ const SUPPORTED_PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
21
+ const REQUEST_TIMEOUT_MS = 15000;
22
+ const GROUP_TYPES = ['subscriptions', 'users', 'directory-groups'];
23
+ const SUBSCRIPTION_STATUSES = ['TRIAL', 'TRIAL_ENDED', 'PENDING', 'ACTIVE', 'SUSPENDED', 'EXPIRED',
24
+ 'PENDING_CANCELLATION', 'CANCELLED', 'TERMINATED', 'ENDED'];
25
+
26
+ // ---------------------------------------------------------------------------------------------
27
+ // Configuration
28
+ // ---------------------------------------------------------------------------------------------
29
+
30
+ function readSetting(name) {
31
+ const value = (process.env[name] ?? '').trim();
32
+ // A host that did not fill in a placeholder passes it through literally; treat that as unset.
33
+ return value.startsWith('${') ? '' : value;
34
+ }
35
+
36
+ function normalizeBaseUrl(value) {
37
+ if (!value) {
38
+ return null;
39
+ }
40
+ let url;
41
+ try {
42
+ url = new URL(value);
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password
48
+ || url.search || url.hash) {
49
+ return null;
50
+ }
51
+ const path = url.pathname.replace(/\/+$/, '');
52
+ return `${url.protocol}//${url.host}${path}`;
53
+ }
54
+
55
+ function loadConfig() {
56
+ const rawBaseUrl = readSetting('PMITZ_BASE_URL');
57
+ const baseUrl = normalizeBaseUrl(rawBaseUrl);
58
+ const apiKey = readSetting('PMITZ_API_KEY');
59
+ const readOnly = ['1', 'true', 'yes', 'on'].includes(readSetting('PMITZ_MCP_READ_ONLY').toLowerCase());
60
+
61
+ const problems = [];
62
+ if (!rawBaseUrl) {
63
+ problems.push('PMITZ_BASE_URL is not set.');
64
+ }
65
+ else if (!baseUrl) {
66
+ problems.push('PMITZ_BASE_URL must be an http or https URL without credentials, query or fragment.');
67
+ }
68
+ if (!apiKey) {
69
+ problems.push('PMITZ_API_KEY is not set.');
70
+ }
71
+
72
+ return {
73
+ baseUrl,
74
+ apiKey,
75
+ problems,
76
+ readOnly,
77
+ };
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------------------------
81
+ // Tool definitions
82
+ // ---------------------------------------------------------------------------------------------
83
+
84
+ const subjectProperties = {
85
+ groupType: {
86
+ type: 'string',
87
+ enum: GROUP_TYPES,
88
+ description: 'Kind of subject. Use "subscriptions" when access depends on a plan.',
89
+ },
90
+ groupId: { type: 'string', description: 'Identifier of the subscription, user or directory group.' },
91
+ productId: { type: 'string', description: 'Product ID from the catalog.' },
92
+ featureId: { type: 'string', description: 'Feature ID inside that product.' },
93
+ };
94
+ const subjectRequired = ['groupId', 'productId', 'featureId'];
95
+ const unitsProperty = {
96
+ type: 'object',
97
+ description: 'Units per limit ID, for example {"monthly-exports": 1}. Each value is a positive integer.',
98
+ additionalProperties: { type: 'integer', minimum: 1 },
99
+ };
100
+
101
+ const TOOLS = [
102
+ {
103
+ name: 'pmitz_connection_status',
104
+ write: false,
105
+ description: 'Shows which Pmitz server this connector is configured for, whether it is reachable, and '
106
+ + 'whether it is in read-only mode. It never shows the API key.',
107
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
108
+ },
109
+ {
110
+ name: 'pmitz_verify_entitlement',
111
+ write: false,
112
+ description: 'Checks whether a subject may use a feature. Returns featureAllowed and, on denial, the cause '
113
+ + '(INVALID_SUBSCRIPTION, PRODUCT_NOT_ALLOWED or FEATURE_NOT_ALLOWED).',
114
+ inputSchema: { type: 'object', properties: subjectProperties, required: subjectRequired, additionalProperties: false },
115
+ },
116
+ {
117
+ name: 'pmitz_check_limits',
118
+ write: false,
119
+ description: 'Previews whether the requested units fit. Returns featureStatus (AVAILABLE, LIMIT_EXCEEDED or '
120
+ + 'NOT_ALLOWED) and the units that would remain after the action. Nothing is reserved or recorded.',
121
+ inputSchema: {
122
+ type: 'object',
123
+ properties: { ...subjectProperties, units: unitsProperty },
124
+ required: [...subjectRequired, 'units'],
125
+ additionalProperties: false,
126
+ },
127
+ },
128
+ {
129
+ name: 'pmitz_get_remaining_limits',
130
+ write: false,
131
+ description: 'Reads the remaining units of each limit of a feature for a subject. For a subscription the '
132
+ + 'limits of its plan are applied. A negative value means usage is already above the limit.',
133
+ inputSchema: { type: 'object', properties: subjectProperties, required: subjectRequired, additionalProperties: false },
134
+ },
135
+ {
136
+ name: 'pmitz_find_subscription',
137
+ write: false,
138
+ description: 'Reads a subscription: its status, expiration date and plan per product.',
139
+ inputSchema: {
140
+ type: 'object',
141
+ properties: { subscriptionId: { type: 'string', description: 'Subscription ID.' } },
142
+ required: ['subscriptionId'],
143
+ additionalProperties: false,
144
+ },
145
+ },
146
+ {
147
+ name: 'pmitz_create_product',
148
+ write: true,
149
+ destructive: false,
150
+ description: 'Creates a product with its features, limits and plans. Fails with a conflict if the product ID '
151
+ + 'already exists; there is no update, so changing a product means removing it and creating it again.',
152
+ inputSchema: {
153
+ type: 'object',
154
+ properties: {
155
+ product: {
156
+ type: 'object',
157
+ description: 'One product object with productId, features and plans, in the Pmitz catalog format.',
158
+ },
159
+ },
160
+ required: ['product'],
161
+ additionalProperties: false,
162
+ },
163
+ },
164
+ {
165
+ name: 'pmitz_remove_product',
166
+ write: true,
167
+ destructive: true,
168
+ description: 'Removes a product definition. Every check for that product is refused until it is created '
169
+ + 'again. Stored usage and subscriptions are kept.',
170
+ inputSchema: {
171
+ type: 'object',
172
+ properties: { productId: { type: 'string', description: 'Product ID to remove.' } },
173
+ required: ['productId'],
174
+ additionalProperties: false,
175
+ },
176
+ },
177
+ {
178
+ name: 'pmitz_create_subscription',
179
+ write: true,
180
+ destructive: false,
181
+ description: 'Creates a subscription and assigns a plan per product. Fails with a conflict if the '
182
+ + 'subscription ID already exists.',
183
+ inputSchema: {
184
+ type: 'object',
185
+ properties: {
186
+ subscriptionId: { type: 'string', description: 'New subscription ID.' },
187
+ status: { type: 'string', enum: SUBSCRIPTION_STATUSES, description: 'Initial status, usually ACTIVE.' },
188
+ plans: {
189
+ type: 'object',
190
+ description: 'Plan ID per product ID, for example {"reports": "free"}.',
191
+ additionalProperties: { type: 'string' },
192
+ },
193
+ expirationDate: {
194
+ type: 'string',
195
+ description: 'Optional ISO date-time with an offset, for example 2027-01-31T00:00:00Z.',
196
+ },
197
+ },
198
+ required: ['subscriptionId', 'status', 'plans'],
199
+ additionalProperties: false,
200
+ },
201
+ },
202
+ {
203
+ name: 'pmitz_update_subscription_status',
204
+ write: true,
205
+ destructive: true,
206
+ description: 'Changes the status of a subscription. A status that is not valid, such as SUSPENDED or '
207
+ + 'CANCELLED, makes every feature check for that subscription fail.',
208
+ inputSchema: {
209
+ type: 'object',
210
+ properties: {
211
+ subscriptionId: { type: 'string', description: 'Subscription ID.' },
212
+ status: { type: 'string', enum: SUBSCRIPTION_STATUSES, description: 'New status.' },
213
+ },
214
+ required: ['subscriptionId', 'status'],
215
+ additionalProperties: false,
216
+ },
217
+ },
218
+ {
219
+ name: 'pmitz_record_usage',
220
+ write: true,
221
+ destructive: false,
222
+ description: 'Records consumed units for a subject. Refused when a limit would be exceeded. To test an '
223
+ + 'application integration, trigger the action through the application instead of calling this tool.',
224
+ inputSchema: {
225
+ type: 'object',
226
+ properties: { ...subjectProperties, units: unitsProperty },
227
+ required: [...subjectRequired, 'units'],
228
+ additionalProperties: false,
229
+ },
230
+ },
231
+ {
232
+ name: 'pmitz_reduce_usage',
233
+ write: true,
234
+ destructive: true,
235
+ description: 'Subtracts units from the recorded usage of a subject, for example after a seat is freed. '
236
+ + 'It subtracts; it does not restore an earlier value.',
237
+ inputSchema: {
238
+ type: 'object',
239
+ properties: { ...subjectProperties, units: unitsProperty },
240
+ required: [...subjectRequired, 'units'],
241
+ additionalProperties: false,
242
+ },
243
+ },
244
+ ];
245
+
246
+ function toolListing(tool) {
247
+ return {
248
+ name: tool.name,
249
+ description: tool.description,
250
+ inputSchema: tool.inputSchema,
251
+ annotations: {
252
+ readOnlyHint: !tool.write,
253
+ destructiveHint: Boolean(tool.write && tool.destructive),
254
+ idempotentHint: !tool.write,
255
+ openWorldHint: false,
256
+ },
257
+ };
258
+ }
259
+
260
+ // ---------------------------------------------------------------------------------------------
261
+ // Argument checks
262
+ // ---------------------------------------------------------------------------------------------
263
+
264
+ class ToolError extends Error {}
265
+
266
+ function requireId(args, name) {
267
+ const value = args[name];
268
+ if (typeof value !== 'string' || value.trim() === '') {
269
+ throw new ToolError(`"${name}" must be a non-empty string.`);
270
+ }
271
+ return value;
272
+ }
273
+
274
+ function requireEnum(args, name, allowed, fallback) {
275
+ const value = args[name] ?? fallback;
276
+ if (!allowed.includes(value)) {
277
+ throw new ToolError(`"${name}" must be one of: ${allowed.join(', ')}.`);
278
+ }
279
+ return value;
280
+ }
281
+
282
+ function requireUnits(args) {
283
+ const units = args.units;
284
+ if (units === null || typeof units !== 'object' || Array.isArray(units) || Object.keys(units).length === 0) {
285
+ throw new ToolError('"units" must be an object with at least one limit ID.');
286
+ }
287
+ for (const [limitId, value] of Object.entries(units)) {
288
+ if (!Number.isInteger(value) || value < 1) {
289
+ throw new ToolError(`"units.${limitId}" must be a positive integer.`);
290
+ }
291
+ }
292
+ return units;
293
+ }
294
+
295
+ function subjectPath(args, operation) {
296
+ const groupType = requireEnum(args, 'groupType', GROUP_TYPES, 'subscriptions');
297
+ const segments = [groupType, requireId(args, 'groupId'), operation, requireId(args, 'productId'),
298
+ requireId(args, 'featureId')];
299
+ return '/' + segments.map(encodeURIComponent).join('/');
300
+ }
301
+
302
+ // ---------------------------------------------------------------------------------------------
303
+ // REST calls
304
+ // ---------------------------------------------------------------------------------------------
305
+
306
+ // Sends one request to the configured Pmitz server and returns { status, body }.
307
+ function createRestTransport(config) {
308
+ return async function callPmitz(method, path, body) {
309
+ const controller = new AbortController();
310
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
311
+ try {
312
+ const headers = { 'X-Api-Key': config.apiKey };
313
+ if (body !== undefined) {
314
+ headers['Content-Type'] = 'application/json';
315
+ }
316
+ const response = await fetch(config.baseUrl + path, {
317
+ method,
318
+ headers,
319
+ body: (body === undefined) ? undefined : JSON.stringify(body),
320
+ signal: controller.signal,
321
+ redirect: 'error',
322
+ });
323
+ const text = await response.text();
324
+ let parsed = null;
325
+ if (text) {
326
+ try {
327
+ parsed = JSON.parse(text);
328
+ }
329
+ catch {
330
+ parsed = text.slice(0, 2000);
331
+ }
332
+ }
333
+ return { status: response.status, body: parsed };
334
+ }
335
+ catch (error) {
336
+ const reason = (error?.name === 'AbortError')
337
+ ? `no answer within ${REQUEST_TIMEOUT_MS / 1000} seconds`
338
+ : (error?.cause?.code ?? error?.message ?? 'request failed');
339
+ throw new ToolError(`Could not reach the Pmitz server at ${config.baseUrl}: ${reason}.`);
340
+ }
341
+ finally {
342
+ clearTimeout(timer);
343
+ }
344
+ };
345
+ }
346
+
347
+ // ---------------------------------------------------------------------------------------------
348
+ // Toolset
349
+ // ---------------------------------------------------------------------------------------------
350
+
351
+ // Builds the tools for one Pmitz server. The context supplies how to reach it:
352
+ // server label shown in results, normally the base URL
353
+ // callPmitz async (method, path, body) => ({ status, body })
354
+ // connectionStatus async () => object, the answer of pmitz_connection_status
355
+ // readOnly true to offer only the tools that read
356
+ // problems configuration problems; when not empty every other tool is refused
357
+ // omit tool names to leave out
358
+ export function createToolset(context) {
359
+ const omitted = new Set(context.omit ?? []);
360
+ const problems = context.problems ?? [];
361
+ const callPmitz = context.callPmitz;
362
+
363
+ function outcome(response, meanings) {
364
+ const meaning = meanings[response.status]
365
+ ?? ((response.status === 401 || response.status === 403)
366
+ ? 'The Pmitz server rejected the API key.'
367
+ : `Unexpected HTTP ${response.status} from the Pmitz server.`);
368
+ return {
369
+ ok: response.status >= 200 && response.status < 300,
370
+ server: context.server,
371
+ httpStatus: response.status,
372
+ meaning,
373
+ result: response.body,
374
+ };
375
+ }
376
+
377
+ const HANDLERS = {
378
+ async pmitz_connection_status() {
379
+ return context.connectionStatus();
380
+ },
381
+
382
+ async pmitz_verify_entitlement(args) {
383
+ const response = await callPmitz('GET', subjectPath(args, 'subscription-check'));
384
+ return outcome(response, { 200: 'Entitlement decision returned. Read featureAllowed.' });
385
+ },
386
+
387
+ async pmitz_check_limits(args) {
388
+ const path = subjectPath(args, 'limits-check');
389
+ const response = await callPmitz('POST', path, requireUnits(args));
390
+ return outcome(response, { 200: 'Preview returned. Read featureStatus; nothing was recorded.' });
391
+ },
392
+
393
+ async pmitz_get_remaining_limits(args) {
394
+ const response = await callPmitz('GET', subjectPath(args, 'usage'));
395
+ const limitIds = Object.keys(response.body?.remainingUsageUnits ?? {});
396
+ const groupType = args.groupType ?? 'subscriptions';
397
+ if (response.status !== 200 || groupType !== 'subscriptions' || limitIds.length === 0) {
398
+ return outcome(response, { 200: 'Current status and remaining units returned.' });
399
+ }
400
+ // In Pmitz 0.10.0 the usage endpoint ignores the subscription's plan and answers with the
401
+ // feature's default limits. The preview endpoint applies the plan, so the current values are
402
+ // derived from a preview of one unit per limit, which records nothing.
403
+ const oneUnitEach = Object.fromEntries(limitIds.map((limitId) => [limitId, 1]));
404
+ const preview = await callPmitz('POST', subjectPath(args, 'limits-check'), oneUnitEach);
405
+ const afterOneUnit = preview.body?.remainingUsageUnits;
406
+ if (preview.status !== 200 || !afterOneUnit || limitIds.some((id) => !Number.isFinite(afterOneUnit[id]))) {
407
+ return outcome(preview, { 200: 'The Pmitz server did not return the remaining units.' });
408
+ }
409
+ const remaining = Object.fromEntries(limitIds.map((limitId) => [limitId, afterOneUnit[limitId] + 1]));
410
+ const values = Object.values(remaining);
411
+ response.body = {
412
+ featureStatus: values.some((value) => value < 0) ? 'LIMIT_EXCEEDED' : 'AVAILABLE',
413
+ remainingUsageUnits: remaining,
414
+ limitReached: values.some((value) => value <= 0),
415
+ };
416
+ return outcome(response, { 200: 'Current remaining units, with the limits of the subscription\'s plan applied.' });
417
+ },
418
+
419
+ async pmitz_find_subscription(args) {
420
+ const path = '/subscriptions/' + encodeURIComponent(requireId(args, 'subscriptionId'));
421
+ const response = await callPmitz('GET', path);
422
+ return outcome(response, { 200: 'Subscription found.', 404: 'No subscription has this ID.' });
423
+ },
424
+
425
+ async pmitz_create_product(args) {
426
+ const product = args.product;
427
+ if (product === null || typeof product !== 'object' || Array.isArray(product)) {
428
+ throw new ToolError('"product" must be one product object, not an array.');
429
+ }
430
+ requireId(product, 'productId');
431
+ const response = await callPmitz('POST', '/products', product);
432
+ return outcome(response, {
433
+ 200: 'Product created.',
434
+ 409: 'A product with this ID already exists. It was left unchanged.',
435
+ });
436
+ },
437
+
438
+ async pmitz_remove_product(args) {
439
+ const path = '/products/' + encodeURIComponent(requireId(args, 'productId'));
440
+ const response = await callPmitz('DELETE', path);
441
+ return outcome(response, { 200: 'Product removed.', 404: 'No product has this ID.' });
442
+ },
443
+
444
+ async pmitz_create_subscription(args) {
445
+ const plans = args.plans;
446
+ if (plans === null || typeof plans !== 'object' || Array.isArray(plans)
447
+ || Object.values(plans).some((planId) => typeof planId !== 'string' || planId === '')) {
448
+ throw new ToolError('"plans" must be an object that maps product IDs to plan IDs.');
449
+ }
450
+ const subscription = {
451
+ subscriptionId: requireId(args, 'subscriptionId'),
452
+ status: requireEnum(args, 'status', SUBSCRIPTION_STATUSES),
453
+ plans,
454
+ };
455
+ if (args.expirationDate !== undefined) {
456
+ subscription.expirationDate = requireId(args, 'expirationDate');
457
+ }
458
+ const response = await callPmitz('POST', '/subscriptions', subscription);
459
+ return outcome(response, {
460
+ 200: 'Subscription created.',
461
+ 409: 'A subscription with this ID already exists. It was left unchanged.',
462
+ });
463
+ },
464
+
465
+ async pmitz_update_subscription_status(args) {
466
+ const path = '/subscriptions/' + encodeURIComponent(requireId(args, 'subscriptionId')) + '/status';
467
+ const body = { status: requireEnum(args, 'status', SUBSCRIPTION_STATUSES) };
468
+ const response = await callPmitz('PATCH', path, body);
469
+ return outcome(response, { 200: 'Status updated.', 404: 'No subscription has this ID.' });
470
+ },
471
+
472
+ async pmitz_record_usage(args) {
473
+ const body = { units: requireUnits(args), reduceUnits: false };
474
+ const response = await callPmitz('POST', subjectPath(args, 'usage'), body);
475
+ return outcome(response, {
476
+ 200: 'Usage recorded.',
477
+ 422: 'Refused: a limit would be exceeded. Nothing was recorded.',
478
+ 500: 'The server failed. In Pmitz 0.10.0 this is also the answer when the subject is not entitled '
479
+ + 'to the feature; check with pmitz_verify_entitlement.',
480
+ });
481
+ },
482
+
483
+ async pmitz_reduce_usage(args) {
484
+ const body = { units: requireUnits(args), reduceUnits: true };
485
+ const response = await callPmitz('POST', subjectPath(args, 'usage'), body);
486
+ return outcome(response, {
487
+ 200: 'Usage reduced.',
488
+ 500: 'The server failed. In Pmitz 0.10.0 this is also the answer when the subject is not entitled '
489
+ + 'to the feature; check with pmitz_verify_entitlement.',
490
+ });
491
+ },
492
+ };
493
+
494
+ // In read-only mode the write tools are hidden, and refused again when a call is dispatched.
495
+ function listTools() {
496
+ return TOOLS.filter((tool) => !omitted.has(tool.name) && (!tool.write || !context.readOnly)).map(toolListing);
497
+ }
498
+
499
+ async function callTool(name, args) {
500
+ const tool = TOOLS.find((candidate) => candidate.name === name && !omitted.has(candidate.name));
501
+ if (!tool) {
502
+ throw new ToolError(`Unknown tool: ${name}.`);
503
+ }
504
+ if (tool.write && context.readOnly) {
505
+ throw new ToolError(context.readOnlyMessage ?? 'The connector is in read-only mode. A person has to turn '
506
+ + 'that off by unsetting PMITZ_MCP_READ_ONLY and restarting the connector.');
507
+ }
508
+ if (name !== 'pmitz_connection_status' && problems.length > 0) {
509
+ throw new ToolError('The connector is not configured: ' + problems.join(' '));
510
+ }
511
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) {
512
+ throw new ToolError('Tool arguments must be an object.');
513
+ }
514
+ return HANDLERS[name](args);
515
+ }
516
+
517
+ return { listTools, callTool };
518
+ }
519
+
520
+ // The toolset for the server named in the environment: what the stdio connector serves.
521
+ function createLocalToolset(config) {
522
+ return createToolset({
523
+ server: config.baseUrl,
524
+ callPmitz: createRestTransport(config),
525
+ readOnly: config.readOnly,
526
+ problems: config.problems,
527
+ async connectionStatus() {
528
+ const status = {
529
+ server: config.baseUrl,
530
+ apiKeyConfigured: Boolean(config.apiKey),
531
+ readOnly: config.readOnly,
532
+ configurationProblems: config.problems,
533
+ };
534
+ if (config.readOnly) {
535
+ status.readOnlyNote = 'Read-only mode is on (PMITZ_MCP_READ_ONLY). Only the tools that read are offered.';
536
+ }
537
+ if (config.problems.length === 0) {
538
+ try {
539
+ const response = await fetch(config.baseUrl + '/actuator/health', {
540
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
541
+ redirect: 'error',
542
+ });
543
+ status.reachable = response.ok;
544
+ status.healthHttpStatus = response.status;
545
+ }
546
+ catch (error) {
547
+ status.reachable = false;
548
+ status.reachError = error?.cause?.code ?? error?.message ?? 'request failed';
549
+ }
550
+ }
551
+ return status;
552
+ },
553
+ });
554
+ }
555
+
556
+ export { ToolError, SERVER_VERSION, SUBSCRIPTION_STATUSES, GROUP_TYPES };
557
+
558
+ // ---------------------------------------------------------------------------------------------
559
+ // MCP over stdio (only when this file is run as a program)
560
+ // ---------------------------------------------------------------------------------------------
561
+
562
+ function send(message) {
563
+ process.stdout.write(JSON.stringify(message) + '\n');
564
+ }
565
+
566
+ function reply(id, result) {
567
+ send({ jsonrpc: '2.0', id, result });
568
+ }
569
+
570
+ function replyError(id, code, message) {
571
+ send({ jsonrpc: '2.0', id, error: { code, message } });
572
+ }
573
+
574
+ function toolResult(value, isError) {
575
+ const text = (typeof value === 'string') ? value : JSON.stringify(value, null, 2);
576
+ return { content: [{ type: 'text', text }], isError };
577
+ }
578
+
579
+ async function handle(message) {
580
+ const { id, method, params } = message;
581
+ const isRequest = id !== undefined && id !== null;
582
+
583
+ switch (method) {
584
+ case 'initialize': {
585
+ const requested = params?.protocolVersion;
586
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
587
+ ? requested
588
+ : SUPPORTED_PROTOCOL_VERSIONS[0];
589
+ reply(id, {
590
+ protocolVersion,
591
+ capabilities: { tools: {} },
592
+ serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
593
+ instructions: 'Tools for one Pmitz server chosen in the connector configuration. Call '
594
+ + 'pmitz_connection_status first to see which server it is. The tools that change the server '
595
+ + 'act on real data: confirm with the user before using them.',
596
+ });
597
+ return;
598
+ }
599
+ case 'ping':
600
+ reply(id, {});
601
+ return;
602
+ case 'tools/list':
603
+ reply(id, { tools: toolset.listTools() });
604
+ return;
605
+ case 'tools/call': {
606
+ try {
607
+ const result = await toolset.callTool(params?.name, params?.arguments ?? {});
608
+ reply(id, toolResult(result, result?.ok === false));
609
+ }
610
+ catch (error) {
611
+ if (error instanceof ToolError) {
612
+ reply(id, toolResult(error.message, true));
613
+ }
614
+ else {
615
+ process.stderr.write(`pmitz-mcp: unexpected error in ${params?.name}: ${error?.message}\n`);
616
+ reply(id, toolResult('The connector hit an unexpected error.', true));
617
+ }
618
+ }
619
+ return;
620
+ }
621
+ default:
622
+ if (isRequest) {
623
+ replyError(id, -32601, `Method not found: ${method}`);
624
+ }
625
+ }
626
+ }
627
+
628
+ let toolset;
629
+
630
+ function startStdio() {
631
+ toolset = createLocalToolset(loadConfig());
632
+ const pending = new Set();
633
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
634
+
635
+ lines.on('line', (line) => {
636
+ if (line.trim() === '') {
637
+ return;
638
+ }
639
+ let message;
640
+ try {
641
+ message = JSON.parse(line);
642
+ }
643
+ catch {
644
+ replyError(null, -32700, 'Parse error');
645
+ return;
646
+ }
647
+ if (message === null || typeof message !== 'object' || typeof message.method !== 'string') {
648
+ // Responses to requests this server never sends, or malformed input: nothing to do.
649
+ return;
650
+ }
651
+ const task = handle(message).finally(() => pending.delete(task));
652
+ pending.add(task);
653
+ });
654
+
655
+ lines.on('close', async () => {
656
+ await Promise.allSettled([...pending]);
657
+ process.exit(0);
658
+ });
659
+ }
660
+
661
+ function runAsProgram() {
662
+ try {
663
+ return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
664
+ }
665
+ catch {
666
+ return false;
667
+ }
668
+ }
669
+
670
+ if (runAsProgram()) {
671
+ startStdio();
672
+ }