drone-path 1.0.0 → 1.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/README.md CHANGED
@@ -1,20 +1,24 @@
1
1
  # drone-path
2
2
 
3
- Render a flight-path map overlay video from a DJI recording with CAM-meta
4
- telemetry or a matching SRT sidecar. Use Node.js 24 or later.
3
+ Render flight-path map overlay videos from DJI recordings with CAM-meta
4
+ telemetry or a matching SRT sidecar, index and search a local recording library,
5
+ or expose your library to AI agents over an MCP server. Use Node.js 24 or later.
5
6
 
6
7
  ```sh
7
8
  npx drone-path "my-flight.mp4"
9
+ npx drone-path archive scan "./flights" --recurse --json
10
+ npx drone-path mcp --allow-root "./flights"
8
11
  npx drone-path --help
9
12
  ```
10
13
 
11
- By default, the command writes the overlay to `out/my-flight_map.mp4`.
14
+ By default, rendering writes the overlay to `out/my-flight_map.mp4`.
12
15
  See the [CLI guide](https://github.com/MrManny/drone-path/blob/main/docs/user/cli.md)
13
- for configuration, rendering requirements, and track export.
16
+ for configuration, archive search, MCP tools, rendering requirements, and track
17
+ export.
14
18
 
15
- The `drone-path` export provides typed CLI functions for Node.js. For
16
- telemetry and rendering APIs, use `drone-path-core` and
17
- `drone-path-engine`.
19
+ The `drone-path` export provides typed CLI functions for Node.js. For telemetry,
20
+ library indexing, and rendering APIs, use `drone-path-core`,
21
+ `drone-path-archive`, and `drone-path-engine`.
18
22
 
19
23
  Install `@types/node` for your Node.js major version. In TypeScript 6, list
20
24
  `node` in `compilerOptions.types` to load the Node declarations.
@@ -1,5 +1,7 @@
1
1
  # Third-party notices
2
2
 
3
- Commander is licensed under MIT and includes its license text in its npm
4
- package. See the notices shipped with `drone-path-core` and
5
- `drone-path-engine` for the telemetry and rendering dependencies.
3
+ Commander and Zod are licensed under MIT and ship their license texts in their
4
+ npm packages. `@modelcontextprotocol/server` and `@modelcontextprotocol/core` are
5
+ licensed under Apache-2.0 and ship their `LICENSE` files in their npm packages.
6
+ See the notices shipped with `drone-path-core` and `drone-path-engine` for the
7
+ telemetry and rendering dependencies.
@@ -1,7 +1,8 @@
1
1
  import { Option } from 'commander';
2
- import { exportArchiveMap, exportArchiveTracks } from 'drone-path-archive/export';
2
+ import { exportArchiveMap, exportArchiveMarkers, exportArchiveTracks } from 'drone-path-archive/export';
3
3
  import { archiveDbPath } from 'drone-path-archive/paths';
4
- import { DEFAULT_RADIUS_M, listArchive, listArchiveFlights, nearArchive, parseDateBound } from 'drone-path-archive/query';
4
+ import { DEFAULT_RADIUS_M, listArchive, listArchiveFlights, listArchiveSegments, nearArchive, parseDateBound } from 'drone-path-archive/query';
5
+ import { SHOT_TYPES } from 'drone-path-core/shot-segmentation';
5
6
  function decimal(text) {
6
7
  const value = text.trim();
7
8
  return /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/iu.test(value) ? Number(value) : NaN;
@@ -17,6 +18,13 @@ function availability(text) {
17
18
  throw new Error('expected online or offline status');
18
19
  return text;
19
20
  }
21
+ function smoothnessScore(text) {
22
+ const value = decimal(text);
23
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
24
+ throw new Error('expected a smoothness score between 0 and 1');
25
+ }
26
+ return value;
27
+ }
20
28
  function point(text) {
21
29
  const [lat, lon, extra] = text.split(',').map(decimal);
22
30
  if (!(Math.abs(lat) <= 90 && Math.abs(lon) <= 180) || extra !== undefined) {
@@ -38,11 +46,19 @@ function writeJson(value) {
38
46
  process.stdout.write(JSON.stringify(value) + '\n');
39
47
  }
40
48
  function listOptions(options) {
41
- const { inBbox, after, before, minDist, status } = options;
49
+ const { inBbox, after, before, minDist, status, segmentType, minSmoothness } = options;
42
50
  if (after !== undefined && before !== undefined && after > before) {
43
51
  throw new Error('expected --after at or before --before');
44
52
  }
45
- return { bbox: inBbox, afterMs: after, beforeMs: before, minDistanceM: minDist, availability: status };
53
+ return {
54
+ bbox: inBbox,
55
+ afterMs: after,
56
+ beforeMs: before,
57
+ minDistanceM: minDist,
58
+ availability: status,
59
+ ...(segmentType !== undefined ? { segmentType } : {}),
60
+ ...(minSmoothness !== undefined ? { minSmoothness } : {}),
61
+ };
46
62
  }
47
63
  export function archiveCommand(command) {
48
64
  return command
@@ -57,7 +73,9 @@ function listFilters(command) {
57
73
  .option('--after <date>', 'earliest camera date or timestamp, inclusive', parseDateBound)
58
74
  .option('--before <date>', 'latest camera date or timestamp, exclusive', parseDateBound)
59
75
  .option('--min-dist <m>', 'minimum track distance in meters', meters)
60
- .option('--status <state>', 'filter by online or offline availability', availability);
76
+ .option('--status <state>', 'filter by online or offline availability', availability)
77
+ .addOption(new Option('--segment-type <type>', 'filter by kinematic shot segment type').choices([...SHOT_TYPES]))
78
+ .option('--min-smoothness <score>', 'minimum segment smoothness score between 0 and 1', smoothnessScore);
61
79
  }
62
80
  function exportOptions(command) {
63
81
  return archiveCommand(listFilters(command))
@@ -83,6 +101,19 @@ export function addArchiveQueries(program) {
83
101
  }
84
102
  return;
85
103
  }
104
+ if (options.segmentType !== undefined || options.minSmoothness !== undefined) {
105
+ const segments = listArchiveSegments(db, filters);
106
+ if (options.json)
107
+ writeJson(segments);
108
+ else
109
+ for (const segment of segments) {
110
+ const exposure = segment.exposureStable ? 'stable' : 'exposure-shift';
111
+ process.stdout.write(`${segment.type} ${segment.startSec.toFixed(1)}s-${segment.endSec.toFixed(1)}s ` +
112
+ `(smoothness ${segment.smoothness.toFixed(3)}, ${exposure}) ` +
113
+ `[${segment.clip.availability}] ${segment.clip.path}\n`);
114
+ }
115
+ return;
116
+ }
86
117
  const clips = listArchive(db, filters);
87
118
  if (options.json)
88
119
  writeJson(clips);
@@ -125,4 +156,12 @@ export function addArchiveQueries(program) {
125
156
  filters: listOptions(options), redactLaunchM: options.redactLaunch,
126
157
  });
127
158
  });
159
+ archiveCommand(listFilters(program.command('export-markers')))
160
+ .description('Write matching shot segments as DaVinci Resolve CSV or FCPXML markers.')
161
+ .argument('<out>', 'output .csv or .fcpxml file')
162
+ .action((output, options) => {
163
+ exportArchiveMarkers(archiveDbPath(options.archiveDb), output, {
164
+ filters: listOptions(options),
165
+ });
166
+ });
128
167
  }
package/dist/cli.js CHANGED
@@ -2,6 +2,8 @@ import fs from 'node:fs';
2
2
  import { Command, Option } from 'commander';
3
3
  import { ERROR_PREFIX, errorMessage } from 'drone-path-core/errors';
4
4
  import { runArchive } from './archive-cli.js';
5
+ import { runExtractFrame } from './extract-frame-cli.js';
6
+ import { runMcp } from './mcp-cli.js';
5
7
  import { VERSION } from './version.js';
6
8
  import { CONFIG_FILE_OPTION, CONFIG_OPTIONS, OVERRIDE_NORMALIZERS, TELEMETRY_JSON_ALIAS, cliDefaultOf, } from 'drone-path-engine/config';
7
9
  import { resolveConfig } from 'drone-path-engine/configfile';
@@ -29,7 +31,7 @@ export function buildProgram() {
29
31
  }
30
32
  program.addOption(new Option(TELEMETRY_JSON_ALIAS.flags, TELEMETRY_JSON_ALIAS.help));
31
33
  program.option(CONFIG_FILE_OPTION.flags, CONFIG_FILE_OPTION.help);
32
- return program.addHelpText('after', '\nLibrary inventory: drone-path archive scan --help');
34
+ return program.addHelpText('after', '\nLibrary inventory: drone-path archive scan --help\nMCP stdio server: drone-path mcp --help');
33
35
  }
34
36
  function givenOnCommandLine(program, name) {
35
37
  return program.getOptionValueSource(name) === 'cli';
@@ -137,6 +139,14 @@ export async function main(argv = process.argv) {
137
139
  await runArchive(argv.slice(3));
138
140
  return;
139
141
  }
142
+ if (argv[2] === 'extract-frame') {
143
+ await runExtractFrame(argv.slice(3));
144
+ return;
145
+ }
146
+ if (argv[2] === 'mcp') {
147
+ await runMcp(argv.slice(3));
148
+ return;
149
+ }
140
150
  const invocation = resolveInvocation(argv);
141
151
  // Deprecation warnings are not progress output: they print even with --quiet.
142
152
  for (const warning of invocation.deprecationWarnings) {
@@ -0,0 +1 @@
1
+ export declare function runExtractFrame(argv: string[]): Promise<void>;
@@ -0,0 +1,63 @@
1
+ import { Command } from 'commander';
2
+ import { requireFfmpegTools } from 'drone-path-core/ffmpeg';
3
+ import { resolveFfmpegTools } from 'drone-path-core/ffmpeg-tools';
4
+ import { extractKeyframes, parseKeyframeSpecs } from 'drone-path-core/keyframes';
5
+ function parseMaxWidth(text) {
6
+ const trimmed = text.trim();
7
+ if (!/^\d+$/u.test(trimmed)) {
8
+ throw new Error('expected a positive integer for --max-width');
9
+ }
10
+ const value = Number(trimmed);
11
+ if (!Number.isSafeInteger(value) || value < 1) {
12
+ throw new Error('expected a positive integer for --max-width');
13
+ }
14
+ return value;
15
+ }
16
+ export async function runExtractFrame(argv) {
17
+ const program = new Command('drone-path extract-frame')
18
+ .description('Extract targeted JPEG keyframes and telemetry snapshots from a recording.')
19
+ .exitOverride()
20
+ .argument('<video>', 'recording video file')
21
+ .requiredOption('--at <specs>', 'comma-separated timestamps (s) or frames (fN, frame:N)')
22
+ .option('--max-width <px>', 'maximum output width in pixels, preserving aspect ratio', parseMaxWidth)
23
+ .option('--out-dir <dir>', 'output directory (defaults to video directory)')
24
+ .option('--ffmpeg <path>', 'path to the ffmpeg executable')
25
+ .option('--ffprobe <path>', 'path to the ffprobe executable')
26
+ .option('--json', 'write extracted keyframes JSON array to stdout');
27
+ program.parse(argv, { from: 'user' });
28
+ const [video] = program.args;
29
+ const opts = program.opts();
30
+ const requests = parseKeyframeSpecs(opts.at);
31
+ const tools = resolveFfmpegTools({
32
+ ffmpeg: opts.ffmpeg ?? null,
33
+ ffprobe: opts.ffprobe ?? null,
34
+ });
35
+ const controller = new AbortController();
36
+ const interrupt = () => controller.abort(new Error('keyframe extraction canceled'));
37
+ process.on('SIGINT', interrupt);
38
+ try {
39
+ await requireFfmpegTools(tools, controller.signal);
40
+ const keyframes = await extractKeyframes(video, {
41
+ at: requests,
42
+ maxWidth: opts.maxWidth,
43
+ outDir: opts.outDir,
44
+ tools,
45
+ signal: controller.signal,
46
+ });
47
+ if (opts.json) {
48
+ process.stdout.write(JSON.stringify(keyframes) + '\n');
49
+ return;
50
+ }
51
+ for (const kf of keyframes) {
52
+ process.stdout.write(`${kf.path} (frame ${kf.frame}, ${kf.tSec.toFixed(3)}s, ${kf.width}x${kf.height})\n`);
53
+ }
54
+ process.stderr.write(`[drone-path] extracted ${keyframes.length} keyframe(s)\n`);
55
+ }
56
+ catch (error) {
57
+ controller.signal.throwIfAborted();
58
+ throw error;
59
+ }
60
+ finally {
61
+ process.off('SIGINT', interrupt);
62
+ }
63
+ }
@@ -0,0 +1 @@
1
+ export declare function runMcp(argv: string[]): Promise<void>;
@@ -0,0 +1,29 @@
1
+ import { Command } from 'commander';
2
+ import { createMcpServer } from './mcp-server.js';
3
+ export async function runMcp(argv) {
4
+ const program = new Command('drone-path mcp')
5
+ .description('Run a stdio MCP server exposing archive, telemetry, keyframe, and rendering tools.')
6
+ .exitOverride()
7
+ .option('--archive-db <path>', 'override the per-user archive database path')
8
+ .requiredOption('--allow-root <dir...>', 'restrict file and folder tool access to these root directories (required)');
9
+ program.parse(argv, { from: 'user' });
10
+ const opts = program.opts();
11
+ const server = createMcpServer({
12
+ archiveDb: opts.archiveDb,
13
+ allowedRoots: opts.allowRoot,
14
+ });
15
+ const onSignal = () => {
16
+ void server.close();
17
+ };
18
+ process.on('SIGINT', onSignal);
19
+ process.on('SIGTERM', onSignal);
20
+ try {
21
+ const rootCount = server.allowedRoots.length;
22
+ process.stderr.write(`[drone-path] mcp stdio server ready (roots: ${rootCount})\n`);
23
+ await server.start();
24
+ }
25
+ finally {
26
+ process.off('SIGINT', onSignal);
27
+ process.off('SIGTERM', onSignal);
28
+ }
29
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Resolves a path by canonicalizing its deepest existing ancestor via realpath
3
+ * (following symlinks, including dangling symlinks) and reattaching remaining
4
+ * non-existent segments so boundary checks defeat `..` and symlink escapes.
5
+ */
6
+ export declare function canonicalizePath(targetPath: string, depth?: number, seen?: Set<string>): string;
7
+ export declare function resolveAllowedRoots(roots?: readonly string[]): string[];
8
+ export declare function isPathWithinRoot(canonicalTarget: string, canonicalRoot: string): boolean;
9
+ export declare function isPathInAllowedRoots(targetPath: string, allowedRoots: readonly string[]): boolean;
10
+ export declare function assertPathInAllowedRoots(targetPath: string, allowedRoots: readonly string[]): string;
11
+ export declare function isSamePath(a: string, b: string): boolean;
12
+ export declare function assertNotArchiveDb(outputPath: string, archiveDb: string): void;
@@ -0,0 +1,140 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ const MAX_SYMLINK_DEPTH = 40;
4
+ function pathKey(filePath) {
5
+ return process.platform === 'win32' ? filePath.toLowerCase() : filePath;
6
+ }
7
+ function isErrno(error, code) {
8
+ return error?.code === code;
9
+ }
10
+ /**
11
+ * Resolves a path by canonicalizing its deepest existing ancestor via realpath
12
+ * (following symlinks, including dangling symlinks) and reattaching remaining
13
+ * non-existent segments so boundary checks defeat `..` and symlink escapes.
14
+ */
15
+ export function canonicalizePath(targetPath, depth = 0, seen = new Set()) {
16
+ if (typeof targetPath !== 'string' || targetPath.trim() === '') {
17
+ throw new Error('path must not be empty');
18
+ }
19
+ if (targetPath.includes('\0')) {
20
+ throw new Error('path contains null byte');
21
+ }
22
+ const absolute = path.resolve(targetPath);
23
+ const pending = [];
24
+ let current = absolute;
25
+ for (;;) {
26
+ try {
27
+ const stat = fs.lstatSync(current);
28
+ try {
29
+ const real = fs.realpathSync(current);
30
+ return pending.length > 0 ? path.join(real, ...pending) : real;
31
+ }
32
+ catch (err) {
33
+ if (!isErrno(err, 'ENOENT') || !stat.isSymbolicLink()) {
34
+ throw err;
35
+ }
36
+ if (depth >= MAX_SYMLINK_DEPTH || seen.has(current)) {
37
+ throw new Error(`symlink loop detected while resolving path: ${targetPath}`, {
38
+ cause: err,
39
+ });
40
+ }
41
+ seen.add(current);
42
+ const linkTarget = fs.readlinkSync(current);
43
+ const resolvedTarget = path.resolve(path.dirname(current), linkTarget);
44
+ const canonicalTarget = canonicalizePath(resolvedTarget, depth + 1, seen);
45
+ return pending.length > 0 ? path.join(canonicalTarget, ...pending) : canonicalTarget;
46
+ }
47
+ }
48
+ catch (err) {
49
+ if (!isErrno(err, 'ENOENT')) {
50
+ throw err;
51
+ }
52
+ const parent = path.dirname(current);
53
+ if (parent === current) {
54
+ return pending.length > 0 ? path.join(current, ...pending) : current;
55
+ }
56
+ pending.unshift(path.basename(current));
57
+ current = parent;
58
+ }
59
+ }
60
+ }
61
+ export function resolveAllowedRoots(roots) {
62
+ if (!roots || roots.length === 0) {
63
+ throw new Error('at least one allowed root directory is required (pass --allow-root <dir>)');
64
+ }
65
+ const candidates = roots;
66
+ const resolved = [];
67
+ const seen = new Set();
68
+ for (const root of candidates) {
69
+ if (typeof root !== 'string' || root.trim() === '') {
70
+ throw new Error('allowed root must not be empty');
71
+ }
72
+ if (root.includes('\0')) {
73
+ throw new Error('allowed root contains null byte');
74
+ }
75
+ const absolute = path.resolve(root);
76
+ let canonical;
77
+ try {
78
+ canonical = fs.realpathSync(absolute);
79
+ }
80
+ catch (err) {
81
+ throw new Error(`allowed root does not exist: ${root}`, { cause: err });
82
+ }
83
+ if (!fs.statSync(canonical).isDirectory()) {
84
+ throw new Error(`allowed root is not a directory: ${root}`);
85
+ }
86
+ const key = pathKey(canonical);
87
+ if (!seen.has(key)) {
88
+ seen.add(key);
89
+ resolved.push(canonical);
90
+ }
91
+ }
92
+ return resolved;
93
+ }
94
+ export function isPathWithinRoot(canonicalTarget, canonicalRoot) {
95
+ const rel = path.relative(pathKey(canonicalRoot), pathKey(canonicalTarget));
96
+ return rel === '' || (rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel));
97
+ }
98
+ export function isPathInAllowedRoots(targetPath, allowedRoots) {
99
+ try {
100
+ const canonical = canonicalizePath(targetPath);
101
+ return allowedRoots.some((root) => isPathWithinRoot(canonical, root));
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ }
107
+ export function assertPathInAllowedRoots(targetPath, allowedRoots) {
108
+ const canonical = canonicalizePath(targetPath);
109
+ if (!allowedRoots.some((root) => isPathWithinRoot(canonical, root))) {
110
+ throw new Error(`path is outside allowed roots: ${targetPath}`);
111
+ }
112
+ return canonical;
113
+ }
114
+ function sameInode(a, b) {
115
+ if (!fs.existsSync(a) || !fs.existsSync(b))
116
+ return false;
117
+ const statA = fs.statSync(a, { bigint: true });
118
+ const statB = fs.statSync(b, { bigint: true });
119
+ return statA.dev === statB.dev && statA.ino === statB.ino;
120
+ }
121
+ export function isSamePath(a, b) {
122
+ const canonicalA = canonicalizePath(a);
123
+ const canonicalB = canonicalizePath(b);
124
+ if (pathKey(canonicalA) === pathKey(canonicalB))
125
+ return true;
126
+ return sameInode(canonicalA, canonicalB);
127
+ }
128
+ export function assertNotArchiveDb(outputPath, archiveDb) {
129
+ const protectedPaths = [
130
+ archiveDb,
131
+ `${archiveDb}-wal`,
132
+ `${archiveDb}-shm`,
133
+ `${archiveDb}-journal`,
134
+ ];
135
+ for (const target of protectedPaths) {
136
+ if (isSamePath(outputPath, target)) {
137
+ throw new Error('output path cannot overwrite the archive database');
138
+ }
139
+ }
140
+ }
@@ -0,0 +1,21 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+ import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
3
+ import type { LogFn } from 'drone-path-engine/logging';
4
+ import { runBatch } from 'drone-path-engine/pipeline';
5
+ export interface McpServerOptions {
6
+ archiveDb?: string;
7
+ allowedRoots?: readonly string[];
8
+ input?: Readable;
9
+ output?: Writable;
10
+ log?: LogFn;
11
+ tools?: FfmpegToolPaths;
12
+ getTools?: () => Promise<FfmpegToolPaths>;
13
+ runBatch?: typeof runBatch;
14
+ }
15
+ export interface McpServer {
16
+ readonly archiveDb: string;
17
+ readonly allowedRoots: readonly string[];
18
+ start: () => Promise<void>;
19
+ close: () => Promise<void>;
20
+ }
21
+ export declare function createMcpServer(options?: McpServerOptions): McpServer;
@@ -0,0 +1,95 @@
1
+ import { McpServer as SdkMcpServer } from '@modelcontextprotocol/server';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
3
+ import { archiveDbPath } from 'drone-path-archive/paths';
4
+ import { errorMessage } from 'drone-path-core/errors';
5
+ import { requireFfmpegTools } from 'drone-path-core/ffmpeg';
6
+ import { resolveFfmpegTools } from 'drone-path-core/ffmpeg-tools';
7
+ import { runBatch } from 'drone-path-engine/pipeline';
8
+ import { resolveAllowedRoots } from './mcp-paths.js';
9
+ import { registerMcpTools, sanitizeMcpErrorMessage } from './mcp-tools.js';
10
+ import { VERSION } from './version.js';
11
+ function defaultLogger() {
12
+ return (msg) => {
13
+ process.stderr.write(`[drone-path] ${msg}\n`);
14
+ };
15
+ }
16
+ function createGetTools(options) {
17
+ if (options.getTools)
18
+ return options.getTools;
19
+ let cached = null;
20
+ return () => {
21
+ cached ??= (async () => {
22
+ if (options.tools)
23
+ return options.tools;
24
+ const resolved = resolveFfmpegTools({ ffmpeg: null, ffprobe: null });
25
+ await requireFfmpegTools(resolved);
26
+ return resolved;
27
+ })().catch((err) => {
28
+ cached = null;
29
+ throw err;
30
+ });
31
+ return cached;
32
+ };
33
+ }
34
+ export function createMcpServer(options = {}) {
35
+ const archiveDb = archiveDbPath(options.archiveDb);
36
+ const allowedRoots = resolveAllowedRoots(options.allowedRoots);
37
+ const input = options.input ?? process.stdin;
38
+ const output = options.output ?? process.stdout;
39
+ const log = options.log ?? defaultLogger();
40
+ const sdkServer = new SdkMcpServer({ name: 'drone-path', version: VERSION }, { capabilities: { tools: {} } });
41
+ sdkServer.server.onerror = (err) => {
42
+ log(`mcp error: ${sanitizeMcpErrorMessage(errorMessage(err))}`);
43
+ };
44
+ registerMcpTools(sdkServer, {
45
+ archiveDb,
46
+ allowedRoots,
47
+ getTools: createGetTools(options),
48
+ runBatch: options.runBatch ?? runBatch,
49
+ log,
50
+ });
51
+ let started = false;
52
+ let closeResolve = null;
53
+ async function start() {
54
+ if (started) {
55
+ throw new Error('mcp server is already started');
56
+ }
57
+ started = true;
58
+ const transport = new StdioServerTransport(input, output);
59
+ const closed = new Promise((resolve) => {
60
+ closeResolve = resolve;
61
+ });
62
+ const prevOnClose = sdkServer.server.onclose;
63
+ sdkServer.server.onclose = () => {
64
+ prevOnClose?.();
65
+ started = false;
66
+ const done = closeResolve;
67
+ closeResolve = null;
68
+ done?.();
69
+ };
70
+ try {
71
+ await sdkServer.connect(transport);
72
+ }
73
+ catch (err) {
74
+ started = false;
75
+ const done = closeResolve;
76
+ closeResolve = null;
77
+ done?.();
78
+ throw err;
79
+ }
80
+ await closed;
81
+ }
82
+ async function close() {
83
+ await sdkServer.close();
84
+ started = false;
85
+ const done = closeResolve;
86
+ closeResolve = null;
87
+ done?.();
88
+ }
89
+ return {
90
+ archiveDb,
91
+ allowedRoots,
92
+ start,
93
+ close,
94
+ };
95
+ }
@@ -0,0 +1,14 @@
1
+ import type { McpServer as SdkMcpServer } from '@modelcontextprotocol/server';
2
+ import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
3
+ import type { LogFn } from 'drone-path-engine/logging';
4
+ import type { runBatch } from 'drone-path-engine/pipeline';
5
+ export interface McpToolContext {
6
+ archiveDb: string;
7
+ allowedRoots: readonly string[];
8
+ getTools: () => Promise<FfmpegToolPaths>;
9
+ runBatch: typeof runBatch;
10
+ log: LogFn;
11
+ }
12
+ export declare const MAX_MCP_RENDER_VIDEOS = 10;
13
+ export declare function sanitizeMcpErrorMessage(raw: string): string;
14
+ export declare function registerMcpTools(sdkServer: SdkMcpServer, ctx: McpToolContext): void;
@@ -0,0 +1,596 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { z } from 'zod';
4
+ import { exportArchiveMarkers } from 'drone-path-archive/export';
5
+ import { scanArchive } from 'drone-path-archive/indexed-scan';
6
+ import { DEFAULT_RADIUS_M, listArchive, listArchiveFlights, listArchiveSegments, nearArchive, parseDateBound, } from 'drone-path-archive/query';
7
+ import { errorMessage } from 'drone-path-core/errors';
8
+ import { probeVideo } from 'drone-path-core/ffmpeg';
9
+ import { extractKeyframes, parseKeyframeSpecs } from 'drone-path-core/keyframes';
10
+ import { markerFormatOf, serializeDaVinciResolveCsv, serializeFcpxmlMarkers, } from 'drone-path-core/nle-markers';
11
+ import { SHOT_TYPES, segmentFlightShots } from 'drone-path-core/shot-segmentation';
12
+ import { loadTelemetrySamples } from 'drone-path-core/telemetry';
13
+ import { computeTelemetry } from 'drone-path-core/telemetry-math';
14
+ import { telemetrySummary } from 'drone-path-core/telemetry-summary';
15
+ import { CODEC_VALUES, ENCODER_PRESET_VALUES, MAP_STYLE_VALUES, QUALITY_VALUES, asTrailColor, parseHud, } from 'drone-path-engine/config';
16
+ import { resolveConfig } from 'drone-path-engine/configfile';
17
+ import { planOutputs } from 'drone-path-engine/pipeline';
18
+ import { collectRecordings } from 'drone-path-engine/recordings';
19
+ import { assertNotArchiveDb, assertPathInAllowedRoots, canonicalizePath, isPathInAllowedRoots, } from './mcp-paths.js';
20
+ const DEFAULT_MAX_SAMPLES = 100;
21
+ export const MAX_MCP_RENDER_VIDEOS = 10;
22
+ function isMcpOverwriteAllowed() {
23
+ const envOverwrite = process.env.DRONE_PATH_MCP_ALLOW_OVERWRITE?.trim().toLowerCase();
24
+ return envOverwrite === '1' || envOverwrite === 'true';
25
+ }
26
+ const BboxSchema = z
27
+ .object({
28
+ minLat: z.number().finite().min(-90).max(90),
29
+ minLon: z.number().finite().min(-180).max(180),
30
+ maxLat: z.number().finite().min(-90).max(90),
31
+ maxLon: z.number().finite().min(-180).max(180),
32
+ })
33
+ .strict()
34
+ .refine((b) => b.minLat <= b.maxLat, {
35
+ message: 'bbox minLat must be at or below maxLat',
36
+ });
37
+ const DateBoundSchema = z.union([z.string().min(1), z.number().finite()]);
38
+ const ArchiveFiltersSchema = z
39
+ .object({
40
+ bbox: BboxSchema.optional(),
41
+ after: DateBoundSchema.optional(),
42
+ before: DateBoundSchema.optional(),
43
+ afterMs: z.number().finite().optional(),
44
+ beforeMs: z.number().finite().optional(),
45
+ minDistanceM: z.number().finite().min(0).optional(),
46
+ availability: z.enum(['online', 'offline']).optional(),
47
+ segmentType: z.enum(SHOT_TYPES).optional(),
48
+ minSmoothness: z.number().finite().min(0).max(1).optional(),
49
+ })
50
+ .strict();
51
+ function resolveDateBound(bound, ms, label) {
52
+ if (bound !== undefined && ms !== undefined) {
53
+ throw new Error(`specify either ${label} or ${label}Ms, not both`);
54
+ }
55
+ if (ms !== undefined)
56
+ return ms;
57
+ if (bound === undefined)
58
+ return undefined;
59
+ return typeof bound === 'string' ? parseDateBound(bound) : bound;
60
+ }
61
+ function toListFilters(raw) {
62
+ const afterMs = resolveDateBound(raw.after, raw.afterMs, 'after');
63
+ const beforeMs = resolveDateBound(raw.before, raw.beforeMs, 'before');
64
+ if (afterMs !== undefined && beforeMs !== undefined && afterMs > beforeMs) {
65
+ throw new Error('expected after at or before before');
66
+ }
67
+ return {
68
+ ...(raw.bbox !== undefined ? { bbox: raw.bbox } : {}),
69
+ ...(afterMs !== undefined ? { afterMs } : {}),
70
+ ...(beforeMs !== undefined ? { beforeMs } : {}),
71
+ ...(raw.minDistanceM !== undefined ? { minDistanceM: raw.minDistanceM } : {}),
72
+ ...(raw.availability !== undefined ? { availability: raw.availability } : {}),
73
+ ...(raw.segmentType !== undefined ? { segmentType: raw.segmentType } : {}),
74
+ ...(raw.minSmoothness !== undefined ? { minSmoothness: raw.minSmoothness } : {}),
75
+ };
76
+ }
77
+ function sampleTrackRecords(records, maxSamples) {
78
+ if (records.length === 0)
79
+ return [];
80
+ const indices = [];
81
+ if (maxSamples === 1) {
82
+ indices.push(0);
83
+ }
84
+ else if (records.length <= maxSamples) {
85
+ for (let i = 0; i < records.length; i++)
86
+ indices.push(i);
87
+ }
88
+ else {
89
+ const step = (records.length - 1) / (maxSamples - 1);
90
+ for (let i = 0; i < maxSamples; i++) {
91
+ indices.push(Math.round(i * step));
92
+ }
93
+ }
94
+ return indices.map((idx) => {
95
+ const r = records[idx];
96
+ const altAbsM = r.altAbs ?? (typeof r.gpsAltMm === 'number' ? r.gpsAltMm / 1000 : null);
97
+ return {
98
+ tSec: r.tSec,
99
+ lat: r.lat ?? null,
100
+ lon: r.lng ?? null,
101
+ altRelM: r.altRel ?? null,
102
+ altAbsM,
103
+ yawDeg: r.yawDeg ?? null,
104
+ gimbalPitchDeg: r.gimbalPitchDeg ?? null,
105
+ iso: r.iso ?? null,
106
+ shutterTime: r.shutterTime ?? null,
107
+ };
108
+ });
109
+ }
110
+ function parseAtSpec(at) {
111
+ if (typeof at === 'string')
112
+ return parseKeyframeSpecs(at);
113
+ return at.flatMap((entry) => typeof entry === 'number'
114
+ ? [{ kind: 'time', tSec: entry }]
115
+ : parseKeyframeSpecs(entry));
116
+ }
117
+ const FpsSchema = z.union([
118
+ z.number().finite().positive(),
119
+ z
120
+ .object({
121
+ num: z.number().int().positive(),
122
+ den: z.number().int().positive(),
123
+ value: z.number().finite().positive().optional(),
124
+ str: z.string().min(1).optional(),
125
+ })
126
+ .strict(),
127
+ ]);
128
+ function normalizeFps(input) {
129
+ if (typeof input === 'number') {
130
+ if (Number.isInteger(input)) {
131
+ return { num: input, den: 1, value: input, str: String(input) };
132
+ }
133
+ const den = 1000;
134
+ const num = Math.round(input * den);
135
+ return { num, den, value: input, str: `${num}/${den}` };
136
+ }
137
+ const value = input.value ?? input.num / input.den;
138
+ const str = input.str ?? (input.den === 1 ? String(input.num) : `${input.num}/${input.den}`);
139
+ return { num: input.num, den: input.den, value, str };
140
+ }
141
+ function archiveSegmentToMarkerRange(segment) {
142
+ const video = segment.clip.video;
143
+ if (!video ||
144
+ video.durationSec === null ||
145
+ !Number.isFinite(video.durationSec) ||
146
+ video.durationSec <= 0 ||
147
+ !Number.isFinite(video.fps.value) ||
148
+ video.fps.value <= 0) {
149
+ throw new Error(`clip ${segment.clip.path} is missing video timing metadata for marker export`);
150
+ }
151
+ const durationSec = video.durationSec;
152
+ const startSec = Math.max(0, Math.min(durationSec, segment.startSec));
153
+ const endSec = Math.max(startSec, Math.min(durationSec, segment.endSec));
154
+ const clipName = segment.clip.path.split(/[\\/]/u).at(-1);
155
+ return {
156
+ clipPath: segment.clip.path,
157
+ ...(clipName ? { clipName } : {}),
158
+ fps: video.fps,
159
+ durationSec,
160
+ startSec,
161
+ endSec,
162
+ label: segment.type,
163
+ note: `smoothness ${segment.smoothness.toFixed(3)}, ` +
164
+ `speed ${segment.meanSpeedMps.toFixed(2)} m/s, ` +
165
+ `yawRate ${segment.meanYawRateDegPerSec.toFixed(2)} deg/s`,
166
+ };
167
+ }
168
+ function serializeMarkers(format, markers) {
169
+ return format === 'csv'
170
+ ? serializeDaVinciResolveCsv(markers)
171
+ : serializeFcpxmlMarkers(markers);
172
+ }
173
+ const ABSOLUTE_PATH_RX = /(^|[\s"'(=])(\\\\[^\s"')\],;<>|/\\\r\n]+(?:[\\/][^\s"')\],;<>|/\\\r\n]*)*(?: [^\s"')\],;<>|/\\\r\n]+(?:[\\/][^\s"')\],;<>|/\\\r\n]*)+)*|[A-Za-z]:[\\/][^\s"')\],;<>|/\\\r\n]*(?:[\\/][^\s"')\],;<>|/\\\r\n]*)*(?: [^\s"')\],;<>|/\\\r\n]+(?:[\\/][^\s"')\],;<>|/\\\r\n]*)+)*|\/[^\s"')\],;<>|/\\\r\n]+(?:[\\/][^\s"')\],;<>|/\\\r\n]*)*(?: [^\s"')\],;<>|/\\\r\n]+(?:[\\/][^\s"')\],;<>|/\\\r\n]*)+)*)/gu;
174
+ export function sanitizeMcpErrorMessage(raw) {
175
+ return raw.replace(ABSOLUTE_PATH_RX, '$1<path>');
176
+ }
177
+ function toolHandler(log, handler) {
178
+ return async (args) => {
179
+ try {
180
+ const result = await handler(args);
181
+ return {
182
+ content: [{ type: 'text', text: JSON.stringify(result) }],
183
+ structuredContent: result,
184
+ };
185
+ }
186
+ catch (err) {
187
+ const sanitized = sanitizeMcpErrorMessage(errorMessage(err));
188
+ log(`tool error: ${sanitized}`);
189
+ return {
190
+ content: [{ type: 'text', text: sanitized }],
191
+ isError: true,
192
+ };
193
+ }
194
+ };
195
+ }
196
+ export function registerMcpTools(sdkServer, ctx) {
197
+ const wrap = (handler) => toolHandler(ctx.log, handler);
198
+ sdkServer.registerTool('archive_scan', {
199
+ description: 'Scan one or more allowed folders for DJI MP4 recordings and index telemetry, tracks, footprints, and shot segments into the archive database.',
200
+ inputSchema: z
201
+ .object({
202
+ dirs: z.array(z.string().min(1)).min(1),
203
+ recurse: z.boolean().optional(),
204
+ prune: z.boolean().optional(),
205
+ })
206
+ .strict(),
207
+ }, wrap(async (args) => {
208
+ const dirs = args.dirs.map((dir) => assertPathInAllowedRoots(dir, ctx.allowedRoots));
209
+ const records = await scanArchive(dirs, {
210
+ db: ctx.archiveDb,
211
+ recurse: args.recurse,
212
+ prune: args.prune,
213
+ getTools: ctx.getTools,
214
+ onRecord: (record) => ctx.log(`archive_scan ${record.status}: ${path.basename(record.path)}`),
215
+ });
216
+ return { db: ctx.archiveDb, count: records.length, records };
217
+ }));
218
+ sdkServer.registerTool('archive_list_clips', {
219
+ description: 'List indexed recordings matching optional spatial, date, distance, availability, or kinematic shot filters.',
220
+ inputSchema: ArchiveFiltersSchema,
221
+ }, wrap(async (args) => {
222
+ const clips = listArchive(ctx.archiveDb, toListFilters(args)).filter((clip) => isPathInAllowedRoots(clip.path, ctx.allowedRoots));
223
+ return { count: clips.length, clips };
224
+ }));
225
+ sdkServer.registerTool('archive_list_flights', {
226
+ description: 'List indexed recordings grouped into inferred flights matching optional filters.',
227
+ inputSchema: ArchiveFiltersSchema,
228
+ }, wrap(async (args) => {
229
+ const flights = listArchiveFlights(ctx.archiveDb, toListFilters(args))
230
+ .map((flight) => ({
231
+ ...flight,
232
+ clips: flight.clips.filter((clip) => isPathInAllowedRoots(clip.path, ctx.allowedRoots)),
233
+ }))
234
+ .filter((flight) => flight.clips.length > 0);
235
+ return { count: flights.length, flights };
236
+ }));
237
+ sdkServer.registerTool('archive_find_at_point', {
238
+ description: 'Find indexed clips whose GPS track passes within a radius of a coordinate, optionally including estimated camera gaze footprints.',
239
+ inputSchema: z
240
+ .object({
241
+ lat: z.number().finite().min(-90).max(90),
242
+ lon: z.number().finite().min(-180).max(180),
243
+ radiusM: z.number().finite().min(0).optional(),
244
+ includeGaze: z.boolean().optional(),
245
+ })
246
+ .strict(),
247
+ }, wrap(async (args) => {
248
+ const hits = nearArchive(ctx.archiveDb, { lat: args.lat, lon: args.lon }, args.radiusM ?? DEFAULT_RADIUS_M, args.includeGaze ?? false).filter((hit) => isPathInAllowedRoots(hit.clip.path, ctx.allowedRoots));
249
+ return { count: hits.length, hits };
250
+ }));
251
+ sdkServer.registerTool('archive_list_segments', {
252
+ description: 'List indexed kinematic shot segments ordered by smoothness score and matching optional filters.',
253
+ inputSchema: ArchiveFiltersSchema,
254
+ }, wrap(async (args) => {
255
+ const segments = listArchiveSegments(ctx.archiveDb, toListFilters(args)).filter((seg) => isPathInAllowedRoots(seg.clip.path, ctx.allowedRoots));
256
+ return { count: segments.length, segments };
257
+ }));
258
+ sdkServer.registerTool('clip_get_telemetry', {
259
+ description: 'Probe a recording and extract its telemetry summary, kinematic shot segments, and a bounded track sample preview.',
260
+ inputSchema: z
261
+ .object({
262
+ videoPath: z.string().min(1),
263
+ includeSamples: z.boolean().optional(),
264
+ maxSamples: z.number().int().min(1).max(2000).optional(),
265
+ })
266
+ .strict(),
267
+ }, wrap(async (args) => {
268
+ const videoPath = assertPathInAllowedRoots(args.videoPath, ctx.allowedRoots);
269
+ const tools = await ctx.getTools();
270
+ const probe = await probeVideo(tools, videoPath);
271
+ const loaded = await loadTelemetrySamples(tools, videoPath, probe.durationSec, probe.camMeta);
272
+ const video = {
273
+ fps: probe.fps,
274
+ frames: probe.frames,
275
+ durationSec: Number.isFinite(probe.durationSec) ? probe.durationSec : null,
276
+ width: probe.width,
277
+ height: probe.height,
278
+ creationTime: probe.creationTime ?? null,
279
+ };
280
+ if (!loaded) {
281
+ return {
282
+ videoPath,
283
+ status: 'no-telemetry',
284
+ video,
285
+ telemetry: null,
286
+ segments: [],
287
+ totalTrackRecords: 0,
288
+ samples: [],
289
+ };
290
+ }
291
+ const segments = segmentFlightShots(loaded.trackValues);
292
+ const fixCount = loaded.samples.filter((sample) => sample.fix !== null).length;
293
+ let status;
294
+ let telemetry;
295
+ if (fixCount >= 2) {
296
+ const computed = computeTelemetry(loaded, {
297
+ frames: probe.frames,
298
+ fpsValue: probe.fps.value,
299
+ });
300
+ status = 'ok';
301
+ telemetry = {
302
+ ...telemetrySummary(computed),
303
+ sampleCount: computed.sampleCount,
304
+ bbox: computed.bbox,
305
+ };
306
+ }
307
+ else {
308
+ status = 'no-gps';
309
+ telemetry = {
310
+ source: loaded.source,
311
+ method: loaded.method,
312
+ headingMode: null,
313
+ fixCount,
314
+ noLock: loaded.noLock,
315
+ trackDistanceM: 0,
316
+ sampleCount: loaded.samples.length,
317
+ bbox: null,
318
+ };
319
+ }
320
+ const samples = args.includeSamples === false
321
+ ? []
322
+ : sampleTrackRecords(loaded.trackValues, args.maxSamples ?? DEFAULT_MAX_SAMPLES);
323
+ return {
324
+ videoPath,
325
+ status,
326
+ video,
327
+ telemetry,
328
+ segments,
329
+ totalTrackRecords: loaded.trackValues.length,
330
+ samples,
331
+ };
332
+ }));
333
+ sdkServer.registerTool('clip_extract_keyframes', {
334
+ description: 'Extract targeted JPEG keyframes and nearest telemetry snapshots from a recording at specified timestamps or frame numbers.',
335
+ inputSchema: z
336
+ .object({
337
+ videoPath: z.string().min(1),
338
+ at: z.union([
339
+ z.string().min(1),
340
+ z.array(z.union([z.string().min(1), z.number().finite().min(0)])).min(1),
341
+ ]),
342
+ maxWidth: z.number().int().min(1).optional(),
343
+ outDir: z.string().min(1).optional(),
344
+ })
345
+ .strict(),
346
+ }, wrap(async (args) => {
347
+ const videoPath = assertPathInAllowedRoots(args.videoPath, ctx.allowedRoots);
348
+ const outDir = assertPathInAllowedRoots(args.outDir ?? path.dirname(videoPath), ctx.allowedRoots);
349
+ assertNotArchiveDb(outDir, ctx.archiveDb);
350
+ const requests = parseAtSpec(args.at);
351
+ const tools = await ctx.getTools();
352
+ const keyframes = await extractKeyframes(videoPath, {
353
+ at: requests,
354
+ maxWidth: args.maxWidth,
355
+ outDir,
356
+ tools,
357
+ });
358
+ return { videoPath, outDir, count: keyframes.length, keyframes };
359
+ }));
360
+ const MarkerRangeInputSchema = z
361
+ .object({
362
+ clipPath: z.string().min(1),
363
+ startSec: z.number().finite().min(0),
364
+ endSec: z.number().finite().min(0),
365
+ label: z.string().min(1),
366
+ note: z.string().optional(),
367
+ color: z.string().optional(),
368
+ durationSec: z.number().finite().positive().optional(),
369
+ fps: FpsSchema.optional(),
370
+ })
371
+ .strict();
372
+ sdkServer.registerTool('export_markers', {
373
+ description: 'Export shot markers as DaVinci Resolve CSV (.csv) or Final Cut Pro XML (.fcpxml) from explicit ranges or indexed archive segments.',
374
+ inputSchema: z
375
+ .object({
376
+ outputPath: z.string().min(1),
377
+ ranges: z.array(MarkerRangeInputSchema).optional(),
378
+ filters: ArchiveFiltersSchema.optional(),
379
+ })
380
+ .strict(),
381
+ }, wrap(async (args) => {
382
+ if (args.ranges !== undefined && args.filters !== undefined) {
383
+ throw new Error('specify either ranges or filters, not both');
384
+ }
385
+ const outputPath = assertPathInAllowedRoots(args.outputPath, ctx.allowedRoots);
386
+ assertNotArchiveDb(outputPath, ctx.archiveDb);
387
+ const allowOverwrite = isMcpOverwriteAllowed();
388
+ const assertCanWriteOutput = () => {
389
+ if (fs.existsSync(outputPath) && !allowOverwrite) {
390
+ throw new Error('refusing to overwrite existing marker output file (set DRONE_PATH_MCP_ALLOW_OVERWRITE=1 to allow)');
391
+ }
392
+ };
393
+ const format = markerFormatOf(outputPath);
394
+ if (args.ranges !== undefined) {
395
+ const archiveMeta = new Map();
396
+ if (args.ranges.some((r) => r.durationSec === undefined || r.fps === undefined)) {
397
+ if (fs.existsSync(ctx.archiveDb)) {
398
+ for (const clip of listArchive(ctx.archiveDb)) {
399
+ if (clip.video &&
400
+ clip.video.durationSec !== null &&
401
+ Number.isFinite(clip.video.durationSec) &&
402
+ clip.video.durationSec > 0) {
403
+ archiveMeta.set(canonicalizePath(clip.path), {
404
+ durationSec: clip.video.durationSec,
405
+ fps: clip.video.fps,
406
+ });
407
+ }
408
+ }
409
+ }
410
+ }
411
+ const markers = [];
412
+ for (const range of args.ranges) {
413
+ const clipPath = assertPathInAllowedRoots(range.clipPath, ctx.allowedRoots);
414
+ let durationSec = range.durationSec;
415
+ let fps = range.fps !== undefined ? normalizeFps(range.fps) : undefined;
416
+ if (durationSec === undefined || fps === undefined) {
417
+ let meta = archiveMeta.get(clipPath);
418
+ if (!meta) {
419
+ const tools = await ctx.getTools();
420
+ const probe = await probeVideo(tools, clipPath);
421
+ if (!Number.isFinite(probe.durationSec) || probe.durationSec <= 0) {
422
+ throw new Error(`clip ${clipPath} is missing duration metadata for marker export`);
423
+ }
424
+ meta = { durationSec: probe.durationSec, fps: probe.fps };
425
+ archiveMeta.set(clipPath, meta);
426
+ }
427
+ durationSec ??= meta.durationSec;
428
+ fps ??= meta.fps;
429
+ }
430
+ markers.push({
431
+ clipPath,
432
+ fps,
433
+ durationSec,
434
+ startSec: range.startSec,
435
+ endSec: range.endSec,
436
+ label: range.label,
437
+ ...(range.note !== undefined ? { note: range.note } : {}),
438
+ ...(range.color !== undefined ? { color: range.color } : {}),
439
+ });
440
+ }
441
+ const content = serializeMarkers(format, markers);
442
+ assertCanWriteOutput();
443
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
444
+ fs.writeFileSync(outputPath, content, 'utf8');
445
+ return { outputPath, format, count: markers.length };
446
+ }
447
+ const filters = args.filters ? toListFilters(args.filters) : {};
448
+ const allSegments = listArchiveSegments(ctx.archiveDb, filters);
449
+ const allowedSegments = allSegments.filter((seg) => isPathInAllowedRoots(seg.clip.path, ctx.allowedRoots));
450
+ assertCanWriteOutput();
451
+ if (allowedSegments.length === allSegments.length) {
452
+ exportArchiveMarkers(ctx.archiveDb, outputPath, { filters });
453
+ }
454
+ else {
455
+ const markers = allowedSegments.map(archiveSegmentToMarkerRange);
456
+ const content = serializeMarkers(format, markers);
457
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
458
+ fs.writeFileSync(outputPath, content, 'utf8');
459
+ }
460
+ return { outputPath, format, count: allowedSegments.length };
461
+ }));
462
+ const HudInputSchema = z.union([
463
+ z.string().min(1),
464
+ z
465
+ .object({
466
+ heading: z.boolean(),
467
+ alt: z.boolean(),
468
+ speed: z.boolean(),
469
+ })
470
+ .strict(),
471
+ ]);
472
+ sdkServer.registerTool('render_map_video', {
473
+ description: 'Render flight-path map overlay videos (and optional track export) for allowed recordings or folders.',
474
+ inputSchema: z
475
+ .object({
476
+ inputs: z.array(z.string().min(1)).min(1).max(MAX_MCP_RENDER_VIDEOS),
477
+ outDir: z.string().min(1).optional(),
478
+ outSuffix: z.string().min(1).optional(),
479
+ width: z.number().int().min(1).optional(),
480
+ height: z.number().int().min(1).optional(),
481
+ style: z.enum(MAP_STYLE_VALUES).optional(),
482
+ view: z.enum(['follow', 'overview']).optional(),
483
+ camera: z.enum(['follow', 'overview']).optional(),
484
+ zoom: z.number().finite().min(0).optional(),
485
+ zoomOut: z.number().finite().min(0).optional(),
486
+ introSec: z.number().finite().min(0).optional(),
487
+ outroSec: z.number().finite().min(0).optional(),
488
+ trailColor: z.string().nullable().optional(),
489
+ hud: HudInputSchema.optional(),
490
+ codec: z.enum(CODEC_VALUES).optional(),
491
+ quality: z.enum(QUALITY_VALUES).optional(),
492
+ preset: z.enum(ENCODER_PRESET_VALUES).optional(),
493
+ trackOut: z.string().min(1).optional(),
494
+ skipExisting: z.boolean().optional(),
495
+ recurse: z.boolean().optional(),
496
+ frameStart: z.number().int().min(0).optional(),
497
+ frameEnd: z.number().int().min(0).optional(),
498
+ })
499
+ .strict(),
500
+ }, wrap(async (args) => {
501
+ if ((args.frameStart !== undefined) !== (args.frameEnd !== undefined)) {
502
+ throw new Error('frameStart and frameEnd must be provided together');
503
+ }
504
+ if (args.frameStart !== undefined &&
505
+ args.frameEnd !== undefined &&
506
+ args.frameStart > args.frameEnd) {
507
+ throw new Error('frameStart must be at or before frameEnd');
508
+ }
509
+ if (args.view !== undefined && args.camera !== undefined && args.view !== args.camera) {
510
+ throw new Error('view and camera cannot specify conflicting modes');
511
+ }
512
+ const inputs = args.inputs.map((item) => assertPathInAllowedRoots(item, ctx.allowedRoots));
513
+ const outDir = args.outDir !== undefined
514
+ ? assertPathInAllowedRoots(args.outDir, ctx.allowedRoots)
515
+ : undefined;
516
+ const trackOut = args.trackOut !== undefined
517
+ ? assertPathInAllowedRoots(args.trackOut, ctx.allowedRoots)
518
+ : undefined;
519
+ if (trackOut !== undefined) {
520
+ assertNotArchiveDb(trackOut, ctx.archiveDb);
521
+ }
522
+ const cli = {
523
+ quiet: true,
524
+ json: false,
525
+ ...(outDir !== undefined ? { outDir } : {}),
526
+ ...(args.outSuffix !== undefined ? { outSuffix: args.outSuffix } : {}),
527
+ ...(args.width !== undefined ? { width: args.width } : {}),
528
+ ...(args.height !== undefined ? { height: args.height } : {}),
529
+ ...(args.style !== undefined ? { style: args.style } : {}),
530
+ ...(args.view ?? args.camera ? { view: args.view ?? args.camera } : {}),
531
+ ...(args.zoom !== undefined ? { zoom: args.zoom } : {}),
532
+ ...(args.zoomOut !== undefined ? { zoomOut: args.zoomOut } : {}),
533
+ ...(args.introSec !== undefined ? { introSec: args.introSec } : {}),
534
+ ...(args.outroSec !== undefined ? { outroSec: args.outroSec } : {}),
535
+ ...(args.trailColor !== undefined
536
+ ? { trailColor: asTrailColor(args.trailColor, 'trailColor') }
537
+ : {}),
538
+ ...(args.hud !== undefined
539
+ ? { hud: typeof args.hud === 'string' ? parseHud(args.hud) : args.hud }
540
+ : {}),
541
+ ...(args.codec !== undefined ? { codec: args.codec } : {}),
542
+ ...(args.quality !== undefined ? { quality: args.quality } : {}),
543
+ ...(args.preset !== undefined ? { preset: args.preset } : {}),
544
+ ...(trackOut !== undefined ? { trackOut } : {}),
545
+ ...(args.skipExisting !== undefined ? { skipExisting: args.skipExisting } : {}),
546
+ ...(args.recurse !== undefined ? { recurse: args.recurse } : {}),
547
+ };
548
+ const { config } = resolveConfig({
549
+ cli,
550
+ cwd: ctx.allowedRoots[0],
551
+ onDeprecated: (msg) => ctx.log(sanitizeMcpErrorMessage(msg)),
552
+ });
553
+ if (config.outDir) {
554
+ assertPathInAllowedRoots(config.outDir, ctx.allowedRoots);
555
+ assertNotArchiveDb(config.outDir, ctx.archiveDb);
556
+ }
557
+ if (config.trackOut) {
558
+ assertPathInAllowedRoots(config.trackOut, ctx.allowedRoots);
559
+ assertNotArchiveDb(config.trackOut, ctx.archiveDb);
560
+ }
561
+ if (/[\\/\0]/u.test(config.outSuffix)) {
562
+ throw new Error('outSuffix must not contain path separators');
563
+ }
564
+ const videos = collectRecordings(inputs, { recurse: config.recurse });
565
+ if (videos.length > MAX_MCP_RENDER_VIDEOS) {
566
+ throw new Error(`refusing to render more than ${MAX_MCP_RENDER_VIDEOS} recordings in a single MCP tool call (found ${videos.length})`);
567
+ }
568
+ for (const video of videos) {
569
+ assertPathInAllowedRoots(video, ctx.allowedRoots);
570
+ }
571
+ const allowOverwrite = isMcpOverwriteAllowed();
572
+ if (config.trackOut && fs.existsSync(config.trackOut) && !allowOverwrite) {
573
+ throw new Error('refusing to overwrite existing track output file (set DRONE_PATH_MCP_ALLOW_OVERWRITE=1 to allow)');
574
+ }
575
+ for (const plan of planOutputs(videos, config)) {
576
+ assertPathInAllowedRoots(plan.out, ctx.allowedRoots);
577
+ assertNotArchiveDb(plan.out, ctx.archiveDb);
578
+ if (fs.existsSync(plan.out) && !allowOverwrite) {
579
+ throw new Error('refusing to overwrite existing render output file (set DRONE_PATH_MCP_ALLOW_OVERWRITE=1 to allow)');
580
+ }
581
+ }
582
+ const tools = await ctx.getTools();
583
+ if (config.outDir)
584
+ fs.mkdirSync(config.outDir, { recursive: true });
585
+ const summaries = [];
586
+ const range = args.frameStart !== undefined && args.frameEnd !== undefined
587
+ ? { start: args.frameStart, end: args.frameEnd }
588
+ : undefined;
589
+ const batch = await ctx.runBatch(videos, config, (msg) => ctx.log(sanitizeMcpErrorMessage(msg)), (summary) => summaries.push(summary), { tools, range });
590
+ return {
591
+ ...batch,
592
+ outDir: config.outDir,
593
+ summaries,
594
+ };
595
+ }));
596
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Render flight-path map overlay videos (exactly the source frame rate and frame count) from DJI drone recordings - telemetry from the embedded CAM-meta (DVTM) stream or the .SRT sidecar.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -50,9 +50,11 @@
50
50
  "prepack": "npm run build:cli --prefix ../.."
51
51
  },
52
52
  "dependencies": {
53
+ "@modelcontextprotocol/server": "~2.4.0",
53
54
  "commander": "~15.1.0",
54
- "drone-path-archive": "~1.0.0",
55
- "drone-path-core": "~1.0.0",
56
- "drone-path-engine": "~1.0.0"
55
+ "drone-path-archive": "~1.1.0",
56
+ "drone-path-core": "~1.1.0",
57
+ "drone-path-engine": "~1.1.0",
58
+ "zod": "~4.6.7"
57
59
  }
58
60
  }