Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat(api): manage agent schedules over MCP (#61)

Croff3d635acd332a
diff --git a/apps/api/src/agent-schedules/__tests__/integration/agent-schedules.test.ts b/apps/api/src/agent-schedules/__tests__/integration/agent-schedules.test.ts
new file mode 100644
index 00000000..9458f4e8
--- /dev/null
+++ b/apps/api/src/agent-schedules/__tests__/integration/agent-schedules.test.ts
@@ -0,0 +1,189 @@
+import { describe, it, expect, beforeEach } from 'bun:test';
+import { authedApi, type Api } from '../../../__tests__/helpers/app';
+import { signUpTestUser } from '../../../__tests__/helpers/auth';
+import { resetDb } from '../../../__tests__/helpers/db';
+import { untaggedRoutes } from '../../../__tests__/helpers/mcp';
+
+// A schedule sends a fixed task to an internal agent on a cron, in UTC. The worker
+// picks up the queued runs, so a run created here stays pending. Access is the
+// ai_agents permission resource.
+
+const schedules = (api: Api) => api.projects({ projectKey: 'MKT' })['agent-schedules'];
+
+async function setup() {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ return { asOwner };
+}
+
+async function createAgent(
+ api: Api,
+ opts: { username?: string; kind?: 'internal' | 'external'; projectKey?: string } = {},
+): Promise<number> {
+ const res = await api.projects({ projectKey: opts.projectKey ?? 'MKT' })['ai-agents'].post({
+ name: 'Triage Bot',
+ username: opts.username ?? 'triage',
+ kind: opts.kind ?? 'internal',
+ });
+ return res.data!.agent.id;
+}
+
+async function createSchedule(api: Api, agentId: number, cron = '0 9 * * *') {
+ return schedules(api).post({
+ agentId,
+ name: 'Daily triage',
+ prompt: 'Triage the new issues.',
+ cron,
+ });
+}
+
+describe('agent schedules', () => {
+ beforeEach(async () => {
+ await resetDb();
+ });
+
+ it('creates a schedule and lists it with its next run', async () => {
+ const { asOwner } = await setup();
+ const agentId = await createAgent(asOwner);
+ const created = await createSchedule(asOwner, agentId);
+ expect(created.status).toBe(201);
+ expect(created.data).toMatchObject({
+ agentId,
+ agentName: 'Triage Bot',
+ name: 'Daily triage',
+ cron: '0 9 * * *',
+ timezone: 'UTC',
+ status: 'active',
+ lastRunAt: null,
+ lastRunStatus: null,
+ });
+ expect(new Date(created.data!.nextRunAt).getTime()).toBeGreaterThan(Date.now());
+
+ const list = await schedules(asOwner).get();
+ expect(list.status).toBe(200);
+ expect(list.data).toHaveLength(1);
+ expect(list.data?.[0].id).toBe(created.data!.id);
+ });
+
+ it('rejects an invalid cron expression', async () => {
+ const { asOwner } = await setup();
+ const agentId = await createAgent(asOwner);
+ const res = await createSchedule(asOwner, agentId, 'not a cron');
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects a blank name', async () => {
+ const { asOwner } = await setup();
+ const agentId = await createAgent(asOwner);
+ const res = await schedules(asOwner).post({
+ agentId,
+ name: ' ',
+ prompt: 'Triage the new issues.',
+ cron: '0 9 * * *',
+ });
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects an external agent and an agent of another project', async () => {
+ const { asOwner } = await setup();
+ const externalId = await createAgent(asOwner, { username: 'hook', kind: 'external' });
+ expect((await createSchedule(asOwner, externalId)).status).toBe(400);
+
+ await asOwner.projects.post({ key: 'ENG', name: 'Engineering' });
+ const foreignId = await createAgent(asOwner, { username: 'eng', projectKey: 'ENG' });
+ expect((await createSchedule(asOwner, foreignId)).status).toBe(400);
+ });
+
+ it('pauses a schedule and moves the next run when it is resumed', async () => {
+ const { asOwner } = await setup();
+ const agentId = await createAgent(asOwner);
+ const created = await createSchedule(asOwner, agentId);
+ const scheduleId = created.data!.id;
+
+ const paused = await schedules(asOwner)({ scheduleId }).patch({ status: 'paused' });
+ expect(paused.status).toBe(200);
+ expect(paused.data).toMatchObject({ status: 'paused' });
+ expect(new Date(paused.data!.nextRunAt).getTime()).toBe(
+ new Date(created.data!.nextRunAt).getTime(),
+ );
+
+ const resumed = await schedules(asOwner)({ scheduleId }).patch({ status: 'active' });
+ expect(resumed.data).toMatchObject({ status: 'active' });
+ expect(new Date(resumed.data!.nextRunAt).getTime()).toBeGreaterThan(Date.now());
+ });
+
+ it('recomputes the next run when the cron changes', async () => {
+ const { asOwner } = await setup();
+ const agentId = await createAgent(asOwner);
+ const created = await createSchedule(asOwner, agentId, '0 9 * * *');
+ const updated = await schedules(asOwner)({ scheduleId: created.data!.id }).patch({
+ cron: '30 9 * * *',
+ prompt: 'Triage and label the new issues.',
+ });
+ expect(updated.status).toBe(200);
+ expect(updated.data).toMatchObject({
+ cron: '30 9 * * *',
+ prompt: 'Triage and label the new issues.',
+ });
+ expect(new Date(updated.data!.nextRunAt).getUTCMinutes()).toBe(30);
+ });
+
+ it('queues a manual run and reports it in the run history', async () => {
+ const { asOwner } = await setup();
+ const agentId = await createAgent(asOwner);
+ const created = await createSchedule(asOwner, agentId);
+ const scheduleId = created.data!.id;
+
+ const run = await schedules(asOwner)({ scheduleId }).run.post();
+ expect(run.status).toBe(202);
+ expect(typeof run.data?.runId).toBe('number');
+
+ const runs = await schedules(asOwner)({ scheduleId }).runs.get();
+ expect(runs.status).toBe(200);
+ expect(runs.data).toHaveLength(1);
+ expect(runs.data?.[0]).toMatchObject({
+ id: run.data!.runId,
+ trigger: 'manual',
+ status: 'pending',
+ prompt: 'Triage the new issues.',
+ output: null,
+ finishedAt: null,
+ });
+ });
+
+ it('deletes a schedule and 404s on it afterwards', async () => {
+ const { asOwner } = await setup();
+ const agentId = await createAgent(asOwner);
+ const scheduleId = (await createSchedule(asOwner, agentId)).data!.id;
+
+ expect((await schedules(asOwner)({ scheduleId }).delete()).status).toBe(204);
+ expect((await schedules(asOwner).get()).data).toEqual([]);
+ expect((await schedules(asOwner)({ scheduleId }).delete()).status).toBe(404);
+ });
+
+ it('404s on an unknown schedule', async () => {
+ const { asOwner } = await setup();
+ const patched = await schedules(asOwner)({ scheduleId: 999999 }).patch({ status: 'paused' });
+ expect(patched.status).toBe(404);
+ expect((await schedules(asOwner)({ scheduleId: 999999 }).run.post()).status).toBe(404);
+ expect((await schedules(asOwner)({ scheduleId: 999999 }).runs.get()).status).toBe(404);
+ });
+
+ it('denies a non-member', async () => {
+ const { asOwner } = await setup();
+ const agentId = await createAgent(asOwner);
+ const scheduleId = (await createSchedule(asOwner, agentId)).data!.id;
+ const outsider = await signUpTestUser({ name: 'Outsider' });
+ const asOutsider = authedApi(outsider.cookie);
+
+ expect((await schedules(asOutsider).get()).status).toBe(403);
+ expect((await schedules(asOutsider)({ scheduleId }).run.post()).status).toBe(403);
+ expect((await schedules(asOutsider)({ scheduleId }).delete()).status).toBe(403);
+ });
+
+ // Schedules are managed entirely over MCP: every route is a tool.
+ it('exposes every schedule route to MCP', () => {
+ expect(untaggedRoutes((route) => route.includes('/agent-schedules'))).toEqual([]);
+ });
+});
diff --git a/apps/api/src/agent-schedules/routes.ts b/apps/api/src/agent-schedules/routes.ts
index 121b112a..57d42696 100644
--- a/apps/api/src/agent-schedules/routes.ts
+++ b/apps/api/src/agent-schedules/routes.ts
@@ -4,6 +4,7 @@ import { guards } from '../shared/guards';
import { noContent } from '../shared/http';
import { HttpError } from '../shared/lib';
import { ErrorResponse } from '../shared/responses';
+import { mcpTool } from '../mcp/generate';
import { nextCronRun } from './cron';
import {
createAgentSchedule,
@@ -15,16 +16,64 @@ import {
updateAgentSchedule,
} from './store';
-const params = t.Object({ projectKey: t.String(), scheduleId: t.Numeric() });
-const status = t.UnionEnum(['active', 'paused']);
+const params = t.Object({
+ projectKey: t.String(),
+ scheduleId: t.Numeric({ description: 'Schedule id from list_agent_schedules.' }),
+});
+const status = t.UnionEnum(['active', 'paused'], {
+ description: "'active' runs on the cron, 'paused' stops it until it is set back to 'active'.",
+});
const scheduleBody = t.Object({
- agentId: t.Number(),
- name: t.String({ minLength: 1, maxLength: 120 }),
- prompt: t.String({ minLength: 1, maxLength: 20_000 }),
- cron: t.String({ minLength: 1, maxLength: 120 }),
+ agentId: t.Number({ description: 'Internal agent id from list_ai_agents that runs the task.' }),
+ name: t.String({ minLength: 1, maxLength: 120, description: 'Display name of the schedule.' }),
+ prompt: t.String({
+ minLength: 1,
+ maxLength: 20_000,
+ description: 'Task sent to the agent on every run.',
+ }),
+ cron: t.String({
+ minLength: 1,
+ maxLength: 120,
+ description: "Five-field cron expression in UTC, e.g. '0 9 * * 1' for Mondays at 09:00.",
+ }),
status: t.Optional(status),
});
+// A schedule DTO (AgentScheduleRow from the store).
+const AgentScheduleResponse = t.Object({
+ id: t.Number(),
+ agentId: t.Number(),
+ agentName: t.String(),
+ name: t.String(),
+ prompt: t.String(),
+ cron: t.String(),
+ timezone: t.Literal('UTC'),
+ status,
+ nextRunAt: t.String(),
+ lastRunAt: t.Nullable(t.String()),
+ lastRunStatus: t.Nullable(t.String()),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+});
+
+// One run of a schedule (ScheduleRunRow from the store), with the agent's answer in
+// `output` once the run has finished.
+const ScheduleRunResponse = t.Object({
+ id: t.Number(),
+ status: t.String(),
+ trigger: t.String(),
+ prompt: t.String(),
+ attempts: t.Number(),
+ lastError: t.Nullable(t.String()),
+ output: t.Nullable(t.String()),
+ scheduledFor: t.Nullable(t.String()),
+ startedAt: t.Nullable(t.String()),
+ finishedAt: t.Nullable(t.String()),
+ createdAt: t.String(),
+});
+
+const QueuedRunResponse = t.Object({ runId: t.Number() });
+
function requiredText(value: string, field: string): string {
const trimmed = value.trim();
if (!trimmed) throw new HttpError(400, `${field} is required`);
@@ -39,7 +88,19 @@ export const agentScheduleRoutes = new Elysia({
.use(guards)
.get('/projects/:projectKey/agent-schedules', ({ project }) => listAgentSchedules(project.id), {
permission: ['ai_agents', 'read'],
- detail: { summary: 'List agent schedules' },
+ response: {
+ 200: t.Array(AgentScheduleResponse),
+ 401: ErrorResponse,
+ 403: ErrorResponse,
+ 404: ErrorResponse,
+ },
+ detail: {
+ summary: 'List agent schedules',
+ description:
+ "List the project's agent schedules: which internal agent runs which task on which cron, " +
+ 'with the next and last run.',
+ ...mcpTool('list_agent_schedules'),
+ },
})
.post(
'/projects/:projectKey/agent-schedules',
@@ -61,8 +122,20 @@ export const agentScheduleRoutes = new Elysia({
{
body: scheduleBody,
permission: ['ai_agents', 'create'],
- response: { 400: ErrorResponse, 401: ErrorResponse, 403: ErrorResponse, 404: ErrorResponse },
- detail: { summary: 'Create an agent schedule' },
+ response: {
+ 201: AgentScheduleResponse,
+ 400: ErrorResponse,
+ 401: ErrorResponse,
+ 403: ErrorResponse,
+ 404: ErrorResponse,
+ },
+ detail: {
+ summary: 'Create an agent schedule',
+ description:
+ 'Create a schedule that sends a task to an internal agent on a cron. It starts active ' +
+ "unless status is 'paused'.",
+ ...mcpTool('create_agent_schedule'),
+ },
},
)
.patch(
@@ -91,8 +164,20 @@ export const agentScheduleRoutes = new Elysia({
params,
body: t.Partial(scheduleBody),
permission: ['ai_agents', 'edit'],
- response: { 400: ErrorResponse, 401: ErrorResponse, 403: ErrorResponse, 404: ErrorResponse },
- detail: { summary: 'Update an agent schedule' },
+ response: {
+ 200: AgentScheduleResponse,
+ 400: ErrorResponse,
+ 401: ErrorResponse,
+ 403: ErrorResponse,
+ 404: ErrorResponse,
+ },
+ detail: {
+ summary: 'Update an agent schedule',
+ description:
+ "Update a schedule's agent, task, or cron, and pause or resume it through status. " +
+ 'Resuming and a new cron both move the next run to the next matching time.',
+ ...mcpTool('update_agent_schedule'),
+ },
},
)
.delete(
@@ -106,7 +191,20 @@ export const agentScheduleRoutes = new Elysia({
{
params,
permission: ['ai_agents', 'delete'],
- detail: { summary: 'Delete an agent schedule' },
+ response: {
+ 204: t.Void(),
+ 400: ErrorResponse,
+ 401: ErrorResponse,
+ 403: ErrorResponse,
+ 404: ErrorResponse,
+ },
+ detail: {
+ summary: 'Delete an agent schedule',
+ description:
+ 'Delete a schedule with its run history and the conversation its runs shared. ' +
+ 'Irreversible; pause it instead to keep it.',
+ ...mcpTool('delete_agent_schedule'),
+ },
},
)
.post(
@@ -117,7 +215,25 @@ export const agentScheduleRoutes = new Elysia({
set.status = 202;
return { runId };
},
- { params, permission: ['ai_agents', 'edit'], detail: { summary: 'Run an agent schedule now' } },
+ {
+ params,
+ permission: ['ai_agents', 'edit'],
+ response: {
+ 202: QueuedRunResponse,
+ 400: ErrorResponse,
+ 401: ErrorResponse,
+ 403: ErrorResponse,
+ 404: ErrorResponse,
+ },
+ detail: {
+ summary: 'Run an agent schedule now',
+ description:
+ 'Queue a run of the schedule right away, without waiting for its cron, and return the ' +
+ "run id. The run is executed in the background: read its status and the agent's answer " +
+ 'with list_agent_schedule_runs.',
+ ...mcpTool('run_agent_schedule'),
+ },
+ },
)
.get(
'/projects/:projectKey/agent-schedules/:scheduleId/runs',
@@ -126,5 +242,22 @@ export const agentScheduleRoutes = new Elysia({
if (!rows) throw new HttpError(404, 'Schedule not found');
return rows;
},
- { params, permission: ['ai_agents', 'read'], detail: { summary: 'List agent schedule runs' } },
+ {
+ params,
+ permission: ['ai_agents', 'read'],
+ response: {
+ 200: t.Array(ScheduleRunResponse),
+ 400: ErrorResponse,
+ 401: ErrorResponse,
+ 403: ErrorResponse,
+ 404: ErrorResponse,
+ },
+ detail: {
+ summary: 'List agent schedule runs',
+ description:
+ "The schedule's last 50 runs, newest first, each with its status, the agent's answer " +
+ 'in output, and the error of a failed run.',
+ ...mcpTool('list_agent_schedule_runs'),
+ },
+ },
);