mirthcraft 0.1.1__py3-none-any.whl

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.
mirthcraft/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """MirthCraft — MCP bridge for Mirth Connect and Open Integration Engine."""
2
+
3
+ __version__ = "0.1.1"
4
+ __all__ = ["__version__"]
mirthcraft/cli.py ADDED
@@ -0,0 +1,506 @@
1
+ """MirthCraft command-line entrypoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from typing import Any
9
+
10
+ from mirthcraft import __version__
11
+ from mirthcraft.config import (
12
+ Settings,
13
+ allowed_tools,
14
+ is_tool_allowed,
15
+ registered_tools_for_policy,
16
+ resolve_active_profile,
17
+ resolve_runtime_password,
18
+ )
19
+ from mirthcraft.server import create_mcp_server
20
+
21
+
22
+ def main(argv: list[str] | None = None) -> int:
23
+ parser = argparse.ArgumentParser(prog="mirthcraft", description="MirthCraft MCP bridge")
24
+ parser.add_argument("--version", action="version", version=f"mirthcraft {__version__}")
25
+ sub = parser.add_subparsers(dest="command", required=True)
26
+
27
+ serve = sub.add_parser("serve", help="Start the MCP server")
28
+ serve.add_argument(
29
+ "--transport",
30
+ choices=("stdio", "http", "streamable-http"),
31
+ default="stdio",
32
+ help="MCP transport (`http` is an alias for streamable-http)",
33
+ )
34
+ serve.add_argument(
35
+ "--host",
36
+ default="127.0.0.1",
37
+ help="Bind host for streamable-http (default 127.0.0.1)",
38
+ )
39
+ serve.add_argument(
40
+ "--port",
41
+ type=int,
42
+ default=8080,
43
+ help="Bind port for streamable-http (default 8080)",
44
+ )
45
+ serve.add_argument(
46
+ "--path",
47
+ default="/mcp",
48
+ help="URL path for streamable-http (default /mcp)",
49
+ )
50
+
51
+ info = sub.add_parser("info", help="Show active profile and registered tools")
52
+ info.add_argument("--json", action="store_true")
53
+
54
+ compile_cmd = sub.add_parser(
55
+ "compile",
56
+ help="Patch-compile a pulled channel directory into XML (writes channel.compiled.xml)",
57
+ )
58
+ compile_cmd.add_argument(
59
+ "channel_dir",
60
+ help="Path to workspace/channels/<slug> containing .mirth_base.xml",
61
+ )
62
+ compile_cmd.add_argument(
63
+ "-o",
64
+ "--output",
65
+ default=None,
66
+ help="Output XML path (default: <channel_dir>/channel.compiled.xml)",
67
+ )
68
+
69
+ push_cmd = sub.add_parser(
70
+ "push",
71
+ help="Compile + lint-gate and push a channel (default: dry-run)",
72
+ )
73
+ push_cmd.add_argument(
74
+ "channel_dir",
75
+ help="Channel directory path or slug under workspace/channels/",
76
+ )
77
+ push_cmd.add_argument(
78
+ "--apply",
79
+ action="store_true",
80
+ help="Actually PUT to the server (omit for dry-run)",
81
+ )
82
+ push_cmd.add_argument(
83
+ "--override",
84
+ action="store_true",
85
+ help="Override server revision conflict",
86
+ )
87
+ push_cmd.add_argument("--json", action="store_true", help="Print PushResult JSON")
88
+
89
+ diff_cmd = sub.add_parser(
90
+ "diff",
91
+ help="Diff local channel scripts vs server or .mirth_base.xml",
92
+ )
93
+ diff_cmd.add_argument(
94
+ "channel_dir",
95
+ help="Channel directory path or slug under workspace/channels/",
96
+ )
97
+ diff_cmd.add_argument(
98
+ "--base",
99
+ action="store_true",
100
+ help="Compare against pulled .mirth_base.xml instead of live server",
101
+ )
102
+ diff_cmd.add_argument("--json", action="store_true", help="Print DiffResult JSON")
103
+
104
+ validate_cmd = sub.add_parser(
105
+ "validate",
106
+ help="Lint workspace channel scripts against coding_standards.yaml",
107
+ )
108
+ validate_cmd.add_argument(
109
+ "workspace",
110
+ nargs="?",
111
+ default=None,
112
+ help="Workspace root (default: MIRTHCRAFT_WORKSPACE / ./workspace)",
113
+ )
114
+ validate_cmd.add_argument(
115
+ "--json",
116
+ action="store_true",
117
+ help="Print full LintReport JSON",
118
+ )
119
+
120
+ release_cmd = sub.add_parser(
121
+ "prepare-prod-release",
122
+ help="Offline compare workspace to a PROD pull/backup tree (no live PROD session)",
123
+ )
124
+ release_cmd.add_argument(
125
+ "prod_tree",
126
+ help="Path to PROD pull workspace root or export_backup directory",
127
+ )
128
+ release_cmd.add_argument(
129
+ "--channel-id",
130
+ action="append",
131
+ dest="channel_ids",
132
+ default=None,
133
+ help="Limit comparison to channel id (repeatable)",
134
+ )
135
+ release_cmd.add_argument(
136
+ "--no-code-templates",
137
+ action="store_true",
138
+ help="Skip code_templates/ comparison",
139
+ )
140
+ release_cmd.add_argument(
141
+ "--json",
142
+ action="store_true",
143
+ help="Print PrepareProdReleaseResult JSON",
144
+ )
145
+
146
+ map_cmd = sub.add_parser(
147
+ "map-channel-ids",
148
+ help="Resolve channel_id ↔ local_channel_id from an offline d_channels dump",
149
+ )
150
+ map_cmd.add_argument(
151
+ "map_file",
152
+ help="CSV or JSON dump of d_channels (channel_id, local_channel_id)",
153
+ )
154
+ map_cmd.add_argument(
155
+ "--channel-id",
156
+ default=None,
157
+ help="Look up local_channel_id for this UUID",
158
+ )
159
+ map_cmd.add_argument(
160
+ "--local-channel-id",
161
+ type=int,
162
+ default=None,
163
+ help="Look up channel_id for this numeric local id",
164
+ )
165
+ map_cmd.add_argument("--json", action="store_true", help="Print JSON mapping/result")
166
+
167
+ args = parser.parse_args(argv)
168
+
169
+ if args.command == "compile":
170
+ from pathlib import Path
171
+
172
+ from mirthcraft.core.xml_engine import XmlEngine
173
+
174
+ channel_dir = Path(args.channel_dir)
175
+ out = Path(args.output) if args.output else channel_dir / "channel.compiled.xml"
176
+ xml_bytes = XmlEngine().compile_channel(channel_dir)
177
+ out.write_bytes(xml_bytes)
178
+ print(f"wrote {out} ({len(xml_bytes)} bytes)")
179
+ return 0
180
+
181
+ if args.command == "validate":
182
+ from pathlib import Path
183
+
184
+ from mirthcraft.tools.workspace import validate_workspace
185
+
186
+ settings, _profile, _defaults = resolve_active_profile(Settings())
187
+ root = Path(args.workspace) if args.workspace else settings.workspace
188
+ report = validate_workspace(root, standards_path=settings.coding_standards_path())
189
+ if args.json:
190
+ print(json.dumps(report, indent=2))
191
+ else:
192
+ findings = report.get("findings") or []
193
+ errors = [f for f in findings if f.get("severity") == "error"]
194
+ warnings = [f for f in findings if f.get("severity") == "warning"]
195
+ print(
196
+ f"validate ok={report.get('ok')} "
197
+ f"files={report.get('files_scanned')} "
198
+ f"errors={len(errors)} warnings={len(warnings)}"
199
+ )
200
+ for finding in findings:
201
+ loc = finding.get("path", "")
202
+ if finding.get("line"):
203
+ loc = f"{loc}:{finding['line']}"
204
+ print(
205
+ f" [{finding.get('severity')}] {finding.get('rule')}: "
206
+ f"{finding.get('message')} ({loc})"
207
+ )
208
+ return 0 if report.get("ok") else 1
209
+
210
+ if args.command == "diff":
211
+ import asyncio
212
+
213
+ from mirthcraft.client.mirth_api import MirthClient
214
+ from mirthcraft.tools.authoring import diff_channel
215
+
216
+ settings, profile, defaults = resolve_active_profile(Settings())
217
+ against_server = not args.base
218
+
219
+ async def _diff() -> dict[str, Any]:
220
+ if against_server:
221
+ password = resolve_runtime_password(settings, profile)
222
+ async with MirthClient(profile, defaults, password=password) as client:
223
+ result = await diff_channel(
224
+ client,
225
+ settings.workspace,
226
+ channel_dir=args.channel_dir,
227
+ against_server=True,
228
+ )
229
+ else:
230
+ result = await diff_channel(
231
+ None,
232
+ settings.workspace,
233
+ channel_dir=args.channel_dir,
234
+ against_server=False,
235
+ )
236
+ return result.as_dict()
237
+
238
+ payload: dict[str, Any] = asyncio.run(_diff())
239
+ if args.json:
240
+ print(json.dumps(payload, indent=2))
241
+ else:
242
+ changes = payload.get("script_changes") or []
243
+ print(
244
+ f"diff compared_to={payload.get('compared_to')} "
245
+ f"identical={payload.get('identical')} "
246
+ f"changes={len(changes) if isinstance(changes, list) else 0}"
247
+ )
248
+ if isinstance(changes, list):
249
+ for change in changes:
250
+ if isinstance(change, dict):
251
+ print(f" [{change.get('change')}] {change.get('path')}")
252
+ if payload.get("detail"):
253
+ print(payload["detail"])
254
+ return 0 if payload.get("ok") else 1
255
+
256
+ if args.command == "prepare-prod-release":
257
+ from mirthcraft.tools.release import prepare_prod_release
258
+
259
+ settings, profile, _defaults = resolve_active_profile(Settings())
260
+ if not is_tool_allowed("prepare_prod_release", profile.policy):
261
+ print(
262
+ f"Refusing prepare-prod-release under policy={profile.policy.value} "
263
+ f"(target={profile.key}). DEV or PROD only.",
264
+ file=sys.stderr,
265
+ )
266
+ return 2
267
+ release_result = prepare_prod_release(
268
+ settings.workspace,
269
+ args.prod_tree,
270
+ channel_ids=args.channel_ids,
271
+ include_code_templates=not args.no_code_templates,
272
+ )
273
+ release_payload = release_result.as_dict()
274
+ if args.json:
275
+ print(json.dumps(release_payload, indent=2))
276
+ else:
277
+ print(
278
+ f"prepare-prod-release identical={release_payload.get('identical')} "
279
+ f"layout={release_payload.get('prod_layout')} "
280
+ f"channels={len(release_payload.get('channels') or [])} "
281
+ f"templates={len(release_payload.get('code_templates') or [])}"
282
+ )
283
+ for channel in release_payload.get("channels") or []:
284
+ if not isinstance(channel, dict):
285
+ continue
286
+ print(
287
+ f" channel [{channel.get('presence')}] "
288
+ f"{channel.get('channel_name') or channel.get('channel_id')} "
289
+ f"identical={channel.get('identical')}"
290
+ )
291
+ for change in channel.get("script_changes") or []:
292
+ if isinstance(change, dict):
293
+ print(f" [{change.get('change')}] {change.get('path')}")
294
+ for library in release_payload.get("code_templates") or []:
295
+ if not isinstance(library, dict):
296
+ continue
297
+ print(
298
+ f" template [{library.get('presence')}] "
299
+ f"{library.get('library_name') or library.get('library_id')} "
300
+ f"identical={library.get('identical')}"
301
+ )
302
+ if release_payload.get("detail"):
303
+ print(release_payload["detail"])
304
+ return 0 if release_payload.get("ok") and release_payload.get("identical") else 1
305
+
306
+ if args.command == "map-channel-ids":
307
+ from pathlib import Path
308
+
309
+ from mirthcraft.tools.db_bridge import (
310
+ load_channel_id_map,
311
+ resolve_channel_id,
312
+ resolve_local_channel_id,
313
+ )
314
+
315
+ mapping = load_channel_id_map(Path(args.map_file))
316
+ if args.channel_id:
317
+ local_id = resolve_local_channel_id(args.channel_id, mapping)
318
+ payload_map: dict[str, Any] = {
319
+ "channel_id": args.channel_id,
320
+ "local_channel_id": local_id,
321
+ }
322
+ elif args.local_channel_id is not None:
323
+ channel_id = resolve_channel_id(args.local_channel_id, mapping)
324
+ payload_map = {
325
+ "channel_id": channel_id,
326
+ "local_channel_id": args.local_channel_id,
327
+ }
328
+ else:
329
+ payload_map = {
330
+ "count": len(mapping),
331
+ "channels": [
332
+ {"channel_id": cid, "local_channel_id": lid}
333
+ for cid, lid in sorted(mapping.items(), key=lambda item: item[1])
334
+ ],
335
+ }
336
+ if args.json:
337
+ print(json.dumps(payload_map, indent=2))
338
+ elif "channels" in payload_map:
339
+ print(f"mapped_channels={payload_map['count']}")
340
+ channels = payload_map["channels"]
341
+ assert isinstance(channels, list)
342
+ for row in channels:
343
+ if isinstance(row, dict):
344
+ print(f" {row['local_channel_id']}\t{row['channel_id']}")
345
+ else:
346
+ print(
347
+ f"channel_id={payload_map['channel_id']} "
348
+ f"local_channel_id={payload_map['local_channel_id']}"
349
+ )
350
+ return 0
351
+
352
+ if args.command == "push":
353
+ import asyncio
354
+
355
+ from mirthcraft.client.mirth_api import MirthClient
356
+ from mirthcraft.core.audit import AuditLogger
357
+ from mirthcraft.tools.authoring import prepare_channel_push, push_channel
358
+
359
+ settings, profile, defaults = resolve_active_profile(Settings())
360
+ audit = AuditLogger(settings.audit_dir, enabled=defaults.audit_enabled)
361
+ if not args.apply:
362
+ result, _compiled = prepare_channel_push(
363
+ settings.workspace,
364
+ standards_path=settings.coding_standards_path(),
365
+ channel_dir=args.channel_dir,
366
+ dry_run=True,
367
+ override=args.override,
368
+ target=profile.key,
369
+ )
370
+ payload = result.as_dict()
371
+ audit.log(
372
+ tool="push_channel",
373
+ environment=profile.key,
374
+ policy=profile.policy.value,
375
+ status="ok" if payload.get("ok") else "blocked",
376
+ params_summary={
377
+ "channel_dir": args.channel_dir,
378
+ "dry_run": True,
379
+ "override": args.override,
380
+ },
381
+ detail=str(payload.get("detail") or payload.get("action")),
382
+ actor="cli",
383
+ )
384
+ else:
385
+ if not is_tool_allowed("push_channel", profile.policy):
386
+ audit.log(
387
+ tool="push_channel",
388
+ environment=profile.key,
389
+ policy=profile.policy.value,
390
+ status="denied",
391
+ params_summary={
392
+ "channel_dir": args.channel_dir,
393
+ "dry_run": False,
394
+ "override": args.override,
395
+ },
396
+ detail="CLI push --apply denied by policy",
397
+ actor="cli",
398
+ )
399
+ print(
400
+ f"Refusing push --apply under policy={profile.policy.value} "
401
+ f"(target={profile.key}). DEV only.",
402
+ file=sys.stderr,
403
+ )
404
+ return 2
405
+
406
+ password = resolve_runtime_password(settings, profile)
407
+
408
+ async def _push() -> dict[str, object]:
409
+ async with MirthClient(profile, defaults, password=password) as client:
410
+ pushed = await push_channel(
411
+ client,
412
+ settings.workspace,
413
+ standards_path=settings.coding_standards_path(),
414
+ channel_dir=args.channel_dir,
415
+ dry_run=False,
416
+ override=args.override,
417
+ )
418
+ return pushed.as_dict()
419
+
420
+ try:
421
+ payload = asyncio.run(_push())
422
+ audit.log(
423
+ tool="push_channel",
424
+ environment=profile.key,
425
+ policy=profile.policy.value,
426
+ status="ok" if payload.get("ok") else "error",
427
+ params_summary={
428
+ "channel_dir": args.channel_dir,
429
+ "dry_run": False,
430
+ "override": args.override,
431
+ "channel_id": payload.get("channel_id"),
432
+ },
433
+ detail=str(payload.get("detail") or payload.get("action")),
434
+ actor="cli",
435
+ )
436
+ except Exception as exc:
437
+ audit.log(
438
+ tool="push_channel",
439
+ environment=profile.key,
440
+ policy=profile.policy.value,
441
+ status="error",
442
+ params_summary={
443
+ "channel_dir": args.channel_dir,
444
+ "dry_run": False,
445
+ "override": args.override,
446
+ },
447
+ detail=str(exc),
448
+ actor="cli",
449
+ )
450
+ raise
451
+
452
+ if args.json:
453
+ print(json.dumps(payload, indent=2))
454
+ else:
455
+ print(
456
+ f"push action={payload.get('action')} ok={payload.get('ok')} "
457
+ f"channel_id={payload.get('channel_id')} bytes={payload.get('compiled_bytes')}"
458
+ )
459
+ if payload.get("detail"):
460
+ print(payload["detail"])
461
+ return 0 if payload.get("ok") else 1
462
+
463
+ if args.command == "info":
464
+ settings, profile, _defaults = resolve_active_profile(Settings())
465
+ registered = registered_tools_for_policy(profile.policy)
466
+ info_payload: dict[str, Any] = {
467
+ "version": __version__,
468
+ "target": profile.key,
469
+ "policy": profile.policy.value,
470
+ "base_url": profile.base_url,
471
+ "workspace": str(settings.workspace),
472
+ "registered_tools": registered,
473
+ "policy_allowed_tools": allowed_tools(profile.policy),
474
+ }
475
+ if args.json:
476
+ print(json.dumps(info_payload, indent=2))
477
+ else:
478
+ print(f"mirthcraft {__version__}")
479
+ print(f"target={profile.key} policy={profile.policy.value}")
480
+ print(f"base_url={profile.base_url}")
481
+ print(f"workspace={settings.workspace}")
482
+ print("registered_tools:")
483
+ for name in registered:
484
+ print(f" - {name}")
485
+ return 0
486
+
487
+ if args.command == "serve":
488
+ transport = args.transport
489
+ if transport == "http":
490
+ transport = "streamable-http"
491
+ if transport == "streamable-http":
492
+ create_mcp_server().run(
493
+ transport="streamable-http",
494
+ host=args.host,
495
+ port=args.port,
496
+ streamable_http_path=args.path,
497
+ )
498
+ else:
499
+ create_mcp_server().run(transport="stdio")
500
+ return 0
501
+
502
+ return 1
503
+
504
+
505
+ if __name__ == "__main__":
506
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,67 @@
1
+ """Mirth / OIE REST API path constants and compatibility helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from urllib.parse import quote
6
+
7
+
8
+ class ApiPaths:
9
+ """Paths relative to the server base URL (no trailing slash on base)."""
10
+
11
+ LOGIN = "/api/users/_login"
12
+ LOGOUT = "/api/users/_logout"
13
+ SERVER_ABOUT = "/api/server/about"
14
+ SERVER_STATUS = "/api/server/status"
15
+ CHANNELS = "/api/channels"
16
+ CHANNEL = "/api/channels/{channel_id}"
17
+ CHANNELS_STATUSES = "/api/channels/statuses"
18
+ CHANNEL_STATISTICS = "/api/channels/{channel_id}/statistics"
19
+ MESSAGES = "/api/channels/{channel_id}/messages"
20
+ MESSAGE = "/api/channels/{channel_id}/messages/{message_id}"
21
+ CODE_TEMPLATES = "/api/codeTemplates"
22
+ CODE_TEMPLATE = "/api/codeTemplates/{template_id}"
23
+ CODE_TEMPLATE_LIBRARIES = "/api/codeTemplateLibraries"
24
+ CODE_TEMPLATE_LIBRARY = "/api/codeTemplateLibraries/{library_id}"
25
+ CONFIG_MAP = "/api/server/configurationMap"
26
+ SYSTEM_INFO = "/api/system/info"
27
+ SYSTEM_STATS = "/api/system/stats"
28
+
29
+
30
+ def _q(value: str) -> str:
31
+ return quote(str(value), safe="")
32
+
33
+
34
+ def channel_path(channel_id: str) -> str:
35
+ return ApiPaths.CHANNEL.format(channel_id=_q(channel_id))
36
+
37
+
38
+ def channel_statistics_path(channel_id: str) -> str:
39
+ return ApiPaths.CHANNEL_STATISTICS.format(channel_id=_q(channel_id))
40
+
41
+
42
+ def messages_path(channel_id: str) -> str:
43
+ return ApiPaths.MESSAGES.format(channel_id=_q(channel_id))
44
+
45
+
46
+ def message_path(channel_id: str, message_id: str) -> str:
47
+ return ApiPaths.MESSAGE.format(channel_id=_q(channel_id), message_id=_q(message_id))
48
+
49
+
50
+ def code_template_path(template_id: str) -> str:
51
+ return ApiPaths.CODE_TEMPLATE.format(template_id=_q(template_id))
52
+
53
+
54
+ def code_template_library_path(library_id: str) -> str:
55
+ return ApiPaths.CODE_TEMPLATE_LIBRARY.format(library_id=_q(library_id))
56
+
57
+
58
+ def channel_deploy_path(channel_id: str) -> str:
59
+ return f"{channel_path(channel_id)}/_deploy"
60
+
61
+
62
+ def channel_undeploy_path(channel_id: str) -> str:
63
+ return f"{channel_path(channel_id)}/_undeploy"
64
+
65
+
66
+ def channel_control_path(channel_id: str, action: str) -> str:
67
+ return f"{channel_path(channel_id)}/_{action}"