import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { RISK_CATEGORIES, TICKET_TYPES, type TicketType } from '@teamtrail/core'; import { z } from 'zod'; import { OperationError, type TrailAgent, type WaitControl } from './agent'; import { assertLineSafe, toolShapes } from './lineSafety'; import { assertNoHumanInputs, humanRoles, markHumanInputs, type HumanRole } from './remoteGate'; import { withRefusedWrites } from './withRefusedWrites'; export const ticketType = z.enum(TICKET_TYPES as [TicketType, ...TicketType[]]); export const trail = z .string() .optional() .describe('Trail id, key (#3) or title. Default: the current trail, else the most recently active one.'); export const ticket = z.string().describe('Ticket key (#12) or id (12).'); export const riskCategory = z .enum(RISK_CATEGORIES) .describe("What the call touches, for the project's risk policy: high-risk categories are the human's to decide."); export const guidesFilter = z .array(z.string()) .max(20) .optional() .describe('Only take tickets with one of these guides (e.g. ["qa"]). Tickets without a guide are left out.'); export const guideId = z .string() .describe( "Rarely needed: one more guide for this ticket beyond the ones its type gets from the trail (list_guides). Must be an installed guide made for the ticket's type.", ); export const checklistAnswers = z .array( z.object({ guide: z.string().optional().describe('The guide whose checklist this answers; needed with several guides.'), item: z.string().describe('The item text, or its number'), done: z.boolean(), note: z.string().optional(), }), ) .max(100) .optional() .describe( "Answers to the checklists of the ticket's guides: one per item of every guide. Required when its guides have checklists.", ); export const riskPaths = z .array(z.string()) .max(200) .describe( 'Repo-relative files the decision changes (an absolute path inside the repo counts as relative; nothing outside it); checked against the risk policy path rules. Required for a remote completion of verified work.', ); type Extra = { signal: AbortSignal; _meta?: { progressToken?: string | number }; sendNotification: (n: { method: 'notifications/progress'; params: { progressToken: string | number; progress: number; message?: string }; }) => Promise; }; function result(v: unknown) { return { content: [{ type: 'text' as const, text: JSON.stringify(v, null, 2) }] }; } /** Tells the agent, once, that a claim it held went back to the queue while it was silent. */ function withLostLeases(v: unknown, lost: string[]) { if (!lost.length || !v || typeof v !== 'object' || Array.isArray(v)) return v; return { ...v, leaseLost: { tickets: lost, note: 'Your claim went back to the queue (no tool calls for the lease length, or released in the Lookout). claim_ticket it again to continue, unless another agent took it.', }, }; } function failure(e: unknown) { const msg = e instanceof OperationError ? e.message : `${(e as Error).message ?? e}`; return { isError: true, content: [{ type: 'text' as const, text: msg }] }; } export function waitControl(extra: Extra, message = 'Waiting on the human in the Lookout'): WaitControl { const token = extra._meta?.progressToken; return { signal: extra.signal, onProgress: token === undefined ? undefined : (s) => void extra .sendNotification({ method: 'notifications/progress', params: { progressToken: token, progress: s, message }, }) .catch(() => {}), }; } /** * A tool with `retired` inputs lets unknown inputs through instead of dropping them, so its handler can refuse a * retired one by name (record_decision's `decidedBy`) while the schema agents read no longer lists it. */ const inputSchema = (shape: S, retired?: string[]) => retired?.length ? z.looseObject(shape) : shape; /** * Registers one tool: its result is JSON text, errors become tool errors, and agent state is flushed after every * call. Every string input is a single line unless its schema is `text()` (lineSafety.ts). `human` says whether the tool speaks for the human (remoteGate.ts): a remote session doesn't get a tool * that does, and can't pass the inputs that claim the human's word. */ export function toolDefiner(server: McpServer, agent: TrailAgent) { return ( name: string, meta: { title: string; description: string; human: HumanRole; readOnly?: boolean; retired?: string[] }, shape: S, fn: (args: z.infer>, extra: Extra) => Promise, ) => { humanRoles(server).set(name, meta.human); toolShapes(server).set(name, shape); const actsForHuman = meta.human !== 'none' && meta.human.kind === 'acts'; if (agent.remote && actsForHuman) return undefined; return server.registerTool( name, { title: meta.title, description: meta.description, inputSchema: inputSchema(agent.remote ? markHumanInputs(shape, meta.human) : shape, meta.retired), annotations: { readOnlyHint: !!meta.readOnly, openWorldHint: false }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any (async (args: any, extra: any) => { try { agent.noteCall(extra?._meta); agent.heartbeat(); assertLineSafe(name, shape, args); if (agent.remote) assertNoHumanInputs(name, meta.human, args); const told = withLostLeases(await fn(args, extra), agent.takeLostLeases()); return result(withRefusedWrites(told, () => agent.takeRefusedWrites())); } catch (e) { return failure(e); } finally { agent.flush(); } }) as never, ); }; } export type DefineTool = ReturnType;