feat(server): introduce Zod request validation, starting with MCP tools

Adds Zod as the validation library for apps/server (in place of
express-validator), scoped here to a low-risk slice rather than a
full migration:

- MCP tool-call arguments (apps/server/src/api-mcp) are now validated
  end to end. Every tool's inputSchema is generated from its Zod
  schema via z.toJSONSchema() instead of hand-maintained JSON Schema
  literals, and every handler now parses its arguments before use —
  previously every handler did an unchecked `args as SomeType` cast
  with no runtime validation at all.
- A new validate.ts middleware (validateBody/validateParams) replaces
  the express-validator chokepoint for two reference routers, session
  and url-presets, demonstrating the pattern the remaining ~11 routers
  will follow in later PRs.
- An oxlint no-restricted-imports guardrail keeps zod importable only
  from apps/server, so it can never leak into the apps/client bundle.

The bulk of the REST router migration (automation, rundown, and the
rest of api-data) is intentionally left for follow-up PRs to keep this
change reviewable.
This commit is contained in:
Claude
2026-07-18 13:34:07 +00:00
parent f39892dc6e
commit 972a246bb6
18 changed files with 845 additions and 550 deletions
+1 -1
View File
@@ -23,7 +23,7 @@
"no-restricted-imports": [
"error",
{
"patterns": ["ontime-types/src/*", "ontime-utils/src/*"]
"patterns": ["ontime-types/src/*", "ontime-utils/src/*", "zod"]
}
]
},
+9 -1
View File
@@ -1,5 +1,13 @@
{
"$schema": "../../node_modules/oxlint/configuration_schema.json",
"extends": ["../../.oxlintrc.json"],
"plugins": ["unicorn", "typescript", "oxc", "vitest", "node", "promise"]
"plugins": ["unicorn", "typescript", "oxc", "vitest", "node", "promise"],
"rules": {
"no-restricted-imports": [
"error",
{
"patterns": ["ontime-types/src/*", "ontime-utils/src/*"]
}
]
}
}
+2 -1
View File
@@ -22,7 +22,8 @@
"osc-min": "2.1.2",
"sanitize-filename": "^1.6.3",
"ws": "^8.18.0",
"xlsx": "^0.18.5"
"xlsx": "^0.18.5",
"zod": "catalog:"
},
"devDependencies": {
"@types/cookie-parser": "1.4.10",
@@ -0,0 +1,57 @@
import { describe, expect, it } from 'vitest';
import { runMiddleware } from '../../validation-utils/__tests__/testMiddleware.js';
import { validateGenerateUrl } from '../session.validation.js';
describe('validateGenerateUrl', () => {
it('accepts a valid payload and normalises req.body', () => {
const { nextCalled, req } = runMiddleware(validateGenerateUrl, {
body: {
baseUrl: 'https://ontime.example',
path: '/timer',
authenticate: true,
lockConfig: false,
lockNav: false,
},
});
expect(nextCalled).toBe(true);
expect(req.body).toMatchObject({ baseUrl: 'https://ontime.example', path: '/timer' });
});
it('accepts an optional preset field', () => {
const { nextCalled, req } = runMiddleware(validateGenerateUrl, {
body: {
baseUrl: 'https://ontime.example',
path: '/timer',
authenticate: true,
lockConfig: false,
lockNav: false,
preset: 'my-preset',
},
});
expect(nextCalled).toBe(true);
expect(req.body.preset).toBe('my-preset');
});
it('rejects a missing required field with a 422', () => {
const { nextCalled, statusCode } = runMiddleware(validateGenerateUrl, {
body: { path: '/timer', authenticate: true, lockConfig: false, lockNav: false },
});
expect(nextCalled).toBe(false);
expect(statusCode).toBe(422);
});
it('rejects a wrong-typed field', () => {
const { nextCalled, statusCode } = runMiddleware(validateGenerateUrl, {
body: {
baseUrl: 'https://ontime.example',
path: '/timer',
authenticate: 'yes', // should be boolean
lockConfig: false,
lockNav: false,
},
});
expect(nextCalled).toBe(false);
expect(statusCode).toBe(422);
});
});
@@ -4,6 +4,7 @@ import type { ErrorResponse, GetInfo, GetUrl, SessionStats } from 'ontime-types'
import { getErrorMessage } from 'ontime-utils';
import * as sessionService from './session.service.js';
import type { GenerateUrlInput } from './session.validation.js';
import { validateGenerateUrl } from './session.validation.js';
export const router: Router = express.Router();
@@ -28,17 +29,21 @@ router.get('/info', (_req: Request, res: Response<GetInfo | ErrorResponse>) => {
}
});
router.post('/url', validateGenerateUrl, (req: Request, res: Response<GetUrl | ErrorResponse>) => {
try {
const url = sessionService.generateShareUrl(req.body.baseUrl, req.body.path, {
authenticate: req.body.authenticate,
lockConfig: req.body.lockConfig,
lockNav: req.body.lockNav,
preset: req.body.preset,
});
res.status(200).send({ url: url.toString() });
} catch (error) {
const message = getErrorMessage(error);
res.status(500).send({ message });
}
});
router.post(
'/url',
validateGenerateUrl,
(req: Request<unknown, GetUrl | ErrorResponse, GenerateUrlInput>, res: Response<GetUrl | ErrorResponse>) => {
try {
const url = sessionService.generateShareUrl(req.body.baseUrl, req.body.path, {
authenticate: req.body.authenticate,
lockConfig: req.body.lockConfig,
lockNav: req.body.lockNav,
preset: req.body.preset,
});
res.status(200).send({ url: url.toString() });
} catch (error) {
const message = getErrorMessage(error);
res.status(500).send({ message });
}
},
);
@@ -1,15 +1,14 @@
import { body } from 'express-validator';
import { z } from 'zod';
import { requestValidationFunction } from '../validation-utils/validationFunction.js';
import { validateBody } from '../validation-utils/validate.js';
export const validateGenerateUrl = [
body('baseUrl').isString().trim().notEmpty(),
body('path').isString().trim().notEmpty(),
body('authenticate').isBoolean(),
body('lockConfig').isBoolean(),
body('lockNav').isBoolean(),
body('preset').optional().isString().trim().notEmpty(),
requestValidationFunction,
];
const generateUrlSchema = z.object({
baseUrl: z.string().trim().min(1),
path: z.string().trim().min(1),
authenticate: z.boolean(),
lockConfig: z.boolean(),
lockNav: z.boolean(),
preset: z.string().trim().min(1).optional(),
});
export type GenerateUrlInput = z.infer<typeof generateUrlSchema>;
export const validateGenerateUrl = validateBody(generateUrlSchema);
@@ -0,0 +1,64 @@
import { OntimeView } from 'ontime-types';
import { describe, expect, it } from 'vitest';
import { runMiddleware } from '../../validation-utils/__tests__/testMiddleware.js';
import { validateNewPreset, validatePresetParam } from '../urlPresets.validation.js';
const validPreset = {
enabled: true,
alias: 'my-preset',
target: OntimeView.Cuesheet,
search: '',
displayInNav: true,
};
describe('validateNewPreset', () => {
it('accepts a valid preset', () => {
const { nextCalled } = runMiddleware(validateNewPreset, { body: validPreset });
expect(nextCalled).toBe(true);
});
it('accepts optional cuesheet options', () => {
const { nextCalled, req } = runMiddleware(validateNewPreset, {
body: { ...validPreset, options: { read: 'a', write: 'b' } },
});
expect(nextCalled).toBe(true);
expect(req.body.options).toEqual({ read: 'a', write: 'b' });
});
it('rejects a missing required field', () => {
const { alias: _alias, ...withoutAlias } = validPreset;
const { nextCalled, statusCode } = runMiddleware(validateNewPreset, { body: withoutAlias });
expect(nextCalled).toBe(false);
expect(statusCode).toBe(422);
});
it('rejects "editor" as a target — URL presets cannot point at the editor view', () => {
const { nextCalled, statusCode } = runMiddleware(validateNewPreset, {
body: { ...validPreset, target: OntimeView.Editor },
});
expect(nextCalled).toBe(false);
expect(statusCode).toBe(422);
});
it('rejects an unknown target value', () => {
const { nextCalled, statusCode } = runMiddleware(validateNewPreset, {
body: { ...validPreset, target: 'not-a-real-view' },
});
expect(nextCalled).toBe(false);
expect(statusCode).toBe(422);
});
});
describe('validatePresetParam', () => {
it('accepts a non-empty alias param', () => {
const { nextCalled } = runMiddleware(validatePresetParam, { params: { alias: 'my-preset' } });
expect(nextCalled).toBe(true);
});
it('rejects an empty alias param', () => {
const { nextCalled, statusCode } = runMiddleware(validatePresetParam, { params: { alias: '' } });
expect(nextCalled).toBe(false);
expect(statusCode).toBe(422);
});
});
@@ -5,6 +5,7 @@ import { getErrorMessage } from 'ontime-utils';
import { sendRefetch } from '../../adapters/WebsocketAdapter.js';
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
import type { NewPresetInput, PresetAliasParam, UpdatePresetInput } from './urlPresets.validation.js';
import { validateNewPreset, validatePresetParam, validateUpdatePreset } from './urlPresets.validation.js';
export const router: Router = express.Router();
@@ -14,80 +15,98 @@ router.get('/', (_req: Request, res: Response<URLPreset[]>) => {
res.status(200).send(presets as URLPreset[]);
});
router.post('/', validateNewPreset, async (req: Request, res: Response<URLPreset[] | ErrorResponse>) => {
try {
const newPreset: URLPreset = {
enabled: req.body.enabled,
alias: req.body.alias,
target: req.body.target,
search: req.body.search,
displayInNav: req.body.displayInNav,
options: req.body.options,
};
router.post(
'/',
validateNewPreset,
async (
req: Request<unknown, URLPreset[] | ErrorResponse, NewPresetInput>,
res: Response<URLPreset[] | ErrorResponse>,
) => {
try {
const newPreset: URLPreset = {
enabled: req.body.enabled,
alias: req.body.alias,
target: req.body.target,
search: req.body.search,
displayInNav: req.body.displayInNav,
options: req.body.options,
};
const currentPresets = getDataProvider().getUrlPresets();
if (currentPresets.some((preset) => preset.alias === newPreset.alias)) {
throw new Error(`Preset with alias ${newPreset.alias} already exists.`);
const currentPresets = getDataProvider().getUrlPresets();
if (currentPresets.some((preset) => preset.alias === newPreset.alias)) {
throw new Error(`Preset with alias ${newPreset.alias} already exists.`);
}
const newPresets = [...currentPresets, newPreset];
// Update the URL presets in the data provider
await getDataProvider().setUrlPresets(newPresets);
sendRefetch(RefetchKey.UrlPresets);
res.status(201).send(newPresets);
} catch (error) {
const message = getErrorMessage(error);
res.status(400).send({ message });
}
},
);
const newPresets = [...currentPresets, newPreset];
router.put(
'/:alias',
validateUpdatePreset,
async (
req: Request<PresetAliasParam, URLPreset[] | ErrorResponse, UpdatePresetInput>,
res: Response<URLPreset[] | ErrorResponse>,
) => {
try {
const alias = req.params.alias;
const currentPresets = getDataProvider().getUrlPresets();
const existingPreset = currentPresets.find((preset) => preset.alias === alias);
if (!existingPreset) {
throw new Error(`Preset with alias ${alias} does not exist.`);
}
// Update the URL presets in the data provider
await getDataProvider().setUrlPresets(newPresets);
sendRefetch(RefetchKey.UrlPresets);
res.status(201).send(newPresets);
} catch (error) {
const message = getErrorMessage(error);
res.status(400).send({ message });
}
});
const updatedPreset: URLPreset = {
enabled: req.body.enabled,
alias: req.body.alias,
target: req.body.target,
search: req.body.search,
displayInNav: req.body.displayInNav,
options: req.body.options ?? existingPreset.options,
};
router.put('/:alias', validateUpdatePreset, async (req: Request, res: Response<URLPreset[] | ErrorResponse>) => {
try {
const alias = req.params.alias;
const currentPresets = getDataProvider().getUrlPresets();
const existingPreset = currentPresets.find((preset) => preset.alias === alias);
if (!existingPreset) {
throw new Error(`Preset with alias ${alias} does not exist.`);
if (alias !== updatedPreset.alias) {
throw new Error('Changing alias is not permitted');
}
const newPresets = currentPresets.map((preset) => (preset.alias === alias ? updatedPreset : preset));
// Update the URL presets in the data provider
await getDataProvider().setUrlPresets(newPresets);
sendRefetch(RefetchKey.UrlPresets);
res.status(200).send(newPresets);
} catch (error) {
const message = getErrorMessage(error);
res.status(400).send({ message });
}
},
);
const updatedPreset: URLPreset = {
enabled: req.body.enabled,
alias: req.body.alias,
target: req.body.target,
search: req.body.search,
displayInNav: req.body.displayInNav,
options: req.body.options ?? existingPreset.options,
};
router.delete(
'/:alias',
validatePresetParam,
async (req: Request<PresetAliasParam>, res: Response<URLPreset[] | ErrorResponse>) => {
try {
const alias = req.params.alias;
const currentPresets = getDataProvider().getUrlPresets();
const newPresets = currentPresets.filter((preset) => preset.alias !== alias);
if (alias !== updatedPreset.alias) {
throw new Error('Changing alias is not permitted');
// Update the URL presets in the data provider
await getDataProvider().setUrlPresets(newPresets);
sendRefetch(RefetchKey.UrlPresets);
res.status(200).send(newPresets);
} catch (error) {
const message = getErrorMessage(error);
res.status(400).send({ message });
}
const newPresets = currentPresets.map((preset) => (preset.alias === alias ? updatedPreset : preset));
// Update the URL presets in the data provider
await getDataProvider().setUrlPresets(newPresets);
sendRefetch(RefetchKey.UrlPresets);
res.status(200).send(newPresets);
} catch (error) {
const message = getErrorMessage(error);
res.status(400).send({ message });
}
});
router.delete('/:alias', validatePresetParam, async (req: Request, res: Response<URLPreset[] | ErrorResponse>) => {
try {
const alias = req.params.alias;
const currentPresets = getDataProvider().getUrlPresets();
const newPresets = currentPresets.filter((preset) => preset.alias !== alias);
// Update the URL presets in the data provider
await getDataProvider().setUrlPresets(newPresets);
sendRefetch(RefetchKey.UrlPresets);
res.status(200).send(newPresets);
} catch (error) {
const message = getErrorMessage(error);
res.status(400).send({ message });
}
});
},
);
@@ -1,40 +1,36 @@
import { body, param } from 'express-validator';
import { OntimeView } from 'ontime-types';
import { OntimeView, type OntimeViewPresettable } from 'ontime-types';
import { z } from 'zod';
import { requestValidationFunction } from '../validation-utils/validationFunction.js';
import { validateBody, validateParams } from '../validation-utils/validate.js';
// URL presets cannot target the editor (see OntimeViewPresettable) — the previous
// express-validator check allowed any OntimeView value including 'editor', which URLPreset's
// own type never permitted; narrowed here now that the field is properly typed end to end.
const presettableViews = Object.values(OntimeView).filter(
(view): view is OntimeViewPresettable => view !== OntimeView.Editor,
);
const presetOptionsSchema = z.record(z.string(), z.string()).optional();
/**
* validate array of URL preset objects
*/
export const validateNewPreset = [
body().isObject().withMessage('No data found in request'),
body('enabled').isBoolean(),
body('alias').isString().trim().notEmpty(),
body('target').isString().trim().notEmpty().isIn(Object.values(OntimeView)),
body('search').isString().trim(),
body('displayInNav').isBoolean(),
const newPresetSchema = z.object({
enabled: z.boolean(),
alias: z.string().trim().min(1),
target: z.enum(presettableViews),
search: z.string().trim(),
displayInNav: z.boolean(),
// options are currently only provided for cuesheet presets
body('options').optional().isObject(),
body('options.*').isString().trim(),
options: presetOptionsSchema,
});
export type NewPresetInput = z.infer<typeof newPresetSchema>;
export const validateNewPreset = validateBody(newPresetSchema);
requestValidationFunction,
];
const presetAliasParamSchema = z.object({ alias: z.string().trim().min(1) });
export type PresetAliasParam = z.infer<typeof presetAliasParamSchema>;
export const validatePresetParam = validateParams(presetAliasParamSchema);
export const validateUpdatePreset = [
param('alias').isString().trim().notEmpty(),
body().isObject().withMessage('No data found in request'),
body('enabled').isBoolean(),
body('alias').isString().trim().notEmpty(),
body('target').isString().trim().notEmpty().isIn(Object.values(OntimeView)),
body('search').isString().trim(),
body('displayInNav').isBoolean(),
// options are currently only provided for cuesheet presets
body('options').optional().isObject(),
body('options.*').isString().trim(),
requestValidationFunction,
];
export const validatePresetParam = [param('alias').isString().trim().notEmpty(), requestValidationFunction];
// update reuses the same body shape as create, plus the alias param check
export type UpdatePresetInput = NewPresetInput;
export const validateUpdatePreset = [validateParams(presetAliasParamSchema), validateBody(newPresetSchema)];
@@ -0,0 +1,30 @@
import type { NextFunction, Request, Response } from 'express';
/**
* Exercises a single Express middleware (e.g. validateBody(schema)) against a minimal
* fake req/res, without standing up supertest or a running app — matches this codebase's
* convention of testing validation logic directly rather than through an HTTP layer.
*/
export function runMiddleware(
middleware: (req: Request, res: Response, next: NextFunction) => void,
req: Partial<Request>,
) {
let statusCode: number | undefined;
let payload: unknown;
const res = {
status(code: number) {
statusCode = code;
return this;
},
json(data: unknown) {
payload = data;
},
} as Response;
let nextCalled = false;
middleware(req as Request, res, () => {
nextCalled = true;
});
return { nextCalled, statusCode, payload, req: req as Request };
}
@@ -0,0 +1,47 @@
import type { NextFunction, Request, Response } from 'express';
import { z, type ZodType } from 'zod';
type Target = 'body' | 'params';
/**
* Builds an Express middleware that safe-parses req[target] against `schema`.
* - Uses safeParse: no throw/catch on the hot invalid-input path.
* - On success, replaces req[target] with the parsed value (defaults filled,
* unknown keys stripped, .trim()/.transform() applied) and calls next().
* - On failure, responds 422 with { errors: [...] }.
*/
function validate<T extends ZodType>(target: Target, schema: T) {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req[target]);
if (!result.success) {
const errors = result.error.issues.map((issue) => ({
location: target,
path: issue.path.join('.'),
message: issue.message,
}));
res.status(422).json({ errors });
return;
}
req[target] = result.data;
next();
};
}
export const validateBody = <T extends ZodType>(schema: T) => validate('body', schema);
export const validateParams = <T extends ZodType>(schema: T) => validate('params', schema);
/** Direct replacement for the old paramsWithId */
export const idParamSchema = z.object({ id: z.string().trim().min(1) });
export const validateIdParam = validateParams(idParamSchema);
/**
* Direct replacement for requestValidationFunctionWithFile — unrelated to Zod (it's a
* check on multer's req.file, not on body/params shape), kept as its own middleware.
*/
export function requireUploadedFile(req: Request & { file?: unknown }, res: Response, next: NextFunction) {
if (!req.file) {
res.status(422).json({ errors: 'File not found' });
return;
}
next();
}
@@ -0,0 +1,103 @@
import { describe, expect, it, vi } from 'vitest';
vi.mock('../../api-data/project-data/projectData.dao.js', () => ({
editCurrentProjectData: vi.fn(),
getProjectData: vi.fn(() => ({ title: 'Test project' })),
}));
vi.mock('../../api-data/rundown/rundown.dao.js', () => ({
getProjectCustomFields: vi.fn(() => ({})),
getRundownMetadata: vi.fn(() => ({})),
}));
vi.mock('../../api-data/rundown/rundown.service.js', () => ({
createNewRundown: vi.fn(),
deleteRundown: vi.fn(),
duplicateExistingRundown: vi.fn(),
loadRundown: vi.fn(),
renameRundown: vi.fn(),
}));
vi.mock('../../classes/data-provider/DataProvider.js', () => ({
getDataProvider: vi.fn(() => ({ getProjectRundowns: () => ({}) })),
}));
vi.mock('../../models/dataModel.js', () => ({
makeNewProject: vi.fn(() => ({ project: {} })),
}));
vi.mock('../../services/project-service/ProjectService.js', () => ({
createProjectWithPatch: vi.fn(),
deleteProjectFile: vi.fn(),
duplicateProjectFile: vi.fn(),
getProjectList: vi.fn(),
loadProjectFile: vi.fn(),
renameProjectFile: vi.fn(),
}));
vi.mock('../../stores/runtimeState.js', () => ({
getState: vi.fn(() => ({})),
}));
vi.mock('../mcp.service.js', () => ({
batchCreateEntriesForMcp: vi.fn(),
batchUpdateEntriesForMcp: vi.fn(),
createCustomFieldForMcp: vi.fn(),
createEntryForMcp: vi.fn(),
deleteCustomFieldForMcp: vi.fn(),
deleteEntriesForMcp: vi.fn(),
findEntry: vi.fn(),
getRundownById: vi.fn(() => ({ id: 'r1', order: [], entries: {} })),
groupEntriesForMcp: vi.fn(),
reorderEntryForMcp: vi.fn(),
toRundownList: vi.fn(),
ungroupEntryForMcp: vi.fn(),
updateCustomFieldForMcp: vi.fn(),
updateEntryForMcp: vi.fn(),
}));
const { TOOL_DEFINITIONS, handleToolCall } = await import('../mcp.tools.js');
describe('MCP tool schema generation', () => {
it('generates a well-formed JSON Schema inputSchema for every tool', () => {
expect(TOOL_DEFINITIONS.length).toBeGreaterThan(0);
for (const tool of TOOL_DEFINITIONS) {
expect(tool.inputSchema).toMatchObject({ type: 'object' });
expect(typeof tool.inputSchema.properties).toBe('object');
}
});
});
describe('MCP tool-call argument validation', () => {
it('rejects a required field missing entirely (previously silently miscast)', async () => {
const result = await handleToolCall('ontime_create_rundown', {});
expect(result.isError).toBe(true);
});
it('rejects a field with the wrong primitive type', async () => {
const result = await handleToolCall('ontime_reorder_entry', {
entryId: 'a',
destinationId: 'b',
order: 'sideways', // not one of before/after/insert
});
expect(result.isError).toBe(true);
});
it('rejects an unknown enum value on a nested field', async () => {
const result = await handleToolCall('ontime_create_entry', {
type: 'not-a-real-type',
});
expect(result.isError).toBe(true);
});
it('accepts a minimal valid payload for a tool with no required fields', async () => {
const result = await handleToolCall('ontime_get_rundown', {});
expect(result.isError).toBeFalsy();
});
it('reports unknown tool names distinctly from validation failures', async () => {
const result = await handleToolCall('ontime_does_not_exist', {});
expect(result.isError).toBe(true);
expect(result.content[0]).toMatchObject({ type: 'text' });
});
});
+58 -51
View File
@@ -1,3 +1,6 @@
import { EndAction, TimerType, TimeStrategy } from 'ontime-types';
import { z } from 'zod';
/**
* Agent-facing Ontime MCP documentation.
*
@@ -9,70 +12,74 @@
* Keep this file concise and update it when MCP-exposed fields change.
*/
// ---- Shared event field JSON schemas ----
// Imported by mcp.tools.ts and spread into tool inputSchema.properties.
// ---- Shared event field schemas ----
// Zod shape fragments, spread into z.object({...}) calls in mcp.tools.schema.ts.
// Field descriptions carry through into the generated inputSchema (z.toJSONSchema) and
// are what the MCP client/LLM actually reads — keep them in sync with reality.
export const EVENT_TIMER_FIELDS = {
timerType: {
type: 'string',
enum: ['count-down', 'count-up', 'clock', 'none'],
description: 'count-down: countdown from duration; count-up: elapsed time; clock: wall clock; none: no timer shown',
},
endAction: {
type: 'string',
enum: ['none', 'load-next', 'play-next'],
description: 'Action when event ends: none = stop, load-next = cue next event, play-next = auto-start next event',
},
linkStart: {
type: 'boolean',
description:
timerType: z
.enum(TimerType)
.optional()
.describe('count-down: countdown from duration; count-up: elapsed time; clock: wall clock; none: no timer shown'),
endAction: z
.enum(EndAction)
.optional()
.describe('Action when event ends: none = stop, load-next = cue next event, play-next = auto-start next event'),
linkStart: z
.boolean()
.optional()
.describe(
"Link this event's start time to the previous playable event's end time. Linked events allow time changes to propagate through the rundown. Unlinking would prevent propagation and lock this event's start time to the schedule",
},
countToEnd: {
type: 'boolean',
description:
),
countToEnd: z
.boolean()
.optional()
.describe(
'Advanced timing mode: countdown targets the scheduled timeEnd instead of the event duration. This can surprise operators when an event starts late or the schedule shifts; only set true after explaining the behaviour and confirming the user wants it. This can be useful for a deadline, where an event always needs to end at the schedule time, ie: a curfew or a broadcast window.',
},
timeStrategy: {
type: 'string',
enum: ['lock-duration', 'lock-end'],
description:
),
timeStrategy: z
.enum(TimeStrategy)
.optional()
.describe(
'How linked events adapt to an inherited start: lock-duration recalculates end, lock-end recalculates duration',
},
timeWarning: { type: 'number', description: 'ms before timeEnd to enter warning state (e.g. 300000 = 5 min)' },
timeDanger: { type: 'number', description: 'ms before timeEnd to enter danger state (e.g. 60000 = 1 min)' },
} as const;
),
timeWarning: z.number().optional().describe('ms before timeEnd to enter warning state (e.g. 300000 = 5 min)'),
timeDanger: z.number().optional().describe('ms before timeEnd to enter danger state (e.g. 60000 = 1 min)'),
};
export const EVENT_WRITABLE_FIELDS = {
cue: { type: 'string', description: 'Short free-form cue label — ask the user what naming convention they prefer' },
title: { type: 'string', description: 'Event title shown in the rundown and views' },
note: { type: 'string', description: 'Free-text note for production notes or references' },
colour: {
type: 'string',
description:
cue: z.string().optional().describe('Short free-form cue label — ask the user what naming convention they prefer'),
title: z.string().optional().describe('Event title shown in the rundown and views'),
note: z.string().optional().describe('Free-text note for production notes or references'),
colour: z
.string()
.optional()
.describe(
'Hex colour (#RRGGBB) for visual grouping — ask the user what colour convention they use, and prefer the default Ontime palette from ontime://style-guide so colours match the editor swatches',
},
skip: { type: 'boolean', description: 'If true, event is skipped during playback' },
flag: {
type: 'boolean',
description: 'Mark the event as a critical operational marker — use sparingly for maximum impact',
},
custom: {
type: 'object',
additionalProperties: { type: 'string' },
description:
),
skip: z.boolean().optional().describe('If true, event is skipped during playback'),
flag: z
.boolean()
.optional()
.describe('Mark the event as a critical operational marker — use sparingly for maximum impact'),
custom: z
.record(z.string(), z.string())
.optional()
.describe(
'Custom field values keyed by project field key, e.g. { "Camera": "CAM 2" }. Keys are case-sensitive — get them with ontime_get_custom_fields, and create missing fields with ontime_create_custom_field.',
},
),
...EVENT_TIMER_FIELDS,
} as const;
};
export const RUNDOWN_TARGET_FIELD = {
rundownId: {
type: 'string',
description:
rundownId: z
.string()
.optional()
.describe(
'Optional target rundown ID. Omit to target the currently loaded live rundown; provide an ID from ontime_list_rundowns to edit a background rundown without loading it.',
},
} as const;
),
};
// ---- Agent-readable schema document ----
// Served at ontime://schema. Agents read this once per session to orient themselves
+27 -50
View File
@@ -1,12 +1,8 @@
import {
EntryId,
EventPostPayload,
InsertOptions,
OntimeDelay,
OntimeEntry,
OntimeEvent,
OntimeGroup,
OntimeMilestone,
PatchWithId,
ProjectRundowns,
Rundown,
@@ -29,40 +25,25 @@ import {
} from '../api-data/rundown/rundown.service.js';
import { normalisedToRundownArray } from '../api-data/rundown/rundown.utils.js';
import { getDataProvider } from '../classes/data-provider/DataProvider.js';
export type EventFieldArgs = Partial<
Pick<
OntimeEvent,
| 'cue'
| 'title'
| 'note'
| 'colour'
| 'skip'
| 'flag'
| 'custom'
| 'timerType'
| 'endAction'
| 'linkStart'
| 'countToEnd'
| 'timeStrategy'
| 'timeWarning'
| 'timeDanger'
| 'timeStart'
| 'timeEnd'
| 'duration'
>
>;
export type MilestoneFieldArgs = Partial<Pick<OntimeMilestone, 'cue' | 'title' | 'note' | 'colour' | 'custom'>>;
export type DelayFieldArgs = Partial<Pick<OntimeDelay, 'duration'>>;
export type GroupFieldArgs = Partial<Pick<OntimeGroup, 'title' | 'note' | 'colour' | 'targetDuration' | 'custom'>>;
export type EntryFieldArgs = EventFieldArgs & MilestoneFieldArgs & DelayFieldArgs & GroupFieldArgs;
export type TargetRundownArgs = { rundownId?: string };
export type CreateEntryArgs = EntryFieldArgs & InsertOptions & TargetRundownArgs & { type?: `${SupportedEntry}` };
export type BatchCreateEntryArgs = CreateEntryArgs & { children?: BatchCreateEntryArgs[] };
export type UpdateEntryArgs = EntryFieldArgs & TargetRundownArgs & { id: EntryId };
export type GroupEntriesArgs = GroupFieldArgs & TargetRundownArgs & { ids: EntryId[] };
export type UngroupEntryArgs = TargetRundownArgs & { id: EntryId };
// *Args types are now derived from the Zod schemas in mcp.tools.schema.ts — that file is
// the single source of truth for MCP tool input shape, validation, and typing.
import type {
BatchCreateEntriesArgs,
BatchCreateEntryArgs,
BatchUpdateEntriesArgs,
CreateCustomFieldArgs,
CreateEntryArgs,
DeleteCustomFieldArgs,
DeleteEntriesArgs,
EntryFieldArgs,
GetEntryArgs,
GroupEntriesArgs,
ReorderEntryArgs,
TargetRundownArgs,
UngroupEntryArgs,
UpdateCustomFieldArgs,
UpdateEntryArgs,
} from './mcp.tools.schema.js';
export function resolveTargetRundownId(args: TargetRundownArgs): string {
return args.rundownId ?? getCurrentRundownId();
@@ -78,7 +59,7 @@ export function getRundownById(rundownId?: string): Readonly<Rundown> {
return targetId === getCurrentRundownId() ? getCurrentRundown() : getDataProvider().getRundown(targetId);
}
export function findEntry(args: TargetRundownArgs & { id?: EntryId; cue?: string }): OntimeEntry | undefined {
export function findEntry(args: GetEntryArgs): OntimeEntry | undefined {
const rundown = getRundownById(args.rundownId);
if (args.id) {
return rundown.entries[args.id];
@@ -194,15 +175,13 @@ export async function updateEntryForMcp(args: UpdateEntryArgs) {
return { target: getTargetMeta(rundownId), entry };
}
export async function deleteEntriesForMcp(args: TargetRundownArgs & { ids: EntryId[] }) {
export async function deleteEntriesForMcp(args: DeleteEntriesArgs) {
const rundownId = resolveTargetRundownId(args);
const rundown = await deleteEntries(rundownId, args.ids);
return { target: getTargetMeta(rundownId), deleted: args.ids, order: rundown.order };
}
export async function reorderEntryForMcp(
args: TargetRundownArgs & { entryId: EntryId; destinationId: EntryId; order: 'before' | 'after' | 'insert' },
) {
export async function reorderEntryForMcp(args: ReorderEntryArgs) {
const rundownId = resolveTargetRundownId(args);
const rundown = await reorderEntry(rundownId, args.entryId, args.destinationId, args.order);
return { target: getTargetMeta(rundownId), order: rundown.order };
@@ -259,9 +238,7 @@ export async function ungroupEntryForMcp(args: UngroupEntryArgs) {
return { target: getTargetMeta(rundownId), ungrouped: args.id, order: updatedRundown.order };
}
export async function batchCreateEntriesForMcp(
args: TargetRundownArgs & { entries: BatchCreateEntryArgs[]; after?: EntryId },
) {
export async function batchCreateEntriesForMcp(args: BatchCreateEntriesArgs) {
const { entries = [], after } = args;
validateBatchCreateEntries(entries);
const allEntries = flattenBatchCreateEntries(entries);
@@ -336,14 +313,14 @@ async function createBatchEntry(
return { entry, created };
}
export async function batchUpdateEntriesForMcp(args: TargetRundownArgs & { ids: EntryId[]; data: EntryFieldArgs }) {
export async function batchUpdateEntriesForMcp(args: BatchUpdateEntriesArgs) {
assertKnownCustomFields(args.data.custom);
const rundownId = resolveTargetRundownId(args);
const rundown = await batchEditEntries(rundownId, args.ids, args.data);
return { target: getTargetMeta(rundownId), updated: args.ids, order: rundown.order };
}
export async function createCustomFieldForMcp(args: { label: string; type: 'text' | 'image'; colour: string }) {
export async function createCustomFieldForMcp(args: CreateCustomFieldArgs) {
const label = args.label?.trim();
// same constraint the HTTP route enforces in customFields.validation.ts
if (!label || !checkRegex.isAlphanumericWithSpace(label)) {
@@ -364,13 +341,13 @@ export async function createCustomFieldForMcp(args: { label: string; type: 'text
return { key, customFields: updated };
}
export async function updateCustomFieldForMcp(args: { key: string; label?: string; colour?: string }) {
export async function updateCustomFieldForMcp(args: UpdateCustomFieldArgs) {
const projectRundowns = getDataProvider().getProjectRundowns();
const updated = await editCustomField(args.key, { label: args.label, colour: args.colour }, projectRundowns);
return { customFields: updated };
}
export async function deleteCustomFieldForMcp(args: { key: string }) {
export async function deleteCustomFieldForMcp(args: DeleteCustomFieldArgs) {
const projectRundowns = getDataProvider().getProjectRundowns();
const updated = await deleteCustomField(args.key, projectRundowns);
return { customFields: updated };
+226
View File
@@ -0,0 +1,226 @@
/**
* Zod schemas for MCP tool inputs.
*
* Each schema is the single source of truth for three things:
* - the generated `inputSchema` served to MCP clients (via z.toJSONSchema in mcp.tools.ts)
* - runtime validation of incoming tool-call arguments (via .safeParse in mcp.tools.ts)
* - the TypeScript types used by mcp.service.ts's business logic
*
* Field shapes intentionally mirror the hand-written JSON Schema this file replaces, not
* the full canonical domain types in ontime-types — e.g. `colour` stays a plain string,
* matching what was (not) validated before this migration.
*/
import { z } from 'zod';
import { EVENT_WRITABLE_FIELDS, RUNDOWN_TARGET_FIELD } from './mcp.schema.js';
// ---- Shared fragments ----
const entryTimingFields = {
timeStart: z.number().optional().describe('Start time in ms from midnight'),
timeEnd: z.number().optional().describe('End time in ms from midnight'),
duration: z.number().optional().describe('Duration in ms'),
targetDuration: z.number().optional().describe('Groups only: planned length of the group in ms'),
};
// All writable fields of any entry type, flattened — reused as the base for create/update/
// batch schemas via .extend(). Matches the previous EntryFieldArgs shape.
const entryFieldsSchema = z.object({ ...entryTimingFields, ...EVENT_WRITABLE_FIELDS });
export type EntryFieldArgs = z.infer<typeof entryFieldsSchema>;
const groupWritableFields = {
title: z.string().optional().describe('Group title shown in the rundown and views'),
note: z.string().optional().describe('Free-text group note for production notes or references'),
colour: z
.string()
.optional()
.describe('Hex colour (#RRGGBB) for the group — prefer the default Ontime palette from ontime://style-guide'),
custom: z
.record(z.string(), z.string())
.optional()
.describe('Custom field values keyed by existing project field key'),
targetDuration: z.number().optional().describe('Planned length of the group in ms'),
};
// ---- Rundown read ----
export const getRundownSchema = z.object({ ...RUNDOWN_TARGET_FIELD });
export const getRundownMetadataSchema = z.object({});
export const getEntrySchema = z.object({
...RUNDOWN_TARGET_FIELD,
id: z.string().optional().describe('Entry ID (from rundown.entries key or entry.id)'),
cue: z.string().optional().describe('Human-facing cue label'),
});
// ---- Rundown mutations ----
export const createEntrySchema = entryFieldsSchema.extend({
...RUNDOWN_TARGET_FIELD,
type: z
.enum(['event', 'delay', 'milestone', 'group'])
.optional()
.describe(
'Entry type, defaults to event. event: timed show item; milestone: non-timed marker; delay: schedule shift; group: named container of entries',
),
// Overrides entryFieldsSchema's generic timing descriptions with create-specific guidance.
timeStart: z.number().optional().describe('Event start time in ms from midnight (e.g. 09:00 = 32400000)'),
timeEnd: z.number().optional().describe('Event end time in ms from midnight'),
duration: z
.number()
.optional()
.describe('Duration in ms (events: should equal timeEnd - timeStart; delays: the schedule shift)'),
after: z.string().optional().describe('Insert after this entry ID'),
before: z.string().optional().describe('Insert before this entry ID'),
});
export const updateEntrySchema = entryFieldsSchema.extend({
...RUNDOWN_TARGET_FIELD,
id: z.string().describe('ID of the entry to update'),
});
export const deleteEntriesSchema = z.object({
...RUNDOWN_TARGET_FIELD,
ids: z.array(z.string()).describe('Array of entry IDs to delete'),
});
export const reorderEntrySchema = z.object({
...RUNDOWN_TARGET_FIELD,
entryId: z.string().describe('ID of the entry to move'),
destinationId: z.string().describe('ID of the target entry (sibling or parent group)'),
order: z.enum(['before', 'after', 'insert']).describe('before/after: place as sibling; insert: place inside a group'),
});
export const groupEntriesSchema = z.object({
...RUNDOWN_TARGET_FIELD,
ids: z.array(z.string()).describe('Existing top-level entry IDs to group'),
...groupWritableFields,
});
export const ungroupEntrySchema = z.object({
...RUNDOWN_TARGET_FIELD,
id: z.string().describe('Group entry ID to dissolve'),
});
// Recursive: a group entry in a batch may include `children` of the same shape. `type`/
// `children` are declared outside entryFieldsSchema so the lazy() wrapper can reference
// the schema being defined.
export interface BatchCreateEntryArgs extends EntryFieldArgs {
type?: 'event' | 'delay' | 'milestone' | 'group';
children?: BatchCreateEntryArgs[];
}
export const batchCreateEntrySchema: z.ZodType<BatchCreateEntryArgs> = z.lazy(() =>
entryFieldsSchema.extend({
type: z.enum(['event', 'delay', 'milestone', 'group']).optional().describe('Entry type, defaults to event'),
children: z
.array(batchCreateEntrySchema)
.optional()
.describe(
'For group entries only: child events, milestones, or delays to create inside this group in order. Nested groups are not supported.',
),
}),
);
export const batchCreateEntriesSchema = z.object({
...RUNDOWN_TARGET_FIELD,
after: z.string().optional().describe('Insert the first entry after this entry ID'),
entries: z.array(batchCreateEntrySchema).describe('Array of entries to create, in desired order'),
});
export const batchUpdateEntriesSchema = z.object({
...RUNDOWN_TARGET_FIELD,
ids: z.array(z.string()).describe('Array of entry IDs to update'),
data: entryFieldsSchema.describe('Partial entry fields to apply to every ID'),
});
// ---- Rundown management ----
export const listRundownsSchema = z.object({});
export const createRundownSchema = z.object({ title: z.string().describe('Title for the new rundown') });
export const loadRundownSchema = z.object({ id: z.string().describe('Rundown ID to load') });
export const renameRundownSchema = z.object({
id: z.string().describe('Rundown ID to rename'),
title: z.string().describe('New title'),
});
export const deleteRundownSchema = z.object({ id: z.string().describe('Rundown ID to delete') });
export const duplicateRundownSchema = z.object({ id: z.string().describe('Rundown ID to duplicate') });
// ---- Timer & project ----
export const getTimerStateSchema = z.object({});
export const getProjectInfoSchema = z.object({});
export const updateProjectInfoSchema = z.object({
title: z.string().optional().describe('Project title'),
description: z.string().optional().describe('Project description'),
url: z.string().optional().describe('URL shown on viewer pages'),
info: z.string().optional().describe('Info text shown on viewer pages'),
});
export const getCustomFieldsSchema = z.object({});
export const createCustomFieldSchema = z.object({
label: z
.string()
.describe(
'Human-readable label (letters, numbers and spaces, e.g. "Camera"). Determines the key. Reuse an existing field over creating near-duplicates like "Cam", "camera", "Cameras".',
),
type: z
.enum(['text', 'image'])
.describe(
'Field type — cannot be changed after creation. Use "text" for short text values; "image" for image URLs.',
),
colour: z
.string()
.describe(
'Hex colour (#RRGGBB) used to visually identify this column in the cuesheet — for department fields, match the department colour convention (see ontime://style-guide).',
),
});
export const updateCustomFieldSchema = z.object({
key: z.string().describe('Current field key (from ontime_get_custom_fields)'),
label: z
.string()
.optional()
.describe('New human-readable label (optional). Changes the derived key and cascades to all entries.'),
colour: z.string().optional().describe('New hex colour (#RRGGBB) (optional)'),
});
export const deleteCustomFieldSchema = z.object({
key: z.string().describe('Field key to delete (from ontime_get_custom_fields)'),
});
// ---- Project file management ----
export const listProjectsSchema = z.object({});
export const loadProjectSchema = z.object({
filename: z.string().describe('Project filename, e.g. "my-show.json"'),
});
export const createProjectSchema = z.object({
filename: z.string().describe('Filename without extension, e.g. "my-show"'),
title: z.string().optional().describe('Optional project title'),
description: z.string().optional().describe('Optional project description'),
});
export const renameProjectSchema = z.object({
filename: z.string().describe('Current filename (with .json extension)'),
newFilename: z.string().describe('New filename (with .json extension)'),
});
export const duplicateProjectSchema = z.object({
filename: z.string().describe('Source filename to copy (with .json extension)'),
newFilename: z.string().describe('Filename of the new copy (with .json extension)'),
});
export const deleteProjectSchema = z.object({
filename: z.string().describe('Project filename to delete (with .json extension)'),
});
// ---- Inferred types consumed by mcp.service.ts (replaces its hand-written *Args types) ----
export type TargetRundownArgs = z.infer<typeof getRundownSchema>;
export type GetEntryArgs = z.infer<typeof getEntrySchema>;
export type CreateEntryArgs = z.infer<typeof createEntrySchema>;
export type UpdateEntryArgs = z.infer<typeof updateEntrySchema>;
export type DeleteEntriesArgs = z.infer<typeof deleteEntriesSchema>;
export type ReorderEntryArgs = z.infer<typeof reorderEntrySchema>;
export type GroupEntriesArgs = z.infer<typeof groupEntriesSchema>;
export type UngroupEntryArgs = z.infer<typeof ungroupEntrySchema>;
export type BatchCreateEntriesArgs = z.infer<typeof batchCreateEntriesSchema>;
export type BatchUpdateEntriesArgs = z.infer<typeof batchUpdateEntriesSchema>;
export type ProjectInfoArgs = z.infer<typeof updateProjectInfoSchema>;
export type CreateCustomFieldArgs = z.infer<typeof createCustomFieldSchema>;
export type UpdateCustomFieldArgs = z.infer<typeof updateCustomFieldSchema>;
export type DeleteCustomFieldArgs = z.infer<typeof deleteCustomFieldSchema>;
+68 -319
View File
@@ -1,5 +1,6 @@
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { EntryId, ProjectData } from 'ontime-types';
import { ProjectData } from 'ontime-types';
import { z } from 'zod';
import { editCurrentProjectData, getProjectData } from '../api-data/project-data/projectData.dao.js';
import { getProjectCustomFields, getRundownMetadata } from '../api-data/rundown/rundown.dao.js';
@@ -21,7 +22,6 @@ import {
renameProjectFile,
} from '../services/project-service/ProjectService.js';
import { getState } from '../stores/runtimeState.js';
import { EVENT_WRITABLE_FIELDS, RUNDOWN_TARGET_FIELD } from './mcp.schema.js';
import {
batchCreateEntriesForMcp,
batchUpdateEntriesForMcp,
@@ -37,14 +37,19 @@ import {
ungroupEntryForMcp,
updateCustomFieldForMcp,
updateEntryForMcp,
type BatchCreateEntryArgs,
type CreateEntryArgs,
type EntryFieldArgs,
type GroupEntriesArgs,
type TargetRundownArgs,
type UngroupEntryArgs,
type UpdateEntryArgs,
} from './mcp.service.js';
import * as schemas from './mcp.tools.schema.js';
/**
* Parses tool-call arguments against `schema`, throwing on failure. handleToolCall (below)
* already wraps every handler in try/catch and formats thrown errors into a CallToolResult,
* so this reuses that existing error path rather than inventing a second one — unlike the
* REST validation layer (apps/server/src/api-data/validation-utils/validate.ts), tool calls
* are not a hot request path, so .parse()'s throw-based control flow costs nothing here.
*/
function parseArgs<T extends z.ZodType>(schema: T, args: Record<string, unknown>): z.infer<T> {
return schema.parse(args);
}
// Graceful truncation to keep tool responses within typical MCP context windows
const CHARACTER_LIMIT = 25_000;
@@ -68,28 +73,21 @@ export const TOOL_DEFINITIONS = [
name: 'ontime_get_rundown',
description:
'Get a rundown. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to read a background rundown. Returns { order: EntryId[], entries: { [id]: OntimeEntry } }. If the rundown exceeds 25 000 chars, returns only the order array with a warning — fetch individual entries with ontime_get_entry.',
inputSchema: { type: 'object', properties: { ...RUNDOWN_TARGET_FIELD } },
inputSchema: z.toJSONSchema(schemas.getRundownSchema),
annotations: READ,
},
{
name: 'ontime_get_rundown_metadata',
description:
'Get cached metadata for the current rundown. Returns: totalDelay, totalDuration, totalDays, firstStart, lastEnd, flags (flagged entry IDs), playableEventOrder, timedEventOrder, flatEntryOrder.',
inputSchema: { type: 'object', properties: {} },
inputSchema: z.toJSONSchema(schemas.getRundownMetadataSchema),
annotations: READ,
},
{
name: 'ontime_get_entry',
description:
'Get a single entry by id or cue. Provide either id or cue (not both). Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to read a background rundown. Returns the full entry object.',
inputSchema: {
type: 'object',
properties: {
...RUNDOWN_TARGET_FIELD,
id: { type: 'string', description: 'Entry ID (from rundown.entries key or entry.id)' },
cue: { type: 'string', description: 'Human-facing cue label' },
},
},
inputSchema: z.toJSONSchema(schemas.getEntrySchema),
annotations: READ,
},
// --- Rundown mutations ---
@@ -97,186 +95,56 @@ export const TOOL_DEFINITIONS = [
name: 'ontime_create_entry',
description:
'Create a new entry. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. If playback is running and rundownId is omitted or matches the loaded rundown, confirm the user intends to change the live rundown before calling. Omit after/before to append at the end. For type "event" provide title plus enough timing data for Ontime to infer a strategy: timeStart+duration calculates timeEnd, timeStart+timeEnd calculates duration and locks end, timeEnd+duration calculates timeStart, and all three prioritise duration. For "milestone" provide cue/title/note/colour and optional custom values using existing project custom field keys. For "delay" provide duration. For "group" provide title plus optional note/colour/custom/targetDuration.',
inputSchema: {
type: 'object',
properties: {
...RUNDOWN_TARGET_FIELD,
type: {
type: 'string',
enum: ['event', 'delay', 'milestone', 'group'],
description:
'Entry type, defaults to event. event: timed show item; milestone: non-timed marker; delay: schedule shift; group: named container of entries',
},
timeStart: { type: 'number', description: 'Event start time in ms from midnight (e.g. 09:00 = 32400000)' },
timeEnd: { type: 'number', description: 'Event end time in ms from midnight' },
duration: {
type: 'number',
description: 'Duration in ms (events: should equal timeEnd - timeStart; delays: the schedule shift)',
},
targetDuration: { type: 'number', description: 'Groups only: planned length of the group in ms' },
after: { type: 'string', description: 'Insert after this entry ID' },
before: { type: 'string', description: 'Insert before this entry ID' },
...EVENT_WRITABLE_FIELDS,
},
},
inputSchema: z.toJSONSchema(schemas.createEntrySchema),
annotations: WRITE,
},
{
name: 'ontime_update_entry',
description:
'Update fields of an existing entry (event, milestone, delay or group). Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. If playback is running and rundownId is omitted or matches the loaded rundown, confirm the user intends to change the live rundown before calling. Only provided fields are changed. Event time fields (timeStart, timeEnd, duration) are reconciled server-side — you may provide any combination. Group fields: title, note, colour, custom, targetDuration. Delay field: duration. Milestone fields: cue, title, note, colour, custom. Custom values must use existing project custom field keys; adding a new custom field is a separate operation.',
inputSchema: {
type: 'object',
required: ['id'],
properties: {
...RUNDOWN_TARGET_FIELD,
id: { type: 'string', description: 'ID of the entry to update' },
timeStart: { type: 'number', description: 'Start time in ms from midnight' },
timeEnd: { type: 'number', description: 'End time in ms from midnight' },
duration: { type: 'number', description: 'Duration in ms' },
targetDuration: { type: 'number', description: 'Groups only: planned length of the group in ms' },
...EVENT_WRITABLE_FIELDS,
},
},
inputSchema: z.toJSONSchema(schemas.updateEntrySchema),
annotations: WRITE_DESTRUCTIVE,
},
{
name: 'ontime_delete_entries',
description:
'Delete one or more entries (events, milestones, delays, or groups). Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it.',
inputSchema: {
type: 'object',
required: ['ids'],
properties: {
...RUNDOWN_TARGET_FIELD,
ids: { type: 'array', items: { type: 'string' }, description: 'Array of entry IDs to delete' },
},
},
inputSchema: z.toJSONSchema(schemas.deleteEntriesSchema),
annotations: WRITE_DESTRUCTIVE,
},
{
name: 'ontime_reorder_entry',
description:
'Move an entry to a new position relative to another entry. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. Use before/after for sibling reordering; use insert for targeted moves into a group. For grouping several existing top-level entries, prefer ontime_group_entries.',
inputSchema: {
type: 'object',
required: ['entryId', 'destinationId', 'order'],
properties: {
...RUNDOWN_TARGET_FIELD,
entryId: { type: 'string', description: 'ID of the entry to move' },
destinationId: { type: 'string', description: 'ID of the target entry (sibling or parent group)' },
order: {
type: 'string',
enum: ['before', 'after', 'insert'],
description: 'before/after: place as sibling; insert: place inside a group',
},
},
},
inputSchema: z.toJSONSchema(schemas.reorderEntrySchema),
annotations: WRITE_IDEM,
},
{
name: 'ontime_group_entries',
description:
'Create a group from existing top-level entries. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. If playback is running and rundownId is omitted or matches the loaded rundown, confirm the user intends to change the live rundown before calling. Entries must be existing top-level non-group entries; groups cannot be nested. Optional title, note, colour, custom, and targetDuration are applied to the created group.',
inputSchema: {
type: 'object',
required: ['ids'],
properties: {
...RUNDOWN_TARGET_FIELD,
ids: { type: 'array', items: { type: 'string' }, description: 'Existing top-level entry IDs to group' },
title: { type: 'string', description: 'Group title shown in the rundown and views' },
note: { type: 'string', description: 'Free-text group note for production notes or references' },
colour: {
type: 'string',
description:
'Hex colour (#RRGGBB) for the group — prefer the default Ontime palette from ontime://style-guide',
},
custom: {
type: 'object',
additionalProperties: { type: 'string' },
description: 'Custom field values keyed by existing project field key',
},
targetDuration: { type: 'number', description: 'Planned length of the group in ms' },
},
},
inputSchema: z.toJSONSchema(schemas.groupEntriesSchema),
annotations: WRITE,
},
{
name: 'ontime_ungroup_entry',
description:
'Dissolve a group by moving its children to the top level where the group was. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. If playback is running and rundownId is omitted or matches the loaded rundown, confirm the user intends to change the live rundown before calling.',
inputSchema: {
type: 'object',
required: ['id'],
properties: {
...RUNDOWN_TARGET_FIELD,
id: { type: 'string', description: 'Group entry ID to dissolve' },
},
},
inputSchema: z.toJSONSchema(schemas.ungroupEntrySchema),
annotations: WRITE_DESTRUCTIVE,
},
{
name: 'ontime_batch_create_entries',
description:
'Create multiple entries, including groups with nested children. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. If playback is running and rundownId is omitted or matches the loaded rundown, confirm the user intends to change the live rundown before calling. Use this for "build from agenda" flows to avoid many round trips. Entries are inserted in array order; if `after` is provided it positions the first top-level entry, subsequent top-level entries chain from the previous. A group entry may include `children`; those entries are created inside the group in array order. Groups cannot be nested. For events, provide title plus enough timing data for Ontime to infer a strategy: timeStart+duration calculates timeEnd, timeStart+timeEnd calculates duration and locks end, timeEnd+duration calculates timeStart, and all three prioritise duration.',
inputSchema: {
type: 'object',
required: ['entries'],
properties: {
...RUNDOWN_TARGET_FIELD,
after: { type: 'string', description: 'Insert the first entry after this entry ID' },
entries: {
type: 'array',
description: 'Array of entries to create, in desired order',
items: {
type: 'object',
properties: {
type: {
type: 'string',
enum: ['event', 'delay', 'milestone', 'group'],
description: 'Entry type, defaults to event',
},
timeStart: { type: 'number', description: 'Event start time in ms from midnight' },
timeEnd: { type: 'number', description: 'Event end time in ms from midnight' },
duration: { type: 'number', description: 'Duration in ms' },
targetDuration: { type: 'number', description: 'Groups only: planned length of the group in ms' },
children: {
type: 'array',
description:
'For group entries only: child events, milestones, or delays to create inside this group in order. Nested groups are not supported.',
items: { type: 'object' },
},
...EVENT_WRITABLE_FIELDS,
},
},
},
},
},
inputSchema: z.toJSONSchema(schemas.batchCreateEntriesSchema),
annotations: WRITE,
},
{
name: 'ontime_batch_update_entries',
description:
'Apply the same field values to multiple entries by ID. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. Use for bulk operations like recolouring all keynotes, skipping all breaks, or setting the same custom value on several entries. Custom values must use existing project custom field keys. Do not use for changes where each entry needs a different value, such as time shifts with different timeStart/timeEnd values; compute those per entry and call ontime_update_entry for each.',
inputSchema: {
type: 'object',
required: ['ids', 'data'],
properties: {
...RUNDOWN_TARGET_FIELD,
ids: { type: 'array', items: { type: 'string' }, description: 'Array of entry IDs to update' },
data: {
type: 'object',
description: 'Partial entry fields to apply to every ID',
properties: {
timeStart: { type: 'number', description: 'Start time in ms from midnight' },
timeEnd: { type: 'number', description: 'End time in ms from midnight' },
duration: { type: 'number', description: 'Duration in ms' },
targetDuration: { type: 'number', description: 'Groups only: planned length of the group in ms' },
...EVENT_WRITABLE_FIELDS,
},
},
},
},
inputSchema: z.toJSONSchema(schemas.batchUpdateEntriesSchema),
annotations: WRITE_DESTRUCTIVE,
},
// --- Rundown management ---
@@ -284,62 +152,39 @@ export const TOOL_DEFINITIONS = [
name: 'ontime_list_rundowns',
description:
'List all rundowns in the current project. Returns rundown IDs and titles, plus the ID of the currently loaded one.',
inputSchema: { type: 'object', properties: {} },
inputSchema: z.toJSONSchema(schemas.listRundownsSchema),
annotations: READ,
},
{
name: 'ontime_create_rundown',
description:
'Create a new empty rundown in the current project. Does not switch to it — use ontime_load_rundown to activate.',
inputSchema: {
type: 'object',
required: ['title'],
properties: { title: { type: 'string', description: 'Title for the new rundown' } },
},
inputSchema: z.toJSONSchema(schemas.createRundownSchema),
annotations: WRITE,
},
{
name: 'ontime_load_rundown',
description:
'Make a rundown the active rundown. This resets the runtime and clears playback state. If playback is running, confirm the user accepts interrupting the live rundown before calling. To edit a background rundown without interrupting playback, advise using the cuesheet view.',
inputSchema: {
type: 'object',
required: ['id'],
properties: { id: { type: 'string', description: 'Rundown ID to load' } },
},
inputSchema: z.toJSONSchema(schemas.loadRundownSchema),
annotations: WRITE_DESTRUCTIVE,
},
{
name: 'ontime_rename_rundown',
description: 'Rename an existing rundown',
inputSchema: {
type: 'object',
required: ['id', 'title'],
properties: {
id: { type: 'string', description: 'Rundown ID to rename' },
title: { type: 'string', description: 'New title' },
},
},
inputSchema: z.toJSONSchema(schemas.renameRundownSchema),
annotations: WRITE_IDEM,
},
{
name: 'ontime_delete_rundown',
description: 'Delete a rundown (cannot delete the currently loaded rundown or the last remaining rundown)',
inputSchema: {
type: 'object',
required: ['id'],
properties: { id: { type: 'string', description: 'Rundown ID to delete' } },
},
inputSchema: z.toJSONSchema(schemas.deleteRundownSchema),
annotations: WRITE_DESTRUCTIVE,
},
{
name: 'ontime_duplicate_rundown',
description: 'Duplicate a rundown, creating a copy with a new ID. Does not switch to the copy.',
inputSchema: {
type: 'object',
required: ['id'],
properties: { id: { type: 'string', description: 'Rundown ID to duplicate' } },
},
inputSchema: z.toJSONSchema(schemas.duplicateRundownSchema),
annotations: WRITE,
},
// --- Timer & project ---
@@ -347,171 +192,93 @@ export const TOOL_DEFINITIONS = [
name: 'ontime_get_timer_state',
description:
'Get the current timer/playback state. Returns: clock (time of day), timer ({ playback, current, elapsed, phase, expectedFinish, addedTime, startedAt }), eventNow (full event object or null), eventNext (full event object or null), offset.',
inputSchema: { type: 'object', properties: {} },
inputSchema: z.toJSONSchema(schemas.getTimerStateSchema),
annotations: READ,
},
{
name: 'ontime_get_project_info',
description:
'Get current project metadata: title, description, url, info, logo, and custom header fields (array of { title, value, url }).',
inputSchema: { type: 'object', properties: {} },
inputSchema: z.toJSONSchema(schemas.getProjectInfoSchema),
annotations: READ,
},
{
name: 'ontime_update_project_info',
description: 'Update project metadata fields. All fields are optional — only provided fields are updated.',
inputSchema: {
type: 'object',
properties: {
title: { type: 'string', description: 'Project title' },
description: { type: 'string', description: 'Project description' },
url: { type: 'string', description: 'URL shown on viewer pages' },
info: { type: 'string', description: 'Info text shown on viewer pages' },
},
},
inputSchema: z.toJSONSchema(schemas.updateProjectInfoSchema),
annotations: WRITE_DESTRUCTIVE,
},
{
name: 'ontime_get_custom_fields',
description:
'Get the project custom field definitions. Returns { [key]: { label, type: "text"|"image", colour } }. Keys are referenced in entry.custom[key].',
inputSchema: { type: 'object', properties: {} },
inputSchema: z.toJSONSchema(schemas.getCustomFieldsSchema),
annotations: READ,
},
{
name: 'ontime_create_custom_field',
description:
'Create a new project-level custom field definition. Custom fields add typed columns to every entry in all rundowns. The key is auto-derived from the label (spaces → underscores, e.g. "Camera Angle" → "Camera_Angle"). Creation is non-destructive — check ontime_get_custom_fields for an existing field covering the concept, and if none exists create directly without asking the user. After creation, use the returned key in entry.custom.',
inputSchema: {
type: 'object',
required: ['label', 'type', 'colour'],
properties: {
label: {
type: 'string',
description:
'Human-readable label (letters, numbers and spaces, e.g. "Camera"). Determines the key. Reuse an existing field over creating near-duplicates like "Cam", "camera", "Cameras".',
},
type: {
type: 'string',
enum: ['text', 'image'],
description:
'Field type — cannot be changed after creation. Use "text" for short text values; "image" for image URLs.',
},
colour: {
type: 'string',
description:
'Hex colour (#RRGGBB) used to visually identify this column in the cuesheet — for department fields, match the department colour convention (see ontime://style-guide).',
},
},
},
inputSchema: z.toJSONSchema(schemas.createCustomFieldSchema),
annotations: WRITE,
},
{
name: 'ontime_update_custom_field',
description:
'Update a custom field label or colour. Changing the label renames the derived key (spaces → underscores) and updates all entry references across all rundowns. Field type cannot be changed.',
inputSchema: {
type: 'object',
required: ['key'],
properties: {
key: { type: 'string', description: 'Current field key (from ontime_get_custom_fields)' },
label: {
type: 'string',
description: 'New human-readable label (optional). Changes the derived key and cascades to all entries.',
},
colour: { type: 'string', description: 'New hex colour (#RRGGBB) (optional)' },
},
},
inputSchema: z.toJSONSchema(schemas.updateCustomFieldSchema),
annotations: WRITE_IDEM,
},
{
name: 'ontime_delete_custom_field',
description:
'Delete a custom field definition and remove its values from all entries in all rundowns. Destructive and cannot be undone — confirm with the user before calling.',
inputSchema: {
type: 'object',
required: ['key'],
properties: {
key: { type: 'string', description: 'Field key to delete (from ontime_get_custom_fields)' },
},
},
inputSchema: z.toJSONSchema(schemas.deleteCustomFieldSchema),
annotations: WRITE_DESTRUCTIVE,
},
// --- Project file management ---
{
name: 'ontime_list_projects',
description: 'List all project files on disk. Returns filenames, timestamps, and the last-loaded project name.',
inputSchema: { type: 'object', properties: {} },
inputSchema: z.toJSONSchema(schemas.listProjectsSchema),
annotations: READ,
},
{
name: 'ontime_load_project',
description:
'Load a different project file by filename. This swaps the database and reinitialises runtime. If playback is running, confirm the user accepts interrupting the live project before calling.',
inputSchema: {
type: 'object',
required: ['filename'],
properties: { filename: { type: 'string', description: 'Project filename, e.g. "my-show.json"' } },
},
inputSchema: z.toJSONSchema(schemas.loadProjectSchema),
annotations: WRITE_DESTRUCTIVE,
},
{
name: 'ontime_create_project',
description:
'Create a new project file and switch to it. This swaps the loaded project. If playback is running, confirm the user accepts interrupting the live project before calling. Omit the .json extension — Ontime appends it.',
inputSchema: {
type: 'object',
required: ['filename'],
properties: {
filename: { type: 'string', description: 'Filename without extension, e.g. "my-show"' },
title: { type: 'string', description: 'Optional project title' },
description: { type: 'string', description: 'Optional project description' },
},
},
inputSchema: z.toJSONSchema(schemas.createProjectSchema),
annotations: WRITE_DESTRUCTIVE,
},
{
name: 'ontime_rename_project',
description: 'Rename a project file. If the renamed project is currently loaded, it is reloaded with the new name.',
inputSchema: {
type: 'object',
required: ['filename', 'newFilename'],
properties: {
filename: { type: 'string', description: 'Current filename (with .json extension)' },
newFilename: { type: 'string', description: 'New filename (with .json extension)' },
},
},
inputSchema: z.toJSONSchema(schemas.renameProjectSchema),
annotations: WRITE_IDEM,
},
{
name: 'ontime_duplicate_project',
description: 'Duplicate a project file on disk with a new filename. Does not switch to the copy.',
inputSchema: {
type: 'object',
required: ['filename', 'newFilename'],
properties: {
filename: { type: 'string', description: 'Source filename to copy (with .json extension)' },
newFilename: { type: 'string', description: 'Filename of the new copy (with .json extension)' },
},
},
inputSchema: z.toJSONSchema(schemas.duplicateProjectSchema),
annotations: WRITE,
},
{
name: 'ontime_delete_project',
description: 'Delete a project file from disk. Fails if the file is currently loaded.',
inputSchema: {
type: 'object',
required: ['filename'],
properties: { filename: { type: 'string', description: 'Project filename to delete (with .json extension)' } },
},
inputSchema: z.toJSONSchema(schemas.deleteProjectSchema),
annotations: WRITE_DESTRUCTIVE,
},
] as const;
type ToolName = (typeof TOOL_DEFINITIONS)[number]['name'];
type ProjectInfoArgs = Partial<Pick<ProjectData, 'title' | 'description' | 'url' | 'info'>>;
// ---- Response helpers (module-level to avoid re-allocation on every tool call) ----
const text = (data: unknown): string => JSON.stringify(data);
@@ -528,7 +295,7 @@ export const err = (e: unknown): CallToolResult => ({
// into an existing service and formats the response. Business logic belongs in the services.
const TOOL_HANDLERS: Record<ToolName, (args: Record<string, unknown>) => Promise<CallToolResult>> = {
ontime_get_rundown: async (args) => {
const targetArgs = args as TargetRundownArgs;
const targetArgs = parseArgs(schemas.getRundownSchema, args);
const rundown = getRundownById(targetArgs.rundownId);
const data = { order: rundown.order, entries: rundown.entries };
const serialised = text(data);
@@ -546,7 +313,7 @@ const TOOL_HANDLERS: Record<ToolName, (args: Record<string, unknown>) => Promise
ontime_get_rundown_metadata: async () => ok(getRundownMetadata()),
ontime_get_entry: async (args) => {
const entryArgs = args as TargetRundownArgs & { id?: EntryId; cue?: string };
const entryArgs = parseArgs(schemas.getEntrySchema, args);
const entry = findEntry(entryArgs);
if (entry) return ok(entry);
if (entryArgs.id) return err(`No entry with id ${entryArgs.id}`);
@@ -555,71 +322,61 @@ const TOOL_HANDLERS: Record<ToolName, (args: Record<string, unknown>) => Promise
},
ontime_create_entry: async (args) => {
return ok(await createEntryForMcp(args as CreateEntryArgs));
return ok(await createEntryForMcp(parseArgs(schemas.createEntrySchema, args)));
},
ontime_update_entry: async (args) => {
return ok(await updateEntryForMcp(args as UpdateEntryArgs));
return ok(await updateEntryForMcp(parseArgs(schemas.updateEntrySchema, args)));
},
ontime_delete_entries: async (args) => {
return ok(await deleteEntriesForMcp(args as TargetRundownArgs & { ids: EntryId[] }));
return ok(await deleteEntriesForMcp(parseArgs(schemas.deleteEntriesSchema, args)));
},
ontime_reorder_entry: async (args) => {
return ok(
await reorderEntryForMcp(
args as TargetRundownArgs & {
entryId: EntryId;
destinationId: EntryId;
order: 'before' | 'after' | 'insert';
},
),
);
return ok(await reorderEntryForMcp(parseArgs(schemas.reorderEntrySchema, args)));
},
ontime_group_entries: async (args) => {
return ok(await groupEntriesForMcp(args as GroupEntriesArgs));
return ok(await groupEntriesForMcp(parseArgs(schemas.groupEntriesSchema, args)));
},
ontime_ungroup_entry: async (args) => {
return ok(await ungroupEntryForMcp(args as UngroupEntryArgs));
return ok(await ungroupEntryForMcp(parseArgs(schemas.ungroupEntrySchema, args)));
},
ontime_batch_create_entries: async (args) => {
return ok(
await batchCreateEntriesForMcp(args as TargetRundownArgs & { entries: BatchCreateEntryArgs[]; after?: EntryId }),
);
return ok(await batchCreateEntriesForMcp(parseArgs(schemas.batchCreateEntriesSchema, args)));
},
ontime_batch_update_entries: async (args) => {
return ok(await batchUpdateEntriesForMcp(args as TargetRundownArgs & { ids: EntryId[]; data: EntryFieldArgs }));
return ok(await batchUpdateEntriesForMcp(parseArgs(schemas.batchUpdateEntriesSchema, args)));
},
ontime_list_rundowns: async () => ok(toRundownList(getDataProvider().getProjectRundowns())),
ontime_create_rundown: async (args) => {
const { title } = args as { title: string };
const { title } = parseArgs(schemas.createRundownSchema, args);
return ok(toRundownList(await createNewRundown(title)));
},
ontime_load_rundown: async (args) => {
const { id } = args as { id: string };
const { id } = parseArgs(schemas.loadRundownSchema, args);
return ok(toRundownList(await loadRundown(id)));
},
ontime_rename_rundown: async (args) => {
const { id, title } = args as { id: string; title: string };
const { id, title } = parseArgs(schemas.renameRundownSchema, args);
return ok(toRundownList(await renameRundown(id, title)));
},
ontime_delete_rundown: async (args) => {
const { id } = args as { id: string };
const { id } = parseArgs(schemas.deleteRundownSchema, args);
return ok(toRundownList(await deleteRundown(id)));
},
ontime_duplicate_rundown: async (args) => {
const { id } = args as { id: string };
const { id } = parseArgs(schemas.duplicateRundownSchema, args);
return ok(toRundownList(await duplicateExistingRundown(id)));
},
@@ -631,61 +388,53 @@ const TOOL_HANDLERS: Record<ToolName, (args: Record<string, unknown>) => Promise
ontime_get_project_info: async () => ok(getProjectData()),
ontime_update_project_info: async (args) => {
const updated = await editCurrentProjectData(args as ProjectInfoArgs);
const updated = await editCurrentProjectData(parseArgs(schemas.updateProjectInfoSchema, args));
return ok(updated);
},
ontime_get_custom_fields: async () => ok(getProjectCustomFields()),
ontime_create_custom_field: async (args) => {
return ok(await createCustomFieldForMcp(args as { label: string; type: 'text' | 'image'; colour: string }));
return ok(await createCustomFieldForMcp(parseArgs(schemas.createCustomFieldSchema, args)));
},
ontime_update_custom_field: async (args) => {
return ok(await updateCustomFieldForMcp(args as { key: string; label?: string; colour?: string }));
return ok(await updateCustomFieldForMcp(parseArgs(schemas.updateCustomFieldSchema, args)));
},
ontime_delete_custom_field: async (args) => {
return ok(await deleteCustomFieldForMcp(args as { key: string }));
return ok(await deleteCustomFieldForMcp(parseArgs(schemas.deleteCustomFieldSchema, args)));
},
ontime_list_projects: async () => ok(await getProjectList()),
ontime_load_project: async (args) => {
const { filename } = args as { filename: string };
const { filename } = parseArgs(schemas.loadProjectSchema, args);
await loadProjectFile(filename);
return ok(await getProjectList());
},
ontime_create_project: async (args) => {
const {
filename,
title = '',
description = '',
} = args as {
filename: string;
title?: string;
description?: string;
};
const { filename, title = '', description = '' } = parseArgs(schemas.createProjectSchema, args);
const project: ProjectData = { ...makeNewProject().project, title, description };
const newFileName = await createProjectWithPatch(filename, { project });
return ok({ filename: newFileName });
},
ontime_rename_project: async (args) => {
const { filename, newFilename } = args as { filename: string; newFilename: string };
const { filename, newFilename } = parseArgs(schemas.renameProjectSchema, args);
await renameProjectFile(filename, newFilename);
return ok(await getProjectList());
},
ontime_duplicate_project: async (args) => {
const { filename, newFilename } = args as { filename: string; newFilename: string };
const { filename, newFilename } = parseArgs(schemas.duplicateProjectSchema, args);
await duplicateProjectFile(filename, newFilename);
return ok(await getProjectList());
},
ontime_delete_project: async (args) => {
const { filename } = args as { filename: string };
const { filename } = parseArgs(schemas.deleteProjectSchema, args);
await deleteProjectFile(filename);
return ok(await getProjectList());
},
+6
View File
@@ -21,6 +21,9 @@ catalogs:
vitest:
specifier: 4.0.17
version: 4.0.17
zod:
specifier: 4.4.3
version: 4.4.3
importers:
@@ -275,6 +278,9 @@ importers:
xlsx:
specifier: ^0.18.5
version: 0.18.5
zod:
specifier: 'catalog:'
version: 4.4.3
devDependencies:
'@types/cookie-parser':
specifier: 1.4.10
+1
View File
@@ -8,6 +8,7 @@ catalog:
ts-essentials: 10.1.1
typescript: 7.0.2
vitest: 4.0.17
zod: 4.4.3
allowBuilds:
'@parcel/watcher': true